text:
package org.assertj.db.api.assertions.impl;

import org.assertj.core.api.WritableAssertionInfo;
import org.assertj.core.internal.Failures;
import org.assertj.db.api.AbstractAssert;
import org.assertj.db.type.Change;
import org.assertj.db.util.Changes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.assertj.db.error.ShouldHaveModifications.shouldHaveModifications;
import static org.assertj.db.error.ShouldHaveNumberOfModifications.shouldHaveNumberOfModifications;

/**
 * Implements the assertion methods on modified columns.
 *
 * @author Régis Pouiller
 * @see org.assertj.db.api.assertions.AssertOnModifiedColumns
 */
public class AssertionsOnModifiedColumns {

  /**
   * To notice failures in the assertion.
   */
  private final static Failures failures = Failures.instance();

  /**
   * Private constructor.
   */
  private AssertionsOnModifiedColumns() {
    // Empty
  }

  /**
   * Verifies that the number of columns with a modification in the values between the start point and the end point
   * is equals to the number in parameter.
   *
   * @param <A>       The type of the assertion which call this method.
   * @param assertion The assertion which call this method.
   * @param info      Writable information about an assertion.
   * @param change    The change.
   * @param number    The expected number of modified columns
   * @return {@code this} assertion object.
   * @throws AssertionError If the number of modified columns is different to the number in parameter.
   */
  public static <A extends AbstractAssert> A hasNumberOfModifiedColumns(A assertion, WritableAssertionInfo info,
                                                                        Change change, int number) {
    Integer[] indexesOfModifiedColumns = Changes.getIndexesOfModifiedColumns(change);

    if (number != indexesOfModifiedColumns.length) {
      throw failures.failure(info, shouldHaveNumberOfModifications(indexesOfModifiedColumns.length, number));
    }
    return assertion;
  }

  /**
   * Verifies that the indexes of columns with a modification in the values between the start point and the end point
   * is equals to the parameters.
   *
   * @param <A>       The type of the assertion which call this method.
   * @param assertion The assertion which call this method.
   * @param info      Writable information about an assertion.
   * @param change    The change.
   * @param indexes   Indexes of the modified columns.
   * @return {@code this} assertion object.
   * @throws AssertionError If the indexes of the modified columns are different to the indexes in parameters.
   */
  public static <A extends AbstractAssert> A hasModifiedColumns(A assertion, WritableAssertionInfo info, Change change,
                                                                Integer... indexes) {
    if (indexes == null) {
      throw new NullPointerException("Columns indexes must be not null");
    }

    // Create a sorted list from the modified columns
    Integer[] indexesOfModifiedColumns = Changes.getIndexesOfModifiedColumns(change);
    List<Integer> indexesOfModifiedList = Arrays.asList(indexesOfModifiedColumns);
    Collections.sort(indexesOfModifiedList);

    // Create a sorted list from the parameters
    List<Integer> indexesList = new ArrayList<>();
    for (Integer index : indexes) {
      if (index == null) {
        throw new NullPointerException("Column index must be not null");
      }
      indexesList.add(index);
    }
    Collections.sort(indexesList);

    // Compare each list
    if (!indexesList.equals(indexesOfModifiedList)) {
      throw failures.failure(info, shouldHaveModifications(indexesOfModifiedColumns, indexes));
    }

    return assertion;
  }

  /**
   * Verifies that the names of columns with a modification in the values between the start point and the end point
   * is equals to the parameters.
   *
   * @param <A>       The type of the assertion which call this method.
   * @param assertion The assertion which call this method.
   * @param info      Writable information about an assertion.
   * @param change    The change.
   * @param names     The names of the modified columns.
   * @return {@code this} assertion object.
   * @throws AssertionError If the names of the modified columns are different to the names in parameters.
   */
  public static <A extends AbstractAssert> A hasModifiedColumns(A assertion, WritableAssertionInfo info, Change change,
                                                                String... names) {
    if (names == null) {
      throw new NullPointerException("Columns names must be not null");
    }

    // Create a sorted list from the parameters
    List<String> namesList = new ArrayList<>();
    for (String name : names) {
      if (name == null) {
        throw new NullPointerException("Column name must be not null");
      }
      namesList.add(name.toUpperCase());
    }
    Collections.sort(namesList);

    // Create a sorted list from the modified columns
    Integer[] indexesOfModifiedColumns = Changes.getIndexesOfModifiedColumns(change);
    String[] namesOfModifiedColumns = new String[names.length];
    List<String> columnsNameList = change.getColumnsNameList();
    for (int i = 0; i < indexesOfModifiedColumns.length; i++) {
      namesOfModifiedColumns[i] = columnsNameList.get(indexesOfModifiedColumns[i]);
    }
    List<String> namesOfModifiedList = Arrays.asList(namesOfModifiedColumns);
    Collections.sort(namesOfModifiedList);

    // Compare each list
    if (!namesList.equals(namesOfModifiedList)) {
      throw failures.failure(info, shouldHaveModifications(namesOfModifiedColumns, names));
    }

    return assertion;
  }
}


text:
import { whenSpacing } from "./whenSpacing";

export const objectAsKeyValueString = (obj) => Object
    .entries(obj)
    .map(([k, v]) => `${whenSpacing}${k} = ${v}`)
    .join("\n");

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function*() {
  const message = this.query.message;

  this.logger.debug('debug %s', message);
  this.logger.info('info %s', message);
  this.logger.warn('warn %s', message);
  this.logger.error(new Error('error ' + message));

  this.coreLogger.debug('core debug %s', message);
  this.coreLogger.info('core info %s', message);
  this.coreLogger.warn('core warn %s', message);
  this.coreLogger.error(new Error('core error ' + message));

  this.body = 'logger';
};


text:
class AddNameToTaskList < ActiveRecord::Migration
  def change
    add_column :task_lists, :name, :string
  end
end


text:
sudo xcodebuild -license
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" # Homebrew
brew update
brew doctor
brew install ansible

# oh-my-zsh
sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" # oh-my-zsh

echo "Done installing, now run ansible to setup dotfiles"


text:
// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2010 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

/** @class

  Renders a checkbox button view specifically.

  This view is basically a button view preconfigured to generate the correct
  HTML and to set to use a TOGGLE_BEHAVIOR for its buttons.

  This view renders a simulated checkbox that can display a mixed state and
  has other features not found in platform-native controls.

  @extends SC.FieldView
  @since SproutCore 1.0
*/
SC.CheckboxView = SC.ButtonView.extend(SC.StaticLayout, SC.Button,
  /** @scope SC.CheckboxView.prototype */ {

  classNames: ['sc-checkbox-view'],
  tagName: 'label',

  /* Ellipsis is disabled by default to allow multiline text */
  needsEllipsis: NO,

  render: function(context, firstTime) {
    var dt, elem,
        value = this.get('value'),
        ariaValue = value === SC.MIXED_MODE ?
                'mixed' : (value === this.get('toggleOnValue') ?
                    'true': 'false');

    // add checkbox -- set name to view guid to separate it from others
    if (firstTime) {
      var blank = SC.BLANK_IMAGE_URL,
          disabled = this.get('isEnabled') ? '' : 'disabled="disabled"',
          guid = SC.guidFor(this);

      context.attr('role', 'checkbox');
      dt = this._field_currentDisplayTitle = this.get('displayTitle');

      if(SC.browser.msie) context.attr('for', guid);
      context.push('');
      if(this.get('needsEllipsis')){
        context.push('', dt, '');
      }else{
        context.push('', dt, '');
      }
      context.attr('name', guid);

    // since we don't want to regenerate the contents each time
    // actually search for and update the displayTitle.
    } else {

      dt = this.get('displayTitle');
      if (dt !== this._field_currentDisplayTitle) {
        this._field_currentDisplayTitle = dt;
        this.$('span.label').text(dt);
      }
    }
    context.attr('aria-checked', ariaValue);
  },

  acceptsFirstResponder: function() {
    if(!SC.SAFARI_FOCUS_BEHAVIOR) return this.get('isEnabled');
    else return NO;
  }.property('isEnabled'),

  mouseDown: function(evt) {
    if(!this.get('isEnabled')) return YES;
    this.set('isActive', YES);
    this._isMouseDown = YES;
    // even if radiobuttons are not set to get firstResponder, allow default
    // action, that way textfields loose focus as expected.
    if (evt) evt.allowDefault();
    return YES;
  },

  mouseUp: function(evt) {
    if(!this.get('isEnabled') ||
      (evt && evt.target && !this.$().within(evt.target))) {
      return YES;
    }
    var val = this.get('value');
    if (val === this.get('toggleOnValue')) {
      this.$().attr('aria-checked', 'false');
      this.set('value', this.get('toggleOffValue'));
    }
    else {
      this.$().attr('aria-checked', 'true');
      this.set('value', this.get('toggleOnValue'));
    }
    this.set('isActive', NO);
    this._isMouseDown = NO;
    return YES;
  },

  touchStart: function(evt) {
    return this.mouseDown(evt);
  },

  touchEnd: function(evt) {
    return this.mouseUp(evt);
  }

}) ;


text:
package mtutils

import (
	"runtime"
	"sync"
)

// template type Monitor(A)

type AccessFuncMonitor func(interface{})

type Monitor struct {
	sync.Mutex
	obj interface{}
}

func NewMonitor(obj interface{}) *Monitor {
	ret := new(Monitor)
	ret.obj = obj
	runtime.SetFinalizer(ret, func(m *Monitor) {
		m.Unlock()
	})
	return ret
}

func (m *Monitor) Capture() interface{} {
	m.Lock()
	return m.obj
}

func (m *Monitor) Release() {
	m.Unlock()
}

func (m *Monitor) Access(f AccessFuncMonitor) {
	m.Lock()
	defer m.Unlock()
	f(m.obj)
}


text:
<menu>
   <Services>
      <UDPBroadcastRelay VisibleName="UDP Broadcast Relay" cssClass="fa fa-bolt fa-fw" url="/ui/udpbroadcastrelay"/>
   </Services>
</menu>


text:
version: 1.0.1
title: Vlastné Mix Tasky
---

Vytváranie vlastných Mix taskov pre vaše Elixir projekty

{% include toc.html %}

## Úvod

Občas sa stáva, že do svojho projektu potrebujete pridať vlastné špeciálnu funkcionalitu pridaním Mix taskov. Predtým, než si ukážeme, ako takéto vlastné Mix tasky vytvárať, pozrime sa na tie, ktoré už existujú:

```shell
$ mix phoenix.new my_phoenix_app

* creating my_phoenix_app/config/config.exs
* creating my_phoenix_app/config/dev.exs
* creating my_phoenix_app/config/prod.exs
* creating my_phoenix_app/config/prod.secret.exs
* creating my_phoenix_app/config/test.exs
* creating my_phoenix_app/lib/my_phoenix_app.ex
* creating my_phoenix_app/lib/my_phoenix_app/endpoint.ex
* creating my_phoenix_app/test/views/error_view_test.exs
...
```

Ako môžeme vidieť z výstupu príkazu vyššie, framework Phoenix má vlastný Mix task určený na generovanie nového projektu. Čo keby sme mohli vytvoriť niečo podobné aj pre náš projekt? Dobrá správa! Elixir je na to pripravený, tak si poďme ukázať ako na to.

## Nový projekt

Vytvorme si veľmi jednoduchú Mix aplikáciu.

```shell
$ mix new hello

* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/hello.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

cd hello
mix test

Run "mix help" for more commands.
```

V súbore **lib/hello.ex**, ktorý nám Mix vygeneroval, vytvorme jednoduchú funkciu ktorá nám vypíše reťazec "Hello, World!"

```elixir
defmodule Hello do
  @doc """
  Output's `Hello, World!` everytime.
  """
  def say do
    IO.puts("Hello, World!")
  end
end
```

## Vlastný Mix Task

Teraz si vytvorme vlastný Mix task. Vytvorme nový adresár a súbor **hello/lib/mix/tasks/hello.ex**. Do tohto súboru vložíme nasledujúci kód:

```elixir
defmodule Mix.Tasks.Hello do
  use Mix.Task

  @shortdoc "Spustí funkciu Hello.say/0."
  def run(_) do
    # calling our Hello.say() function from earlier
    Hello.say()
  end
end
```

Všimnite si, že názov modulu začína na `Mix.Task` a nasleduje meno, ktorým chceme náš task spúšťať z príkazového riadku (teda v tomto prípade `Hello`). Nasleduje uvedenie modulu `Mix.Task`, ktorým do nášho modulu vnesieme rovnomenný behaviour (niečo ako interface v objektových jazykoch). Ďalej implementujeme povinnú funkciu run, ktorá bude nateraz ignorovať svoje argumenty. V tejto funkcii už len zavoláme našu funkciu `say` z modulu `Hello`.

## Mix Tasky v Akcii

Nadišiel čas náš nový task vyskúšať. V príkazovom riadku zadajme `mix hello` a mali by sme vidieť nasledovné:

```shell
$ mix hello
Hello, World!
```

Mix je celkom prívetivý a tolerantný - vie, že ľudia robia občas chyby a preklepy, takže používa techniku nazývanú *fuzzy string matching* aby navrhol možné opravy:

```shell
$ mix hell
** (Mix) The task "hell" could not be found. Did you mean "hello"?
```

Možno ste si všimli, že sme v definícii nášho tasku použili nový modulový atribút `@shortdoc`. Tento sa výborne hodí na popis špeciálnych taskov nášho projektu. Keď používateľ zadá do príkazového riadku v adresári nášho projektu `mix help`, uvidí aj popis nášho tasku `hello`:

```shell
$ mix help

mix app.start         # Starts all registered apps
...
mix hello             # Spustí funkciu Hello.say/0.
...
```


text:
package com.facebook.imageformat;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;

import com.facebook.common.soloader.SoLoaderShim;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

/**
 * Tests {@link ImageFormatChecker}
 */
@RunWith(RobolectricTestRunner.class)
public class ImageFormatCheckerTest {

  static {
    SoLoaderShim.setInTestMode();
  }

  @Test
  public void testSimpleWebps() throws Exception {
    singleImageTypeTest(
        getNames(2, "webps/%d_webp_plain.webp"),
        DefaultImageFormats.WEBP_SIMPLE);
  }

  @Test
  public void testLosslessWebps() throws Exception {
    singleImageTypeTest(
        getNames(5, "webps/%d_webp_ll.webp"),
        DefaultImageFormats.WEBP_LOSSLESS);
  }

  @Test
  public void testExtendedWebpsWithAlpha() throws Exception {
    singleImageTypeTest(
        getNames(5, "webps/%d_webp_ea.webp"),
        DefaultImageFormats.WEBP_EXTENDED_WITH_ALPHA);
  }

  @Test
  public void testExtendedWebpsWithoutAlpha() throws Exception {
    singleImageTypeTest(
        getName("webps/1_webp_e.webp"),
        DefaultImageFormats.WEBP_EXTENDED);
  }

  @Test
  public void testAnimatedWebps() throws Exception {
    singleImageTypeTest(
        getName("webps/1_webp_anim.webp"),
        DefaultImageFormats.WEBP_ANIMATED);
  }

  @Test
  public void testJpegs() throws Exception {
    singleImageTypeTest(
        getNames(5, "jpegs/%d.jpeg"),
        DefaultImageFormats.JPEG);
  }

  @Test
  public void testPngs() throws Exception {
    singleImageTypeTest(
        getNames(5, "pngs/%d.png"),
        DefaultImageFormats.PNG);
  }

  @Test
  public void testGifs() throws Exception {
    singleImageTypeTest(
        getNames(5, "gifs/%d.gif"),
        DefaultImageFormats.GIF);
  }

  @Test
  public void testBmps() throws Exception {
    singleImageTypeTest(
        getNames(5, "bmps/%d.bmp"),
        DefaultImageFormats.BMP);
  }

  private void singleImageTypeTest(
      final List<String> resourceNames,
      final ImageFormat expectedImageType)
      throws Exception {
    for (String name : resourceNames) {
      final InputStream resourceStream = getResourceStream(name);
      try {
        assertSame(
            "failed with resource: " + name,
            expectedImageType,
            ImageFormatChecker.getImageFormat(resourceStream));
      } finally {
        resourceStream.close();
      }
    }
  }

  private static List<String> getName(String path) {
    return Arrays.asList(path);
  }

  private static List<String> getNames(int amount, String pathFormat) {
    List<String> result = new ArrayList<>();
    for (int i = 1; i <= amount; ++i) {
      result.add(String.format(pathFormat, i));
    }
    return result;
  }

  private InputStream getResourceStream(String name) throws IOException {
    InputStream is = ImageFormatCheckerTest.class.getResourceAsStream(name);
    assertNotNull("failed to read resource: " + name, is);
    return is;
  }
}


text:
using System.Net.Http;
using System.Threading.Tasks;
using Sinch.WebApiClient;

namespace Sinch.ServerSdk.ApiFilters
{
    public class PublicFilter : IActionFilter
    {
        readonly string _key;
        readonly Task<bool> _successTask = Task.FromResult(true);

        public PublicFilter(string key)
        {
            _key = key;
        }

        public Task OnActionExecuting(HttpRequestMessage requestMessage)
        {
            requestMessage.Headers.TryAddWithoutValidation("authorization", "application " + _key);
            return _successTask;
        }

        public Task OnActionExecuted(HttpResponseMessage responseMessage)
        {
            return _successTask;
        }
    }
}


text:
Sign up

  <form class="form" name="form" ng-submit="register(form)" novalidate>

          <md-input-container>
            Name
            <input type="text" ng-model="user.name" required />

              A name is required

          </md-input-container>

          <md-input-container>
            Email
            <input type="email" name="email" ng-model="user.email" required mongoose-error/>

              Doesn't look like a valid email.

              What's your email address?

              {{ errors.email }}

          </md-input-container>

          <md-input-container>
            Password
            <input type="password" name="password" ng-model="user.password" ng-minlength="3" required mongoose-error/>

              Password must be at least 3 characters.

              {{ errors.password }}

          </md-input-container>

        <md-button class="md-primary md-raised" type="submit">
          Sign up
        </md-button>
        <md-button href="/login">
          Login
        </md-button>

  </form>


text:
using Xunit;

namespace System.Collections.Generic
{
    public class ConsistentHashTests
    {
        [Fact()]
        public void Test()
        {
            string[] array = { "AAA", "BBB", "CCC", "DDD" };
            string[] array2 = { array[0], array[1], array[2] };
            ConsistentHash<string> s = new ConsistentHash<string>(array);
            s.Add(array[3]);
            for(int i = 0; i < 100; i++)
            {
                Assert.Contains(s.GetNode(i.ToString()), array);
            }

        }
    }
}


text:
package com.github.mjdbc.test.asset.sql.error;

import com.github.mjdbc.Sql;
import com.github.mjdbc.test.asset.model.error.NonFinalMapperBean;
import com.github.mjdbc.test.asset.model.error.NonPublicMapperBean;

public interface NonPublicMapperBeanSql {

    @Sql("SELECT 1")
    NonPublicMapperBean select();

}


text:
"""
Contains form validator classes designed for use with WTForms.

Copyright: (c) 2012-2014 Artem Nezvigin <artem@artnez.com>
License: MIT, see LICENSE for details
"""

from wtforms.validators import ValidationError
from faceoff.db import use_db

class UniqueNickname(object):
    """
    Validates that a value is a unique user nickname.
    """

    def __init__(self, message=None):
        self.message = message

    @use_db
    def __call__(self, db, form, field):
        if db.find('user', nickname=field.data):
            if self.message is None:
                self.message = 'is already in use'
            raise ValidationError(self.message)


text:
package fpt.qa.mdnlib.mldm.method.jgibbslda;

public class Conversion {
	public static String ZeroPad( int number, int width )
	{
	      StringBuilder result = new StringBuilder("");
	      for( int i = 0; i < width-Integer.toString(number).length(); i++ )
	         result.append( "0" );
	      result.append( Integer.toString(number) );

	      return result.toString();
	}
}


text:
<?php

namespace GraphQLGen\Generator\Writer\Namespaced\Classes\ContentCreator;

use Exception;
use GraphQLGen\Generator\FragmentGenerators\FieldsFetchableInterface;
use GraphQLGen\Generator\FragmentGenerators\FragmentGeneratorInterface;
use GraphQLGen\Generator\FragmentGenerators\Main\EnumFragmentGenerator;
use GraphQLGen\Generator\FragmentGenerators\Main\InterfaceFragmentGenerator;
use GraphQLGen\Generator\FragmentGenerators\Main\ScalarFragmentGenerator;
use GraphQLGen\Generator\FragmentGenerators\Main\TypeDeclarationFragmentGenerator;
use GraphQLGen\Generator\FragmentGenerators\Main\UnionFragmentGenerator;
use GraphQLGen\Generator\InterpretedTypes\Main\EnumInterpretedType;
use GraphQLGen\Generator\InterpretedTypes\Main\ScalarInterpretedType;
use GraphQLGen\Generator\InterpretedTypes\Nested\FieldInterpretedType;
use GraphQLGen\Generator\Writer\Namespaced\Classes\Resolver;

class ResolverContent extends BaseContentCreator {
	/**
	 * @var Resolver
	 */
	protected $_resolverClass;

	/**
	 * @var FragmentGeneratorInterface
	 */
	protected $_fragmentGenerator;

	/**
	 * @return Resolver
	 */
	public function getResolverClass() {
		return $this->_resolverClass;
	}

	/**
	 * @param Resolver $resolverClass
	 */
	public function setResolverClass($resolverClass) {
		$this->_resolverClass = $resolverClass;
	}

	/**
	 * @return string
	 */
	public function getContent() {
		$contentAsLines = [];

		if ($this->getFragmentGenerator() instanceof InterfaceFragmentGenerator) {
			$contentAsLines[] = "function resolveType(\$value) { /** ToDo: Implement */ }";
		}

        if ($this->getFragmentGenerator() instanceof UnionFragmentGenerator) {
            $contentAsLines[] = "function resolve(\$value, \$context, \$info) { /** ToDo: Implement */ }";
        }

        if ($this->getFragmentGenerator() instanceof ScalarFragmentGenerator) {
			$contentAsLines[] = "public function serialize(\$value) { /** ToDo: Implement */ }";
			$contentAsLines[] = "public function parseValue(\$value) { /** ToDo: Implement */ }";
			$contentAsLines[] = "public function parseLiteral(\$value) { /** ToDo: Implement */ }";
        }

		if($this->getFragmentGenerator() instanceof FieldsFetchableInterface) {
			/** @var InterfaceFragmentGenerator|TypeDeclarationFragmentGenerator $typeGenerator */
			$typeGenerator = $this->getFragmentGenerator();

			foreach($typeGenerator->getFields() as $field) {
				$typeHasArguments = ($field instanceof FieldInterpretedType) && !empty($field->getArguments());
				if (!$typeHasArguments &&
					($field->getFieldType()->isPrimaryType() ||
					$typeGenerator->getFormatter()->canInterpretedTypeSkipResolver($field->getFieldType()->getTypeName()))) {
					continue;
				}

			    $fieldNameFirstLetterCapped = ucwords($field->getName());
				$contentAsLines[] = "function resolve{$fieldNameFirstLetterCapped}(\$root, \$args) { /** ToDo: Implement */ }";
			}
		}

		return implode(PHP_EOL, $contentAsLines);
	}

	/**
	 * @return string
	 */
	public function getVariables() {
		return "";
	}

	/**
	 * @return string
	 */
	public function getNamespace() {
		return $this->getResolverClass()->getNamespace();
	}

	/**
	 * @return string
	 */
	public function getClassName() {
		return $this->getResolverClass()->getClassName();
	}

	/**
	 * @return FragmentGeneratorInterface
	 */
	public function getFragmentGenerator() {
		return $this->_fragmentGenerator;
	}

	/**
	 * @param FragmentGeneratorInterface $fragmentGenerator
	 */
	public function setFragmentGenerator($fragmentGenerator) {
		$this->_fragmentGenerator = $fragmentGenerator;
	}

	/**
	 * @return string
	 * @throws Exception
	 */
	public function getTypeGeneratorClass() {
		if ($this->getFragmentGenerator() === null) {
			throw new Exception("Internal Exception: Type generator is not defined for {$this->getResolverClass()->getClassName()}");
		}

		return get_class($this->_fragmentGenerator);
	}

	/**
	 * @return string
	 */
	public function getParentClassName() {
		return "";
	}
}


text:
(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";
  // declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL

  var Pos = CodeMirror.Pos;
  var svgNS = "http://www.w3.org/2000/svg";

  function DiffView(mv, type) {
    this.mv = mv;
    this.type = type;
    this.classes = type == "left"
      ? {chunk: "CodeMirror-merge-l-chunk",
         start: "CodeMirror-merge-l-chunk-start",
         end: "CodeMirror-merge-l-chunk-end",
         insert: "CodeMirror-merge-l-inserted",
         del: "CodeMirror-merge-l-deleted",
         connect: "CodeMirror-merge-l-connect"}
      : {chunk: "CodeMirror-merge-r-chunk",
         start: "CodeMirror-merge-r-chunk-start",
         end: "CodeMirror-merge-r-chunk-end",
         insert: "CodeMirror-merge-r-inserted",
         del: "CodeMirror-merge-r-deleted",
         connect: "CodeMirror-merge-r-connect"};
  }

  DiffView.prototype = {
    constructor: DiffView,
    init: function(pane, orig, options) {
      this.edit = this.mv.edit;
      this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: true}, copyObj(options)));

      this.diff = getDiff(asString(orig), asString(options.value));
      this.diffOutOfDate = false;

      this.showDifferences = options.showDifferences !== false;
      this.forceUpdate = registerUpdate(this);
      setScrollLock(this, true, false);
      registerScroll(this);
    },
    setShowDifferences: function(val) {
      val = val !== false;
      if (val != this.showDifferences) {
        this.showDifferences = val;
        this.forceUpdate("full");
      }
    }
  };

  function registerUpdate(dv) {
    var edit = {from: 0, to: 0, marked: []};
    var orig = {from: 0, to: 0, marked: []};
    var debounceChange;
    function update(mode) {
      if (mode == "full") {
        if (dv.svg) clear(dv.svg);
        clear(dv.copyButtons);
        clearMarks(dv.edit, edit.marked, dv.classes);
        clearMarks(dv.orig, orig.marked, dv.classes);
        edit.from = edit.to = orig.from = orig.to = 0;
      }
      if (dv.diffOutOfDate) {
        dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
        dv.diffOutOfDate = false;
        CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
      }
      if (dv.showDifferences) {
        updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
        updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
      }
      drawConnectors(dv);
    }
    function set(slow) {
      clearTimeout(debounceChange);
      debounceChange = setTimeout(update, slow == true ? 250 : 100);
    }
    function change() {
      if (!dv.diffOutOfDate) {
        dv.diffOutOfDate = true;
        edit.from = edit.to = orig.from = orig.to = 0;
      }
      set(true);
    }
    dv.edit.on("change", change);
    dv.orig.on("change", change);
    dv.edit.on("markerAdded", set);
    dv.edit.on("markerCleared", set);
    dv.orig.on("markerAdded", set);
    dv.orig.on("markerCleared", set);
    dv.edit.on("viewportChange", set);
    dv.orig.on("viewportChange", set);
    update();
    return update;
  }

  function registerScroll(dv) {
    dv.edit.on("scroll", function() {
      syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
    });
    dv.orig.on("scroll", function() {
      syncScroll(dv, DIFF_DELETE) && drawConnectors(dv);
    });
  }

  function syncScroll(dv, type) {
    // Change handler will do a refresh after a timeout when diff is out of date
    if (dv.diffOutOfDate) return false;
    if (!dv.lockScroll) return true;
    var editor, other, now = +new Date;
    if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
    else { editor = dv.orig; other = dv.edit; }
    // Don't take action if the position of this editor was recently set
    // (to prevent feedback loops)
    if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;

    var sInfo = editor.getScrollInfo(), halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
    var mid = editor.lineAtHeight(midY, "local");
    var around = chunkBoundariesAround(dv.diff, mid, type == DIFF_INSERT);
    var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
    var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
    var ratio = (midY - off.top) / (off.bot - off.top);
    var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);

    var botDist, mix;
    // Some careful tweaking to make sure no space is left out of view
    // when scrolling to top or bottom.
    if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
      targetPos = targetPos * mix + sInfo.top * (1 - mix);
    } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
      var otherInfo = other.getScrollInfo();
      var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
      if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
        targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
    }

    other.scrollTo(sInfo.left, targetPos);
    other.state.scrollSetAt = now;
    other.state.scrollSetBy = dv;
    return true;
  }

  function getOffsets(editor, around) {
    var bot = around.after;
    if (bot == null) bot = editor.lastLine() + 1;
    return {top: editor.heightAtLine(around.before || 0, "local"),
            bot: editor.heightAtLine(bot, "local")};
  }

  function setScrollLock(dv, val, action) {
    dv.lockScroll = val;
    if (val && action != false) syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
    dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db  \u21da";
  }

  // Updating the marks for editor content

  function clearMarks(editor, arr, classes) {
    for (var i = 0; i < arr.length; ++i) {
      var mark = arr[i];
      if (mark instanceof CodeMirror.TextMarker) {
        mark.clear();
      } else {
        editor.removeLineClass(mark, "background", classes.chunk);
        editor.removeLineClass(mark, "background", classes.start);
        editor.removeLineClass(mark, "background", classes.end);
      }
    }
    arr.length = 0;
  }

  // FIXME maybe add a margin around viewport to prevent too many updates
  function updateMarks(editor, diff, state, type, classes) {
    var vp = editor.getViewport();
    editor.operation(function() {
      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
        clearMarks(editor, state.marked, classes);
        markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
        state.from = vp.from; state.to = vp.to;
      } else {
        if (vp.from < state.from) {
          markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
          state.from = vp.from;
        }
        if (vp.to > state.to) {
          markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
          state.to = vp.to;
        }
      }
    });
  }

  function markChanges(editor, diff, type, marks, from, to, classes) {
    var pos = Pos(0, 0);
    var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
    var cls = type == DIFF_DELETE ? classes.del : classes.insert;
    function markChunk(start, end) {
      var bfrom = Math.max(from, start), bto = Math.min(to, end);
      for (var i = bfrom; i < bto; ++i) {
        var line = editor.addLineClass(i, "background", classes.chunk);
        if (i == start) editor.addLineClass(line, "background", classes.start);
        if (i == end - 1) editor.addLineClass(line, "background", classes.end);
        marks.push(line);
      }
      // When the chunk is empty, make sure a horizontal line shows up
      if (start == end && bfrom == end && bto == end) {
        if (bfrom)
          marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
        else
          marks.push(editor.addLineClass(bfrom, "background", classes.start));
      }
    }

    var chunkStart = 0;
    for (var i = 0; i < diff.length; ++i) {
      var part = diff[i], tp = part[0], str = part[1];
      if (tp == DIFF_EQUAL) {
        var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
        moveOver(pos, str);
        var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
        if (cleanTo > cleanFrom) {
          if (i) markChunk(chunkStart, cleanFrom);
          chunkStart = cleanTo;
        }
      } else {
        if (tp == type) {
          var end = moveOver(pos, str, true);
          var a = posMax(top, pos), b = posMin(bot, end);
          if (!posEq(a, b))
            marks.push(editor.markText(a, b, {className: cls}));
          pos = end;
        }
      }
    }
    if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
  }

  // Updating the gap between editor and original

  function drawConnectors(dv) {
    if (!dv.showDifferences) return;

    if (dv.svg) {
      clear(dv.svg);
      var w = dv.gap.offsetWidth;
      attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
    }
    clear(dv.copyButtons);

    var flip = dv.type == "left";
    var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
    var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
    iterateChunks(dv.diff, function(topOrig, botOrig, topEdit, botEdit) {
      if (topEdit > vpEdit.to || botEdit < vpEdit.from ||
          topOrig > vpOrig.to || botOrig < vpOrig.from)
        return;
      var topLpx = dv.orig.heightAtLine(topOrig, "local") - sTopOrig, top = topLpx;
      if (dv.svg) {
        var topRpx = dv.edit.heightAtLine(topEdit, "local") - sTopEdit;
        if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
        var botLpx = dv.orig.heightAtLine(botOrig, "local") - sTopOrig;
        var botRpx = dv.edit.heightAtLine(botEdit, "local") - sTopEdit;
        if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
        var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
        var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
        attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
              "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
              "class", dv.classes.connect);
      }
      var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
                                                "CodeMirror-merge-copy"));
      copy.title = "Revert chunk";
      copy.chunk = {topEdit: topEdit, botEdit: botEdit, topOrig: topOrig, botOrig: botOrig};
      copy.style.top = top + "px";
    });
  }

  function copyChunk(dv, chunk) {
    if (dv.diffOutOfDate) return;
    dv.edit.replaceRange(dv.orig.getRange(Pos(chunk.topOrig, 0), Pos(chunk.botOrig, 0)),
                         Pos(chunk.topEdit, 0), Pos(chunk.botEdit, 0));
  }

  // Merge view, containing 0, 1, or 2 diff views.

  var MergeView = CodeMirror.MergeView = function(node, options) {
    if (!(this instanceof MergeView)) return new MergeView(node, options);

    var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
    var hasLeft = origLeft != null, hasRight = origRight != null;
    var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
    var wrap = [], left = this.left = null, right = this.right = null;

    if (hasLeft) {
      left = this.left = new DiffView(this, "left");
      var leftPane = elt("div", null, "CodeMirror-merge-pane");
      wrap.push(leftPane);
      wrap.push(buildGap(left));
    }

    var editPane = elt("div", null, "CodeMirror-merge-pane");
    wrap.push(editPane);

    if (hasRight) {
      right = this.right = new DiffView(this, "right");
      wrap.push(buildGap(right));
      var rightPane = elt("div", null, "CodeMirror-merge-pane");
      wrap.push(rightPane);
    }

    (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";

    wrap.push(elt("div", null, null, "height: 0; clear: both;"));
    var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
    this.edit = CodeMirror(editPane, copyObj(options));

    if (left) left.init(leftPane, origLeft, options);
    if (right) right.init(rightPane, origRight, options);

    var onResize = function() {
      if (left) drawConnectors(left);
      if (right) drawConnectors(right);
    };
    CodeMirror.on(window, "resize", onResize);
    var resizeInterval = setInterval(function() {
      for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
      if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
    }, 5000);
  };

  function buildGap(dv) {
    var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
    lock.title = "Toggle locked scrolling";
    var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
    CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
    dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
    CodeMirror.on(dv.copyButtons, "click", function(e) {
      var node = e.target || e.srcElement;
      if (node.chunk) copyChunk(dv, node.chunk);
    });
    var gapElts = [dv.copyButtons, lockWrap];
    var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
    if (svg && !svg.createSVGRect) svg = null;
    dv.svg = svg;
    if (svg) gapElts.push(svg);

    return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
  }

  MergeView.prototype = {
    constuctor: MergeView,
    editor: function() { return this.edit; },
    rightOriginal: function() { return this.right && this.right.orig; },
    leftOriginal: function() { return this.left && this.left.orig; },
    setShowDifferences: function(val) {
      if (this.right) this.right.setShowDifferences(val);
      if (this.left) this.left.setShowDifferences(val);
    },
    rightChunks: function() {
      return this.right && getChunks(this.right.diff);
    },
    leftChunks: function() {
      return this.left && getChunks(this.left.diff);
    }
  };

  function asString(obj) {
    if (typeof obj == "string") return obj;
    else return obj.getValue();
  }

  // Operations on diffs

  var dmp = new diff_match_patch();
  function getDiff(a, b) {
    var diff = dmp.diff_main(a, b);
    dmp.diff_cleanupSemantic(diff);
    // The library sometimes leaves in empty parts, which confuse the algorithm
    for (var i = 0; i < diff.length; ++i) {
      var part = diff[i];
      if (!part[1]) {
        diff.splice(i--, 1);
      } else if (i && diff[i - 1][0] == part[0]) {
        diff.splice(i--, 1);
        diff[i][1] += part[1];
      }
    }
    return diff;
  }

  function iterateChunks(diff, f) {
    var startEdit = 0, startOrig = 0;
    var edit = Pos(0, 0), orig = Pos(0, 0);
    for (var i = 0; i < diff.length; ++i) {
      var part = diff[i], tp = part[0];
      if (tp == DIFF_EQUAL) {
        var startOff = startOfLineClean(diff, i) ? 0 : 1;
        var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
        moveOver(edit, part[1], null, orig);
        var endOff = endOfLineClean(diff, i) ? 1 : 0;
        var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
        if (cleanToEdit > cleanFromEdit) {
          if (i) f(startOrig, cleanFromOrig, startEdit, cleanFromEdit);
          startEdit = cleanToEdit; startOrig = cleanToOrig;
        }
      } else {
        moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
      }
    }
    if (startEdit <= edit.line || startOrig <= orig.line)
      f(startOrig, orig.line + 1, startEdit, edit.line + 1);
  }

  function getChunks(diff) {
    var collect = [];
    iterateChunks(diff, function(topOrig, botOrig, topEdit, botEdit) {
      collect.push({origFrom: topOrig, origTo: botOrig,
                    editFrom: topEdit, editTo: botEdit});
    });
    return collect;
  }

  function endOfLineClean(diff, i) {
    if (i == diff.length - 1) return true;
    var next = diff[i + 1][1];
    if (next.length == 1 || next.charCodeAt(0) != 10) return false;
    if (i == diff.length - 2) return true;
    next = diff[i + 2][1];
    return next.length > 1 && next.charCodeAt(0) == 10;
  }

  function startOfLineClean(diff, i) {
    if (i == 0) return true;
    var last = diff[i - 1][1];
    if (last.charCodeAt(last.length - 1) != 10) return false;
    if (i == 1) return true;
    last = diff[i - 2][1];
    return last.charCodeAt(last.length - 1) == 10;
  }

  function chunkBoundariesAround(diff, n, nInEdit) {
    var beforeE, afterE, beforeO, afterO;
    iterateChunks(diff, function(fromOrig, toOrig, fromEdit, toEdit) {
      var fromLocal = nInEdit ? fromEdit : fromOrig;
      var toLocal = nInEdit ? toEdit : toOrig;
      if (afterE == null) {
        if (fromLocal > n) { afterE = fromEdit; afterO = fromOrig; }
        else if (toLocal > n) { afterE = toEdit; afterO = toOrig; }
      }
      if (toLocal <= n) { beforeE = toEdit; beforeO = toOrig; }
      else if (fromLocal <= n) { beforeE = fromEdit; beforeO = fromOrig; }
    });
    return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
  }

  // General utilities

  function elt(tag, content, className, style) {
    var e = document.createElement(tag);
    if (className) e.className = className;
    if (style) e.style.cssText = style;
    if (typeof content == "string") e.appendChild(document.createTextNode(content));
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
    return e;
  }

  function clear(node) {
    for (var count = node.childNodes.length; count > 0; --count)
      node.removeChild(node.firstChild);
  }

  function attrs(elt) {
    for (var i = 1; i < arguments.length; i += 2)
      elt.setAttribute(arguments[i], arguments[i+1]);
  }

  function copyObj(obj, target) {
    if (!target) target = {};
    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
    return target;
  }

  function moveOver(pos, str, copy, other) {
    var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
    for (;;) {
      var nl = str.indexOf("\n", at);
      if (nl == -1) break;
      ++out.line;
      if (other) ++other.line;
      at = nl + 1;
    }
    out.ch = (at ? 0 : out.ch) + (str.length - at);
    if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
    return out;
  }

  function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
  function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
});


text:
package io.hekate.cluster;

import io.hekate.core.HekateException;

/**
 * Error in {@link ClusterService}.
 */
public class ClusterException extends HekateException {
    /** Serial version. */
    private static final long serialVersionUID = 1;

    /**
     * Constructs a new instance.
     *
     * @param message Error message.
     */
    public ClusterException(String message) {
        super(message);
    }

    /**
     * Constructs a new instance.
     *
     * @param message Error message.
     * @param cause Error cause.
     */
    public ClusterException(String message, Throwable cause) {
        super(message, cause);
    }

    @Override
    public HekateException forkFromAsync() {
        return new ClusterException(getMessage(), this);
    }
}


text:
<?php

/**
 * @namespace
 */
namespace ZendTest\Controller\Router\Route;
use Zend\Controller\Router\Route;
use Zend\Controller\Router;
use Zend\Controller;
use Zend\Config;

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Controller
 * @group      Zend_Controller_Router
 */
class ChainTest extends \PHPUnit_Framework_TestCase
{

    public function testChaining()
    {
        $request = new Request('http://localhost/foo/bar');

        $foo = new Route\Route('foo');
        $bar = new Route\Route('bar');

        $chain = $foo->addChain($bar);

        $this->assertType('Zend\Controller\Router\Route\Chain', $chain);
    }

    public function testChainingMatch()
    {
        $chain = new Route\Chain();
        $foo = new Route\Hostname('www.zend.com', array('foo' => 1));
        $bar = new Route\StaticRoute('bar', array('bar' => 2));

        $chain->addChain($foo)->addChain($bar);

        $request = new Request('http://www.zend.com/bla');
        $res = $chain->match($request);

        $this->assertFalse($res);

        $request = new Request('http://www.zend.com/bar');
        $res = $chain->match($request);

        $this->assertEquals(1, $res['foo']);
        $this->assertEquals(2, $res['bar']);
    }

    public function testChainingShortcutMatch()
    {
        $foo = new Route\Hostname('www.zend.com', array('foo' => 1));
        $bar = new Route\StaticRoute('bar', array('bar' => 2, 'controller' => 'foo', 'action' => 'bar'));

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/bar');
        $res = $chain->match($request);

        $this->assertEquals(1, $res['foo']);
        $this->assertEquals(2, $res['bar']);
    }

    public function testChainingMatchFailure()
    {
        $foo = new Route\Hostname('www.zend.com', array('foo' => 1));
        $bar = new Route\StaticRoute('bar', array('bar' => 2, 'controller' => 'foo', 'action' => 'bar'));

        $chain = $foo->addChain($bar);

        $request = new Request('http://nope.zend.com/bar');
        $res = $chain->match($request);

        $this->assertFalse($res);
    }

    public function testChainingVariableOverriding()
    {
        $foo = new Route\Hostname('www.zend.com', array('foo' => 1, 'controller' => 'foo', 'module' => 'foo'));
        $bar = new Route\Route('bar', array('bar' => 2, 'controller' => 'bar', 'action' => 'bar'));

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/bar');
        $res = $chain->match($request);

        $this->assertEquals('foo', $res['module']);
        $this->assertEquals('bar', $res['controller']);
        $this->assertEquals('bar', $res['action']);
    }

    public function testChainingTooLongPath()
    {
        $foo = new Route\StaticRoute('foo', array('foo' => 1));
        $bar = new Route\StaticRoute('bar', array('bar' => 2));

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/foo/bar/baz');
        $res = $chain->match($request);

        $this->assertFalse($res);
    }

    public function testChainingRegex()
    {
        $foo = new Route\Regex('f..', array('foo' => 1));
        $bar = new Route\Regex('b..', array('bar' => 2));

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/foo/bar');
        $res = $chain->match($request);

        $this->assertEquals(1, $res['foo']);
        $this->assertEquals(2, $res['bar']);
    }

    public function testChainingModule()
    {
        $foo = new Route\StaticRoute('foo', array('foo' => 'bar'));
        $bar = new Route\Module();

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/foo/bar/baz/var/val');
        $res = $chain->match($request);

        $this->assertEquals('bar', $res['foo']);
        $this->assertEquals('bar', $res['controller']);
        $this->assertEquals('baz', $res['action']);
        $this->assertEquals('val', $res['var']);
    }

    public function testVariableOmittingWhenPartial()
    {
        $foo = new Route\Route(':foo', array('foo' => 'foo'));
        $bar = new Route\Route(':bar', array('bar' => 'bar'));

        $chain = $foo->addChain($bar);

        $path = $chain->assemble(array());

        $this->assertEquals('foo/', $path);
    }

    public function testVariableUnsettingRoute()
    {
        $foo = new Route\Route(':foo');
        $bar = new Route\Module(array('controller' => 'ctrl', 'action' => 'act'));

        $chain = $foo->addChain($bar);

        $path = $chain->assemble(array('foo' => 'bar', 'baz' => 'bat'));

        $this->assertEquals('bar/ctrl/act/baz/bat', $path);
    }

    public function testVariableUnsettingRegex()
    {
        $foo = new Route\Regex('([^/]+)', array(), array(1 => 'foo'), '%s');
        $bar = new Route\Module(array('controller' => 'ctrl', 'action' => 'act'));

        $chain = $foo->addChain($bar);

        $path = $chain->assemble(array('foo' => 'bar', 'baz' => 'bat'));

        $this->assertEquals('bar/ctrl/act/baz/bat', $path);
    }

    public function testChainingSeparatorOverriding()
    {
        $foo = new Route\StaticRoute('foo', array('foo' => 1));
        $bar = new Route\StaticRoute('bar', array('bar' => 2));
        $baz = new Route\StaticRoute('baz', array('baz' => 3));

        $chain = $foo->addChain($bar, '.');

        $res = $chain->match(new Request('http://localhost/foo.bar'));

        $this->assertType('array', $res);

        $res = $chain->match(new Request('http://localhost/foo/bar'));
        $this->assertEquals(false, $res);

        $chain->addChain($baz, ':');

        $res = $chain->match(new Request('http://localhost/foo.bar:baz'));
        $this->assertType('array', $res);
    }

    public function testI18nChaining()
    {
        $lang = new Route\Route(':lang', array('lang' => 'en'));
        $profile = new Route\Route('user/:id', array('controller' => 'foo', 'action' => 'bar'));

        $chain = $lang->addChain($profile);

        $res = $chain->match(new Request('http://localhost/en/user/1'));

        $this->assertEquals('en', $res['lang']);
        $this->assertEquals('1', $res['id']);
    }

    public function testChainingAssembleWithRoutePlaceholder()
    {
        $chain = new Route\Chain();

        $foo = new Route\Hostname(':account.zend.com');
        $bar = new Route\Route('bar/*');

        $chain->addChain($foo)->addChain($bar);

        $request = new Request('http://foobar.zend.com/bar');
        $res = $chain->match($request);

        $this->assertType('array', $res);
        $this->assertRegexp('#[^a-z0-9]?foobar\.zend\.com/bar/foo/bar#i', $chain->assemble(array('account' => 'foobar', 'foo' => 'bar')));
    }

    public function testChainingAssembleWithStatic()
    {
        $chain = new Route\Chain();

        $foo = new Route\Hostname('www.zend.com', array('foo' => 'foo'));
        $bar = new Route\StaticRoute('bar', array('bar' => 'bar'));

        $chain->addChain($foo)->addChain($bar);

        $request = new Request('http://www.zend.com/bar');
        $res = $chain->match($request);

        $this->assertType('array', $res);
        $this->assertRegexp('#[^a-z0-9]?www\.zend\.com/bar$#i', $chain->assemble());
    }

    public function testChainingAssembleWithRegex()
    {
        $chain = new Route\Chain();

        $foo = new Route\Hostname('www.zend.com', array('foo' => 'foo'));
        $bar = new Route\Regex('bar', array('bar' => 'bar'), array(), 'bar');

        $chain->addChain($foo)->addChain($bar);

        $request = new Request('http://www.zend.com/bar');
        $res = $chain->match($request);

        $this->assertType('array', $res);
        $this->assertRegexp('#[^a-z0-9]?www\.zend\.com/bar$#i', $chain->assemble());
    }

    public function testChainingReuse()
    {
        $foo = new Route\Hostname('www.zend.com', array('foo' => 'foo'));
        $profile = new Route\Route('user/:id', array('controller' => 'prof'));
        $article = new Route\Route('article/:id', array('controller' => 'art', 'action' => 'art'));

        $profileChain = $foo->addChain($profile);
        $articleChain = $foo->addChain($article);

        $request = new Request('http://www.zend.com/user/1');
        $res = $profileChain->match($request);

        $this->assertType('array', $res);
        $this->assertEquals('prof', $res['controller']);

        $request = new Request('http://www.zend.com/article/1');
        $res = $articleChain->match($request);

        $this->assertType('array', $res);
        $this->assertEquals('art', $res['controller']);
        $this->assertEquals('art', $res['action']);
    }

    public function testConfigChaining()
    {
        $routes = array(

            /** Abstract routes */

            'www' => array(
                'type'  => 'Zend\Controller\Router\Route\Hostname',
                'route' => 'www.example.com',
                'abstract' => true
            ),
            'user' => array(
                'type'  => 'Zend\Controller\Router\Route\Hostname',
                'route' => 'user.example.com',
                'abstract' => true
            ),
            'index' => array(
                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                'route' => '',
                'abstract' => true,
                'defaults' => array(
                    'module'     => 'default',
                    'controller' => 'index',
                    'action'     => 'index'
                )
            ),
            'imprint' => array(
                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                'route' => 'imprint',
                'abstract' => true,
                'defaults' => array(
                    'module'     => 'default',
                    'controller' => 'index',
                    'action'     => 'imprint'
                )
            ),
            'profile' => array(
                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                'route' => 'profile',
                'abstract' => true,
                'defaults' => array(
                    'module'     => 'user',
                    'controller' => 'profile',
                    'action'     => 'index'
                )
            ),
            'profile-edit' => array(
                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                'route' => 'profile/edit',
                'abstract' => true,
                'defaults' => array(
                    'module'     => 'user',
                    'controller' => 'profile',
                    'action'     => 'edit'
                )
            ),

            /** Chains */

            'www-index' => array(
                'type'  => 'Zend\Controller\Router\Route\Chain',
                'chain' => 'www, index' // or array('www-subdomain', 'index'); / maybe both
            ),
            'www-imprint' => array(
                'type'  => 'Zend\Controller\Router\Route\Chain',
                'chain' => 'www, imprint'
            ),
            'user-index' => array(
                'type'  => 'Zend\Controller\Router\Route\Chain',
                'chain' => 'user, index'
            ),
            'user-profile' => array(
                'type'  => 'Zend\Controller\Router\Route\Chain',
                'chain' => 'user, profile'
            ),
            'user-profile-edit' => array(
                'type'  => 'Zend\Controller\Router\Route\Chain',
                'chain' => 'user, profile-edit'
            )
        );

        $router = new Router\Rewrite();
        $front = Controller\Front::getInstance();
        $front->resetInstance();
        $front->setDispatcher(new Dispatcher());
        $front->setRequest(new Request());
        $router->setFrontController($front);

        $router->addConfig(new Config\Config($routes));

        $request = new Request('http://user.example.com/profile');
        $token   = $router->route($request);

        $this->assertEquals('user',    $token->getModuleName());
        $this->assertEquals('profile', $token->getControllerName());
        $this->assertEquals('index',   $token->getActionName());

        $request = new Request('http://foo.example.com/imprint');
        $token   = $router->route($request);

        $this->assertEquals('application', $token->getModuleName());
        $this->assertEquals('imprint', $token->getControllerName());
        $this->assertEquals('defact',  $token->getActionName());
    }

    public function testConfigChainingAlternative()
    {
        $routes = array(
            'www' => array(
                'type'  => 'Zend\Controller\Router\Route\Hostname',
                'route' => 'www.example.com',
                'chains' => array(
                    'index' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => '',
                        'defaults' => array(
                            'module'     => 'default',
                            'controller' => 'index',
                            'action'     => 'index'
                        )
                    ),
                    'imprint' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => 'imprint',
                        'defaults' => array(
                            'module'     => 'default',
                            'controller' => 'index',
                            'action'     => 'imprint'
                        )
                    ),
                )
            ),
            'user' => array(
                'type'  => 'Zend\Controller\Router\Route\Hostname',
                'route' => 'user.example.com',
                'chains' => array(
                    'profile' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => 'profile',
                        'defaults' => array(
                            'module'     => 'user',
                            'controller' => 'profile',
                            'action'     => 'index'
                        ),
                        'chains' => array(
                            'standard' => array(
                                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                                'route' => 'standard2',
                                'defaults' => array(
                                    'mode' => 'standard'
                                )
                            ),
                            'detail' => array(
                                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                                'route' => 'detail',
                                'defaults' => array(
                                    'mode' => 'detail'
                                )
                            )
                        )
                    ),
                    'profile-edit' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => 'profile/edit',
                        'defaults' => array(
                            'module'     => 'user',
                            'controller' => 'profile',
                            'action'     => 'edit'
                        )
                    ),
                )
            ),
        );

        $router = $this->_getRouter();
        $router->addConfig(new Config\Config($routes));

        $request = new Request('http://user.example.com/profile/edit');
        $token   = $router->route($request);

        $this->assertEquals('user',    $token->getModuleName());
        $this->assertEquals('profile', $token->getControllerName());
        $this->assertEquals('edit',    $token->getActionName());

        $request = new Request('http://user.example.com/profile/detail');
        $token   = $router->route($request);

        $this->assertEquals('user',    $token->getModuleName());
        $this->assertEquals('profile', $token->getControllerName());
        $this->assertEquals('index',   $token->getActionName());
        $this->assertEquals('detail',  $token->getParam('mode'));

        $request = new Request('http://user.example.com/profile');
        $token   = $router->route($request);
    }

    public function testConfigChainingMixed()
    {
        $routes = array(
            'index' => array(
                'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                'route' => '',
                'defaults' => array(
                    'module'     => 'default',
                    'controller' => 'index',
                    'action'     => 'index'
                )
            ),
            'www' => array(
                'type'  => 'Zend\Controller\Router\Route\Hostname',
                'route' => 'www.example.com',
                'chains' => array(
                    'index',
                    'imprint' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => 'imprint',
                        'defaults' => array(
                            'module'     => 'default',
                            'controller' => 'index',
                            'action'     => 'imprint'
                        )
                    ),
                )
            ),
            'user' => array(
                'type'  => 'Zend\Controller\Router\Route\Hostname',
                'route' => 'user.example.com',
                'chains' => array(
                    'index',
                    'profile' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => 'profile',
                        'defaults' => array(
                            'module'     => 'user',
                            'controller' => 'profile',
                            'action'     => 'index'
                        )
                    ),
                    'profile-edit' => array(
                        'type'  => 'Zend\Controller\Router\Route\StaticRoute',
                        'route' => 'profile/edit',
                        'defaults' => array(
                            'module'     => 'user',
                            'controller' => 'profile',
                            'action'     => 'edit'
                        )
                    ),
                )
            ),
        );

        $router = $this->_getRouter();

        $router->addConfig(new Config\Config($routes));

        $request = new Request('http://user.example.com');
        $token   = $router->route($request);

        $this->assertEquals('default',    $token->getModuleName());
        $this->assertEquals('index', $token->getControllerName());
        $this->assertEquals('index',   $token->getActionName());

        $this->assertType('Zend\Controller\Router\Route\Chain', $router->getRoute('user-profile'));
        $this->assertType('Zend\Controller\Router\Route\Chain', $router->getRoute('www-imprint'));
        $this->assertType('Zend\Controller\Router\Route\Chain', $router->getRoute('www-index'));
        $this->assertType('Zend\Controller\Router\Route\Chain', $router->getRoute('www-index'));
    }

    public function testChainingWorksWithWildcardAndNoParameters()
    {
        $foo = new Route\Hostname('www.zend.com', array('module' => 'simple', 'controller' => 'bar', 'action' => 'bar'));
        $bar = new Route\Route(':controller/:action/*', array('controller' => 'index', 'action' => 'index'));

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/foo/bar/');
        $res = $chain->match($request);

        $this->assertEquals('simple', $res['module']);
        $this->assertEquals('foo', $res['controller']);
        $this->assertEquals('bar', $res['action']);
    }

    public function testChainingWorksWithWildcardAndOneParameter()
    {
        $foo = new Route\Hostname('www.zend.com', array('module' => 'simple', 'controller' => 'foo', 'action' => 'bar'));
        $bar = new Route\Route(':controller/:action/*', array('controller' => 'index', 'action' => 'index'));

        $chain = $foo->addChain($bar);

        $request = new Request('http://www.zend.com/foo/bar/id/12');
        $res = $chain->match($request);

        $this->assertEquals('simple', $res['module']);
        $this->assertEquals('foo', $res['controller']);
        $this->assertEquals('bar', $res['action']);
    }

    protected function _getRouter()
    {
        $router = new Router\Rewrite();
        $front = Controller\Front::getInstance();
        $front->resetInstance();
        $front->setRequest(new Request());
        $router->setFrontController($front);

        return $router;
    }
}

/**
 * Zend_Controller_RouterTest_Dispatcher
 */
class Dispatcher extends \Zend\Controller\Dispatcher\Standard
{
    public function getDefaultControllerName()
    {
        return 'defctrl';
    }

    public function getDefaultAction()
    {
        return 'defact';
    }
}

/**
 * Zend_Controller_Router_ChainTest_Request - request object for router testing
 *
 * @uses Zend_Controller_Request_Interface
 */
class Request extends \Zend\Controller\Request\Http
{
    protected $_host;
    protected $_port;

    public function __construct($uri = null)
    {
        if (null === $uri) {
            $uri = 'http://localhost/foo/bar/baz/2';
        }

        $uri = new \Zend\Uri\Url($uri);
        $this->_host = $uri->getHost();
        $this->_port = $uri->getPort();

        parent::__construct($uri);
    }

    public function getHttpHost() {
        $return = $this->_host;
        if ($this->_port)  $return .= ':' . $this->_port;
        return $return;
    }
}


text:
require 'spec_helper'

describe Smartgen::Engine::Base do
  describe "processing" do
    describe "pre processing" do
      before do
        Smartgen::Engine::Base.pre_processors = []
      end

      context "without pre processors" do
        it "should just return body" do
          body = 'body'
          subject.process(body).should == body
        end
      end

      context "with pre processors" do
        class PreProcessor
          def process(body, metadata=Smartgen::ObjectHash.new) # just needs to respond_to?(:process)
            "<pre_processed>#{body}#{metadata[:name]}</pre_processed>"
          end
        end

        it "should pre process body" do
          Smartgen::Engine::Base.register(PreProcessor.new)

          body = 'body'
          subject.process(body).should == "<pre_processed>#{body}</pre_processed>"
        end

        it "should pre process body with metadata" do
          Smartgen::Engine::Base.register(PreProcessor.new)

          body = 'body'
          subject.process(body, Smartgen::ObjectHash.new({:name => " John"})).should == "<pre_processed>body John</pre_processed>"
        end

        it "should do run pre processors in the order they were registered" do
          class AnotherPreProcessor
            def process(body, metadata={})
              body.gsub(/pre_processed/, 'another')
            end
          end

          Smartgen::Engine::Base.register(PreProcessor.new)
          Smartgen::Engine::Base.register(AnotherPreProcessor.new)

          body = 'body'
          subject.process(body).should == "<another>#{body}</another>"
        end

        context "when pre processor has engine setter" do
          class PreProcessor
            attr_accessor :engine
          end

          it "should set engine on pre processor after initializing the engine" do
            pre_processor = PreProcessor.new
            Smartgen::Engine::Base.register(pre_processor)
            subject
            pre_processor.engine.should == subject
          end
        end

        context "when forcing processing without pre processors" do
          it "should return just body" do
            subject.process_without_pre_processors('some body').should == 'some body'
          end
        end

        context "of a subclass" do
          class OtherPreProcessor
            def process(body, metadata={})
              "<another>#{body}</another>"
            end
          end

          class MyCustomEngine < Smartgen::Engine::Base
          end

          it "should pre process body with different processor of ancestor" do
            Smartgen::Engine::Base.register(PreProcessor.new)
            MyCustomEngine.register(OtherPreProcessor.new)

            body = 'body'
            MyCustomEngine.new.process(body).should == "<another>#{body}</another>"
          end
        end
      end
    end
  end
end


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Dos.ORM.SqlServer9.SqlServer9Provider" />
<meta name="generator" content="DocsBuilder" />
<title>SqlServer9Provider 类 (Dos.ORM.SqlServer9)</title>

<link rel="stylesheet" type="text/css" href="../../../styles/zebra.css" />

SqlServer9Provider 类

        System.Object

          Dos.ORM.DbProvider

            Dos.ORM.SqlServer.SqlServerProvider

              Dos.ORM.SqlServer9.SqlServer9Provider

Sql Server 2005

 命名空间:Dos.ORM.SqlServer9

  程序集:Dos.ORM(在 Dos.ORM.dll 中)

public class SqlServer9Provider : SqlServerProvider

字段

          名称
          说明

            dbConnStrBuilder

The db connection string builder

(继承自 DbProvider。)

            dbProviderFactory

The db provider factory.

(继承自 DbProvider。)

            leftToken

【

(继承自 DbProvider。)

            paramPrefixToken

参数前缀

(继承自 DbProvider。)

            rightToken

】

(继承自 DbProvider。)

属性

        名称
        说明

            CacheConfig

缓存配置

(继承自 DbProvider。)

            ConnectionString

Gets the connection string.

(继承自 DbProvider。)

            ConnectionStringsName

ConnectionStrings 节点名称

(继承自 DbProvider。)

            DatabaseType

ConnectionStrings 节点名称

(继承自 DbProvider。)

            DbProviderFactory

Gets the db provider factory.

(继承自 DbProvider。)

            EntitiesCache

实体缓存

(继承自 DbProvider。)

            LeftToken

Gets the left token of table name or column name.

(继承自 DbProvider。)

            ParamPrefix

Gets the param prefix.

(继承自 DbProvider。)

            RightToken

Gets the right token of table name or column name.

(继承自 DbProvider。)

            RowAutoID

自增长字段查询语句

(继承自 DbProvider。)

            SupportBatch

是否支持批量sql提交

(继承自 DbProvider。)

方法

        名称
        说明

            BuildParameterName(String)

Builds the name of the parameter.

(继承自 SqlServerProvider。)

            BuildTableName(String)

Builds the name of the table.

(继承自 DbProvider。)

            CreatePageFromSection(FromSection, Int32, Int32)

创建分页查询

(重写 DbProvider.CreatePageFromSection(FromSection, Int32, Int32)。)

SqlServer9Provider.CreatePageFromSection(FromSection, Int32, Int32) 方法

创建分页查询

public override FromSection CreatePageFromSection(FromSection fromSection, int startIndex, int endIndex)

参数

fromSection

                          类型:Dos.ORM.FromSection

startIndex

                          类型:System.Int32

endIndex

                          类型:System.Int32

返回值

                      类型:Dos.ORM.FromSection

            PrepareCommand(DbCommand)

调整DbCommand命令

(继承自 DbProvider。)

Generated by www.ITdos.com


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

using System;
using System.IO;
using System.Text;
using DiscUtils.Streams;

namespace DiscUtils.Iso9660
{
    internal abstract class SystemUseEntry
    {
        public string Name;
        public byte Version;

        public static SystemUseEntry Parse(byte[] data, int offset, Encoding encoding, SuspExtension extension,
                                           out byte length)
        {
            if (data[offset] == 0)
            {
                // A zero-byte here is invalid and indicates an incorrectly written SUSP field.
                // Return null to indicate to the caller that SUSP parsing is terminated.
                length = 0;

                return null;
            }

            string name = EndianUtilities.BytesToString(data, offset, 2);
            length = data[offset + 2];
            byte version = data[offset + 3];

            switch (name)
            {
                case "CE":
                    return new ContinuationSystemUseEntry(name, length, version, data, offset);

                case "PD":
                    return new PaddingSystemUseEntry(name, length, version);

                case "SP":
                    return new SharingProtocolSystemUseEntry(name, length, version, data, offset);

                case "ST":
                    // Termination entry. There's no point in storing or validating this one.
                    // Return null to indicate to the caller that SUSP parsing is terminated.
                    return null;

                case "ER":
                    return new ExtensionSystemUseEntry(name, length, version, data, offset, encoding);

                case "ES":
                    return new ExtensionSelectSystemUseEntry(name, length, version, data, offset);

                case "AA":
                case "AB":
                case "AS":
                    // Placeholder support for Apple and Amiga extension records.
                    return new GenericSystemUseEntry(name, length, version, data, offset);

                default:
                    if (extension == null)
                    {
                        return new GenericSystemUseEntry(name, length, version, data, offset);
                    }

                    return extension.Parse(name, length, version, data, offset, encoding);
            }
        }

        protected void CheckAndSetCommonProperties(string name, byte length, byte version, byte minLength, byte maxVersion)
        {
            if (length < minLength)
            {
                throw new InvalidDataException("Invalid SUSP " + Name + " entry - too short, only " + length + " bytes");
            }

            if (version > maxVersion || version == 0)
            {
                throw new NotSupportedException("Unknown SUSP " + Name + " entry version: " + version);
            }

            Name = name;
            Version = version;
        }
    }
}


text:
import pytest

from webdriver.error import NoSuchWindowException

from tests.perform_actions.support.refine import get_events
from tests.support.asserts import assert_move_to_coordinates
from tests.support.helpers import filter_dict

def test_null_response_value(session, wheel_chain):
    value = wheel_chain.scroll(0, 0, 0, 10).perform()
    assert value is None

def test_no_top_browsing_context(session, closed_window, wheel_chain):
    with pytest.raises(NoSuchWindowException):
        wheel_chain.scroll(0, 0, 0, 10).perform()

def test_no_browsing_context(session, closed_window, wheel_chain):
    with pytest.raises(NoSuchWindowException):
        wheel_chain.scroll(0, 0, 0, 10).perform()

def test_wheel_scroll(session, test_actions_scroll_page, wheel_chain):
    session.execute_script("document.scrollingElement.scrollTop = 0")

    outer = session.find.css("#outer", all=False)
    wheel_chain.scroll(0, 0, 5, 10, origin=outer).perform()
    events = get_events(session)
    assert len(events) == 1
    assert events[0]["type"] == "wheel"
    assert events[0]["deltaX"] >= 5
    assert events[0]["deltaY"] >= 10
    assert events[0]["deltaZ"] == 0
    assert events[0]["target"] == "outer"

def test_wheel_scroll_overflow(session, test_actions_scroll_page, wheel_chain):
    session.execute_script("document.scrollingElement.scrollTop = 0")

    scrollable = session.find.css("#scrollable", all=False)
    wheel_chain.scroll(0, 0, 5, 10, origin=scrollable).perform()
    events = get_events(session)
    assert len(events) == 1
    assert events[0]["type"] == "wheel"
    assert events[0]["deltaX"] >= 5
    assert events[0]["deltaY"] >= 10
    assert events[0]["deltaZ"] == 0
    assert events[0]["target"] == "scrollContent"

def test_wheel_scroll_iframe(session, test_actions_scroll_page, wheel_chain):
    session.execute_script("document.scrollingElement.scrollTop = 0")

    subframe = session.find.css("#subframe", all=False)
    wheel_chain.scroll(0, 0, 5, 10, origin=subframe).perform()
    events = get_events(session)
    assert len(events) == 1
    assert events[0]["type"] == "wheel"
    assert events[0]["deltaX"] >= 5
    assert events[0]["deltaY"] >= 10
    assert events[0]["deltaZ"] == 0
    assert events[0]["target"] == "iframeContent"


text:
# Autofac.Test.CodeGen

This test project uses the [Verify](https://github.com/VerifyTests/Verify) library to perform snapshot testing of the output of our `Autofac.CodeGen` source generator.

Each time the tests run, the set of generated files will be compared with the committed-to-source-control `*.verified.cs` files in the `Snapshots` folder.

If any of the generated files differ from the saved `verified` file of the same name, the test will fail.

When this happens a file will appear in the `Snapshots` folder with the `*.received.cs` suffix with the new file content. In Visual Studio, your IDE will also open a diff window between the two versions.

> The .gitignore in the Snapshots folder exludes the received files from being saved in git, we don't want to store those.

If you make changes to the generator, check that the outputted file is correct, and once you've tested the generated code, you should "accept" the new version by:

- Deleting the existing `verified` file.
- Renaming the new `received` file to be the `verified` one.

That will then cause the tests to pass, and the new verified files should be committed to source control.


text:
package org.gearvrf.sixaxissensortest;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class Gyroscope implements SensorEventListener {

    private float mMagnitude = 0.0f;

    public Gyroscope(Context context) {
        SensorManager sensorManager = (SensorManager) context
                .getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

        sensorManager.registerListener(this, sensor,
                SensorManager.SENSOR_DELAY_FASTEST);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        mMagnitude = (float) Math.sqrt(event.values[0] * event.values[0]
                + event.values[1] * event.values[1] + event.values[2]
                * event.values[2])
                * 180.0f / (float) Math.PI;
    }

    public float getMagnitude() {
        return mMagnitude;
    }
}


text:
package org.neo4j.cluster.protocol.heartbeat;

import java.net.URI;

import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.com.message.Message;
import org.neo4j.cluster.com.message.MessageHolder;
import org.neo4j.cluster.protocol.cluster.ClusterListener;

/**
 * When an instance joins a cluster, setup a heartbeat for it
 */
public class HeartbeatJoinListener extends ClusterListener.Adapter
{
    private final MessageHolder outgoing;

    public HeartbeatJoinListener( MessageHolder outgoing )
    {
        this.outgoing = outgoing;
    }

    @Override
    public void joinedCluster( InstanceId member, URI atUri )
    {
        outgoing.offer( Message.internal( HeartbeatMessage.reset_send_heartbeat, member ) );
    }
}


text:
package org.jcodec.codecs.h264.io.model;

/**
 * This class is part of JCodec ( www.jcodec.org )
 * This software is distributed under FreeBSD License
 *
 * @author The JCodec project
 */
public class VUIParameters {

    public static class BitstreamRestriction {
        // motion_vectors_over_pic_boundaries_flag
        public boolean motionVectorsOverPicBoundariesFlag;
        // max_bytes_per_pic_denom
        public int maxBytesPerPicDenom;
        // max_bits_per_mb_denom
        public int maxBitsPerMbDenom;
        // log2_max_mv_length_horizontal
        public int log2MaxMvLengthHorizontal;
        // log2_max_mv_length_vertical
        public int log2MaxMvLengthVertical;
        // num_reorder_frames
        public int numReorderFrames;
        // max_dec_frame_buffering
        public int maxDecFrameBuffering;
    }

    // boolean aspect_ratio_info_present_flag
    public boolean aspectRatioInfoPresentFlag;
    // int sar_width
    public int sarWidth;
    // int sar_height
    public int sarHeight;
    // overscan_info_present_flag
    public boolean overscanInfoPresentFlag;
    // overscan_appropriate_flag;
    public boolean overscanAppropriateFlag;
    // video_signal_type_present_flag;
    public boolean videoSignalTypePresentFlag;
    // video_format
    public int videoFormat;
    // video_full_range_flag
    public boolean videoFullRangeFlag;
    // colour_description_present_flag
    public boolean colourDescriptionPresentFlag;
    // colour_primaries
    public int colourPrimaries;
    // transfer_characteristics
    public int transferCharacteristics;
    // matrix_coefficients
    public int matrixCoefficients;
    // chroma_loc_info_present_flag
    public boolean chromaLocInfoPresentFlag;
    // chroma_sample_loc_type_top_field
    public int chromaSampleLocTypeTopField;
    // chroma_sample_loc_type_bottom_field
    public int chromaSampleLocTypeBottomField;
    // timing_info_present_flag
    public boolean timingInfoPresentFlag;
    // num_units_in_tick
    public int numUnitsInTick;
    // time_scale
    public int timeScale;
    // fixed_frame_rate_flag
    public boolean fixedFrameRateFlag;
    // low_delay_hrd_flag
    public boolean lowDelayHrdFlag;
    // pic_struct_present_flag
    public boolean picStructPresentFlag;
    public HRDParameters nalHRDParams;
    public HRDParameters vclHRDParams;

    public BitstreamRestriction bitstreamRestriction;
    // aspect_ratio
    public AspectRatio aspectRatio;

}


text:
<!doctype html>

    <title>Code coverage report for lib/waterline/adapter/compoundQueries.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / lib/waterline/adapter/ compoundQueries.js

        72.73%
        Statements
        16/22

        41.67%
        Branches
        5/12

        100%
        Functions
        2/2

        78.95%
        Lines
        15/19

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

3×
3×
3×

3×

15×
15×

15×

15×
15×

15×

15×

15×
15×
15×

13×

/**
 * Compound Queries Adapter Normalization
 */

var _ = require('lodash');
var normalize = require('../utils/normalize');
var hasOwnProperty = require('../utils/helpers').object.hasOwnProperty;

module.exports = {

  findOrCreate: function(criteria, values, cb, metaContainer) {
    var self = this;
    var connName,
        adapter;

    // If no values were specified, use criteria
    Iif (!values) values = criteria.where ? criteria.where : criteria;

    // Normalize Arguments
    criteria = normalize.criteria(criteria);
    cb = normalize.callback(cb);

    // Build Default Error Message
    var err = 'No find() or create() method defined in adapter!';

    // Custom user adapter behavior
    Iif (hasOwnProperty(this.dictionary, 'findOrCreate')) {
      connName = this.dictionary.findOrCreate;
      adapter = this.connections[connName]._adapter;

      if (hasOwnProperty(adapter, 'findOrCreate')) {
        return adapter.findOrCreate(connName, this.collection, values, cb, metaContainer);
      }
    }

    // Default behavior
    // WARNING: Not transactional!  (unless your data adapter is)
    this.findOne(criteria, function(err, result) {
      Iif (err) return cb(err);
      if (result) return cb(null, result[0]);

      self.create(values, cb, metaContainer);
    }, metaContainer);
  }

};

  Code coverage
  generated by istanbul at Fri Mar 18 2016 12:26:23 GMT-0500 (CDT)


text:
package com.camunda.bpm.demo.bpmn_xpath.nonarquillian;

import org.apache.ibatis.logging.LogFactory;
import org.camunda.bpm.engine.impl.util.LogUtil;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.mock.Mocks;
import org.camunda.spin.impl.xml.dom.SpinXPathFactoryInjector;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import com.camunda.bpm.demo.bpmn_xpath.ArchiveServiceDelegateMock;
import com.camunda.bpm.demo.bpmn_xpath.LoggerDelegate;

import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.*;
import static org.junit.Assert.*;

/**
 * Test case starting an in-memory database-backed Process Engine.
 */
public class InMemoryH2Test {

  @Rule
  public ProcessEngineRule rule = new ProcessEngineRule();

  private static final String PROCESS_DEFINITION_KEY = "handle-invoice";
  private static final String BPMN_FILE = "4_Trisotech_handle-invoice.bpmn";

  // enable more detailed logging
  static {
//    LogUtil.readJavaUtilLoggingConfigFromClasspath(); // process engine
//    LogFactory.useJdkLogging(); // MyBatis
  }

  @Before
  public void setup() {
    init(rule.getProcessEngine());
  }

  /**
   * Just tests if the process definition is deployable.
   */
  @Test
  @Deployment(resources = {BPMN_FILE, "xsdTypes.xsd"})
  public void testParsingAndDeployment() {
    // nothing is done here, as we just want to check for exceptions during deployment
  }

  @Test
  @Deployment(resources = {BPMN_FILE, "xsdTypes.xsd"})
  public void testExecution() {
//    SpinXPathFactoryInjector.injectBpmnXPathFunctionResolver();
    ArchiveServiceDelegateMock archiveService = new ArchiveServiceDelegateMock();
    Mocks.register("archiveService", archiveService);

    ProcessInstance processInstance = runtimeService().startProcessInstanceByKey(PROCESS_DEFINITION_KEY);

    assertThat(processInstance)
      .isStarted()
      .task("assignApprover")
      .isAssignedTo("demo");

    complete(task(), withVariables("approver", "john"));

    assertThat(task("approveInvoice")).isAssignedTo("john");

    complete(task(), withVariables("approved", false));

    assertThat(task("reviewInvoice")).isAssignedTo("demo");

    complete(task(), withVariables("clarified", "yes"));

    assertThat(task("approveInvoice")).isAssignedTo("john");

    complete(task(), withVariables("approved", true));

    assertThat(task("prepareBankTransfer")).hasCandidateGroup("accounting");

    claim(task(), "Jane");

    complete(task());

    assertTrue(archiveService.isCalled());

    assertThat(processInstance).isEnded();
  }

}


text:
<!doctype html>

      <meta charset="utf-8">
      <link rel="stylesheet" href="css/virtual-led.css">

      <title>Sample Dell LED API - Virtual LED</title>


text:
// Jade.go - template engine. Package implements Jade-lang templates for generating Go html/template output.
package jade

import (
	"io/ioutil"
	"path/filepath"
)

/*
Parse parses the template definition string to construct a representation of the template for execution.

Trivial usage:

	package main

	import (
		"fmt"
		"github.com/Joker/jade"
	)

	func main() {
		tpl, err := jade.Parse("tpl_name", "doctype 5: html: body: p Hello world!")
		if err != nil {
			fmt.Printf("Parse error: %v", err)
			return
		}

		fmt.Printf( "Output:\n\n%s", tpl  )
	}

Output:

	<!DOCTYPE html>

Hello world!

*/
func Parse(name, text string) (string, error) {
	outTpl, err := newTree(name).Parse(text, LeftDelim, RightDelim, make(map[string]*tree))
	if err != nil {
		return "", err
	}
	return outTpl.String(), nil
}

// ParseFile parse the jade template file in given filename
func ParseFile(filename string) (string, error) {
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	s := string(b)
	name := filepath.Base(filename)

	return Parse(name, s)
}

func (t *tree) String() string {
	return t.Root.String()
}


text:
@protocol OrgHamcrestMatcher < OrgHamcrestSelfDescribing, NSObject, JavaObject >
- (jboolean)matchesWithId:(id)item;

- (void)_dont_implement_Matcher___instead_extend_BaseMatcher_;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgHamcrestMatcher)

J2OBJC_TYPE_LITERAL_HEADER(OrgHamcrestMatcher)

#endif // _OrgHamcrestMatcher_H_


text:
package nom.bdezonia.zorbage.algorithm;

import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.Ordered;
import nom.bdezonia.zorbage.algebra.Roots;
import nom.bdezonia.zorbage.algebra.Unity;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;

/**
 *
 * @author Barry DeZonia
 *
 */
public class ApproxStdDev {

	// do not instantiate

	private ApproxStdDev() {}

	/**
	 * ApproxStdDev gives an approximate estimate of the standard deviation
	 * of a list of numbers. It is approximate in the sense that adjustments
	 * are made to avoid overall data loss at the expense of absolute
	 * accuracy. If you need absolute accuracy use the {@link StdDev}
	 * algorithm using {@link HighPrecisionMember}s to contain the results.
	 *
	 * @param storage
	 * @param result
	 */
	public static <T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Unity<U> & Invertible<U> & Roots<U> & Ordered<U>, U>
		void compute(T alg, IndexedDataSource<U> storage, U result)
	{
		ApproxVariance.compute(alg, storage, result);
		alg.sqrt().call(result, result);
	}
}