text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>4926 Sankt Marienkirchen am Hausruck, Austria</formatted_address>
  <address_component>
   <long_name>Sankt Marienkirchen am Hausruck</long_name>
   <short_name>Sankt Marienkirchen am Hausruck</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Sankt Marienkirchen am Hausruck</long_name>
   <short_name>Gemeinde St. Marienkirchen am Hausruck</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Ried im Innkreis District</long_name>
   <short_name>Ried im Innkreis District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Upper Austria</long_name>
   <short_name>Upper Austria</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>4926</long_name>
   <short_name>4926</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.1819805</lat>
    <lng>13.5765561</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.1745402</lat>
     <lng>13.5605487</lng>
    </southwest>
    <northeast>
     <lat>48.1894197</lat>
     <lng>13.5925635</lng>
    </northeast>
   </viewport>
  </geometry>
  <place_id>ChIJDyOZKtpydEcR0b5k9C1eRVE</place_id>
 </result>
</GeocodeResponse>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ThinkingHome.Plugins.AlarmClock.Lang {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class AlarmClockUiLang {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal AlarmClockUiLang() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ThinkingHome.Plugins.AlarmClock.Lang.AlarmClockUiLang", typeof(AlarmClockUiLang).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Action.
        /// </summary>
        internal static string Action {
            get {
                return ResourceManager.GetString("Action", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add.
        /// </summary>
        internal static string Add {
            get {
                return ResourceManager.GetString("Add", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Alarms.
        /// </summary>
        internal static string Alarms {
            get {
                return ResourceManager.GetString("Alarms", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to All alarm sounds were stopped..
        /// </summary>
        internal static string All_alarm_sounds_were_stopped {
            get {
                return ResourceManager.GetString("All_alarm_sounds_were_stopped", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Cancel.
        /// </summary>
        internal static string Cancel {
            get {
                return ResourceManager.GetString("Cancel", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Delete.
        /// </summary>
        internal static string Delete {
            get {
                return ResourceManager.GetString("Delete", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Disable.
        /// </summary>
        internal static string Disable {
            get {
                return ResourceManager.GetString("Disable", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Disabled.
        /// </summary>
        internal static string Disabled {
            get {
                return ResourceManager.GetString("Disabled", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Do you want to delete the alarm '{0}'?.
        /// </summary>
        internal static string Do_you_want_to_delete_the_alarm_0 {
            get {
                return ResourceManager.GetString("Do_you_want_to_delete_the_alarm_0", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Edit alarm settings.
        /// </summary>
        internal static string Edit_alarm_settings {
            get {
                return ResourceManager.GetString("Edit_alarm_settings", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Enable.
        /// </summary>
        internal static string Enable {
            get {
                return ResourceManager.GetString("Enable", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Enabled.
        /// </summary>
        internal static string Enabled {
            get {
                return ResourceManager.GetString("Enabled", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Execute user script.
        /// </summary>
        internal static string Execute_user_script {
            get {
                return ResourceManager.GetString("Execute_user_script", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Name.
        /// </summary>
        internal static string Name {
            get {
                return ResourceManager.GetString("Name", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Play sound.
        /// </summary>
        internal static string Play_sound {
            get {
                return ResourceManager.GetString("Play_sound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Save.
        /// </summary>
        internal static string Save {
            get {
                return ResourceManager.GetString("Save", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Stop all.
        /// </summary>
        internal static string Stop_all {
            get {
                return ResourceManager.GetString("Stop_all", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Time.
        /// </summary>
        internal static string Time {
            get {
                return ResourceManager.GetString("Time", resourceCulture);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
.PHONEY: all test ut ut-circle clean setup-env

SRCDIR=calico_containers
PYCALICO=$(wildcard $(SRCDIR)/pycalico/*.py)
BUILD_FILES=Dockerfile requirements.txt

WHEEL_VERSION=0.1.0

default: all
all: test
wheel: dist/pycalico-$(WHEEL_VERSION)-py2-none-any.whl
test: ut

calicobuild.created: $(BUILD_FILES)
	docker build -t calico/build .
	touch calicobuild.created

dist/pycalico-$(WHEEL_VERSION)-py2-none-any.whl: $(PYCALICO)
	mkdir -p dist
	chmod 777 dist
	python setup.py bdist_wheel

ut: calicobuild.created
	# Use the `root` user, since code coverage requires the /code directory to
	# be writable.  It may not be writable for the `user` account inside the
	# container.
	docker run --rm -v `pwd`/calico_containers:/code -u root \
	calico/build bash -c \
	'/tmp/etcd -data-dir=/tmp/default.etcd/ >/dev/null 2>&1 & \
	nosetests tests/unit -c nose.cfg'

ut-circle: calicobuild.created
	# Can't use --rm on circle
	# Circle also requires extra options for reporting.
	docker run \
	-v `pwd`:/code \
	-v $(CIRCLE_TEST_REPORTS):/circle_output \
	-e COVERALLS_REPO_TOKEN=$(COVERALLS_REPO_TOKEN) \
	calico/build bash -c \
	'/tmp/etcd -data-dir=/tmp/default.etcd/ >/dev/null 2>&1 & \
	cd calico_containers; nosetests tests/unit -c nose.cfg \
	--with-xunit --xunit-file=/circle_output/output.xml; RC=$$?;\
	[[ ! -z "$$COVERALLS_REPO_TOKEN" ]] && coveralls || true; exit $$RC'

clean:
	-rm -f *.created
	find . -name '*.pyc' -exec rm -f {} +
	-rm -rf build
	-rm -rf calico_containers/pycalico.egg-info/
	-docker rm -f calico-build
	-docker rmi calico/build

setup-env:
	virtualenv venv
	venv/bin/pip install --upgrade -r requirements.txt
	@echo "run\n. venv/bin/activate"


text:
package org.dkpro.lab.task.impl;

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

import org.dkpro.lab.task.BatchTask;
import org.dkpro.lab.task.Dimension;
import org.dkpro.lab.task.ParameterSpace;
import org.dkpro.lab.task.Task;

public class DefaultBatchTask
    extends TaskBase
    implements BatchTask
{
    protected Set<Task> tasks = new LinkedHashSet<Task>();
    private ParameterSpace parameterSpace;
    private ExecutionPolicy executionPolicy = ExecutionPolicy.RUN_AGAIN;
    private Map<String, Object> inheritedConfig;
    protected Set<String> inheritedScope;

    {
        // Just to make sure there is one run if no parameter space is set.
        parameterSpace = new ParameterSpace(Dimension.create("__DUMMY__", 1));
    }

    public void setParameterSpace(ParameterSpace aParameterSpace)
    {
        parameterSpace = aParameterSpace;
    }

    @Override
    public ParameterSpace getParameterSpace()
    {
        return parameterSpace;
    }

    public void setExecutionPolicy(ExecutionPolicy aPolicy)
    {
        executionPolicy = aPolicy;
    }

    @Override
    public ExecutionPolicy getExecutionPolicy()
    {
        return executionPolicy;
    }

    /**
     * Add a subtask to the batch. Unless otherwise mandated by data dependencies (imports) between
     * the subtasks, the added tasks are executed in the order they are added. This effect can be
     * used e.g. to execute a specific task before all other tasks even though the other tasks have
     * no data dependencies on the first task. Whenever a task needs to access data produced by
     * another tasks, you <b>must</b> import that data. The batch task will still try to execute
     * the tasks in the order they were added, but in case a data dependency for a task is not yet
     * available, the task is moved to the end of the queue.
     *
     * @param aTask the task to be added.
     */
    public void addTask(Task aTask)
    {
        tasks.add(aTask);
    }

    @Override
    public Set<Task> getTasks()
    {
        return Collections.unmodifiableSet(tasks);
    }

    /**
     * Set the subtasks of this batch. If you depend on a specific exeuction order, you have to
     * provide a set with a fixed iteration order here, e.g. an {@code LinkedHashSet}.
     */
    public void setTasks(Set<Task> aTasks)
    {
        tasks = new LinkedHashSet<Task>(aTasks);
    }

    @Override
    public void setConfiguration(Map<String, Object> aConfig)
    {
        parameterSpace.reset();
        inheritedConfig = aConfig;
    }

    @Override
    public Map<String, Object> getConfiguration()
    {
        return inheritedConfig;
    }

    @Override
    public void setScope(Set<String> aScope)
    {
        inheritedScope = aScope;
    }

    @Override
    public Set<String> getScope()
    {
        return inheritedScope;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharpGL;

namespace c14d02_DoubleTransformFeedbakObjects
{
    partial class DemoModel : IBufferSource
    {
        public const string strPosition = "position";
        public const string strPosition2 = "position2";
        private VertexBuffer positionBuffer;
        private VertexBuffer positionBuffer2;

        private IDrawCommand drawCmd;

        private static readonly vec3[] positions = new vec3[3];

        #region IBufferSource 成员

        public IEnumerable<VertexBuffer> GetVertexAttribute(string bufferName)
        {
            if (bufferName == strPosition)
            {
                if (this.positionBuffer == null)
                {
                    this.positionBuffer = positions.GenVertexBuffer(VBOConfig.Vec3, BufferUsage.DynamicCopy);
                }

                yield return this.positionBuffer;
            }
            else if (bufferName == strPosition2)
            {
                if (this.positionBuffer2 == null)
                {
                    this.positionBuffer2 = positions.GenVertexBuffer(VBOConfig.Vec3, BufferUsage.DynamicCopy);
                }

                yield return this.positionBuffer2;
            }
            else
            {
                throw new ArgumentException("bufferName");
            }
        }

        public IEnumerable<IDrawCommand> GetDrawCommand()
        {
            if (this.drawCmd == null)
            {
                this.drawCmd = new DrawArraysCmd(DrawMode.Triangles, positions.Length);
            }

            yield return this.drawCmd;
        }

        #endregion
    }
}


text:
<?php

namespace ActiveCollab\ConfigRepository\Test;

use ActiveCollab\ConfigRepository\ConfigRepository;
use ActiveCollab\ConfigRepository\Adapter\PhpConstantsAdapter;

/**
 * @package ActiveCollab\ConfigRepository\Test
 */
class PhpConstantsAdapterTest extends TestCase
{
    /**
     * @var ConfigRepository
     */
    private $repository;

    /**
     * Set up test environment
     */
    public function setUp()
    {
        parent::setUp();

        $this->repository = new ConfigRepository(new PhpConstantsAdapter(__DIR__ . '/Resources/config.simple.php'));
    }

    /**
     * Test if option exists if an adapter
     */
    public function testExists()
    {
        $this->assertTrue($this->repository->exists('FIRST'));
        $this->assertFalse($this->repository->exists('NOT FOUND'));
    }

    /**
     * Test get value
     */
    public function testGet()
    {
        $this->assertSame(1, $this->repository->get('FIRST'));
        $this->assertSame('not-found', $this->repository->get('NOT FOUND', 'not-found'));
    }

    /**
     * Test must get value
     */
    public function testMustGet()
    {
        $this->assertSame(1, $this->repository->mustGet('FIRST'));
    }

    /**
     * @expectedException \ActiveCollab\ConfigRepository\Exception\OptionNotFound
     */
    public function testMustGetExceptionWhenOptionIsNotFound()
    {
        $this->repository->mustGet('NOT FOUND FOR SURE');
    }

    /**
     * @expectedException \ActiveCollab\ConfigRepository\Exception\LogicException
     */
    public function testSet()
    {
        $this->repository->set('FIRST', 12);
    }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.tutorial.multitenancy;

import java.util.List;

import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.impl.cfg.multitenancy.TenantIdProvider;
import org.camunda.bpm.engine.impl.cfg.multitenancy.TenantIdProviderCaseInstanceContext;
import org.camunda.bpm.engine.impl.cfg.multitenancy.TenantIdProviderHistoricDecisionInstanceContext;
import org.camunda.bpm.engine.impl.cfg.multitenancy.TenantIdProviderProcessInstanceContext;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.identity.Authentication;

/**
 * Provides the tenant-id based on the current authenticated tenant.
 */
public class CustomTenantIdProvider implements TenantIdProvider {

  @Override
  public String provideTenantIdForProcessInstance(TenantIdProviderProcessInstanceContext ctx) {
    return getTenantIdOfCurrentAuthentication();
  }

  @Override
  public String provideTenantIdForCaseInstance(TenantIdProviderCaseInstanceContext ctx) {
    return getTenantIdOfCurrentAuthentication();
  }

  @Override
  public String provideTenantIdForHistoricDecisionInstance(TenantIdProviderHistoricDecisionInstanceContext ctx) {
    return getTenantIdOfCurrentAuthentication();
  }

  protected String getTenantIdOfCurrentAuthentication() {

    IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService();
    Authentication currentAuthentication = identityService.getCurrentAuthentication();

    if (currentAuthentication != null) {

      List<String> tenantIds = currentAuthentication.getTenantIds();
      if (tenantIds.size() == 1) {
        return tenantIds.get(0);

      } else if (tenantIds.isEmpty()) {
        throw new IllegalStateException("no authenticated tenant");

      } else {
        throw new IllegalStateException("more than one authenticated tenant");
      }

    } else {
      throw new IllegalStateException("no authentication");
    }
  }

}


text:
Your friendly guide to understanding the performance characteristics of this
crate.

This guide assumes some familiarity with the public API of this crate, which
can be found here: https://docs.rs/regex

## Theory vs. Practice

One of the design goals of this crate is to provide worst case linear time
behavior with respect to the text searched using finite state automata. This
means that, *in theory*, the performance of this crate is much better than most
regex implementations, which typically use backtracking which has worst case
exponential time.

For example, try opening a Python interpreter and typing this:

    >>> import re
    >>> re.search('(a*)*c', 'a' * 30).span()

I'll wait.

At some point, you'll figure out that it won't terminate any time soon. ^C it.

The promise of this crate is that *this pathological behavior can't happen*.

With that said, just because we have protected ourselves against worst case
exponential behavior doesn't mean we are immune from large constant factors
or places where the current regex engine isn't quite optimal. This guide will
detail those cases and provide guidance on how to avoid them, among other
bits of general advice.

## Thou Shalt Not Compile Regular Expressions In A Loop

**Advice**: Use `lazy_static` to amortize the cost of `Regex` compilation.

Don't do it unless you really don't mind paying for it. Compiling a regular
expression in this crate is quite expensive. It is conceivable that it may get
faster some day, but I wouldn't hold out hope for, say, an order of magnitude
improvement. In particular, compilation can take any where from a few dozen
microseconds to a few dozen milliseconds. Yes, milliseconds. Unicode character
classes, in particular, have the largest impact on compilation performance. At
the time of writing, for example, `\pL{100}` takes around 44ms to compile. This
is because `\pL` corresponds to every letter in Unicode and compilation must
turn it into a proper automaton that decodes a subset of UTF-8 which
corresponds to those letters. Compilation also spends some cycles shrinking the
size of the automaton.

This means that in order to realize efficient regex matching, one must
*amortize the cost of compilation*. Trivially, if a call to `is_match` is
inside a loop, then make sure your call to `Regex::new` is *outside* that loop.

In many programming languages, regular expressions can be conveniently defined
and compiled in a global scope, and code can reach out and use them as if
they were global static variables. In Rust, there is really no concept of
life-before-main, and therefore, one cannot utter this:

    static MY_REGEX: Regex = Regex::new("...").unwrap();

Unfortunately, this would seem to imply that one must pass `Regex` objects
around to everywhere they are used, which can be especially painful depending
on how your program is structured. Thankfully, the
[`lazy_static`](https://crates.io/crates/lazy_static)
crate provides an answer that works well:

    use lazy_static::lazy_static;
    use regex::Regex;

    fn some_helper_function(text: &str) -> bool {
        lazy_static! {
            static ref MY_REGEX: Regex = Regex::new("...").unwrap();
        }
        MY_REGEX.is_match(text)
    }

In other words, the `lazy_static!` macro enables us to define a `Regex` *as if*
it were a global static value. What is actually happening under the covers is
that the code inside the macro (i.e., `Regex::new(...)`) is run on *first use*
of `MY_REGEX` via a `Deref` impl. The implementation is admittedly magical, but
it's self contained and everything works exactly as you expect. In particular,
`MY_REGEX` can be used from multiple threads without wrapping it in an `Arc` or
a `Mutex`. On that note...

## Using a regex from multiple threads

**Advice**: The performance impact from using a `Regex` from multiple threads
is likely negligible. If necessary, clone the `Regex` so that each thread gets
its own copy. Cloning a regex does not incur any additional memory overhead
than what would be used by using a `Regex` from multiple threads
simultaneously. *Its only cost is ergonomics.*

It is supported and encouraged to define your regexes using `lazy_static!` as
if they were global static values, and then use them to search text from
multiple threads simultaneously.

One might imagine that this is possible because a `Regex` represents a
*compiled* program, so that any allocation or mutation is already done, and is
therefore read-only. Unfortunately, this is not true. Each type of search
strategy in this crate requires some kind of mutable scratch space to use
*during search*. For example, when executing a DFA, its states are computed
lazily and reused on subsequent searches. Those states go into that mutable
scratch space.

The mutable scratch space is an implementation detail, and in general, its
mutation should not be observable from users of this crate. Therefore, it uses
interior mutability. This implies that `Regex` can either only be used from one
thread, or it must do some sort of synchronization. Either choice is
reasonable, but this crate chooses the latter, in particular because it is
ergonomic and makes use with `lazy_static!` straight forward.

Synchronization implies *some* amount of overhead. When a `Regex` is used from
a single thread, this overhead is negligible. When a `Regex` is used from
multiple threads simultaneously, it is possible for the overhead of
synchronization from contention to impact performance. The specific cases where
contention may happen is if you are calling any of these methods repeatedly
from multiple threads simultaneously:

* shortest_match
* is_match
* find
* captures

In particular, every invocation of one of these methods must synchronize with
other threads to retrieve its mutable scratch space before searching can start.
If, however, you are using one of these methods:

* find_iter
* captures_iter

Then you may not suffer from contention since the cost of synchronization is
amortized on *construction of the iterator*. That is, the mutable scratch space
is obtained when the iterator is created and retained throughout its lifetime.

## Only ask for what you need

**Advice**: Prefer in this order: `is_match`, `find`, `captures`.

There are three primary search methods on a `Regex`:

* is_match
* find
* captures

In general, these are ordered from fastest to slowest.

`is_match` is fastest because it doesn't actually need to find the start or the
end of the leftmost-first match. It can quit immediately after it knows there
is a match. For example, given the regex `a+` and the haystack, `aaaaa`, the
search will quit after examining the first byte.

In contrast, `find` must return both the start and end location of the
leftmost-first match. It can use the DFA matcher for this, but must run it
forwards once to find the end of the match *and then run it backwards* to find
the start of the match. The two scans and the cost of finding the real end of
the leftmost-first match make this more expensive than `is_match`.

`captures` is the most expensive of them all because it must do what `find`
does, and then run either the bounded backtracker or the Pike VM to fill in the
capture group locations. Both of these are simulations of an NFA, which must
spend a lot of time shuffling states around. The DFA limits the performance hit
somewhat by restricting the amount of text that must be searched via an NFA
simulation.

One other method not mentioned is `shortest_match`. This method has precisely
the same performance characteristics as `is_match`, except it will return the
end location of when it discovered a match. For example, given the regex `a+`
and the haystack `aaaaa`, `shortest_match` may return `1` as opposed to `5`,
the latter of which being the correct end location of the leftmost-first match.

## Literals in your regex may make it faster

**Advice**: Literals can reduce the work that the regex engine needs to do. Use
them if you can, especially as prefixes.

In particular, if your regex starts with a prefix literal, the prefix is
quickly searched before entering the (much slower) regex engine. For example,
given the regex `foo\w+`, the literal `foo` will be searched for using
Boyer-Moore. If there's no match, then no regex engine is ever used. Only when
there's a match is the regex engine invoked at the location of the match, which
effectively permits the regex engine to skip large portions of a haystack.
If a regex is comprised entirely of literals (possibly more than one), then
it's possible that the regex engine can be avoided entirely even when there's a
match.

When one literal is found, Boyer-Moore is used. When multiple literals are
found, then an optimized version of Aho-Corasick is used.

This optimization is in particular extended quite a bit in this crate. Here are
a few examples of regexes that get literal prefixes detected:

* `(foo|bar)` detects `foo` and `bar`
* `(a|b)c` detects `ac` and `bc`
* `[ab]foo[yz]` detects `afooy`, `afooz`, `bfooy` and `bfooz`
* `a?b` detects `a` and `b`
* `a*b` detects `a` and `b`
* `(ab){3,6}` detects `ababab`

Literals in anchored regexes can also be used for detecting non-matches very
quickly. For example, `^foo\w+` and `\w+foo$` may be able to detect a non-match
just by examining the first (or last) three bytes of the haystack.

## Unicode word boundaries may prevent the DFA from being used

**Advice**: In most cases, `\b` should work well. If not, use `(?-u:\b)`
instead of `\b` if you care about consistent performance more than correctness.

It's a sad state of the current implementation. At the moment, the DFA will try
to interpret Unicode word boundaries as if they were ASCII word boundaries.
If the DFA comes across any non-ASCII byte, it will quit and fall back to an
alternative matching engine that can handle Unicode word boundaries correctly.
The alternate matching engine is generally quite a bit slower (perhaps by an
order of magnitude). If necessary, this can be ameliorated in two ways.

The first way is to add some number of literal prefixes to your regular
expression. Even though the DFA may not be used, specialized routines will
still kick in to find prefix literals quickly, which limits how much work the
NFA simulation will need to do.

The second way is to give up on Unicode and use an ASCII word boundary instead.
One can use an ASCII word boundary by disabling Unicode support. That is,
instead of using `\b`, use `(?-u:\b)`.  Namely, given the regex `\b.+\b`, it
can be transformed into a regex that uses the DFA with `(?-u:\b).+(?-u:\b)`. It
is important to limit the scope of disabling the `u` flag, since it might lead
to a syntax error if the regex could match arbitrary bytes. For example, if one
wrote `(?-u)\b.+\b`, then a syntax error would be returned because `.` matches
any *byte* when the Unicode flag is disabled.

The second way isn't appreciably different than just using a Unicode word
boundary in the first place, since the DFA will speculatively interpret it as
an ASCII word boundary anyway. The key difference is that if an ASCII word
boundary is used explicitly, then the DFA won't quit in the presence of
non-ASCII UTF-8 bytes. This results in giving up correctness in exchange for
more consistent performance.

N.B. When using `bytes::Regex`, Unicode support is disabled by default, so one
can simply write `\b` to get an ASCII word boundary.

## Excessive counting can lead to exponential state blow up in the DFA

**Advice**: Don't write regexes that cause DFA state blow up if you care about
match performance.

Wait, didn't I say that this crate guards against exponential worst cases?
Well, it turns out that the process of converting an NFA to a DFA can lead to
an exponential blow up in the number of states. This crate specifically guards
against exponential blow up by doing two things:

1. The DFA is computed lazily. That is, a state in the DFA only exists in
   memory if it is visited. In particular, the lazy DFA guarantees that *at
   most* one state is created for every byte of input. This, on its own,
   guarantees linear time complexity.
2. Of course, creating a new state for *every* byte of input means that search
   will go incredibly slow because of very large constant factors. On top of
   that, creating a state for every byte in a large haystack could result in
   exorbitant memory usage. To ameliorate this, the DFA bounds the number of
   states it can store. Once it reaches its limit, it flushes its cache. This
   prevents reuse of states that it already computed. If the cache is flushed
   too frequently, then the DFA will give up and execution will fall back to
   one of the NFA simulations.

In effect, this crate will detect exponential state blow up and fall back to
a search routine with fixed memory requirements. This does, however, mean that
searching will be much slower than one might expect. Regexes that rely on
counting in particular are strong aggravators of this behavior. For example,
matching `[01]*1[01]{20}$` against a random sequence of `0`s and `1`s.

In the future, it may be possible to increase the bound that the DFA uses,
which would allow the caller to choose how much memory they're willing to
spend.

## Resist the temptation to "optimize" regexes

**Advice**: This ain't a backtracking engine.

An entire book was written on how to optimize Perl-style regular expressions.
Most of those techniques are not applicable for this library. For example,
there is no problem with using non-greedy matching or having lots of
alternations in your regex.


text:
package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"time"

	"github.com/bwmarrin/discordgo"
	"github.com/jmonty42/cosbot/errors"
	"github.com/jmonty42/cosbot/handlers"
	"github.com/jmonty42/cosbot/types"
)

const tokenFileName = "TOKEN"
const defaultChannelForMessages = "channel-move-messages"

func main() {
	cfg := types.Config{}

	tokenBytes, err := ioutil.ReadFile(tokenFileName)
	errors.PanicOnError(err)
	cfg.Token = "Bot " + strings.TrimSpace(string(tokenBytes))

	session, err := discordgo.New(cfg.Token)
	errors.PanicOnError(err)

	fmt.Println(session.Token)

	err = session.Open()
	defer session.Close()
	errors.PanicOnError(err)

	time.Sleep(2 * time.Second)

	userGuilds, err := session.UserGuilds(0, "", "")
	errors.PanicOnError(err)

	cfg.CachedGuilds = make(map[string]*types.CachedGuild)
	cfg.CachedVoiceStates = make(map[string]*types.CachedVoiceState)

	// TODO - break this out as the guildSetup method
	fmt.Printf("Found %d guilds:\n", len(userGuilds))
	for index, userGuild := range userGuilds {
		guild, err := session.Guild(userGuild.ID)
		//put a copy of the current guild object in the cached guilds
		cfg.CachedGuilds[guild.ID] = &types.CachedGuild{
			Guild: guild,
			DefaultMessageChannelId: "",
			ChannelNames:            make(map[string]string)}
		errors.PanicOnError(err)
		fmt.Printf("Guild #%d: %s (ID: %s)\n", index, guild.Name, guild.ID)

		//set the default message channel
		guildChannels, err := session.GuildChannels(guild.ID)
		errors.PanicOnError(err)
		fmt.Printf("  Found %d channels:\n", len(guildChannels))
		for _, channel := range guildChannels {
			cfg.CachedGuilds[guild.ID].ChannelNames[channel.ID] = channel.Name
			var channelType string
			switch channel.Type {
			case discordgo.ChannelTypeGuildText:
				channelType = "Text"
			case discordgo.ChannelTypeGuildVoice:
				channelType = "Voice"
			case discordgo.ChannelTypeGuildCategory:
				channelType = "Category"
			default:
				channelType = "unknown"
			}
			fmt.Printf("  %s (ID: %s) %s\n", channel.Name, channel.ID, channelType)

			// sets the first text channel it finds as the default message channel
			// for that server, then if it finds another text channel that matches the default
			// channel name it sets the message channel to that one
			if (cfg.CachedGuilds[guild.ID].DefaultMessageChannelId == "" ||
				channel.Name == defaultChannelForMessages) &&
				channel.Type == discordgo.ChannelTypeGuildText {
				cfg.CachedGuilds[guild.ID].DefaultMessageChannelId = channel.ID
			}
		}

		//cache the guild's voice states
		fmt.Printf("  Found %d 'VoiceStates':\n", len(guild.VoiceStates))
		for _, voiceState := range guild.VoiceStates {
			user, err := session.User(voiceState.UserID)
			if err != nil {
				fmt.Printf("Got error when trying to get user with id: %s : %s\n",
					voiceState.UserID, err.Error())
			}
			channel, err := session.Channel(voiceState.ChannelID)
			if err != nil {
				fmt.Printf("Got error when trying to get channel with id: %s : %s\n",
					voiceState.ChannelID, err.Error())
			}
			fmt.Printf("    %s: %s\n", user.Username, channel.Name)
			cfg.CachedVoiceStates[voiceState.UserID] = &types.CachedVoiceState{
				VoiceState: voiceState, UserName: user.Username}
		}
		//iterate over the guild members, for those that didn't have corresponding voice states,
		//add an empty voice state to the cache
		for _, member := range guild.Members {
			if _, present := cfg.CachedVoiceStates[member.User.ID]; !present {
				cfg.CachedVoiceStates[member.User.ID] = &types.CachedVoiceState{
					VoiceState: nil, UserName: member.User.Username}
			}
		}

		channel, err := session.Channel(cfg.CachedGuilds[guild.ID].DefaultMessageChannelId)
		if err != nil {
			fmt.Printf("Got error when trying to get the channel %s: %s",
				cfg.CachedGuilds[guild.ID].DefaultMessageChannelId, err.Error())
		} else {
			fmt.Println(" Default channel: ", channel.Name)
		}
	}

	handlers.AddGuildUpdateHandler(session)
	handlers.AddVoiceStateUpdateHandler(session, &cfg)

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Bot running. Press 'Enter' to quit ...")
	reader.ReadBytes('\n')
}

// haven't actually tested this out yet, but will be needed for the command to set the
// channel that messages should be sent to
func getChannelIdFromName(session *discordgo.Session, channelName string,
	guildId string) (string, error) {
	channels, err := session.GuildChannels(guildId)
	if err != nil {
		return "", err
	}

	for _, channel := range channels {
		if channel.Name == channelName && channel.Type == discordgo.ChannelTypeGuildText {
			return channel.ID, nil
		}
	}

	return "", fmt.Errorf("Channel not found: '%s' on server: '%s'", channelName, guildId)
}


text:
'use strict';

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define('pdfjs-test/unit/test_utils', ['exports', 'pdfjs/shared/util'],
      factory);
  } else if (typeof exports !== 'undefined') {
    factory(exports, require('../../src/shared/util.js'));
  } else {
    factory((root.pdfjsTestUnitTestUtils = {}), root.pdfjsSharedUtil);
  }
}(this, function (exports, sharedUtil) {

var CMapCompressionType = sharedUtil.CMapCompressionType;

var NodeCMapReaderFactory = (function NodeCMapReaderFactoryClosure() {
  function NodeCMapReaderFactory(params) {
    this.baseUrl = params.baseUrl || null;
    this.isCompressed = params.isCompressed || false;
  }

  NodeCMapReaderFactory.prototype = {
    fetch: function(params) {
      var name = params.name;
      if (!name) {
        return Promise.reject(new Error('CMap name must be specified.'));
      }
      return new Promise(function (resolve, reject) {
        var url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');

        var fs = require('fs');
        fs.readFile(url, function (error, data) {
          if (error || !data) {
            reject(new Error('Unable to load ' +
                             (this.isCompressed ? 'binary ' : '') +
                             'CMap at: ' + url));
            return;
          }
          resolve({
            cMapData: new Uint8Array(data),
            compressionType: this.isCompressed ?
              CMapCompressionType.BINARY : CMapCompressionType.NONE,
          });
        }.bind(this));
      }.bind(this));
    },
  };

  return NodeCMapReaderFactory;
})();

exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
}));


text:
NS_ASSUME_NONNULL_BEGIN

@interface DThreadContext : NSObject

@property (nonatomic, strong) DAbsThreadState *threadState;

- (void)start;
- (void)getCPU;
- (void)suspend;
- (void)resume;
- (void)stop;

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="description" content="Geo047.GitHub.io : WMAM">

    <link rel="stylesheet" type="text/css" media="screen" href="stylesheets/stylesheet.css">

    <title>Geo047.GitHub.io</title>

          View on GitHub

Geo047.GitHub.io

WMAM

Whole-genome Multi-locus Association Mapping (WMAM)

An R package for performing multiple locus association mapping on a genome-wide scale. The methodology is a hybrid of whole-genome and multi-locus association mapping within a linear mixed model framework. Large portions of the package have been written in C++ and interfaced with R using Rcpp and RcppEigen. Our package makes the fitting of multiple locus models on a genome-wide scale routine.

Installation

Examples

Published with GitHub Pages


text:
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT License. See license.txt in the project root for further information.

package org.thaliproject.p2p.btpollingsynclib;

/**
 * Created by juksilve on 20.5.2015.
 */
public class PeerDataItem {

    public PeerDataItem(String DeviceName,String DeviceAddress,String DeviceData){
        this.Name = DeviceName;
        this.Address = DeviceAddress;
        this.Data = DeviceData;
    }
    public String Name;
    public String Address;
    public String Data;
}


text:
package com.commafeed.backend.task;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.commafeed.backend.service.DatabaseCleaningService;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor(onConstructor = @__({ @Inject }))
@Singleton
public class OrphanedFeedsCleanupTask extends ScheduledTask {

	private final DatabaseCleaningService cleaner;

	@Override
	public void run() {
		cleaner.cleanFeedsWithoutSubscriptions();
	}

	@Override
	public long getInitialDelay() {
		return 15;
	}

	@Override
	public long getPeriod() {
		return 60;
	}

	@Override
	public TimeUnit getTimeUnit() {
		return TimeUnit.MINUTES;
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
		<title>Commons Logging 1.1.1 Reference</title>
		<link rel="stylesheet" type="text/css" href="stylesheet.css" title="style" />

			All Classes

Packages

				org.apache.commons.logging

				org.apache.commons.logging.avalon

				org.apache.commons.logging.config

				org.apache.commons.logging.impl

				org.apache.commons.logging.jdk14

				org.apache.commons.logging.log4j

				org.apache.commons.logging.log4j.log4j12

				org.apache.commons.logging.logkit

				org.apache.commons.logging.noop

				org.apache.commons.logging.pathable

				org.apache.commons.logging.security

				org.apache.commons.logging.servlet

				org.apache.commons.logging.simple

				org.apache.commons.logging.tccl

				org.apache.commons.logging.tccl.custom

				org.apache.commons.logging.tccl.log

				org.apache.commons.logging.tccl.logfactory


text:
# camelcase-keys [![Build Status](https://travis-ci.org/sindresorhus/camelcase-keys.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase-keys)

> Convert object keys to camel case using [`camelcase`](https://github.com/sindresorhus/camelcase)

## Install

```
$ npm install camelcase-keys
```

## Usage

```js
const camelcaseKeys = require('camelcase-keys');

// Convert an object
camelcaseKeys({'foo-bar': true});
//=> {fooBar: true}

// Convert an array of objects
camelcaseKeys([{'foo-bar': true}, {'bar-foo': false}]);
//=> [{fooBar: true}, {barFoo: false}]

camelcaseKeys({'foo-bar': true, nested: {unicorn_rainbow: true}}, {deep: true});
//=> {fooBar: true, nested: {unicornRainbow: true}}

camelcaseKeys({a_b: 1, a_c: {c_d: 1, c_e: {e_f: 1}}}, {deep: true, stopPaths: ['a_c.c_e']}),
//=> {aB: 1, aC: {cD: 1, cE: {e_f: 1}}}

// Convert object keys to pascal case
camelcaseKeys({'foo-bar': true, nested: {unicorn_rainbow: true}}, {deep: true, pascalCase: true});
//=> {FooBar: true, Nested: {UnicornRainbow: true}}
```

```js
const camelcaseKeys = require('camelcase-keys');

const argv = require('minimist')(process.argv.slice(2));
//=> {_: [], 'foo-bar': true}

camelcaseKeys(argv);
//=> {_: [], fooBar: true}
```

## API

### camelcaseKeys(input, options?)

#### input

Type: `object | object[]`

An object or array of objects to camel-case.

#### options

Type: `object`

##### exclude

Type: `Array<string | RegExp>`\
Default: `[]`

Exclude keys from being camel-cased.

##### stopPaths

Type: `string[]`\
Default: `[]`

Exclude children at the given object paths in dot-notation from being camel-cased. For example, with an object like `{a: {b: '🦄'}}`, the object path to reach the unicorn is `'a.b'`.

```js
camelcaseKeys({
	a_b: 1,
	a_c: {
		c_d: 1,
		c_e: {
			e_f: 1
		}
	}
}, {
	deep: true,
	stopPaths: [
		'a_c.c_e'
	]
}),
/*
{
	aB: 1,
	aC: {
		cD: 1,
		cE: {
			e_f: 1
		}
	}
}
*/
```

##### deep

Type: `boolean`\
Default: `false`

Recurse nested objects and objects in arrays.

##### pascalCase

Type: `boolean`\
Default: `false`

Uppercase the first character as in `bye-bye` → `ByeBye`.

## camelcase-keys for enterprise

Available as part of the Tidelift Subscription.

The maintainers of camelcase-keys and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-camelcase-keys?utm_source=npm-camelcase-keys&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

## Related

- [snakecase-keys](https://github.com/bendrucker/snakecase-keys)
- [kebabcase-keys](https://github.com/mattiloh/kebabcase-keys)


text:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import featuredComponent from './featured.component';

let featuredModule = angular.module('featured', [
  uiRouter
])

.component('featured', featuredComponent);

export default featuredModule;


text:
<?php

declare(strict_types=1);

return [
    '(Unknown)' => '(Sconosciuto)',
    'Ability Doubler' => 'Raddoppiatore',
    'Comeback' => 'Gran ritorno',
    'Drop Roller' => 'Atterraggio stiloso',
    'Haunt' => 'Rappresaglia',
    'Ink Recovery Up' => 'Recupero colore +',
    'Ink Resistance Up' => 'Scarpe impermeabili',
    'Ink Saver (Main)' => 'Eco-colore princ.',
    'Ink Saver (Sub)' => 'Eco-colore second.',
    'Intensify Action' => 'Intensificazione',
    'Last-Ditch Effort' => 'Slash finale',
    'Ninja Squid' => 'Calamaro ninja',
    'Object Shredder' => 'Demolitore',
    'Opening Gambit' => 'Partenza a razzo',
    'Quick Respawn' => 'Il tempo è colore',
    'Quick Super Jump' => 'Salti super e veloci',
    'Respawn Punisher' => 'Castigo',
    'Run Speed Up' => 'Velocità +',
    'Special Charge Up' => 'Ricarica speciale +',
    'Special Power Up' => 'Arma speciale +',
    'Special Saver' => 'Riduzione speciale -',
    'Stealth Jump' => 'Salto al buio',
    'Sub Power Up' => 'Arma secondaria +',
    'Sub Resistance Up' => 'Arma sec. impermeabile',
    'Swim Speed Up' => 'Velocità nuoto +',
    'Tenacity' => 'Tenacia',
    'Thermal Ink' => 'Inchiostro termico',
];


text:
@class CUError;

void alert(NSString *title, NSString *message);

MKMapRect optimalRectForCoordinates(CLLocationCoordinate2D c1, CLLocationCoordinate2D c2);
MKMapRect mapRectWithEdgePadding(MKMapRect rect, UIEdgeInsets edgePadding, MKMapView *view);
MKCoordinateRegion defaultRegion();

NSError *errorWithDescription(NSInteger code, NSString *description);
void handleCommonError(CUError *error);

NSString *formattedTime(NSString *fullTime);


text:
<?php namespace Neomerx\Limoncello\Http;

use \Neomerx\Limoncello\Contracts\IntegrationInterface;

/**
 * @package Neomerx\Limoncello
 */
abstract class FrameworkIntegration implements IntegrationInterface
{
    /**
     * @inheritdoc
     */
    public function getContent()
    {
        $content = (string)$this->getCurrentRequest()->getContent();

        return $content === '' ? null : $content;
    }

    /**
     * @inheritdoc
     */
    public function getQueryParameters()
    {
        return $this->getCurrentRequest()->query->all();
    }

    /**
     * @inheritdoc
     */
    public function getHeader($name)
    {
        return $this->getCurrentRequest()->headers->get($name);
    }
}


text:
import {assoc, clone, eqDeep, identity, map, pipe, reduce, repeat, range, trim} from "ramda";
import Class from "classnames";
import Cycle from "cyclejs";
import {merge, randomObjectValue} from "./helpers";
import Piece from "./piece";
import Board from "./board";

let {Rx} = Cycle;
let {Observable, Subject} = Rx;

// CONSTANTS =======================================================================================
const BOARD_ROWS = 12; // have to be able to contain PIECES
const BOARD_COLS = 8; // ...
const INITIAL_POSITION = [2, 2]; // TODO evaluate best position (middle of cols, top + 1 of rows?!)

/**
 LEGEND
   "0" - empty cell
   "1" - written cell
   "P" - piece cell
   "G" - ghost cell
*/

const PIECES = {
  I: [[-1,  0], [ 0,  0], [ 1, 0], [2, 0]],
  T: [[ 0, -1], [-1,  0], [ 0, 0], [1, 0]],
  O: [[ 0, -1], [ 1, -1], [ 0, 0], [1, 0]],
  J: [[-1, -1], [-1,  0], [ 0, 0], [1, 0]],
  L: [[ 1, -1], [-1,  0], [ 0, 0], [1, 0]],
  S: [[ 0, -1], [ 1, -1], [-1, 0], [0, 0]],
  Z: [[-1, -1], [ 0, -1], [ 0, 0], [1, 0]],
};

const TICK_MS = 1000;

const DRAW_MAP = {
 "0": "\u2B1C",
 "1": "\u2B1B",
 "P": "\u2B1B",
 "G": "\u2B1B",
};

const COLLAPSE_FRAMES$ = Observable
  .for(["previous", "cleared", "previous", "cleared", "current"], (v, i) => Observable.return(v).delay(i * 50));

const SCORE_PER_ROW = 100;

//let randomObjectValue = (PIECES) => PIECES.O;

// APP =============================================================================================
function Intent(interactions) {
  // KEYBOARD EVENTS
  let keydown$ = Observable.fromEvent(document, "keydown").debounce(100);
  return {
    // TODO: debounce without delay
    hitEnter$: keydown$.filter(event => event.keyCode == 13),
    hitSpace$: keydown$.filter(event => event.keyCode == 32),
    hitLeftArrow$: keydown$.filter(event => event.keyCode == 37),
    hitUpArrow$: keydown$.filter(event => event.keyCode == 38),
    hitRightArrow$: keydown$.filter(event => event.keyCode == 39),
    hitDownArrow$: keydown$.filter(event => event.keyCode == 40),
  }
}

function Model(intentions) {
  function seedState() {
    return {
      // Game board
      board: Board.create(BOARD_ROWS, BOARD_COLS),

      // Board to collapse
      collapseBoard: undefined,

      // Current piece
      piece: randomObjectValue(PIECES),

      // Next piece
      nextPiece: randomObjectValue(PIECES),

      // Current position (of current piece)
      position: INITIAL_POSITION,

      // Live state (game is not lost)
      live: true,

      // User pause
      paused: true,

      // User scores
      scores: 0,
    };
  }

  function isTicking(state) {
    return state.live && !state.paused;
  }

  // GAME EVENTS
  let moveLeft$ = intentions.hitLeftArrow$.map(() => {
    return function moveLeft(state) {
      if (isTicking(state)) {
        let [cx, cy] = state.position;
        let newPosition = [cx - 1, cy];
        if (Board.doesPieceFit(state.board, state.piece, newPosition)) {
          state = assoc("position", newPosition, state);
        }
      }
      return state;
    };
  });

  let moveRight$ = intentions.hitRightArrow$.map(() => {
    return function moveRight(state) {
      if (isTicking(state)) {
        let [cx, cy] = state.position;
        let newPosition = [cx + 1, cy];
        if (Board.doesPieceFit(state.board, state.piece, newPosition)) {
          state = assoc("position", newPosition, state);
        }
      }
      return state;
    };
  });

  let rotate$ = intentions.hitUpArrow$.map(() => {
    return function rotate(state) {
      if (isTicking(state)) {
        let rotatedPiece = Piece.rotate(state.piece);
        if (Board.doesPieceFit(state.board, rotatedPiece, state.position)) {
          state = assoc("piece", rotatedPiece, state);
        }
      }
      return state;
    };
  });

  let drop$ = intentions.hitSpace$.map(() => {
    return function drop(state) {
      if (isTicking(state)) {
        let dropPosition = Board.getDropPosition(state.board, state.piece, state.position);
        state = merge({
          board: Board.writePiece(state.board, state.piece, dropPosition),
          piece: undefined,
          position: INITIAL_POSITION
        }, state);
      }
      return state;
    };
  });

  let pause$ = intentions.hitEnter$.map(() => {
    return function pause(state) {
      state = assoc("paused", !state.paused, state);
      return state;
    }
  });

  let ticking$ = new Subject();
  ticking$.distinctUntilChanged();

  let tick$ = Observable.interval(TICK_MS).pausable(ticking$);

  let gravity$ = tick$.map(() => {
    return function gravity(state) {
      let [cx, cy] = state.position;
      let newPosition = [cx, cy + 1];
      if (Board.doesPieceFit(state.board, state.piece, newPosition)) {
        state = assoc("position", newPosition, state);
      } else {
        state = merge({
          board: Board.writePiece(state.board, state.piece, state.position),
          piece: undefined,
          position: INITIAL_POSITION
        }, state);
      }
      return state;
    };
  });

  let maybeCollapse$ = Observable.merge(drop$, gravity$).map(() => {
    return function maybeCollapse(state) {
      let filledRowIndexes = Board.getFilledRowIndexes(state.board);
      if (filledRowIndexes.length) {
        let newBoard = Board.collapseFilledRows(state.board);
        state = merge({
          board: newBoard,
          collapseBoard: state.board,
          scores: state.scores + (SCORE_PER_ROW * filledRowIndexes.length),
        }, state);
      }
      return state;
    };
  });

  let maybeEnd$ = Observable.merge(drop$, gravity$).map(() => {
    return function maybeEnd(state) {
      if (state.live && !state.paused) {
        if (state.piece == undefined) {
          let nextPiece = randomObjectValue(PIECES);
          if (Board.doesPieceFit(state.board, nextPiece, INITIAL_POSITION)) {
            // Game continues with next piece
            state = merge({
              piece: state.nextPiece,
              nextPiece: randomObjectValue(PIECES),
              position: INITIAL_POSITION
            }, state);
          } else {
            // Game over
            state = merge({
              piece: undefined,
              position: INITIAL_POSITION,
              live: false
            }, state);
          }
        }
      }
      return state;
    };
  });

  let cleanup$ = new Subject();

  let transform$ = Rx.Observable.merge(
    // Controlled by a Player
    pause$, moveLeft$, moveRight$, rotate$, drop$,

    // Not controlled by a Player
    gravity$, maybeCollapse$, maybeEnd$, cleanup$
  );

  let state$ = transform$
    .startWith(seedState())
    .scan((state, transform) => transform(state))
    .distinctUntilChanged(identity, eqDeep)
    .shareReplay(1);

  state$.subscribe(state => {
    ticking$.onNext(isTicking(state));
  });

  let collapse$ = state$.filter(state => state.collapseBoard);

  let collapseAnimation$ = collapse$
    .flatMap(() => COLLAPSE_FRAMES$)
    .shareReplay(1);

  let animatedState$ = state$.combineLatest(collapseAnimation$.startWith("current"), (state, animationFrame) => {
    if (state.collapseBoard) {
      if (animationFrame == "previous") {
        return assoc("board", state.collapseBoard, state);
      } else if (animationFrame == "cleared") {
        return assoc("board", Board.clearFilledRows(state.collapseBoard), state);
      } else {
        return state;
      }
    } else {
      return state;
    }
  });

  collapseAnimation$
    .distinctUntilChanged()
    .subscribe(() => {
      ticking$.onNext(false);
  });

  collapseAnimation$
    .filter(animationFrame => animationFrame == "current")
    .subscribe(collapseAnimationEnd => {
      if (collapseAnimationEnd) {
        ticking$.onNext(true);
        cleanup$.onNext(function forgotCollapse(state) {
          return assoc("collapseBoard", undefined, state);
        });
      }
  });

  let visualState$ = animatedState$.map(state => {
    return merge(state, {
      primaryBoard: Board.drawPiece(state.board, state.piece, state.position),
      secondaryBoard: Board.drawPiece(Board.create(2, 4), state.nextPiece, [1, 1]),
    });
  });

  return {
    state$: visualState$
  };
}

function View(state) {
  function renderRow(row) {
    return row.map(char => {
      return DRAW_MAP[char];
    }).join("");
  }

  function renderBoard(board) {
    return pipe(
      reduce((canvas, row) => canvas + renderRow(row) + "\n", ""),
      trim
    )(board);
  }

  return state.state$.map((state) =>  {
    let status;
    if (state.live) {
      if (state.paused) {
        status =
Paused!
;
      } else {
        status =
Running!
;
      }
    } else {
      status =
Game over!
;
    }
    return (

              {renderBoard(state.primaryBoard)}

          {status}

                {renderBoard(state.secondaryBoard)}

Scores: {state.scores.toString()}

    );
  });
}

Cycle.applyToDOM("#main", interactions => View(Model(Intent(interactions))));


text:
A simple Github oauth demo written by nodejs, based on express framework.
[Online Demo](http://oauthtest.zenglong.top:8085/)


text:
require 'optparse'

require_relative '../util/struct'

module Kay

  class JoinParse

    @@proj_id = '--project_id <project_id>'

    def self.parse(args)
      options = base_struct
      opt_parser = OptionParser.new do |opts|

        opts.banner = 'Usage: kay join [options]'

        opts.on(@@proj_id, String, 'the project id') do |proj_id|
          options.proj_id = proj_id
        end

      end

      opt_parser.parse!(args)
      self.validate(options)
      options
    end

    def self.validate(options)
      raise '%s required' % [@@proj_id] if options[:proj_id].nil?
    end

  end

end


text:
/*
 * this class defines each GOterm details;
 */
package GOannotation;

import java.util.HashMap;

/**
 *
 * @author ZHAO Qi
 * @version jdk 1.7.0
 */
public class Oboterm {
    private String id="";//The unique id of the current term. This can be any string. This tag must always be the first tag in any term description
    private String name="";//The term name. Any term may only have one name defined. If multiple term names are defined, it is a parse error.
    private String alt_id="";//Defines an alternate id for this term. A term may have any number of alternate ids.
    private String namespace="";//The namespace in which the term belongs. If this tag is not present, the term will be assigned to the default-namespace specified in the file header stanza.
    private String def="";//The definition of the current term. There must be zero or one instances of this tag per term description. More than one definition for a term generates a parse error. The value of this tag should be the quote enclosed definition text, followed by a dbxref list containing dbxrefs that describe the origin of this definition (see Dbxref Formatting for information on how dbxref lists are encoded).
    private String comment="";//A comment for this term. There must be zero or one instances of this tag per term description. More than one comment for a term generates a parse error.
    private String is_a="";//This tag describes a subclassing relationship between one term and another. A term may have any number of is a relationships. Terms with no is a relationships are roots. A term with no is a relationships may not specify any relationship tags. To do so is a parse error.
    private String subset="";//This tag indicates a term subset to which this term belongs. The value of this tag must be a subset name as defined in a subsetdef tag in the file header. If the value of this tag is not mentioned in a subsetdef tag, a parse error will be generated. A term may belong to any number of subsets.
    private String sysnonym="";//This tag gives a synonym for the term; whether the synonym is exact, broad, narrow, or otherwise related to the term is not specified. The value of this tag should be the quote enclosed synonym text, followed by an optional dbxref list containing dbxrefs that describe the origin of this synonym (see Dbxref Formatting for information on how dbxref lists are encoded). A term may have any number of synonyms.
    private String intersection_of="";//This tag indicates that this term is equivalent to the intersection of several other terms. The value is either a term id, or a relationship type id, a space, and a term id.
    private String is_obsolute="";//Whether or not this term is obsolete. Allowable values are "true" and "false" (false is assumed if this tag is not present). Obsolete terms must have no relationships, and no defined is_a, inverse_of, disjoint_from, union_of, or intersection_of tags.
    private String relationship="";//This tag describes a typed relationship between this term and another term. The value of this tag should be the relationship type id, and then the id of the target term. The relationship type name must be a relationship type name as defined in a typedef tag stanza. The [Typedef] must either occur in a document in the current parse batch, or in a file imported via an import header tag. If the relationship type name is undefined, a parse error will be generated. If the id of the target term cannot be resolved by the end of parsing the current batch of files, this tag describes a "dangling reference"; see the parser requirements section for information about how a parser may handle dangling references. If a relationship is specified for a term with an is_obsolete value of true, a parse error will be generated.
    private String union_of="";//This tag indicates that this term represents the union of several other terms. The value is the id of one of the other terms of which this term is a union.
    private String disjoint_from="";//This tag indicates that a term is disjoint from another, meaning that the two terms have no instances or subclasses in common. The value is the id of the term from which the current term is disjoint. This tag may not be applied to relationship types.

    public String getAlt_id() {
        return alt_id;
    }

    public void setAlt_id(String alt_id) {
        this.alt_id = alt_id;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getDef() {
        return def;
    }

    public void setDef(String def) {
        this.def = def;
    }

    public String getDisjoint_from() {
        return disjoint_from;
    }

    public void setDisjoint_from(String disjoint_from) {
        this.disjoint_from = disjoint_from;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getIntersection_of() {
        return intersection_of;
    }

    public void setIntersection_of(String intersection_of) {
        this.intersection_of = intersection_of;
    }

    public String getIs_a() {
        return is_a;
    }

    public void setIs_a(String is_a) {
        this.is_a = is_a;
    }

    public String  isIs_obsolute() {
        return is_obsolute;
    }

    public void setIs_obsolute(String is_obsolute) {
        this.is_obsolute = is_obsolute;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    public String getRelationship() {
        return relationship;
    }

    public void setRelationship(String relationship) {
        this.relationship = relationship;
    }

    public String getSubset() {
        return subset;
    }

    public void setSubset(String subset) {
        this.subset = subset;
    }

    public String getSysnonym() {
        return sysnonym;
    }

    public void setSysnonym(String sysnonym) {
        this.sysnonym = sysnonym;
    }

    public String getUnion_of() {
        return union_of;
    }

    public void setUnion_of(String union_of) {
        this.union_of = union_of;
    }

    public String getPureAcenstor(){
        return this.is_a.substring(0, 10);
    }

    public Oboterm getis_aTerm(HashMap goTOtermMap){
          return (Oboterm) goTOtermMap.get(this.getPureAcenstor());//他的父节点

    }
    @Override
    public String toString() {
        return  "\t" + id + "\t" + name + "\t" + namespace;
    }

}


text:
Users Module

Overview

The Users module works together with Groups and Permissions to give PyroCMS access control.

Add a User

Fill out the user's details (including a password) and save. If you have activation emails enabled in Settings
		an email will be sent to the new user with an activation link.

Activating New Users

If activation emails are disabled in Settings users that register on the website front-end will appear under the Inactive Users
		menu item until you either approve or delete their account. If activation emails are enabled users may register silently, without an admin's help.


text:
class Input
{
    // The window.
    static GLFWwindow* window;

    // The viewer controlling graphical settings
    static Viewer* viewer;

    // List of pressed keys.
    static std::set<int> pressedKeys;

    // Same as the key sets, but for mouse buttons.
    static std::set<int> pressedMouseButtons;

    static std::vector<IGlfwMouseHandler*> additionalMouseHandlers;
    static std::vector<IGlfwKeyHandler*> additionalKeyHandlers;

    // Logs any errors from GLFW
    static void LogGlfwErrors(int error, const char* description);

    // Handles GLFW key callbacks.
    static void GlfwKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
    static void GlfwCharCallback(GLFWwindow* window, unsigned int character);

    // Handles GLFW mouse callbacs
    static void GlfwMouseButtonCallbacks(GLFWwindow* window, int button, int action, int mods);
    static void GlfwScrollCallback(GLFWwindow* window, double xoffset, double yoffset);

    // Handles GLFW window callbacks.
    static void GlfwWindowCloseCallbacks(GLFWwindow* window);
    static void GlfwWindowFocusCallbacks(GLFWwindow* window, int focused);
    static void GlfwWindowResizeCallbacks(GLFWwindow* window, int width, int height);

public:
    static bool hasFocus;

    static void SetupErrorCallback();

    // Sets callbacks this class uses
    static void Setup(GLFWwindow* window, Viewer* viewer);
    static void AddMouseHandler(IGlfwMouseHandler* mouseHandler);
    static void AddKeyHandler(IGlfwKeyHandler* keyHandler);

    // Returns true if a key was pressed, false otherwise.
    static bool IsKeyPressed(int keyId);

    // Same as IsKeyPressed ans IsKeyTyped, but with mouse buttons, respectively.
    static bool IsMouseButtonPressed(int mouseButton);

    static glm::ivec2 GetMousePos();
};


text:
package synergynet.contentsystem.jme.items.utils;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.util.logging.Logger;

import javax.swing.ImageIcon;

import synergynet.contentsystem.jme.items.factory.JMEImplementationItemFactory;

public class ImageUtility {

	private static final Logger log = Logger.getLogger(JMEImplementationItemFactory.class.getName());

	public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels
        boolean hasAlpha = hasAlpha(image);

        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }

            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
        }

        if (bimage == null) {
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }

        Graphics g = bimage.createGraphics();

        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }

    public static boolean hasAlpha(Image image) {
        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage)image;
            return bimage.getColorModel().hasAlpha();
        }

        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
         PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        	log.warning("InterruptedException when grabbing pixels.");
        }

        // Get the image's color model
        ColorModel cm = pg.getColorModel();
        return cm.hasAlpha();
    }

}


text:
package novoda.demo;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

class GalleryAdapter extends BaseAdapter {

    private final Context mContext;

    public GalleryAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return 15;
    }

    public Object getItem(int position) {
        return new Object();
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.carousel_gallery_li, null);
        } else {
            view = convertView;
        }
        final ImageView imageView = (ImageView) view.findViewById(R.id.image);

        Bitmap image = null;
        try {
            InputStream bitmap=mContext.getAssets().open("placeholder.png");
            image=BitmapFactory.decodeStream(bitmap);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        imageView.setImageBitmap(image);
        return view;
    }
}


text:
from setuptools import setup

setup(name="syncnames",
	  version="1.0",
	  description="Sunchronizes the name of file and folder (along with contents in folder) to a single given name",
	  author="Shivaji Byrapaneni",
	  py_module=['syncnames'],
	  install_rqeuires=[
	  		'Click',
	  ],
	  entry_points='''
	  		[console_scripts]
	  		syncnames=syncnames:sync
	  ''',
	)


text:
RSpec.describe Mdm::VulnAttempt, type: :model do
  it_should_behave_like 'Metasploit::Concern.run'

  context 'association' do
    it { is_expected.to belong_to(:vuln).class_name('Mdm::Vuln') }
  end

  context 'database' do

    context 'timestamps'do
      it { is_expected.to have_db_column(:attempted_at).of_type(:datetime) }
    end

    context 'columns' do
      it { is_expected.to have_db_column(:vuln_id).of_type(:integer) }
      it { is_expected.to have_db_column(:exploited).of_type(:boolean) }
      it { is_expected.to have_db_column(:fail_reason).of_type(:string) }
      it { is_expected.to have_db_column(:username).of_type(:string) }
      it { is_expected.to have_db_column(:module).of_type(:text) }
      it { is_expected.to have_db_column(:session_id).of_type(:integer) }
      it { is_expected.to have_db_column(:loot_id).of_type(:integer) }
      it { is_expected.to have_db_column(:fail_detail).of_type(:text) }
    end
  end

  context 'validations' do
    it 'should require a vuln_id' do
      orphan_detail = FactoryBot.build(:mdm_vuln_detail, :vuln => nil)
      expect(orphan_detail).not_to be_valid
      expect(orphan_detail.errors[:vuln_id]).to include("can't be blank")
    end
  end

  context 'factory' do
    it 'should be valid' do
      vuln_attempt = FactoryBot.create(:mdm_vuln_attempt)
      expect(vuln_attempt).to be_valid
    end
  end

  context '#destroy' do
    it 'should successfully destroy the object' do
      vuln_attempt = FactoryBot.create(:mdm_vuln_attempt)
      expect {
        vuln_attempt.destroy
      }.to_not raise_error
      expect {
        vuln_attempt.reload
      }.to raise_error(ActiveRecord::RecordNotFound)
    end
  end

end


text:
package com.vmware.vim25;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for PodStorageDrsEntry complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="PodStorageDrsEntry">
 *   <complexContent>
 *     <extension base="{urn:vim25}DynamicData">
 *       <sequence>
 *         <element name="storageDrsConfig" type="{urn:vim25}StorageDrsConfigInfo"/>
 *         <element name="recommendation" type="{urn:vim25}ClusterRecommendation" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="drsFault" type="{urn:vim25}ClusterDrsFaults" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="actionHistory" type="{urn:vim25}ClusterActionHistory" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PodStorageDrsEntry", propOrder = {
    "storageDrsConfig",
    "recommendation",
    "drsFault",
    "actionHistory"
})
public class PodStorageDrsEntry
    extends DynamicData
{

    @XmlElement(required = true)
    protected StorageDrsConfigInfo storageDrsConfig;
    protected List<ClusterRecommendation> recommendation;
    protected List<ClusterDrsFaults> drsFault;
    protected List<ClusterActionHistory> actionHistory;

    /**
     * Gets the value of the storageDrsConfig property.
     *
     * @return
     *     possible object is
     *     {@link StorageDrsConfigInfo }
     *
     */
    public StorageDrsConfigInfo getStorageDrsConfig() {
        return storageDrsConfig;
    }

    /**
     * Sets the value of the storageDrsConfig property.
     *
     * @param value
     *     allowed object is
     *     {@link StorageDrsConfigInfo }
     *
     */
    public void setStorageDrsConfig(StorageDrsConfigInfo value) {
        this.storageDrsConfig = value;
    }

    /**
     * Gets the value of the recommendation property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the recommendation property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getRecommendation().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ClusterRecommendation }
     *
     *
     */
    public List<ClusterRecommendation> getRecommendation() {
        if (recommendation == null) {
            recommendation = new ArrayList<ClusterRecommendation>();
        }
        return this.recommendation;
    }

    /**
     * Gets the value of the drsFault property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the drsFault property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDrsFault().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ClusterDrsFaults }
     *
     *
     */
    public List<ClusterDrsFaults> getDrsFault() {
        if (drsFault == null) {
            drsFault = new ArrayList<ClusterDrsFaults>();
        }
        return this.drsFault;
    }

    /**
     * Gets the value of the actionHistory property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the actionHistory property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getActionHistory().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ClusterActionHistory }
     *
     *
     */
    public List<ClusterActionHistory> getActionHistory() {
        if (actionHistory == null) {
            actionHistory = new ArrayList<ClusterActionHistory>();
        }
        return this.actionHistory;
    }

}


text:
using ComponentGlue.Tests.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComponentGlue.Tests.Classes
{
	[CustomDefaultComponent(ComponentType = typeof(IBar))]
	public class BarWithCustomDefaultComponentAttribte : IBar
	{
	}
}


text:
/* eslint-disable no-underscore-dangle */
// Because swagerJS generated method contains trailing underscore methods,
// hence disabling eslint no-underscore-dangle rule

import Resource from './Resource';
import APIClientFactory from './APIClientFactory';
import Utils from './Utils';

/**
 * Global and inline API endpoint representation
 * @class Endpoint
 */
export default class Endpoint extends Resource {
    /**
     * Creates an instance of Endpoint.
     * @param {String} name Endpoint name
     * @param {String} type Endpoint Type
     * @param {Number} maxTps Endpoint max TPS
     * @param {Object} kwargs rest
     * @memberof Endpoint
     */
    constructor(name, type, maxTps, kwargs) {
        super();
        let properties = kwargs;
        if (name instanceof Object) {
            properties = name;
        } else {
            this.name = name;
            this.type = type;
            this.maxTps = maxTps;
        }
        this.endpointSecurity = {};
        this.endpointConfig = {};
        for (const key in properties) {
            if (Object.prototype.hasOwnProperty.call(properties, key)) {
                this[key] = properties[key];
            }
        }
    }

    /**
     * Return the service URL of the Endpoint
     * @returns {String} HTTP/HTTPS Service URL
     * @memberof Endpoint
     */
    getServiceUrl() {
        return this.endpointConfig.service_url;
    }

    /**
     * Persist the local endpoint object changes via Endpoint REST API
     * @returns {Promise} Promise resolve with newly created Endpoint object
     * @memberof Endpoint
     */
    save() {
        const promisedEndpoint = this.client.then((client) => {
            return this._serialize().then((serializedData) => {
                const payload = { body: serializedData, 'Content-Type': 'application/json' };
                return client.apis['Endpoint (Collection)'].post_endpoints(payload, Resource._requestMetaData());
            });
        });
        return promisedEndpoint.then((response) => {
            return new Endpoint(response.body);
        });
    }

    /**
     * Serialize the object to send over the wire
     * @returns {Object} serialized JSON object
     * @memberof Endpoint
     */
    _serialize() {
        return this.client.then((client) => {
            const { properties } = client.spec.definitions.EndPoint;
            const data = {};
            for (const property in this) {
                if (property in properties) {
                    data[property] = this[property];
                }
            }
            return data;
        });
    }

    /**
     * Get a global endpoint by giving its UUID
     * @static
     * @param {String} id UUID of the endpoint
     * @returns {Promise} promise resolving to endpoint object
     * @memberof Endpoint
     */
    static get(id) {
        const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
        const promisedGet = apiClient.then((client) => {
            return client.apis['Endpoint (individual)'].get_endpoints__endpointId_(
                {
                    endpointId: id,
                    'Content-Type': 'application/json',
                },
                this._requestMetaData(),
            );
        });
        return promisedGet.then((response) => {
            const endpointJSON = response.body;
            return new Endpoint(endpointJSON);
        });
    }

    /**
     * Get all Global endpoints
     * @static
     * @returns {Array} Array of global Endpoint objects
     * @memberof Endpoint
     */
    static all() {
        const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
        const promisedEndpoints = apiClient.then((client) => {
            return client.apis['Endpoint (Collection)'].get_endpoints({}, this._requestMetaData());
        });
        return promisedEndpoints.then((response) => {
            return response.body.list.map((endpointJSON) => new Endpoint(endpointJSON));
        });
    }
}
/* eslint-enable no-underscore-dangle */


text:
import {
  requestReleases,
  fetchReleases,
  receiveReleasesSuccess,
  receiveReleasesError,
} from '~/releases/store/actions';
import state from '~/releases/store/state';
import * as types from '~/releases/store/mutation_types';
import api from '~/api';
import testAction from 'spec/helpers/vuex_action_helper';
import { releases } from '../mock_data';

describe('Releases State actions', () => {
  let mockedState;

  beforeEach(() => {
    mockedState = state();
  });

  describe('requestReleases', () => {
    it('should commit REQUEST_RELEASES mutation', done => {
      testAction(requestReleases, null, mockedState, [{ type: types.REQUEST_RELEASES }], [], done);
    });
  });

  describe('fetchReleases', () => {
    describe('success', () => {
      it('dispatches requestReleases and receiveReleasesSuccess ', done => {
        spyOn(api, 'releases').and.returnValue(Promise.resolve({ data: releases }));

        testAction(
          fetchReleases,
          releases,
          mockedState,
          [],
          [
            {
              type: 'requestReleases',
            },
            {
              payload: releases,
              type: 'receiveReleasesSuccess',
            },
          ],
          done,
        );
      });
    });

    describe('error', () => {
      it('dispatches requestReleases and receiveReleasesError ', done => {
        spyOn(api, 'releases').and.returnValue(Promise.reject());

        testAction(
          fetchReleases,
          null,
          mockedState,
          [],
          [
            {
              type: 'requestReleases',
            },
            {
              type: 'receiveReleasesError',
            },
          ],
          done,
        );
      });
    });
  });

  describe('receiveReleasesSuccess', () => {
    it('should commit RECEIVE_RELEASES_SUCCESS mutation', done => {
      testAction(
        receiveReleasesSuccess,
        releases,
        mockedState,
        [{ type: types.RECEIVE_RELEASES_SUCCESS, payload: releases }],
        [],
        done,
      );
    });
  });

  describe('receiveReleasesError', () => {
    it('should commit RECEIVE_RELEASES_ERROR mutation', done => {
      testAction(
        receiveReleasesError,
        null,
        mockedState,
        [{ type: types.RECEIVE_RELEASES_ERROR }],
        [],
        done,
      );
    });
  });
});


text:
<!-- do some _.each to get the checkboxes -->
<form id="dagcheckboxes"><% _.each(tags, function (tag) { %>
  <input type="checkbox" value="<%= tag %>" checked>
  <span> tag: <%= tag %> </span>
<% }) %></form>


text:
package org.unitils.mock.report;

import org.unitils.mock.core.Scenario;

/**
 * Creates a report of the given {@link Scenario}.
 *
 * @author Kenny Claes
 * @author Filip Neven
 * @author Tim Ducheyne
 */
public interface ScenarioReport {

    /**
     * Creates a report.
     * @param scenario The scenario to output, not null
     *
     * @return the report, not null
     */
    String createReport(Scenario scenario);

}


text:
// - -------------------------------------------------------------------- - //
// - libs

var lib = {
	factory: require("bauer-factory"),
};

// - -------------------------------------------------------------------- - //

// @Randomizer
var Randomizer = lib.factory.class({

	// @inherits
	inherits: "events.EventEmitter",

	// @constructor
	constructor: function(arg) {

		var config = {};

		if (lib.factory.isObject(arg)) {

			if (lib.factory.isObject(arg.config)) config = arg.config;

			if (lib.factory.isFunction(arg.table)) this.on("table",arg.table);
			if (lib.factory.isFunction(arg.index)) this.on("index",arg.index);
			if (lib.factory.isFunction(arg.view)) this.on("view",arg.view);
			if (lib.factory.isFunction(arg.trigger)) this.on("trigger",arg.trigger);
			if (lib.factory.isFunction(arg.record)) this.on("record",arg.record);
			if (lib.factory.isFunction(arg.begin)) this.on("begin",arg.begin);
			if (lib.factory.isFunction(arg.end)) this.on("end",arg.end);
		}

		if (!lib.factory.isArray(config.types)) {
			config.types = [
				"INTEGER",
				"TEXT",
				"REAL",
				"BLOB",
			];
		}

		if (!lib.factory.isArray(config.letters)) {
			config.letters = [
				"a","b","c","d","e","f","g","h","i",
				"j","k","l","m","n","o","p","q","r",
				"s","t","u","v","x","y","w","z",
			].sort();
			var length = config.letters.length;
			for (var i = 0; i < length; i++) {
				config.letters.push(config.letters[i].toUpperCase());
			}
		}

		if (lib.factory.isNull(config.tables)) {
			config.tables = Math.max(Math.floor(Math.random() * config.types.length * config.types.length),1);
		}

		if (lib.factory.isNull(config.fields)) {
			config.fields = Math.max(Math.floor(Math.random() * config.types.length * config.types.length),1);
		}

		if (lib.factory.isNull(config.indexes)) {
			config.indexes = Math.max(Math.floor(Math.random() * config.types.length * config.types.length),1);
		}

		if (lib.factory.isNull(config.records)) {
			config.records = Math.max(Math.floor(Math.random() * config.letters.length * config.letters.length),1);
		}

		this.config = config;
	},

// - -------------------------------------------------------------------- - //

	// .randomType()
	randomType: function() {
		return this.config.types[Math.floor(Math.random() * this.config.types.length)];
	},

	// .randomName()
	randomName: function() {
		var length = Math.floor(Math.random() * this.config.letters.length) + 3;
		var name = "";
		for (var i = 0; i < length; i++) {
			name += this.config.letters[Math.floor(Math.random() * this.config.letters.length)];
		}
		return name;
	},

	// .randomData(type)
	randomData: function(type) {
		if (type == "TEXT") {
			return this.randomName();
		} else if (type == "REAL") {
			return Math.random();
		} else if (type == "BLOB") {
			return this.randomName();
		} else if (type == "INTEGER") {
			return Math.floor(Math.random() * this.config.letters.length);
		}
	},

	// .randomFields()
	randomFields: function() {
		var fields = {};
		for (var i = 0; i < this.config.fields; i++) {
			fields[this.randomName()] = this.randomType();
		}
		return fields;
	},

	// .randomTables()
	randomTables: function() {
		var type = lib.factory.type(this.config.tables);
		if (type == "number") {
			var tables = {};
			var length = this.config.tables;
			for (var i = 0; i < length; i++) {
				var table = this.randomName();
				var fields = this.randomFields();
				tables[table] = fields;
				this.emit("table",i + 1,table,fields);
			}
			this.tables = tables;
		} else if (type == "object") {
			this.tables = this.config.tables;
			var count = 0;
			for (var table in this.tables) {
				var fields = this.tables[fields];
				this.emit("table",++count,table,fields);
			}
		}
	},

	// .randomIndexes
	randomIndexes: function() {
		var type = lib.factory.type(this.config.indexes);
		if (type == "number") {
			var tables = Object.keys(this.tables);
			var length = this.config.indexes;
			var indexes = {};
			for (var i = 0; i < length; i++) {
				var index = this.randomName();
				var table = tables[Math.floor(Math.random() * tables.length)];
				var fields = Object.keys(this.tables[table]);
				var indexLength = Math.max(Math.floor(Math.random() * fields.length),1);
				var indexFields = fields.slice(0,indexLength);
				this.emit("index",i + 1,index,table,indexFields);
				indexes[index] = table + "." + indexFields.join(".");
			}
			this.indexes = indexes;
		} else if (type == "object") {
			this.indexes = this.config.indexes;
			var count = 0;
			for (var index in this.indexes) {
				var fields = this.indexes[index].split(".");
				var table = fields.shift();
				this.emit("index",++count,table,fields);
			}
		}
	},

	// .randomRecords()
	randomRecords: function() {
		var tables = Object.keys(this.tables);
		for (var i = 0; i < this.config.records; i++) {
			var table = tables[Math.floor(Math.random() * tables.length)];
			var fields = Object.keys(this.tables[table]);
			var recordLength = Math.max(Math.floor(Math.random() * fields.length),1);
			var recordFields = fields.slice(0,recordLength);
			var recordValues = [];
			for (var f = 0; f < recordFields.length; f++) {
				var type = this.tables[table][recordFields[f]];
				recordValues[f] = this.randomData(type);
			}
			this.emit("record",i+1,table,recordFields,recordValues);
		}
	},

// - -------------------------------------------------------------------- - //

	// .start()
	start: function() {
		this.randomTables();
		this.randomIndexes();
		this.randomRecords();
	},

});

// - -------------------------------------------------------------------- - //
// - exports

exports = Randomizer;
module.exports = exports;

// - -------------------------------------------------------------------- - //


text:
using System;
using System.Linq;
using Cake.Core.IO;
using Cake.Core.Tests.Fixtures;
using NSubstitute;
using Xunit;

namespace Cake.Core.Tests.Unit.IO
{
    public sealed class GlobberTests
    {
        public sealed class TheConstructor
        {
            [Fact]
            public void Should_Throw_If_File_System_Is_Null()
            {
                // Given, When
                var environment = Substitute.For<ICakeEnvironment>();
                var result = Record.Exception(() => new Globber(null, environment));

                // Then
                Assert.IsArgumentNullException(result, "fileSystem");
            }

            [Fact]
            public void Should_Throw_If_Environment_Is_Null()
            {
                // Given
                var fileSystem = Substitute.For<IFileSystem>();

                // When
                var result = Record.Exception(() => new Globber(fileSystem, null));

                // Then
                Assert.IsArgumentNullException(result, "environment");
            }
        }

        public sealed class TheMatchMethod
        {
            [Fact]
            public void Should_Throw_If_Pattern_Is_Empty()
            {
                // Given
                var fixture = new GlobberFixture();
                var globber = fixture.CreateGlobber();

                // When
                var result = Record.Exception(() => globber.Match(null));

                // Then
                Assert.IsArgumentNullException(result, "pattern");
            }

            [Fact]
            public void Can_Traverse_Recursivly()
            {
                // Given
                var fixture = new GlobberFixture();
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("/Temp/**/*.txt").ToArray();

                // Then
                Assert.Equal(2, result.Length);
                Assert.Equal("/Temp/Hello/World/Text.txt", result[0].FullPath);
                Assert.Equal("/Temp/Goodbye/OtherText.txt", result[1].FullPath);
            }

            [Fact]
            public void Will_Append_Relative_Root_With_Implicit_Working_Directory()
            {
                // Given
                var fixture = new GlobberFixture();
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("Hello/World/Text.txt").ToArray();

                // Then
                Assert.Equal(1, result.Length);
                Assert.Equal("/Temp/Hello/World/Text.txt", result[0].FullPath);
            }

            [Fact]
            public void Will_Fix_Root_If_Drive_Is_Missing_By_Using_The_Drive_From_The_Working_Directory()
            {
                // Given
                var fixture = new GlobberFixture();
                fixture.SetWorkingDirectory("C:/Working/");
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("/Temp/Hello/World/Text.txt").ToArray();

                // Then
                Assert.Equal(1, result.Length);
                Assert.Equal("C:/Temp/Hello/World/Text.txt", result[0].FullPath);
            }

            [Fact]
            public void Should_Throw_If_Unc_Root_Was_Encountered()
            {
                // Given
                var fixture = new GlobberFixture();
                var globber = fixture.CreateGlobber();

                // When
                var result = Record.Exception(() => globber.Match("//Hello/World/Text.txt"));

                // Then
                Assert.IsType<NotSupportedException>(result);
                Assert.Equal("UNC paths are not supported.", result.Message);
            }

            [Theory]
            [InlineData(true, false)]
            [InlineData(false, true)]
            public void Should_Ignore_Case_Sensitivity_On_Case_Insensitive_Operative_System(bool isFileSystemCaseSensitive, bool shouldFindFile)
            {
                // Given
                var fixture = new GlobberFixture(isFileSystemCaseSensitive);
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("/Temp/**/text.txt").ToArray();

                // Then
                Assert.Equal(shouldFindFile, result.Length == 1);
            }

            [Fact]
            public void Should_Return_Single_Path_For_Absolute_File_Path_Without_Glob_Pattern()
            {
                // Given
                var fixture = new GlobberFixture();
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("/Temp/Hello/World/Text.txt").ToArray();

                // Then
                Assert.Equal(1, result.Length);
                Assert.IsType<FilePath>(result[0]);
                Assert.Equal("/Temp/Hello/World/Text.txt", result[0].FullPath);
            }

            [Fact]
            public void Should_Return_Single_Path_For_Absolute_Directory_Path_Without_Glob_Pattern()
            {
                // Given
                var fixture = new GlobberFixture();
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("/Temp/Hello/World").ToArray();

                // Then
                Assert.Equal(1, result.Length);
                Assert.IsType<DirectoryPath>(result[0]);
                Assert.Equal("/Temp/Hello/World", result[0].FullPath);
            }

            [Fact]
            public void Should_Return_Single_Path_For_Relative_File_Path_Without_Glob_Pattern()
            {
                // Given
                var fixture = new GlobberFixture();
                fixture.SetWorkingDirectory("/Temp/Hello");
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("./World/Text.txt").ToArray();

                // Then
                Assert.Equal(1, result.Length);
                Assert.IsType<FilePath>(result[0]);
                Assert.Equal("/Temp/Hello/World/Text.txt", result[0].FullPath);
            }

            [Fact]
            public void Should_Return_Single_Path_For_Relative_Directory_Path_Without_Glob_Pattern()
            {
                // Given
                var fixture = new GlobberFixture();
                fixture.SetWorkingDirectory("/Temp/Hello");
                var globber = fixture.CreateGlobber();

                // When
                var result = globber.Match("./World").ToArray();

                // Then
                Assert.Equal(1, result.Length);
                Assert.IsType<DirectoryPath>(result[0]);
                Assert.Equal("/Temp/Hello/World", result[0].FullPath);
            }
        }
    }
}


text:
/**
  * This package contains classes to control the game,
  * such as timers for moving ghosts around.
  *
  * @author Arie van Deursen, January 2012.
  */
package org.jpacman.framework.controller;