text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js@0.8.4?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.ts').catch(function (err) {
          console.error(err);
      });
    </script>
  </head>
  <body style="height:300px;width:300px">
    <my-app>Loading...</my-app>
  </body>
</html>


text:
"""Module containing module parser implementation able to properly read and write
configuration files"""

import re
try:
    import ConfigParser as cp
except ImportError:
    # PY3
    import configparser as cp
import inspect
import logging
import abc
import os

from git.odict import OrderedDict
from git.util import LockFile
from git.compat import (
    string_types,
    FileType,
    defenc,
    force_text,
    with_metaclass,
    PY3
)

__all__ = ('GitConfigParser', 'SectionConstraint')

log = logging.getLogger('git.config')

class MetaParserBuilder(abc.ABCMeta):

    """Utlity class wrapping base-class methods into decorators that assure read-only properties"""
    def __new__(metacls, name, bases, clsdict):
        """
        Equip all base-class methods with a needs_values decorator, and all non-const methods
        with a set_dirty_and_flush_changes decorator in addition to that."""
        kmm = '_mutating_methods_'
        if kmm in clsdict:
            mutating_methods = clsdict[kmm]
            for base in bases:
                methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_"))
                for name, method in methods:
                    if name in clsdict:
                        continue
                    method_with_values = needs_values(method)
                    if name in mutating_methods:
                        method_with_values = set_dirty_and_flush_changes(method_with_values)
                    # END mutating methods handling

                    clsdict[name] = method_with_values
                # END for each name/method pair
            # END for each base
        # END if mutating methods configuration is set

        new_type = super(MetaParserBuilder, metacls).__new__(metacls, name, bases, clsdict)
        return new_type

def needs_values(func):
    """Returns method assuring we read values (on demand) before we try to access them"""

    def assure_data_present(self, *args, **kwargs):
        self.read()
        return func(self, *args, **kwargs)
    # END wrapper method
    assure_data_present.__name__ = func.__name__
    return assure_data_present

def set_dirty_and_flush_changes(non_const_func):
    """Return method that checks whether given non constant function may be called.
    If so, the instance will be set dirty.
    Additionally, we flush the changes right to disk"""

    def flush_changes(self, *args, **kwargs):
        rval = non_const_func(self, *args, **kwargs)
        self.write()
        return rval
    # END wrapper method
    flush_changes.__name__ = non_const_func.__name__
    return flush_changes

class SectionConstraint(object):

    """Constrains a ConfigParser to only option commands which are constrained to
    always use the section we have been initialized with.

    It supports all ConfigParser methods that operate on an option"""
    __slots__ = ("_config", "_section_name")
    _valid_attrs_ = ("get_value", "set_value", "get", "set", "getint", "getfloat", "getboolean", "has_option",
                     "remove_section", "remove_option", "options")

    def __init__(self, config, section):
        self._config = config
        self._section_name = section

    def __del__(self):
        # Yes, for some reason, we have to call it explicitly for it to work in PY3 !
        # Apparently __del__ doesn't get call anymore if refcount becomes 0
        # Ridiculous ... .
        self._config.release()

    def __getattr__(self, attr):
        if attr in self._valid_attrs_:
            return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs)
        return super(SectionConstraint, self).__getattribute__(attr)

    def _call_config(self, method, *args, **kwargs):
        """Call the configuration at the given method which must take a section name
        as first argument"""
        return getattr(self._config, method)(self._section_name, *args, **kwargs)

    @property
    def config(self):
        """return: Configparser instance we constrain"""
        return self._config

    def release(self):
        """Equivalent to GitConfigParser.release(), which is called on our underlying parser instance"""
        return self._config.release()

class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, object)):

    """Implements specifics required to read git style configuration files.

    This variation behaves much like the git.config command such that the configuration
    will be read on demand based on the filepath given during initialization.

    The changes will automatically be written once the instance goes out of scope, but
    can be triggered manually as well.

    The configuration file will be locked if you intend to change values preventing other
    instances to write concurrently.

    :note:
        The config is case-sensitive even when queried, hence section and option names
        must match perfectly."""

    #{ Configuration
    # The lock type determines the type of lock to use in new configuration readers.
    # They must be compatible to the LockFile interface.
    # A suitable alternative would be the BlockingLockFile
    t_lock = LockFile
    re_comment = re.compile('^\s*[#;]')

    #} END configuration

    OPTCRE = re.compile(
        r'\s*(?P<option>[^:=\s][^:=]*)'       # very permissive, incuding leading whitespace
        r'\s*(?P<vi>[:=])\s*'                 # any number of space/tab,
                                              # followed by separator
                                              # (either : or =), followed
                                              # by any # space/tab
        r'(?P<value>.*)$'                     # everything up to eol
    )

    # list of RawConfigParser methods able to change the instance
    _mutating_methods_ = ("add_section", "remove_section", "remove_option", "set")

    def __init__(self, file_or_files, read_only=True, merge_includes=True):
        """Initialize a configuration reader to read the given file_or_files and to
        possibly allow changes to it by setting read_only False

        :param file_or_files:
            A single file path or file objects or multiple of these

        :param read_only:
            If True, the ConfigParser may only read the data , but not change it.
            If False, only a single file path or file object may be given. We will write back the changes
            when they happen, or when the ConfigParser is released. This will not happen if other
            configuration files have been included
        :param merge_includes: if True, we will read files mentioned in [include] sections and merge their
            contents into ours. This makes it impossible to write back an individual configuration file.
            Thus, if you want to modify a single conifguration file, turn this off to leave the original
            dataset unaltered when reading it."""
        cp.RawConfigParser.__init__(self, dict_type=OrderedDict)

        # Used in python 3, needs to stay in sync with sections for underlying implementation to work
        if not hasattr(self, '_proxies'):
            self._proxies = self._dict()

        self._file_or_files = file_or_files
        self._read_only = read_only
        self._is_initialized = False
        self._merge_includes = merge_includes
        self._lock = None

        if not read_only:
            if isinstance(file_or_files, (tuple, list)):
                raise ValueError(
                    "Write-ConfigParsers can operate on a single file only, multiple files have been passed")
            # END single file check

            if not isinstance(file_or_files, string_types):
                file_or_files = file_or_files.name
            # END get filename from handle/stream
            # initialize lock base - we want to write
            self._lock = self.t_lock(file_or_files)

            self._lock._obtain_lock()
        # END read-only check

    def __del__(self):
        """Write pending changes if required and release locks"""
        # NOTE: only consistent in PY2
        self.release()

    def release(self):
        """Flush changes and release the configuration write lock. This instance must not be used anymore afterwards.
        In Python 3, it's required to explicitly release locks and flush changes, as __del__ is not called
        deterministically anymore."""
        # checking for the lock here makes sure we do not raise during write()
        # in case an invalid parser was created who could not get a lock
        if self.read_only or (self._lock and not self._lock._has_lock()):
            return

        try:
            try:
                self.write()
            except IOError:
                log.error("Exception during destruction of GitConfigParser", exc_info=True)
            except ReferenceError:
                # This happens in PY3 ... and usually means that some state cannot be written
                # as the sections dict cannot be iterated
                # Usually when shutting down the interpreter, don'y know how to fix this
                pass
        finally:
            self._lock._release_lock()

    def optionxform(self, optionstr):
        """Do not transform options in any way when writing"""
        return optionstr

    def _read(self, fp, fpname):
        """A direct copy of the py2.4 version of the super class's _read method
        to assure it uses ordered dicts. Had to change one line to make it work.

        Future versions have this fixed, but in fact its quite embarassing for the
        guys not to have done it right in the first place !

        Removed big comments to make it more compact.

        Made sure it ignores initial whitespace as git uses tabs"""
        cursect = None                            # None, or a dictionary
        optname = None
        lineno = 0
        is_multi_line = False
        e = None                                  # None, or an exception

        def string_decode(v):
            if v[-1] == '\\':
                v = v[:-1]
            # end cut trailing escapes to prevent decode error

            if PY3:
                return v.encode(defenc).decode('unicode_escape')
            else:
                return v.decode('string_escape')
            # end
        # end

        while True:
            # we assume to read binary !
            line = fp.readline().decode(defenc)
            if not line:
                break
            lineno = lineno + 1
            # comment or blank line?
            if line.strip() == '' or self.re_comment.match(line):
                continue
            if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
                # no leading whitespace
                continue

            # is it a section header?
            mo = self.SECTCRE.match(line.strip())
            if not is_multi_line and mo:
                sectname = mo.group('header').strip()
                if sectname in self._sections:
                    cursect = self._sections[sectname]
                elif sectname == cp.DEFAULTSECT:
                    cursect = self._defaults
                else:
                    cursect = self._dict((('__name__', sectname),))
                    self._sections[sectname] = cursect
                    self._proxies[sectname] = None
                # So sections can't start with a continuation line
                optname = None
            # no section header in the file?
            elif cursect is None:
                raise cp.MissingSectionHeaderError(fpname, lineno, line)
            # an option line?
            elif not is_multi_line:
                mo = self.OPTCRE.match(line)
                if mo:
                    # We might just have handled the last line, which could contain a quotation we want to remove
                    optname, vi, optval = mo.group('option', 'vi', 'value')
                    if vi in ('=', ':') and ';' in optval:
                        pos = optval.find(';')
                        if pos != -1 and optval[pos - 1].isspace():
                            optval = optval[:pos]
                    optval = optval.strip()
                    if optval == '""':
                        optval = ''
                    # end handle empty string
                    optname = self.optionxform(optname.rstrip())
                    if len(optval) > 1 and optval[0] == '"' and optval[-1] != '"':
                        is_multi_line = True
                        optval = string_decode(optval[1:])
                    # end handle multi-line
                    cursect[optname] = optval
                else:
                    if not e:
                        e = cp.ParsingError(fpname)
                    e.append(lineno, repr(line))
                    continue
            else:
                line = line.rstrip()
                if line.endswith('"'):
                    is_multi_line = False
                    line = line[:-1]
                # end handle quotations
                cursect[optname] += string_decode(line)
            # END parse section or option
        # END while reading

        # if any parsing errors occurred, raise an exception
        if e:
            raise e

    def _has_includes(self):
        return self._merge_includes and self.has_section('include')

    def read(self):
        """Reads the data stored in the files we have been initialized with. It will
        ignore files that cannot be read, possibly leaving an empty configuration

        :return: Nothing
        :raise IOError: if a file cannot be handled"""
        if self._is_initialized:
            return
        self._is_initialized = True

        if not isinstance(self._file_or_files, (tuple, list)):
            files_to_read = [self._file_or_files]
        else:
            files_to_read = list(self._file_or_files)
        # end assure we have a copy of the paths to handle

        seen = set(files_to_read)
        num_read_include_files = 0
        while files_to_read:
            file_path = files_to_read.pop(0)
            fp = file_path
            close_fp = False

            # assume a path if it is not a file-object
            if not hasattr(fp, "seek"):
                try:
                    fp = open(file_path, 'rb')
                    close_fp = True
                except IOError:
                    continue
            # END fp handling

            try:
                self._read(fp, fp.name)
            finally:
                if close_fp:
                    fp.close()
            # END read-handling

            # Read includes and append those that we didn't handle yet
            # We expect all paths to be normalized and absolute (and will assure that is the case)
            if self._has_includes():
                for _, include_path in self.items('include'):
                    if not os.path.isabs(include_path):
                        if not close_fp:
                            continue
                        # end ignore relative paths if we don't know the configuration file path
                        assert os.path.isabs(file_path), "Need absolute paths to be sure our cycle checks will work"
                        include_path = os.path.join(os.path.dirname(file_path), include_path)
                    # end make include path absolute
                    include_path = os.path.normpath(include_path)
                    if include_path in seen or not os.access(include_path, os.R_OK):
                        continue
                    seen.add(include_path)
                    files_to_read.append(include_path)
                    num_read_include_files += 1
                # each include path in configuration file
            # end handle includes
        # END for each file object to read

        # If there was no file included, we can safely write back (potentially) the configuration file
        # without altering it's meaning
        if num_read_include_files == 0:
            self._merge_includes = False
        # end

    def _write(self, fp):
        """Write an .ini-format representation of the configuration state in
        git compatible format"""
        def write_section(name, section_dict):
            fp.write(("[%s]\n" % name).encode(defenc))
            for (key, value) in section_dict.items():
                if key != "__name__":
                    fp.write(("\t%s = %s\n" % (key, self._value_to_string(value).replace('\n', '\n\t'))).encode(defenc))
                # END if key is not __name__
        # END section writing

        if self._defaults:
            write_section(cp.DEFAULTSECT, self._defaults)
        for name, value in self._sections.items():
            write_section(name, value)

    def items(self, section_name):
        """:return: list((option, value), ...) pairs of all items in the given section"""
        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']

    @needs_values
    def write(self):
        """Write changes to our file, if there are changes at all

        :raise IOError: if this is a read-only writer instance or if we could not obtain
            a file lock"""
        self._assure_writable("write")

        if isinstance(self._file_or_files, (list, tuple)):
            raise AssertionError("Cannot write back if there is not exactly a single file to write to, have %i files"
                                 % len(self._file_or_files))
        # end assert multiple files

        if self._has_includes():
            log.debug("Skipping write-back of confiuration file as include files were merged in." +
                      "Set merge_includes=False to prevent this.")
            return
        # end

        fp = self._file_or_files
        close_fp = False

        # we have a physical file on disk, so get a lock
        if isinstance(fp, string_types + (FileType, )):
            self._lock._obtain_lock()
        # END get lock for physical files

        if not hasattr(fp, "seek"):
            fp = open(self._file_or_files, "wb")
            close_fp = True
        else:
            fp.seek(0)
            # make sure we do not overwrite into an existing file
            if hasattr(fp, 'truncate'):
                fp.truncate()
            # END
        # END handle stream or file

        # WRITE DATA
        try:
            self._write(fp)
        finally:
            if close_fp:
                fp.close()
        # END data writing

        # we do not release the lock - it will be done automatically once the
        # instance vanishes

    def _assure_writable(self, method_name):
        if self.read_only:
            raise IOError("Cannot execute non-constant method %s.%s" % (self, method_name))

    def add_section(self, section):
        """Assures added options will stay in order"""
        return super(GitConfigParser, self).add_section(section)

    @property
    def read_only(self):
        """:return: True if this instance may change the configuration file"""
        return self._read_only

    def get_value(self, section, option, default=None):
        """
        :param default:
            If not None, the given default value will be returned in case
            the option did not exist
        :return: a properly typed value, either int, float or string

        :raise TypeError: in case the value could not be understood
            Otherwise the exceptions known to the ConfigParser will be raised."""
        try:
            valuestr = self.get(section, option)
        except Exception:
            if default is not None:
                return default
            raise

        types = (int, float)
        for numtype in types:
            try:
                val = numtype(valuestr)

                # truncated value ?
                if val != float(valuestr):
                    continue

                return val
            except (ValueError, TypeError):
                continue
        # END for each numeric type

        # try boolean values as git uses them
        vl = valuestr.lower()
        if vl == 'false':
            return False
        if vl == 'true':
            return True

        if not isinstance(valuestr, string_types):
            raise TypeError("Invalid value type: only int, long, float and str are allowed", valuestr)

        return valuestr

    def _value_to_string(self, value):
        if isinstance(value, (int, float, bool)):
            return str(value)
        return force_text(value)

    @needs_values
    @set_dirty_and_flush_changes
    def set_value(self, section, option, value):
        """Sets the given option in section to the given value.
        It will create the section if required, and will not throw as opposed to the default
        ConfigParser 'set' method.

        :param section: Name of the section in which the option resides or should reside
        :param option: Name of the options whose value to set

        :param value: Value to set the option to. It must be a string or convertible
            to a string
        :return: this instance"""
        if not self.has_section(section):
            self.add_section(section)
        self.set(section, option, self._value_to_string(value))
        return self

    def rename_section(self, section, new_name):
        """rename the given section to new_name
        :raise ValueError: if section doesn't exit
        :raise ValueError: if a section with new_name does already exist
        :return: this instance
        """
        if not self.has_section(section):
            raise ValueError("Source section '%s' doesn't exist" % section)
        if self.has_section(new_name):
            raise ValueError("Destination section '%s' already exists" % new_name)

        super(GitConfigParser, self).add_section(new_name)
        for k, v in self.items(section):
            self.set(new_name, k, self._value_to_string(v))
        # end for each value to copy

        # This call writes back the changes, which is why we don't have the respective decorator
        self.remove_section(section)
        return self

redpajama_set_name: RedPajamaGithub


text:
from string import punctuation
import operator
import pandas as pd

def WordCount(dataframe, country, column_str):
    '''
    This function do word count for a dataframe. It first group the dataframe
    based on the column with the country name, and then cat all the str stored
    in that country together, and perform a wordcount on the concatenated str.
    It returns a dictionary of all the word for each country.

    params: dataframe: the dataframe on which you want to perform wordcount
    params: country: the column on which the dataframe is grouped by
    params: column_name_str: the column in which the str is stored
    '''
    dic = {}
    UniqueNames = dataframe.country.unique()
    dic = {item: pd.DataFrame for item in UniqueNames}
    for key in dic.keys():
        dic[key] = dataframe[dataframe.country == key]
    dic2 = {}
    for p in dic.keys():
        dic2[p] = reduce(lambda x, y: x + y,
                         dic[p][column_str], '')
    wc = {}
    for k, v in dic2.iteritems():
        ls = dic2.get(k).lower().translate(None, punctuation).split(' ')
        freq = {}
        for word in ls:
            freq[word] = ls.count(word)
            sorted_freq = sorted(freq.items(), key=operator.itemgetter(1),
                                 reverse=True)
            wc[k] = sorted_freq
    return wc


text:
package etcdserver

import (
	"sync"

	pb "go.etcd.io/etcd/v3/etcdserver/etcdserverpb"

	humanize "github.com/dustin/go-humanize"
	"go.uber.org/zap"
)

const (
	// DefaultQuotaBytes is the number of bytes the backend Size may
	// consume before exceeding the space quota.
	DefaultQuotaBytes = int64(2 * 1024 * 1024 * 1024) // 2GB
	// MaxQuotaBytes is the maximum number of bytes suggested for a backend
	// quota. A larger quota may lead to degraded performance.
	MaxQuotaBytes = int64(8 * 1024 * 1024 * 1024) // 8GB
)

// Quota represents an arbitrary quota against arbitrary requests. Each request
// costs some charge; if there is not enough remaining charge, then there are
// too few resources available within the quota to apply the request.
type Quota interface {
	// Available judges whether the given request fits within the quota.
	Available(req interface{}) bool
	// Cost computes the charge against the quota for a given request.
	Cost(req interface{}) int
	// Remaining is the amount of charge left for the quota.
	Remaining() int64
}

type passthroughQuota struct{}

func (*passthroughQuota) Available(interface{}) bool { return true }
func (*passthroughQuota) Cost(interface{}) int       { return 0 }
func (*passthroughQuota) Remaining() int64           { return 1 }

type backendQuota struct {
	s               *EtcdServer
	maxBackendBytes int64
}

const (
	// leaseOverhead is an estimate for the cost of storing a lease
	leaseOverhead = 64
	// kvOverhead is an estimate for the cost of storing a key's metadata
	kvOverhead = 256
)

var (
	// only log once
	quotaLogOnce sync.Once

	DefaultQuotaSize = humanize.Bytes(uint64(DefaultQuotaBytes))
	maxQuotaSize     = humanize.Bytes(uint64(MaxQuotaBytes))
)

// NewBackendQuota creates a quota layer with the given storage limit.
func NewBackendQuota(s *EtcdServer, name string) Quota {
	lg := s.getLogger()
	quotaBackendBytes.Set(float64(s.Cfg.QuotaBackendBytes))

	if s.Cfg.QuotaBackendBytes < 0 {
		// disable quotas if negative
		quotaLogOnce.Do(func() {
			lg.Info(
				"disabled backend quota",
				zap.String("quota-name", name),
				zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
			)
		})
		return &passthroughQuota{}
	}

	if s.Cfg.QuotaBackendBytes == 0 {
		// use default size if no quota size given
		quotaLogOnce.Do(func() {
			if lg != nil {
				lg.Info(
					"enabled backend quota with default value",
					zap.String("quota-name", name),
					zap.Int64("quota-size-bytes", DefaultQuotaBytes),
					zap.String("quota-size", DefaultQuotaSize),
				)
			}
		})
		quotaBackendBytes.Set(float64(DefaultQuotaBytes))
		return &backendQuota{s, DefaultQuotaBytes}
	}

	quotaLogOnce.Do(func() {
		if s.Cfg.QuotaBackendBytes > MaxQuotaBytes {
			lg.Warn(
				"quota exceeds the maximum value",
				zap.String("quota-name", name),
				zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
				zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))),
				zap.Int64("quota-maximum-size-bytes", MaxQuotaBytes),
				zap.String("quota-maximum-size", maxQuotaSize),
			)
		}
		lg.Info(
			"enabled backend quota",
			zap.String("quota-name", name),
			zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
			zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))),
		)
	})
	return &backendQuota{s, s.Cfg.QuotaBackendBytes}
}

func (b *backendQuota) Available(v interface{}) bool {
	// TODO: maybe optimize backend.Size()
	return b.s.Backend().Size()+int64(b.Cost(v)) < b.maxBackendBytes
}

func (b *backendQuota) Cost(v interface{}) int {
	switch r := v.(type) {
	case *pb.PutRequest:
		return costPut(r)
	case *pb.TxnRequest:
		return costTxn(r)
	case *pb.LeaseGrantRequest:
		return leaseOverhead
	default:
		panic("unexpected cost")
	}
}

func costPut(r *pb.PutRequest) int { return kvOverhead + len(r.Key) + len(r.Value) }

func costTxnReq(u *pb.RequestOp) int {
	r := u.GetRequestPut()
	if r == nil {
		return 0
	}
	return costPut(r)
}

func costTxn(r *pb.TxnRequest) int {
	sizeSuccess := 0
	for _, u := range r.Success {
		sizeSuccess += costTxnReq(u)
	}
	sizeFailure := 0
	for _, u := range r.Failure {
		sizeFailure += costTxnReq(u)
	}
	if sizeFailure > sizeSuccess {
		return sizeFailure
	}
	return sizeSuccess
}

func (b *backendQuota) Remaining() int64 {
	return b.maxBackendBytes - b.s.Backend().Size()
}


text:
- Multiple sub-jobs (need to work out nomenclature) - allowing testing in different environments
- Refactor models into an API rather than relying on mongo queries everywhere.
- Easier theming (theme plugin type)
- Make strider a class - no more global shared scope
- Auth plugins

# Changelog / Past releases

## 1.4.3 - [milestone](https://github.com/Strider-CD/strider/issues?milestone=10&state=open)

Bugfix release for 1.4. No major new features.

Fixes include:

- [#286](https://github.com/Strider-CD/strider/issues/286) strider crash on large github webhook post body

## 1.4.2 - [milestone](https://github.com/Strider-CD/strider/issues?milestone=10&state=open)

Bugfix release for 1.4. No major new features.

Fixes include:

- [#296](https://github.com/Strider-CD/strider/issues/296) encoding / LOCALE issues
- [#289 / #281](https://github.com/Strider-CD/strider/issues/289) getTime() crash
- [#287](https://github.com/Strider-CD/strider/issues/287) unable to add environment variables

## 1.4.1 - [milestone](https://github.com/Strider-CD/strider/issues?milestone=9&state=open)

Bugfix release for 1.4. No major new features.

Fixes include:

- [#210](https://github.com/Strider-CD/strider/issues/210) collaborator acces level issue
- [#278](https://github.com/Strider-CD/strider/issues/278) failed to load plugins when running as non-root user
- [#280](https://github.com/Strider-CD/strider/issues/280) move plugin aggregation to dynamic route
- [#274](https://github.com/Strider-CD/strider/issues/274) error when promoting user to admin
- [#284](https://github.com/Strider-CD/strider/issues/284) safari displays logged-in cache of / despite logout

## 1.4 - [track progress](https://github.com/Strider-CD/strider/issues/197), [milestone](https://github.com/Strider-CD/strider/issues?milestone=3)

Released Nov 16th 2013

Major refactor, almost everything has changed:

- Pluggable VCS providers enable:
  + Git
  + Github Enterprise
  + BitBucket
  + Generic Git
  + 3rd party projects working on Gitlab

- Per-branch repos and config. E.g. "release" branch can have different config from "master" branch.
- Testing of Pull Requests.
- Per-projet plugin configuration. Plugins can be ordered and configured entirely through the web UI.

## 1.3 [milestone](https://github.com/Strider-CD/strider/issues?milestone=2)
- This seems like ages ago...
- Records are blurry back here - look at the git log for information.


text:
package knub.master_thesis.preprocessing

import java.io.File
import java.nio.file.{Files, Path, Paths}

import cc.mallet.types.Instance
import knub.master_thesis
import master_thesis.util.CorpusReader
import org.apache.commons.io.FileUtils

import scala.collection.JavaConverters._
import scala.xml.XML
import scala.io.Source
import scala.util.matching.Regex

object DataIterators {

    def getIteratorForDataFolderName(dataFolderName: String): (java.util.Iterator[Instance], String) = {
        if (dataFolderName.contains("plain-text")) {
            println("Detected Wikipedia")
            (wikipedia(dataFolderName), "../resources/stopwords.txt")
        } else if (dataFolderName.contains(".restricted")) {
            println("Detected restricted corpus")
            (restrictedCorpus(dataFolderName), "../resources/stopwords.txt")
        } else if (dataFolderName.contains("nips")) {
            (nips(dataFolderName), "../resources/stopwords.txt")
        } else if (dataFolderName.contains("20news-bydate-train-with-classes/sentences.txt")) {
            println("Detected 20 news sentences corpus")
            (twentyNewsSentences(dataFolderName), "../resources/stopwords.20news.txt")
        } else if (dataFolderName.contains("20newsgroups")) {
            println("Detected 20 news corpus")
            (twentyNews(dataFolderName), "../resources/stopwords.txt")
        } else if (dataFolderName.contains("reuters-21578")) {
            println("Detected reuters corpus")
            (reuters(dataFolderName), "../resources/stopwords.txt")
        } else {
            throw new Exception("No data iterator found for given data folder name.")
        }
    }

    def reuters(dataFolderName: String): java.util.Iterator[cc.mallet.types.Instance] = {
        val xml = XML.loadFile(s"$dataFolderName/reut2-000.sgm")
        val bodies = xml \\ "TITLE"
        println(bodies.size)
//        bodies.foreach { n =>
//            println(n.text)
//        }
        throw new RuntimeException("Not yet implemented")
        null
    }

    def restrictedCorpus(dataFolderName: String): java.util.Iterator[cc.mallet.types.Instance] = {
        if (new File(dataFolderName + ".classes").exists()) {
            val vocabulary = Source.fromFile(dataFolderName + ".vocab").getLines.toArray
            val classes = Source.fromFile(dataFolderName + ".classes").getLines.toList
            val corpus = CorpusReader.readCorpus(dataFolderName)

            val documents = corpus.documents.asScala.map { doc =>
                val sb = new StringBuilder
                doc.iterator().asScala.foreach { i =>
                    sb.append(s" ${vocabulary(i.value)}")
                }
                sb.toString()
            }
            assert(documents.length == classes.length)
            documents.zip(classes).map { case (document, clazz) =>
                new Instance(document, clazz.toInt, null, null)
            }.iterator.asJava
        } else {
            val vocabulary = Source.fromFile(dataFolderName + ".vocab").getLines.toArray
            val corpus = CorpusReader.readCorpus(dataFolderName)

            val documents = corpus.documents.asScala.map { doc =>
                val sb = new StringBuilder
                doc.iterator().asScala.foreach { i =>
                    sb.append(s" ${vocabulary(i.value)}")
                }
                sb.toString()
            }
            documents.map { case document =>
                new Instance(document, null, null, null)
            }.iterator.asJava

        }
    }

    def nips(dataFolderName: String): java.util.Iterator[Instance] = {
        val regex = new Regex("nips[0-9]{2}")
        val files = new File(dataFolderName).list().filter { f =>
            regex.findFirstIn(f).isDefined
        }.map { f =>
            new File(dataFolderName + "/" + f)
        }

        val instances = files.flatMap { folder =>
            folder.list().map { document =>
                val origLines = FileUtils.readLines(new File(s"$folder/$document")).asScala.toList
                val lines = origLines.dropWhile(_.length < 5)

                val title = lines.head
                val content = lines.dropWhile(!_.toLowerCase.contains("abstract")).drop(1)

                val text = title + content.mkString("\n")
//                val content = FileUtils.readFileToString(new File())
                new Instance(text, folder.getName, folder + "/" + document, text)
            }
        }

        val nipsArticles = new File(s"$dataFolderName/articles.txt")
        if (nipsArticles.exists()) {
            val texts = files.flatMap { folder =>
                folder.list().map { document =>
                    val origLines = FileUtils.readLines(new File(s"$folder/$document")).asScala.toList
                    val lines = origLines.dropWhile(_.length < 5)

                    val title = lines.head
                    val content = lines.view
                        .map(_.trim)
                        .map { l => if (l.endsWith("-")) s"${l.replaceAll("-$", "")}" else s"$l " }
                        .dropWhile(!_.toLowerCase.contains("abstract"))
                        .drop(1)
                        .takeWhile { l =>
                            !l.startsWith("References") &&
                            !l.startsWith("REFERENCES") &&
                            !l.endsWith("References ") &&
                            !l.endsWith("REFERENCES ") }

                    val text = title + content.mkString("")
                    text
                }
            }.toList.asJavaCollection
//            val texts = instances.map { inst =>
//                inst.getData.asInstanceOf[String]
//            }.toList.asJavaCollection
            FileUtils.writeLines(nipsArticles, texts)
            System.exit(1)
        }

        scala.util.Random.shuffle(instances.toList).iterator.asJava
    }

    def wikipedia(dataFolderName: String) = {
        OnlyNormalPagesIterator.normalPagesIterator(new WikiPlainTextIterator(dataFolderName))
    }

    def twentyNews(dataFolderName: String) = {
        new TwentyNewsIterator(dataFolderName).iterator()
    }
    def twentyNewsSentences(dataFolderName: String): java.util.Iterator[Instance] = {
        Source.fromFile(dataFolderName).getLines().zipWithIndex.map { case (line, idx) =>
            try {
                val split = line.split('\t')
                val doc = split(0).toInt
                val clazz = split(1).toInt
                val text = split(2)
                new Instance(text, clazz, doc, null)
            } catch {
                case e: Exception =>
                    println(s"$idx>>>$line<<<")
                    throw e
            }
        }.asJava
    }
}

object OnlyNormalPagesIterator {
    def normalPagesIterator(wikiPlainTextIterator: WikiPlainTextIterator): java.util.Iterator[Instance] = {
        wikiPlainTextIterator.asScala.filter { inst =>
            val title = inst.getName.asInstanceOf[String]
            !(title.contains("Lists of") ||
                title.contains("List of") ||
                title.contains("isambiguation"))
        }.asJava
    }
}
class TwentyNewsIterator(dataFolderName: String) {

    def iterator(): java.util.Iterator[Instance] = {
        val articlesPath = Paths.get(dataFolderName + "/articles.txt").toFile
        val articlesClassesPath = Paths.get(dataFolderName + "/articles.class.txt").toFile

        val articles = scala.io.Source.fromFile(articlesPath, "UTF-8").getLines().toBuffer
        val classes = scala.io.Source.fromFile(articlesClassesPath, "UTF-8").getLines().toBuffer
        assert(articles.length == classes.length)
        var i = 0
        articles.zip(classes).map { case (articlesLine, clazz) =>
            val split = articlesLine.split('\t')
            assert(split.length == 2, s"split length should be 2 but is ${split.length} at line $i")
            i += 1
            val fileName = split(0)
            val text = split(1)
            new Instance(text, clazz.toInt, fileName, articlesLine)
        }.iterator.asJava
    }
}
class WikiPlainTextIterator(dataFolderName: String) extends java.util.Iterator[Instance] {

    val p = Paths.get(dataFolderName)
    val pathIterator = java.nio.file.Files.walk(p).iterator().asScala.filter(Files.isRegularFile(_))
    var lineIterator: Iterator[String] = null
    var currentPath: Path = null
    val sb = new StringBuilder

    override def hasNext: Boolean = {
        pathIterator.hasNext || lineIterator.hasNext
    }

    override def next(): Instance = {
        if (lineIterator == null || !lineIterator.hasNext) {
            currentPath = pathIterator.next()
            lineIterator = scala.io.Source.fromFile(currentPath.toFile).getLines()
        }
        val firstLine = lineIterator.next
        assert(firstLine.startsWith("<doc"), s"$currentPath: '$firstLine' does not start with <doc")

        sb.clear()
        var currentLine = ""
        while (!currentLine.startsWith("</doc>")) {
            sb.append(currentLine + " ")
            currentLine = lineIterator.next
        }
        new Instance(sb.toString(), null, firstLine, null)
    }
}


text:
CREATE TABLE {$NAMESPACE}_auth.auth_hmackey (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  keyName VARCHAR(64) NOT NULL COLLATE {$COLLATE_TEXT},
  keyValue VARCHAR(128) NOT NULL COLLATE {$COLLATE_TEXT},
  dateCreated INT UNSIGNED NOT NULL,
  dateModified INT UNSIGNED NOT NULL,
  UNIQUE KEY `key_name` (keyName)
) ENGINE=InnoDB, COLLATE {$COLLATE_TEXT};


text:
package com.jme3.network.rmi;

import com.jme3.network.*;
import com.jme3.network.ClientStateListener.DisconnectInfo;
import com.jme3.network.serializing.Serializer;
import com.jme3.util.IntMap;
import com.jme3.util.IntMap.Entry;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ObjectStore {

    private static final Logger logger = Logger.getLogger(ObjectStore.class.getName());

    private static final class Invocation {

        Object retVal;
        boolean available = false;

        @Override
        public String toString(){
            return "Invocation[" + retVal + "]";
        }
    }

    private Client client;
    private Server server;

    private ClientEventHandler clientEventHandler = new ClientEventHandler();
    private ServerEventHandler serverEventHandler = new ServerEventHandler();

    // Local object ID counter
    private volatile short objectIdCounter = 0;

    // Local invocation ID counter
    private volatile short invocationIdCounter = 0;

    // Invocations waiting
    private IntMap<Invocation> pendingInvocations = new IntMap<>();

    // Objects I share with other people
    private IntMap<LocalObject> localObjects = new IntMap<>();

    // Objects others share with me
    private HashMap<String, RemoteObject> remoteObjects = new HashMap<>();
    private IntMap<RemoteObject> remoteObjectsById = new IntMap<>();

    private final Object receiveObjectLock = new Object();

    public class ServerEventHandler implements MessageListener<HostedConnection>,
                                                      ConnectionListener {

        @Override
        public void messageReceived(HostedConnection source, Message m) {
            onMessage(source, m);
        }

        @Override
        public void connectionAdded(Server server, HostedConnection conn) {
            onConnection(conn);
        }

        @Override
        public void connectionRemoved(Server server, HostedConnection conn) {
        }

    }

    public class ClientEventHandler implements MessageListener,
                                                      ClientStateListener {

        @Override
        public void messageReceived(Object source, Message m) {
            onMessage(null, m);
        }

        @Override
        public void clientConnected(Client c) {
            onConnection(null);
        }

        @Override
        public void clientDisconnected(Client c, DisconnectInfo info) {
        }

    }

    static {
        Serializer s = new RmiSerializer();
        Serializer.registerClass(RemoteObjectDefMessage.class, s);
        Serializer.registerClass(RemoteMethodCallMessage.class, s);
        Serializer.registerClass(RemoteMethodReturnMessage.class, s);
    }

    @SuppressWarnings("unchecked")
    public ObjectStore(Client client) {
        this.client = client;
        client.addMessageListener(clientEventHandler,
                RemoteObjectDefMessage.class,
                RemoteMethodCallMessage.class,
                RemoteMethodReturnMessage.class);
        client.addClientStateListener(clientEventHandler);
    }

    public ObjectStore(Server server) {
        this.server = server;
        server.addMessageListener(serverEventHandler,
                RemoteObjectDefMessage.class,
                RemoteMethodCallMessage.class,
                RemoteMethodReturnMessage.class);
        server.addConnectionListener(serverEventHandler);
    }

    private ObjectDef makeObjectDef(LocalObject localObj){
        ObjectDef def = new ObjectDef();
        def.objectName = localObj.objectName;
        def.objectId   = localObj.objectId;
        def.methods    = localObj.methods;
        return def;
    }

    public void exposeObject(String name, Object obj) throws IOException{
        // Create a local object
        LocalObject localObj = new LocalObject();
        localObj.objectName = name;
        localObj.objectId  = objectIdCounter++;
        localObj.theObject = obj;
        //localObj.methods   = obj.getClass().getMethods();

        ArrayList<Method> methodList = new ArrayList<>();
        for (Method method : obj.getClass().getMethods()){
            if (method.getDeclaringClass() == obj.getClass()){
                methodList.add(method);
            }
        }
        localObj.methods = methodList.toArray(new Method[methodList.size()]);

        // Put it in the store
        localObjects.put(localObj.objectId, localObj);

        // Inform the others of its existence
        RemoteObjectDefMessage defMsg = new RemoteObjectDefMessage();
        defMsg.objects = new ObjectDef[]{ makeObjectDef(localObj) };

        if (client != null) {
            client.send(defMsg);
            logger.log(Level.FINE, "Client: Sending {0}", defMsg);
        } else {
            server.broadcast(defMsg);
            logger.log(Level.FINE, "Server: Sending {0}", defMsg);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T getExposedObject(String name, Class<T> type, boolean waitFor) throws InterruptedException{
        RemoteObject ro = remoteObjects.get(name);
        if (ro == null){
            if (!waitFor)
                throw new RuntimeException("Cannot find remote object named: " + name);
            else{
                do {
                    synchronized (receiveObjectLock){
                        receiveObjectLock.wait();
                    }
                } while ( (ro = remoteObjects.get(name)) == null );
            }
        }

        Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ type }, ro);
        ro.loadMethods(type);
        return (T) proxy;
    }

    Object invokeRemoteMethod(RemoteObject remoteObj, Method method, Object[] args){
        Integer methodIdInt = remoteObj.methodMap.get(method);
        if (methodIdInt == null)
             throw new RuntimeException("Method not implemented by remote object owner: "+method);

        boolean needReturn = method.getReturnType() != void.class;
        short objectId = remoteObj.objectId;
        short methodId = methodIdInt.shortValue();
        RemoteMethodCallMessage call = new RemoteMethodCallMessage();
        call.methodId = methodId;
        call.objectId = objectId;
        call.args = args;

        Invocation invoke = null;
        if (needReturn){
            call.invocationId = invocationIdCounter++;
            invoke = new Invocation();
            // Note: could cause threading issues if used from multiple threads
            pendingInvocations.put(call.invocationId, invoke);
        }

        if (server != null){
            remoteObj.client.send(call);
            logger.log(Level.FINE, "Server: Sending {0}", call);
        }else{
            client.send(call);
            logger.log(Level.FINE, "Client: Sending {0}", call);
        }

        if (invoke != null){
            synchronized(invoke){
                while (!invoke.available){
                    try {
                        invoke.wait();
                    } catch (InterruptedException ex){
                        ex.printStackTrace();
                    }
                }
            }
            // Note: could cause threading issues if used from multiple threads
            pendingInvocations.remove(call.invocationId);
            return invoke.retVal;
        }else{
            return null;
        }
    }

    private void onMessage(HostedConnection source, Message message) {
        // Might want to do more strict validation of the data
        // in the message to prevent crashes

        if (message instanceof RemoteObjectDefMessage){
            RemoteObjectDefMessage defMsg = (RemoteObjectDefMessage) message;

            ObjectDef[] defs = defMsg.objects;
            for (ObjectDef def : defs){
                RemoteObject remoteObject = new RemoteObject(this, source);
                remoteObject.objectId = (short)def.objectId;
                remoteObject.methodDefs = def.methodDefs;
                remoteObjects.put(def.objectName, remoteObject);
                remoteObjectsById.put(def.objectId, remoteObject);
            }

            synchronized (receiveObjectLock){
                receiveObjectLock.notifyAll();
            }
        }else if (message instanceof RemoteMethodCallMessage){
            RemoteMethodCallMessage call = (RemoteMethodCallMessage) message;
            LocalObject localObj = localObjects.get(call.objectId);
            if (localObj == null)
                return;

            if (call.methodId < 0 || call.methodId >= localObj.methods.length)
                return;

            Object obj = localObj.theObject;
            Method method = localObj.methods[call.methodId];
            Object[] args = call.args;
            Object ret = null;
            try {
                ret = method.invoke(obj, args);
            } catch (IllegalAccessException ex){
                logger.log(Level.WARNING, "RMI: Error accessing method", ex);
            } catch (IllegalArgumentException ex){
                logger.log(Level.WARNING, "RMI: Invalid arguments", ex);
            } catch (InvocationTargetException ex){
                logger.log(Level.WARNING, "RMI: Invocation exception", ex);
            }

            if (method.getReturnType() != void.class){
                // send return value back
                RemoteMethodReturnMessage retMsg = new RemoteMethodReturnMessage();
                retMsg.invocationID = call.invocationId;
                retMsg.retVal = ret;
                if (server != null){
                    source.send(retMsg);
                    logger.log(Level.FINE, "Server: Sending {0}", retMsg);
                } else{
                    client.send(retMsg);
                    logger.log(Level.FINE, "Client: Sending {0}", retMsg);
                }
            }
        }else if (message instanceof RemoteMethodReturnMessage){
            RemoteMethodReturnMessage retMsg = (RemoteMethodReturnMessage) message;
            Invocation invoke = pendingInvocations.get(retMsg.invocationID);
            if (invoke == null){
                logger.log(Level.WARNING, "Cannot find invocation ID: {0}", retMsg.invocationID);
                return;
            }

            synchronized (invoke){
                invoke.retVal = retMsg.retVal;
                invoke.available = true;
                invoke.notifyAll();
            }
        }
    }

    private void onConnection(HostedConnection conn) {
        if (localObjects.size() > 0){
            // send an object definition message
            ObjectDef[] defs = new ObjectDef[localObjects.size()];
            int i = 0;
            for (Entry<LocalObject> entry : localObjects){
                defs[i] = makeObjectDef(entry.getValue());
                i++;
            }

            RemoteObjectDefMessage defMsg = new RemoteObjectDefMessage();
            defMsg.objects = defs;
            if (this.client != null){
                this.client.send(defMsg);
                logger.log(Level.FINE, "Client: Sending {0}", defMsg);
            } else{
                conn.send(defMsg);
                logger.log(Level.FINE, "Server: Sending {0}", defMsg);
            }
        }
    }

}


text:
import os
import sys

# Add path to nGraph Python API.

sys.path.insert(0, os.path.abspath('../../../python'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
needs_sphinx = '1.7.9'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.mathjax',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',
    'breathe',
    ]

# source_suffix = '.rst'
source_suffix = ['.rst', '.md']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
static_path = ['static']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'nGraph Compiler Stack'
copyright = '2017-2020, Intel Corporation'
author = 'Intel Corporation'

# License specifics see LICENSE of component

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.29'

# The Documentation full version, including alpha/beta/rc tags. Some features
# available in the latest code will not necessarily be documented first
release = '0.29.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'

#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Options for HTML output ----------------------------------------------

html_title = "Documentation for the nGraph Library and Compiler Stack"

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'ngraph_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
html_logo = '../ngraph_theme/static/logo.png'

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '../ngraph_theme/static/favicon.ico'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['../ngraph_theme/static']

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["../"]

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
    '**': [
        'relations.html',  # needs 'show_related': True theme option to display
        'searchbox.html',
    ]
}

html_last_updated_fmt= ''

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'IntelnGraphlibrarydoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'nGraphCompilerStack.tex', u'nGraph Compiler Stack Documentation',
     u'Intel Corporation', 'manual'),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'ngraphcompiler', 'nGraph Compiler stack',
     [author], 1)
]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'IntelnGraphlibrary', 'Intel nGraph Library',
     author, 'IntelnGraphlibrary', 'Documentation for Intel nGraph Library code base',
     'Miscellaneous'),
]

breathe_projects = {
    "ngraph": "../../doxygen/xml",
}

rst_epilog = u"""
.. include:: /replacements.txt
"""

# -- autodoc Extension configuration --------------------------------------

autodoc_mock_imports = ['ngraph.impl', 'ngraph.utils']


text:
package me.chanjar.weixin.mp.bean.result;

import java.io.Serializable;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import lombok.Data;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

/**
 * <pre>
 * 上传群发用的素材的结果.
 * 视频和图文消息需要在群发前上传素材
 * </pre>
 *
 * @author chanjarster
 */
@Data
public class WxMpMassUploadResult implements Serializable {
  private static final long serialVersionUID = 6568157943644994029L;

  private String type;
  private String mediaId;
  private long createdAt;

  public static WxMpMassUploadResult fromJson(String json) {
    return WxMpGsonBuilder.create().fromJson(json, WxMpMassUploadResult.class);
  }

  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
  }

}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   L. David Baron <dbaron@dbaron.org>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef nsILink_h___
#define nsILink_h___

#include "nsISupports.h"
#include "nsILinkHandler.h" // definition of nsLinkState

class nsIURI;

// IID for the nsILink interface
#define NS_ILINK_IID    \
{ 0x6f374a11, 0x212d, 0x47d6, \
  { 0x94, 0xd1, 0xe6, 0x7c, 0x23, 0x4d, 0x34, 0x99 } }

/**
 * This interface allows SelectorMatches to get the canonical
 * URL pointed to by an element representing a link and allows
 * it to store the visited state of a link element in the link.
 * It is needed for performance reasons (to prevent copying of
 * strings and excessive calls to history).
 */
class nsILink : public nsISupports {
public:
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ILINK_IID)

  /**
   * GetLinkState/SetLinkState/GetHrefURI were moved to nsIContent.
   * @see nsIContent
   */

  /**
   * Dispatch a LinkAdded event to the chrome event handler for this document.
   * This is used to notify the chrome listeners when restoring a page
   * presentation.  Currently, this only applies to HTML <link> elements.
   */
  NS_IMETHOD LinkAdded() = 0;

  /**
   * Dispatch a LinkRemoved event to the chrome event handler for this
   * document.  This is used to notify the chrome listeners when saving a page
   * presentation (since the document is not torn down).  Currently, this only
   * applies to HTML <link> elements.
   */
  NS_IMETHOD LinkRemoved() = 0;
};

NS_DEFINE_STATIC_IID_ACCESSOR(nsILink, NS_ILINK_IID)

#endif /* nsILink_h___ */


text:
package org.ovirt.engine.core.bll.snapshots;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;

import java.util.Collections;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.SnapshotDao;

@RunWith(MockitoJUnitRunner.class)
public class SnapshotsValidatorTest {

    /**
     * The class being tested.
     */
    @Spy
    private SnapshotsValidator validator = new SnapshotsValidator();

    @Mock
    private SnapshotDao snapshotDao;
    private Guid vmId;
    private Snapshot snapshot;

    @Before
    public void setUp() {
        vmId = Guid.newGuid();
        snapshot = new Snapshot();
        snapshot.setId(Guid.newGuid());
        snapshot.setType(Snapshot.SnapshotType.REGULAR);
        doReturn(snapshotDao).when(validator).getSnapshotDao();
    }

    @Test
    public void vmNotDuringSnapshotReturnsInvalidResultWhenInSnapshot() throws Exception {
        when(snapshotDao.exists(vmId, SnapshotStatus.LOCKED)).thenReturn(true);
        validateInvalidResult(validator.vmNotDuringSnapshot(vmId),
                EngineMessage.ACTION_TYPE_FAILED_VM_IS_DURING_SNAPSHOT);
    }

    @Test
    public void vmNotDuringSnapshotReturnsValidForNoSnapshotInProgress() throws Exception {
        when(snapshotDao.exists(vmId, SnapshotStatus.LOCKED)).thenReturn(false);
        validateValidResult(validator.vmNotDuringSnapshot(vmId));
    }

    @Test
    public void vmNotInPreviewReturnsInvalidResultWhenInSnapshot() throws Exception {
        when(snapshotDao.exists(vmId, SnapshotStatus.IN_PREVIEW)).thenReturn(true);
        validateInvalidResult(validator.vmNotInPreview(vmId),
                EngineMessage.ACTION_TYPE_FAILED_VM_IN_PREVIEW);
    }

    @Test
    public void vmNotInPreviewReturnsValidForNoSnapshotInProgress() throws Exception {
        when(snapshotDao.exists(vmId, SnapshotStatus.IN_PREVIEW)).thenReturn(false);
        validateValidResult(validator.vmNotInPreview(vmId));
    }

    @Test
    public void snapshotExistsByGuidReturnsInvalidResultWhenNoSnapshot() throws Exception {
        when(snapshotDao.exists(vmId, snapshot.getId())).thenReturn(false);
        validateInvalidResult(validator.snapshotExists(vmId, snapshot.getId()),
                EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST);
    }

    @Test
    public void snapshotExistsByGuidReturnsValidResultWhenSnapshotExists() throws Exception {
        when(snapshotDao.exists(vmId, snapshot.getId())).thenReturn(true);
        validateValidResult(validator.snapshotExists(vmId, snapshot.getId()));
    }

    @Test
    public void snapshotTypeSupported() throws Exception {
        validateValidResult(validator.snapshotTypeSupported(snapshot, Collections.singletonList(snapshot.getType())));
    }

    @Test
    public void snapshotTypeNotSupported() throws Exception {
        validateInvalidResult(validator.snapshotTypeSupported(snapshot,
                Collections.singletonList(Snapshot.SnapshotType.ACTIVE)),
                EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_TYPE_NOT_ALLOWED);
    }

    @Test
    public void snapshotExistsBySnapshotReturnsInvalidResultWhenNoSnapshot() throws Exception {
        validateInvalidResult(validator.snapshotExists(null),
                EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST);
    }

    @Test
    public void snapshotExistsBySnapshotReturnsValidResultWhenSnapshotExists() throws Exception {
        validateValidResult(validator.snapshotExists(snapshot));
    }

    /**
     * Validate that the given result is valid.
     *
     * @param validationResult
     *            The result.
     */
    private static void validateValidResult(ValidationResult validationResult) {
        validateResult(validationResult, true, null);
    }

    /**
     * Validate that the given result is invalid and contains the given message.
     *
     * @param validationResult
     *            The result.
     * @param message
     *            The error to expect.
     */
    private static void validateInvalidResult(ValidationResult validationResult, EngineMessage message) {
        validateResult(validationResult, false, message);
    }

    /**
     * Validate that the result is as expected.
     *
     * @param validationResult
     *            The result.
     * @param isValid
     *            Should be valid or not?
     * @param message
     *            The error to expect.
     */
    private static void validateResult(ValidationResult validationResult, boolean isValid, EngineMessage message) {
        assertEquals(isValid, validationResult.isValid());
        assertEquals(message, validationResult.getMessage());
    }
}


text:
	<title>Moira Stuart's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Moira Stuart's panel show appearances

Moira Stuart (born 1949-09-02[ref]) has appeared in 10 episodes between 1984-2018.  Moira Stuart on IMDB. Moira Stuart on Wikipedia.

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2018-04-21 / Harry Hill's Alien Fun Capsule

2015-07-31 / Would I Lie To You?

2007-06-02 / Have I Got News For You

2003-05-30 / The News Quiz

1988-11-30 / Call My Bluff

1988-11-16 / Call My Bluff

1987-05-14 / Call My Bluff

1987-05-07 / Call My Bluff

1984-10-26 / Call My Bluff

1984-10-19 / Call My Bluff


text:
require_relative '../../spec_helper'
require "ostruct"

describe "OpenStruct#method_missing when called with a method name ending in '='" do
  before :each do
    @os = OpenStruct.new
  end

  it "raises an ArgumentError when not passed any additional arguments" do
    -> { @os.send(:test=) }.should raise_error(ArgumentError)
  end
end

describe "OpenStruct#method_missing when passed additional arguments" do
  it "raises a NoMethodError when the key does not exist" do
    os = OpenStruct.new
    -> { os.test(1, 2, 3) }.should raise_error(NoMethodError)
  end

  it "raises an ArgumentError when the key exists" do
    os = OpenStruct.new(test: 20)
    -> { os.test(1, 2, 3) }.should raise_error(ArgumentError)
  end
end


text:
@interface PopAnimationView ()
//渲染层
@property (nonatomic,strong) CAShapeLayer *maskLayer;

@property (nonatomic,strong) CAShapeLayer *shapeLayer;

@property (nonatomic,strong) CAShapeLayer *loadingLayer;

@property (nonatomic,strong) CAShapeLayer *clickCicrleLayer;

@property (nonatomic,strong) UIButton *button;
@property (nonatomic,strong) UIViewController *fromViewController;
@property (nonatomic,strong) UIViewController *toViewController;

@end

@implementation PopAnimationView

- (void)loadBaseAnimationFromeViewCntorller:(UIViewController *)fromeViewController ToViewController:(UIViewController *)toViewcontroller WithTitle:(NSString *)title BGImage:(UIImage *)image {
    self.fromViewController = fromeViewController;
    self.toViewController = toViewcontroller;
    self.backgroundColor = [UIColor clearColor];
    _shapeLayer = [self drawMask:self.height * 0.5];
    _shapeLayer.fillColor = [UIColor clearColor].CGColor;
    _shapeLayer.strokeColor = [UIColor whiteColor].CGColor;
    _shapeLayer.lineWidth = 2;
    [self.layer addSublayer:_shapeLayer];

    [self.layer addSublayer:self.maskLayer];

    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame = self.bounds;
    [_button setTitle:title forState:UIControlStateNormal];
    [_button setBackgroundImage:image forState:UIControlStateNormal];

    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _button.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [self addSubview:_button];
    [_button addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];

}

-(CAShapeLayer *)maskLayer{
    if(!_maskLayer){
        _maskLayer = [CAShapeLayer layer];
        _maskLayer.opacity = 0;
        _maskLayer.fillColor = [UIColor whiteColor].CGColor;
        _maskLayer.path = [self drawBezierPath:self.frame.size.width/2].CGPath;
    }
    return _maskLayer;
}

-(void)layoutSubviews{
    [super layoutSubviews];

}

-(void)clickBtn{
    [self clickAnimation];
}

-(void)clickAnimation{
    CAShapeLayer *clickCicrleLayer = [CAShapeLayer layer];
    clickCicrleLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    clickCicrleLayer.fillColor = [UIColor whiteColor].CGColor;
    clickCicrleLayer.path = [self drawclickCircleBezierPath:0].CGPath;
    [self.layer addSublayer:clickCicrleLayer];

    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    basicAnimation.duration = 0.15;
    basicAnimation.toValue = (__bridge id _Nullable)([self drawclickCircleBezierPath:(self.bounds.size.height - 10*2)/2].CGPath);
    basicAnimation.removedOnCompletion = NO;
    basicAnimation.fillMode = kCAFillModeForwards;

    [clickCicrleLayer addAnimation:basicAnimation forKey:@"clickCicrleAnimation"];

    _clickCicrleLayer = clickCicrleLayer;

    [self performSelector:@selector(clickNextAnimation) withObject:self afterDelay:basicAnimation.duration];
}

-(void)clickNextAnimation{
    _clickCicrleLayer.fillColor = [UIColor clearColor].CGColor;
    _clickCicrleLayer.strokeColor = [UIColor whiteColor].CGColor;
    _clickCicrleLayer.lineWidth = 10;

    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];

    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    basicAnimation.duration = 0.15;
    basicAnimation.toValue = (__bridge id _Nullable)([self drawclickCircleBezierPath:(self.bounds.size.height - 10*2)].CGPath);
    basicAnimation.removedOnCompletion = NO;
    basicAnimation.fillMode = kCAFillModeForwards;

    CABasicAnimation *basicAnimation1 = [CABasicAnimation animationWithKeyPath:@"opacity"];
    basicAnimation1.beginTime = 0.10;
    basicAnimation1.duration = 0.15;
    basicAnimation1.toValue = @0;
    basicAnimation1.removedOnCompletion = NO;
    basicAnimation1.fillMode = kCAFillModeForwards;

    animationGroup.duration = basicAnimation1.beginTime + basicAnimation1.duration;
    animationGroup.removedOnCompletion = NO;
    animationGroup.fillMode = kCAFillModeForwards;
    animationGroup.animations = @[basicAnimation,basicAnimation1];

    [_clickCicrleLayer addAnimation:animationGroup forKey:@"clickCicrleAnimation1"];

    [self performSelector:@selector(startMaskAnimation) withObject:self afterDelay:animationGroup.duration];

}

-(void)startMaskAnimation{
    _maskLayer.opacity = 0.15;
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    basicAnimation.duration = 0.25;
    basicAnimation.toValue = (__bridge id _Nullable)([self drawBezierPath:self.frame.size.height/2].CGPath);
    basicAnimation.removedOnCompletion = NO;
    basicAnimation.fillMode = kCAFillModeForwards;
    [_maskLayer addAnimation:basicAnimation forKey:@"maskAnimation"];

    [self performSelector:@selector(dismissAnimation) withObject:self afterDelay:0 ];
}

-(void)dismissAnimation{
    [self removeSubViews];
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    basicAnimation.duration = 0.15;
    basicAnimation.toValue = (__bridge id _Nullable)([self drawBezierPath:self.frame.size.width/2].CGPath);
    basicAnimation.removedOnCompletion = NO;
    basicAnimation.fillMode = kCAFillModeForwards;

    [_shapeLayer addAnimation:basicAnimation forKey:@"dismissAnimation"];

    [self performSelector:@selector(loadingAnimation) withObject:self afterDelay:basicAnimation.duration];
}

-(void)loadingAnimation{
    [self performSelector:@selector(removeAllAnimation) withObject:self afterDelay:0.1];

}

-(void)removeSubViews{
    //    [_button removeFromSuperview];s
    [_maskLayer removeFromSuperlayer];
    [_loadingLayer removeFromSuperlayer];
    [_clickCicrleLayer removeFromSuperlayer];
}

-(void)removeAllAnimation{
    [self removeSubViews];
    if (self.toViewController && self.fromViewController) {
         [self.fromViewController presentViewController:self.toViewController animated:YES completion:nil];
    }
}

-(CAShapeLayer *)drawMask:(CGFloat)x{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = self.bounds;
    shapeLayer.path = [self drawBezierPath:x].CGPath;
    return shapeLayer;
}

-(UIBezierPath *)drawBezierPath:(CGFloat)x{
    CGFloat radius = self.bounds.size.height/2 - 3;
    CGFloat right = self.bounds.size.width-x;
    CGFloat left = x;

    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    bezierPath.lineJoinStyle = kCGLineJoinRound;
    bezierPath.lineCapStyle = kCGLineCapRound;

    [bezierPath addArcWithCenter:CGPointMake(right, self.bounds.size.height/2) radius:radius startAngle:-M_PI/2 endAngle:M_PI/2 clockwise:YES];
    [bezierPath addArcWithCenter:CGPointMake(left, self.bounds.size.height/2) radius:radius startAngle:M_PI/2 endAngle:-M_PI/2 clockwise:YES];
    [bezierPath closePath];

    return bezierPath;
}

-(UIBezierPath *)drawLoadingBezierPath{
    CGFloat radius = self.bounds.size.height/2 - 3;
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath addArcWithCenter:CGPointMake(0,0) radius:radius startAngle:M_PI/2 endAngle:M_PI/2+M_PI/2 clockwise:YES];
    return bezierPath;
}

-(UIBezierPath *)drawclickCircleBezierPath:(CGFloat)radius{
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath addArcWithCenter:CGPointMake(0,0) radius:radius startAngle:0 endAngle:M_PI*2 clockwise:YES];
    return bezierPath;
}

@end


text:
<?php
namespace app\controllers\actions;

use yii\base\Action;

class DeleteAction extends Action
{
    public function run()
    {
        return "delete action";
    }
}


text:
<?php

class RokMenuIdFilter extends RecursiveFilterIterator {
    protected $id;

    public function __construct(RecursiveIterator $recursiveIter, $id) {
        $this->id = $id;
        parent::__construct($recursiveIter);
    }
    public function accept() {
        return $this->hasChildren() || $this->current()->getId() == $this->id;
    }

    public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->id);
    }
}


text:
package com.marakana.android.yamba;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;

public class NetworkReceiver extends BroadcastReceiver {
  public static final String TAG = "NetworkReceiver";

  @Override
  public void onReceive(Context context, Intent intent) {

    boolean isNetworkDown = intent.getBooleanExtra(
        ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

    if (isNetworkDown) {
      Log.d(TAG, "onReceive: NOT connected, stopping UpdaterService");
      context.stopService(new Intent(context, UpdaterService.class));
    } else {
      Log.d(TAG, "onReceive: connected, starting UpdaterService");
      context.startService(new Intent(context, UpdaterService.class));
    }
  }

}


text:
package vapourdrive.genloader.world;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.IChunkGenerator;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.common.BiomeDictionary;
import net.minecraftforge.common.BiomeDictionary.Type;
import net.minecraftforge.fml.common.IWorldGenerator;
import net.minecraftforge.fml.common.registry.GameRegistry;
import vapourdrive.genloader.api.generation.EnumGenerationType;
import vapourdrive.genloader.api.generation.Generation;
import vapourdrive.genloader.utils.IBlockStateHelper;

public class GL_WorldGenerator implements IWorldGenerator
{
	public GL_WorldGenerator(File configPath)
	{
		GameRegistry.registerWorldGenerator(this, 0);
	}

	@Override
	public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider)
	{
		for (Generation generation : GenerationManager.finalGenerators) {
			if (random.nextFloat() < generation.getChance()) {
				if (generation.getDimensions().contains(world.provider.getDimension())) {
					if (noSetBiomeFilter(generation)
							|| isBiomeValid(world, chunkX, chunkZ, generation.getBiomeTypes(), generation.getBiomeNames())) {
						IBlockState toReplace = generation.getBlockToReplace();

						if (generation.getGeneratorType() == EnumGenerationType.STANDARDVARIABLECLUSTER) {
							WeightedWorldGenMinable generator = new WeightedWorldGenMinable(generation.getWeightedBlocks(),
									generation.getSize(), new IBlockStateHelper(toReplace));
							generateStandardOre(random, chunkX, chunkZ, world, generation.getFrequency(), generator, generation.getMinY(),
									generation.getMaxY());
						} else if (generation.getGeneratorType() == EnumGenerationType.WEIGHTEDVARIABLECLUSTER) {
							WeightedWorldGenMinable generator = new WeightedWorldGenMinable(generation.getWeightedBlocks(),
									generation.getSize(), new IBlockStateHelper(toReplace));
							generateWeightedOre(random, chunkX, chunkZ, world, generation.getFrequency(), generator, generation.getMinY(),
									generation.getMaxY());
						}
					}
				}
			}
		}
	}

	private boolean noSetBiomeFilter(Generation generation)
	{
		return generation.getBiomeTypes() == null && generation.getBiomeNames() == null;
	}

	private boolean isBiomeValid(World world, int chunkX, int chunkZ, ArrayList<Type> biomeTypes, ArrayList<String> biomeNames)
	{
		if (biomeTypes != null)
		{
			for (Type type : BiomeDictionary.getTypes(world.getBiome(new BlockPos(chunkX * 16, 0, chunkZ * 16))))
			{
				if (biomeTypes.contains(type))
				{
					return true;
				}
			}
		}
		if (biomeNames != null)
		{
			Biome biome = world.getBiome(new BlockPos(chunkX * 16, 0, chunkZ * 16));
			if (biomeNames.contains(biome.getBiomeName()))
			{
				return true;
			}
		}
		return false;
	}

	private void generateStandardOre(Random rand, int chunkX, int chunkZ, World world, int iterations, WorldGenerator gen, int minY,
			int maxY)
	{
		for (int i = 0; i < iterations; i++)
		{
			int x = chunkX * 16 + rand.nextInt(16);
			int y = rand.nextInt(maxY - minY) + minY;
			int z = chunkZ * 16 + rand.nextInt(16);

			gen.generate(world, rand, new BlockPos(x, y, z));
		}
	}

	private void generateWeightedOre(Random rand, int chunkX, int chunkZ, World world, int iterations, WorldGenerator gen, int minY,
			int maxY)
	{
		int centerHeight = (maxY + minY) / 2;
		int spread = (maxY - centerHeight);

		for (int i = 0; i < iterations; i++)
		{
			int x = chunkX * 16 + rand.nextInt(16);
			int y = rand.nextInt(spread) - rand.nextInt(spread) + centerHeight;
			int z = chunkZ * 16 + rand.nextInt(16);

			gen.generate(world, rand, new BlockPos(x, y, z));
		}
	}
}


text:
<?php

class TalksController extends ApiController {
	public function getAction($request, $db) {
        $talk_id = $this->getItemId($request);

        // verbosity
        $verbose = $this->getVerbosity($request);

        // pagination settings
        $start = $this->getStart($request);
        $resultsperpage = $this->getResultsPerPage($request);

        $list = array();
        if(isset($request->url_elements[4])) {
            switch ($request->url_elements[4]) {
                case 'comments':
                    $comment_mapper = new TalkCommentMapper($db, $request);
                    $list = $comment_mapper->getCommentsByTalkId($talk_id, $resultsperpage, $start, $verbose);
                    break;
                case 'starred':
                    $mapper = new TalkMapper($db, $request);
                    $list = $mapper->getUserStarred($talk_id, $request->user_id);
                    break;
            }
        } else {
            if($talk_id) {
                $list = $this->getTalkById($db, $request, $talk_id, $verbose);
                if(false === $list) {
                    throw new Exception('Talk not found', 404);
                }
            } else if (isset($request->parameters['title'])) {
                $keyword = filter_var($request->parameters['title'], FILTER_SANITIZE_STRING);

                $mapper = new TalkMapper($db, $request);
                $list = $mapper->getTalksByTitleSearch($keyword, $resultsperpage, $start, $verbose);
            } else {
                // listing makes no sense
                throw new Exception('Generic talks listing not supported', 405);
            }
        }

        return $list;
	}

    public function postAction($request, $db) {
        if(!isset($request->user_id)) {
            throw new Exception("You must be logged in to create data", 400);
        }
        $talk_id = $this->getItemId($request);

        if(isset($request->url_elements[4])) {
            switch($request->url_elements[4]) {
                case "comments":
                    $comment = $request->getParameter('comment');
                    if(empty($comment)) {
                        throw new Exception('The field "comment" is required', 400);
                    }

                    $rating = $request->getParameter('rating');
                    if(empty($rating)) {
                        throw new Exception('The field "rating" is required', 400);
                    }

                    $private = ($request->getParameter('private') ? 1 : 0);

                    // Get the API key reference to save against the comment
                    $oauth_model = $request->getOauthModel($db);
                    $consumer_name = $oauth_model->getConsumerName($request->getAccessToken());

                    $talk_mapper = new TalkMapper($db, $request);
                    $comment_mapper = new TalkCommentMapper($db, $request);

                    $data['user_id'] = $request->user_id;
                    $data['talk_id'] = $talk_id;
                    $data['comment'] = $comment;
                    $data['rating'] = $rating;
                    $data['private'] = $private;
                    $data['source'] = $consumer_name;

                    try {
                        // run it by akismet if we have it
                        if (isset($this->config['akismet']['apiKey'], $this->config['akismet']['blog'])) {
                            $spamCheckService = new SpamCheckService(
                                $this->config['akismet']['apiKey'],
                                $this->config['akismet']['blog']
                            );
                            $isValid = $spamCheckService->isCommentAcceptable(
                                $data,
                                $request->getClientIP(),
                                $request->getClientUserAgent()
                            );
                            if (!$isValid) {
                                throw new Exception("Comment failed spam check", 400);
                            }
                        }

                        // should rating be allowed?
                        if ($comment_mapper->hasUserRatedThisTalk($data['user_id'], $data['talk_id'])) {
                            $data['rating'] = 0;
                        }
                        if ($talk_mapper->isUserASpeakerOnTalk($data['talk_id'], $data['user_id'])) {
                            // speakers cannot cannot rate their own talk
                            $data['rating'] = 0;
                        }

                        $new_id = $comment_mapper->save($data);
                    } catch (Exception $e) {
                        // just throw this again but with a 400 status code
                        throw new Exception($e->getMessage(), 400);
                    }

                    if($new_id) {
                        $comment = $comment_mapper->getCommentById($new_id);
                        $talk = $talk_mapper->getTalkById($talk_id);
                        $speakers = $talk_mapper->getSpeakerEmailsByTalkId($talk_id);
                        $recipients = array();
                        foreach($speakers as $person) {
                            $recipients[] = $person['email'];
                        }
                        $emailService = new TalkCommentEmailService($this->config, $recipients, $talk, $comment);
                        $emailService->sendEmail();
                        $uri = $request->base . '/' . $request->version . '/talk_comments/' . $new_id;
                        header("Location: " . $uri, true, 201);
                        exit;
                    } else {
                        throw new Exception("The comment could not be stored", 400);
                    }
                case 'starred':
                    // the body of this request is completely irrelevant
                    // The logged in user *is* attending the talk.  Use DELETE to unattend
                    $talk_mapper = new TalkMapper($db, $request);
                    $talk_mapper->setUserStarred($talk_id, $request->user_id);
                    header("Location: " . $request->base . $request->path_info, NULL, 201);
                    exit;
                default:
                    throw new Exception("Operation not supported, sorry", 404);
            }
        } else {
            throw new Exception("method not yet supported - sorry");
        }
    }

    public function deleteAction($request, $db) {
        if(!isset($request->user_id)) {
            throw new Exception("You must be logged in to delete data", 400);
        }
        if(isset($request->url_elements[4])) {
            switch($request->url_elements[4]) {
                case 'starred':
                    $talk_id = $this->getItemId($request);
                    $talk_mapper = new TalkMapper($db, $request);
                    $talk_mapper->setUserNonStarred($talk_id, $request->user_id);
                    header("Location: " . $request->base . $request->path_info, NULL, 200);
                    exit;
                default:
                    throw new Exception("Operation not supported, sorry", 404);
            }
        } else {
            // delete the talk
            $talk_id = $this->getItemId($request);
            $talk_mapper = new TalkMapper($db, $request);
            $list = $talk_mapper->getTalkById($talk_id);
            if(false === $list) {
                // talk isn't there so it's as good as deleted
                header("Content-Length: 0", NULL, 204);
                exit; // no more content
            }

            $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id);
            if(!$is_admin) {
                throw new Exception("You do not have permission to do that", 400);
            }

            $talk_mapper->delete($talk_id);
            header("Content-Length: 0", NULL, 204);
            exit; // no more content
        }
    }

    protected function getTalkById($db, $request, $talk_id, $verbose = false)
    {
        $mapper = new TalkMapper($db, $request);
        $list = $mapper->getTalkById($talk_id, $verbose);
        if(false === $list) {
            throw new Exception('Talk not found', 404);
        }

        return $list;
    }

}


text:
#include "src/core/transport/transport.h"
#include "src/core/transport/transport_impl.h"

size_t grpc_transport_stream_size(grpc_transport *transport) {
  return transport->vtable->sizeof_stream;
}

void grpc_transport_destroy(grpc_transport *transport) {
  transport->vtable->destroy(transport);
}

int grpc_transport_init_stream(grpc_transport *transport, grpc_stream *stream,
                               const void *server_data,
                               grpc_transport_stream_op *initial_op) {
  return transport->vtable->init_stream(transport, stream, server_data,
                                        initial_op);
}

void grpc_transport_perform_stream_op(grpc_transport *transport,
                                      grpc_stream *stream,
                                      grpc_transport_stream_op *op) {
  transport->vtable->perform_stream_op(transport, stream, op);
}

void grpc_transport_perform_op(grpc_transport *transport,
                               grpc_transport_op *op) {
  transport->vtable->perform_op(transport, op);
}

void grpc_transport_destroy_stream(grpc_transport *transport,
                                   grpc_stream *stream) {
  transport->vtable->destroy_stream(transport, stream);
}

void grpc_transport_stream_op_finish_with_failure(
    grpc_transport_stream_op *op) {
  if (op->send_ops) {
    op->on_done_send->cb(op->on_done_send->cb_arg, 0);
  }
  if (op->recv_ops) {
    op->on_done_recv->cb(op->on_done_recv->cb_arg, 0);
  }
  if (op->on_consumed) {
    op->on_consumed->cb(op->on_consumed->cb_arg, 0);
  }
}

void grpc_transport_stream_op_add_cancellation(grpc_transport_stream_op *op,
                                               grpc_status_code status,
                                               grpc_mdstr *message) {
  if (op->cancel_with_status == GRPC_STATUS_OK) {
    op->cancel_with_status = status;
  }
  if (message) {
    GRPC_MDSTR_UNREF(message);
  }
}


text:
``tornado.wsgi`` --- Interoperability with other Python frameworks and servers
==============================================================================

.. automodule:: tornado.wsgi

   .. autoclass:: WSGIContainer
      :members:


text:
using System;
using System.Drawing;
using System.Windows.Forms;
using XenAdmin.Core;
using XenAdmin.Dialogs.OptionsPages;
using XenAdmin.Plugins;

namespace XenAdmin.Dialogs
{
    public partial class OptionsDialog : VerticallyTabbedDialog
    {
        internal OptionsDialog(PluginManager pluginManager)
        {
            InitializeComponent();
            pluginOptionsPage1.SetPluginManager(pluginManager, false);//do not request rebuild; it will be done on load
            verticalTabs.SelectedItem = securityOptionsPage1;

            if (!Application.RenderWithVisualStyles)
                ContentPanel.BackColor = SystemColors.Control;
            // call save serverlist on OK
            saveAndRestoreOptionsPage1.SaveAllAfter = true;

            if (Helpers.CommonCriteriaCertificationRelease)
                verticalTabs.Items.Remove(updatesOptionsPage1);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            foreach (IOptionsPage page in verticalTabs.Items)
                page.Build();
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            foreach (IOptionsPage page in verticalTabs.Items)
            {
                if (!page.IsValidToSave())
                {
                    SelectPage(page);
                    page.ShowValidationMessages();
                    DialogResult = DialogResult.None;
                    return;
                }
            }

            foreach (IOptionsPage page in verticalTabs.Items)
                page.Save();

            Settings.TrySaveSettings();
            Settings.Log();
            Close();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        public void SelectConnectionOptionsPage()
        {
            SelectPage(connectionOptionsPage1);
        }

        public void SelectExternalToolsPage()
        {
            SelectPage(externalToolsOptionsPage1);
        }

        private void OptionsDialog_Move(object sender, EventArgs e)
        {
            HideValidationToolTips();
        }

        private void verticalTabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            HideValidationToolTips();
        }

        private void HideValidationToolTips()
        {
            foreach (IOptionsPage page in verticalTabs.Items)
            {
                page.HideValidationMessages();
            }
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@class PURLog;
@class PUROutput;

typedef void(^PURLogStoreRetrieveCompletionBlock)(NSArray<PURLog *> *logs);

@interface PURLogStore : NSObject

+ (instancetype)defaultLogStore;
- (instancetype)initWithDatabasePath:(NSString *)databasePath;

- (BOOL)prepare;

- (void)retrieveLogsForOutput:(PUROutput *)output completion:(PURLogStoreRetrieveCompletionBlock)completion;
- (void)addLog:(PURLog *)log forOutput:(PUROutput *)output completion:(nullable dispatch_block_t)completion;
- (void)addLogs:(NSArray<PURLog *> *)logs forOutput:(PUROutput *)output completion:(nullable dispatch_block_t)completion;
- (void)removeLogs:(NSArray<PURLog *> *)logs forOutput:(PUROutput *)output completion:(nullable dispatch_block_t)completion;
- (void)clearAll;

@end

NS_ASSUME_NONNULL_END


text:
You may encounter a problem when using guizero, so here are some ways you can get help to solve your problem.

### Getting help

If you have a question about your guizero program it is a good idea to join a community to ask for support:

* [Raspberry Pi Forums](https://www.raspberrypi.org/forums/viewforum.php?f=32&sid=b95bfdce6565681fad633c58a7e0e686) - some people post questions about guizero on these forums and other members of the community step in to help. The creators of guizero periodically check the Python forum.
* [Stack Overflow](https://stackoverflow.com/) - a popular site for techy questions
* [Computing at School](https://www.computingatschool.org.uk/) - a useful site for teachers

If you would like to read guides and resources for guizero there are many freely available:

- [Getting started with GUIs](https://projects.raspberrypi.org/en/projects/getting-started-with-guis) - a beginners guide to guizero by the Raspberry Pi Foundation

- [Python guizero video](https://youtu.be/3dab9xX6Uyg) - a series of videos by [Devon Schafer](https://www.youtube.com/channel/UCTHAn3Viqm9lZO2YSALXNWw) on using guizero.

- [Example programs](https://github.com/lawsie/guizero/tree/master/examples) - some example programs to get you going.

- [Using guizero with hardware](https://github.com/bennuttall/guizero-examples) - Ben Nuttall's projects using guizero combined with hardware

- [Cat name generator](http://www.cotswoldjam.org/downloads/2017-03/cat-name-generator/) - materials for a kids workshop, first run at the [Cotswold Jam](http://www.cotswoldjam.org)

- [Name your pet](https://helloworld.raspberrypi.org/issues/2) - article on page 42 of [Hello World](https://helloworld.raspberrypi.org/) magazine issue 2.

### Bugs and feature requests

Like many Python libraries, guizero has a [GitHub repository](https://github.com/lawsie/guizero) where you can add issues. These issues come under two headings:

+ You found a bug in guizero
+ You would like to request we consider including a new feature

We look at and respond to all issues created on GitHub. However, we ask that you only create issues for bugs and feature requests, rather than support, as we do not have time to answer everything :)


text:
require 'action_view'
require 'active_merchant_allpay/version'
require 'active_merchant'
require 'offsite_payments'

module OffsitePayments
  module Integrations
    autoload :Allpay, 'offsite_payments/integrations/allpay'
  end
end

ActionView::Base.send(:include, OffsitePayments::ActionViewHelper)


text:
package org.pentaho.di.core.exception;

/**
 * This exception is used in value calculations.
 *
 * @author Matt
 * @since 30-MAR-2004
 *
 */
public class KettleValueException extends KettleException {
  public static final long serialVersionUID = 0x8D8EA0264F7A1C18L;

  /**
   * Constructs a new throwable with null as its detail message.
   */
  public KettleValueException() {
    super();
  }

  /**
   * Constructs a new throwable with the specified detail message.
   *
   * @param message
   *          - the detail message. The detail message is saved for later retrieval by the getMessage() method.
   */
  public KettleValueException( String message ) {
    super( message );
  }

  /**
   * Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString())
   * (which typically contains the class and detail message of cause).
   *
   * @param cause
   *          the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and
   *          indicates that the cause is nonexistent or unknown.)
   */
  public KettleValueException( Throwable cause ) {
    super( cause );
  }

  /**
   * Constructs a new throwable with the specified detail message and cause.
   *
   * @param message
   *          the detail message (which is saved for later retrieval by the getMessage() method).
   * @param cause
   *          the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and
   *          indicates that the cause is nonexistent or unknown.)
   */
  public KettleValueException( String message, Throwable cause ) {
    super( message, cause );
  }

}