text:
""" a panflute filter to format elements types
that may contain reference labels, i.e. Math, Image and Table.

The :py:mod:`ipypublish.filters_pandoc.prepare_labels` filter should be run
first to access the functionality below:

If the parent of the element is a Span (or Div for Table), with a class
labelled-Math/labelled-Image/labelled-Table,
then the label of the element will be span.identifier, and
the attributes and classes from this Span will be used to inform the format.

Additionally, for HTML, if a '$$references' key is available in the metadata,
this will be used to add a suffix to the element captions,
with the number of the element.

Finally, if main() is called with strip_spans = True (the default),
The Span/Div elements with classes labelled-Math/labelled-Image/labelled-Table
will be stripped from the document

"""
# TODO format headers with section labels
# (see ipysphinx.transforms.CreateNotebookSectionAnchors)
import json
import re

from panflute import Element, Doc, Span, Div, Math, Image, Table  # noqa: F401
import panflute as pf

from ipypublish.filters_pandoc.utils import convert_units, convert_attributes
from ipypublish.filters_pandoc.prepare_labels import (
    LABELLED_IMAGE_CLASS,
    LABELLED_MATH_CLASS,
    LABELLED_TABLE_CLASS,
)

try:
    from textwrap import indent
except ImportError:  # added in python 3.3

    def indent(text, prefix):
        return "".join(prefix + line for line in text.splitlines(True))

LATEX_FIG_LABELLED = """\\begin{{figure}}[{options}]
\\hypertarget{{{label}}}{{%
\\begin{{center}}
\\adjustimage{{max size={{0.9\\linewidth}}{{0.9\\paperheight}},{size}}}{{{path}}}
\\end{{center}}
\\caption{{{caption}}}\\label{{{label}}}
}}
\\end{{figure}}"""  # noqa: E501

LATEX_FIG_UNLABELLED = """\\begin{{figure}}[{options}]
\\begin{{center}}
\\adjustimage{{max size={{0.9\\linewidth}}{{0.9\\paperheight}},{size}}}{{{path}}}
\\end{{center}}
\\caption{{{caption}}}
\\end{{figure}}"""  # noqa: E501

MATH_ENVS = (
    "equation",
    "align",
    "alignat",
    "eqnarray",
    "multline",
    "gather",
    "flalign",
    "dmath",
)

def format_math(math, doc):
    # type: (Math, Doc) -> Element
    """
    originally adapted from:
    `pandoc-eqnos <https://github.com/tomduck/pandoc-eqnos/>`_
    """
    if not isinstance(math, pf.Math):
        return None

    if math.format != "DisplayMath":
        return None

    # test if the math text is already wrapped in an environment
    regex = re.compile(
        r"\\begin\{{((?:{0})\*?)\}}(.*)\\end\{{((?:{0})\*?)\}}".format(
            "|".join(MATH_ENVS)
        ),
        re.DOTALL,
    )
    wrap_match = regex.match(math.text)

    env = None
    label = None
    if isinstance(math.parent, pf.Span) and LABELLED_MATH_CLASS in math.parent.classes:
        span = math.parent
        numbered = "*" if "unnumbered" in span.classes else ""
        env = span.attributes.get("env", "equation") + numbered
        label = span.identifier

    if doc.format in ("tex", "latex"):
        if wrap_match:
            # TODO edge case where a label has been specified, but the math is already wrapped
            tex = math.text
        else:
            tex = "\\begin{{{0}}}{1}\\label{{{2}}}\\end{{{0}}}".format(
                env or "equation", math.text, label or ""
            )
        return pf.RawInline(tex, format="tex")

    elif doc.format in ("rst"):
        if env:
            tex = indent("\\begin{{{0}}}{1}\\end{{{0}}}".format(env, math.text), "   ")
        else:
            tex = indent(math.text.strip(), "   ")
        rst = "\n\n.. math::\n"
        if wrap_match or env:
            rst += "   :nowrap:\n"
        if label:
            rst += "   :label: {}\n".format(label)
        rst += "\n{}\n\n".format(tex)
        return pf.RawInline(rst, format="rst")

    elif doc.format in ("html", "html5"):
        # new_span = pf.Span(anchor_start, math, anchor_end)
        # TODO add formatting
        # TODO name by count
        if label:
            if not wrap_match:
                math.text = "\\begin{{{0}}}{1}\\end{{{0}}}".format(
                    env or "equation", math.text
                )
            return _wrap_in_anchor(math, label)
        else:
            return None

def format_image(image, doc):
    # type: (Image, Doc) -> Element
    """
    originally adapted from:
    `pandoc-fignos <https://github.com/tomduck/pandoc-fignos/>`_
    """
    if not isinstance(image, pf.Image):
        return None

    span = None
    if (
        isinstance(image.parent, pf.Span)
        and LABELLED_IMAGE_CLASS in image.parent.classes
    ):
        span = image.parent

    if span is not None:
        identifier = span.identifier
        attributes = span.attributes
        #  classes = span.classes
    else:
        identifier = image.identifier
        attributes = image.attributes
        # classes = image.classes

    if doc.format in ("tex", "latex"):
        new_doc = Doc(pf.Para(*image.content))
        new_doc.api_version = doc.api_version
        if image.content:
            caption = pf.run_pandoc(
                json.dumps(new_doc.to_json()), args=["-f", "json", "-t", "latex"]
            ).strip()
        else:
            caption = ""

        options = attributes.get("placement", "")
        size = ""  # max width set as 0.9\linewidth
        if "width" in attributes:
            width = convert_units(attributes["width"], "fraction")
            size = "width={0}\\linewidth".format(width)
        elif "height" in attributes:
            height = convert_units(attributes["height"], "fraction")
            size = "height={0}\\paperheight".format(height)

        if identifier:
            latex = LATEX_FIG_LABELLED.format(
                label=identifier,
                options=options,
                path=image.url,
                caption=caption,
                size=size,
            )
        else:
            latex = LATEX_FIG_UNLABELLED.format(
                options=options, path=image.url, caption=caption, size=size
            )

        return pf.RawInline(latex, format="tex")

    elif doc.format in ("rst",):
        if not image.content.list:
            # If the container is empty, then pandoc will assign an iterative
            # reference identifier to it (image0, image1).
            # However, this iterator restarts for each markdown cell,
            # which can lead to reference clashes.
            # Therefore we specifically assign the identifier here, as its url
            # TODO does this identifier need to be sanitized?
            # (it works fine in the tests)
            identifier = image.url
            image.content = pf.ListContainer(pf.Str(str(identifier)))

        return image
        # TODO formatting and span identifier (convert width/height to %)

    elif doc.format in ("html", "html5"):
        if identifier:
            return _wrap_in_anchor(image, identifier)
        else:
            return image
        # TODO formatting, name by count
    else:
        return None

def format_table(table, doc):
    # type: (Table, Doc) -> Element
    """
    originally adapted from:
    `pandoc-tablenos <https://github.com/tomduck/pandoc-tablenos>`_
    """
    if not isinstance(table, pf.Table):
        return None

    div = None  # type: pf.Div
    if (
        isinstance(table.parent, pf.Div)
        and LABELLED_TABLE_CLASS in table.parent.classes
    ):
        div = table.parent

    if div is None:
        return None

    attributes = convert_attributes(div.attributes)

    if "align" in div.attributes:
        align_text = attributes["align"]
        align = [
            {"l": "AlignLeft", "r": "AlignRight", "c": "AlignCenter"}.get(a, None)
            for a in align_text
        ]
        if None in align:
            raise ValueError(
                "table '{0}' alignment must contain only l,r,c:"
                " {1}".format(div.identifier, align_text)
            )
        table.alignment = align
        attributes["align"] = align

    if "widths" in div.attributes:
        widths = attributes["widths"]
        try:
            widths = [float(w) for w in widths]
        except Exception:
            raise ValueError(
                "table '{0}' widths must be a list of numbers:"
                " {1}".format(div.identifier, widths)
            )
        table.width = widths
        attributes["widths"] = widths

    if doc.format in ("tex", "latex"):
        # TODO placement
        table.caption.append(
            pf.RawInline("\\label{{{0}}}".format(div.identifier), format="tex")
        )
        return table

    if doc.format in ("rst",):
        # pandoc 2.6 doesn't output table options
        if attributes:
            tbl_doc = pf.Doc(table)
            tbl_doc.api_version = doc.api_version
            tbl_str = pf.convert_text(
                tbl_doc, input_format="panflute", output_format="rst"
            )

            tbl_lines = tbl_str.splitlines()
            if tbl_lines[1].strip() == "":
                tbl_lines.insert(1, "   :align: center")
                if "widths" in attributes:
                    # in rst widths must be integers
                    widths = " ".join([str(int(w * 10)) for w in table.width])
                    tbl_lines.insert(1, "   :widths: {}".format(widths))
            # TODO rst column alignment, see
            # https://cloud-sptheme.readthedocs.io/en/latest/lib/cloud_sptheme.ext.table_styling.html

            return [
                pf.Para(
                    pf.RawInline(".. _`{0}`:".format(div.identifier), format="rst")
                ),
                pf.RawBlock("\n".join(tbl_lines) + "\n\n", format=doc.format),
            ]

        return [
            pf.Para(pf.RawInline(".. _`{0}`:".format(div.identifier), format="rst")),
            table,
        ]

    if doc.format in ("html", "html5"):
        return _wrap_in_anchor(table, div.identifier, inline=False)
        # TODO formatting, name by count

def strip_labelled_spans(element, doc):
    # type: (Span, Doc) -> Element

    if isinstance(element, pf.Span) and set(element.classes).intersection(
        [LABELLED_IMAGE_CLASS, LABELLED_MATH_CLASS]
    ):
        return list(element.content)

    if isinstance(element, pf.Div) and set(element.classes).intersection(
        [LABELLED_TABLE_CLASS]
    ):
        return list(element.content)

def _wrap_in_anchor(element, label, inline=True):
    """ wrap element in html anchors

    according to https://stackoverflow.com/a/1828032/5033292
    can wrap inline and block elements in anchor in html5
    """
    if inline:
        raw = pf.RawInline
    else:
        raw = pf.RawBlock
    anchor_start = raw(
        ''.format(label), format="html"
    )
    anchor_end = raw("", format="html")
    return [anchor_start, element, anchor_end]

def prepare(doc):
    # type: (Doc) -> None
    pass

def finalize(doc):
    # type: (Doc) -> None
    pass

def main(doc=None, strip_spans=True):
    # type: (Doc, bool) -> None
    to_run = [format_math, format_image, format_table]
    if strip_spans:
        to_run.append(strip_labelled_spans)
    return pf.run_filters(to_run, prepare, finalize, doc=doc)

if __name__ == "__main__":
    main()


text:
<!DOCTYPE html>
<title>Tests that a degenerate cues without separating blank lines are parsed correctly.</title>
<script src="track-helpers.js"></script>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>
check_cues_from_track("captions-webvtt/tc032-degenerate-cues.vtt", function(track) {
    var expected = [
        { startTime: 0, endTime: 1, text: "" },
        { startTime: 2, endTime: 3, text: "" },
        { startTime: 4, endTime: 5, text: "" }
    ];

    assert_cues_match(track.cues, expected);
});
</script>

redpajama_set_name: RedPajamaGithub


text:
module Tr8n
  class LanguageCasesController < Tr8n::BaseController

    before_filter :validate_current_translator
    before_filter :validate_language_management, :only => [:index]

    # used by a client app
    def index
      @maps = Tr8n::LanguageCaseValueMap.where("language_id = ? and (reported is null or reported = ?)", tr8n_current_language.id, false)
      @maps = @maps.where("keyword like ?", "%#{params[:search]}%") unless params[:search].blank?
      @maps = @maps.order("updated_at desc").page(page).per(per_page)
    end

    def manager
      @lcase = Tr8n::LanguageCase.by_id(params[:case_id]) unless params[:case_id].blank?
      @rule = Tr8n::LanguageCaseRule.by_id(params[:rule_id]) unless params[:rule_id].blank?

      @map = Tr8n::LanguageCaseValueMap.by_language_and_keyword(tr8n_current_language, params[:case_key])
      @map ||= Tr8n::LanguageCaseValueMap.new(:language => tr8n_current_language, :translator => tr8n_current_translator, :keyword => params[:case_key])

      @mode = params[:mode] || (@map.id.nil? ? 'rules_based' : (@map.gender_based? ? 'gender_based' : 'gender_neutral'))

      if @mode == 'rules_based' and params[:reset] and @map.id
        @map.destroy
      end

      render :layout => false
    end

    def update_value_map
      map = Tr8n::LanguageCaseValueMap.find_by_id(params[:map_id]) unless params[:map_id].blank?
      map ||= Tr8n::LanguageCaseValueMap.new(:language => tr8n_current_language, :reported => false)
      map.keyword = params[:case_key]
      map.map = params[:map][:map]
      map.save_with_log!(tr8n_current_translator)

      redirect_to(:action => :manager, :mode => :done)
    end

    def delete_value_map
      map = Tr8n::LanguageCaseValueMap.find_by_id(params[:map_id]) if params[:map_id]
      map.destroy_with_log!(tr8n_current_translator) if map

      redirect_to_source
    end

    def report_value_map
      map = Tr8n::LanguageCaseValueMap.find_by_id(params[:map_id]) unless params[:map_id].blank?
      map.report_with_log!(tr8n_current_translator) if map

      redirect_to_source
    end

  end
end


text:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class ChatClient {

	private static final String ADDRESS = "localhost";
	private static final int PORT = 1234;

	public static void main(String[] args) throws Exception {
		Socket socket = new Socket(InetAddress.getByName(ADDRESS), PORT);
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

			BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
			try {
				System.out.println(in.readLine());
				String username = myInput.readLine();
				out.println(username);
				System.out.println(in.readLine());

			    while(true) {
			    	String messageToSend = myInput.readLine();
			    	out.println(messageToSend);
			    }
		    } catch (IOException e) {
		    	e.printStackTrace();
		    }
		} finally {
		    socket.close();
		}
	}

}


text:
<?php

namespace MyBuilder\Cronos\Tests\Formatter;

use MyBuilder\Cronos\Formatter\Cron;
use PHPUnit\Framework\TestCase;

class CronTest extends TestCase
{
    private $cron;

    protected function setUp(): void
    {
        $this->cron = new Cron;
    }

    /**
     * @test
     */
    public function shouldBuildConfiguration(): void
    {
        $this->cron
            ->header()
                ->setPath('path')
                ->setHome('home')
                ->setMailto('test@example.com')
                ->setShell('shell')
                ->setContentType('text')
                ->setContentTransferEncoding('utf8')
                ->setTimezone('Europe/Paris')
            ->end()
            ->comment('This is a command!')
            ->job('/bin/bash command --env=dev')
                ->setMinute(1)
                ->setHour(2)
                ->setDayOfMonth(3)
                ->setMonth(4)
                ->setDayOfWeek(5)
                ->setStandardOutFile('log')
                ->appendStandardErrorToFile('error')
            ->end()
            ->comment('This is another command!')
            ->job('/bin/php command2 --env=prod')
                ->setMinute('/5')
                ->setDayOfWeek('sun')
                ->suppressOutput()
            ->end();

        $expected = <<<EXP
PATH=path
MAILTO=test@example.com
HOME=home
SHELL=shell
CONTENT_TYPE=text
CONTENT_TRANSFER_ENCODING=utf8
CRON_TZ=Europe/Paris

#This is a command!
1    2    3    4    5    /bin/bash command --env=dev > log 2>> error

#This is another command!
*/5  *    *    *    sun  /bin/php command2 --env=prod > /dev/null 2> /dev/null

EXP;

        $this->assertEquals($expected, $this->cron->format());
    }
}


text:
class SignatureEnvelopeDocumentsResult
  attr_accessor :envelope_id, :documents

  # :internal => :external
  def self.attribute_map
  {
      :envelope_id => :envelopeId, :documents => :documents

  }
  end

  def initialize(attributes = {})
    # Morph attribute keys into undescored rubyish style
    if attributes.to_s != ""

      if SignatureEnvelopeDocumentsResult.attribute_map["envelope_id".to_sym] != nil
        name = "envelope_id".to_sym
        value = attributes["envelopeId"]
        send("#{name}=", value) if self.respond_to?(name)
	      end
      if SignatureEnvelopeDocumentsResult.attribute_map["documents".to_sym] != nil
        name = "documents".to_sym
        value = attributes["documents"]
        if value.is_a?(Array)
	        array = Array.new
	        value.each do |arrayValue|
	          array.push SignatureEnvelopeDocumentInfo.new(arrayValue)
	        end
	        send("#{name}=", array) if self.respond_to?(name)
	      end
        end
      end
  end

  def to_body
    body = {}
    SignatureEnvelopeDocumentsResult.attribute_map.each_pair do |key,value|
      body[value] = self.send(key) unless self.send(key).nil?
    end
    body
  end
end


text:
require 'capybara'
require 'bacon'
require 'webmock'
require 'capybara/dsl'
require 'ramaze/spec/bacon'

require __DIR__('helper/general')
require __DIR__('helper/capybara')

Bacon.extend(Bacon::TapOutput)

# Configure Capybara
Capybara.configure do |config|
  config.default_driver = :rack_test
  config.app            = Ramaze.middleware
end

shared :capybara do
  Ramaze.setup_dependencies
  extend Capybara::DSL
  extend WebMock::API
  extend Zen::Spec::Helper::Capybara
  extend Zen::Spec::Helper::General

  capybara_login
end


text:
class Todo < ActiveRecord::Base
  attr_accessible :title, :completed, :priority
  belongs_to :user
end


text:
package org.camunda.bpm.engine;

/**
 *
Exception resulting from a error during a script compilation.

 *
 * @author Sebastian Menski
 */
public class ScriptCompilationException extends ScriptEngineException {

  private static final long serialVersionUID = 1L;

  public ScriptCompilationException() {
  }

  public ScriptCompilationException(String message, Throwable cause) {
    super(message, cause);
  }

  public ScriptCompilationException(String message) {
    super(message);
  }

  public ScriptCompilationException(Throwable cause) {
    super(cause);
  }

}


text:
Body parsing

Originally taken from [npm-www](https://github.com/isaacs/npm-www)

## Example

```js
var textBody = require("body")
var jsonBody = require("body/json")
var formBody = require("body/form")
var anyBody = require("body/any")
var http = require("http")
var sendJson = require("send-data/json")

http.createServer(function handleRequest(req, res) {
    function send(err, body) {
        sendJson(req, res, body)
    }

    if (req.url === "/body") {
        // all functions can be called with (req, cb)
        textBody(req, send)
    } else if (req.url === "/form") {
        // all functions can be called with (req, opts, cb)
        formBody(req, {}, send)
    } else if (req.url === "/json") {
        // all functions can be called with (req, res, cb)
        jsonBody(req, res, send)
    } else if (req.url === "/any") {
        // all functions can be called with (req, res, opts, cb)
        anyBody(req, res, {}, send)
    }
})
```

`body` simply parses the request body and returns it in the callback. `jsonBody` and `formBody` call JSON.parse and querystring.parse respectively on the body.

anyBody will detect the content-type of the request and use the appropiate body method.

## Example generators

You can use `body` with generators as the body functions will
    return a continuable if you don't pass a callback.

```js
var http = require("http")
var Router = require("routes-router")
var jsonBody = require("body/json")
var formBody = require("body/form")
// async turns a generator into an async function taking a cb
var async = require("gens")

// the router works with normal async functions.
// router automatically handles errors as 500 responses
var app = Router({
    // do whatever you want. the jsonBody error would go here
    errorHandler: function (req, res, err) {
        res.statusCode = 500
        res.end(err.message)
    }
})

app.addRoute("/json", async(function* (req, res) {
    // if jsonBody has an error it just goes to the cb
    // in the called in the router. and it does the correct thing
    // it shows your 500 page.
    var body = yield jsonBody(req, res)

    res.setHeader("content-type", "application/json")
    res.end(JSON.stringify(body))
}))

app.addRoute("/form", async(function* (req, res) {
    var body = yield formBody(req, res)

    res.setHeader("content-type", "application/json")
    res.end(JSON.stringify(body))
}))

// app returned from the router is just a function(req, res) {}
// that dispatches the req/res to the correct route based on
// the routers routing table & req.url
http.createServer(app).listen(8080)
```

## Documentation

### `textBody(req, res?, opts?, cb<Error, String>)`

```ocaml
textBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String
    },
    cb: Callback<err: Error, bodyPayload: String>
) => void
```

`textBody` allows you to get the body from any readable stream.
It will read the entire content of the stream into memory and
give it back to you in the callback.

 - `limit`: You can set `opts.limit` to a custom number to change the
    limit at which `textBody` gives up. By default it will only
    read a 1MB body, if a stream contains more then 1MB it returns
    an error. This prevents someone attacking your HTTP server
    with an infinite body causing an out of memory attack.
 - `encoding`: You can set `encoding`. All encodings that are valid on a
    [`Buffer`](http://nodejs.org/api/buffer.html#buffer_buffer) are
    valid options. It defaults to `'utf8'`

```js
var textBody = require("body")
var http = require("http")

http.createServer(function (req, res) {
    textBody(req, res, function (err, body) {
        // err probably means invalid HTTP protocol or some shiz.
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.end(body)
    })
}).listen(8080)
```

### `formBody(req, res?, opts?, cb<Error, Any>)`

```ocaml
formBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String,
        querystring: {
            parse: (String, Callback<Error, Any>) => void
        }
    },
    cb: Callback<err: Error, bodyPayload: Any>
) => void
```

`formBody` allows you to get the body of a readable stream. It
does the same as `textBody` but assumes the content is querystring
encoded and parses just like it was a <form> submit.

 - `limit`: same as `textBody`
 - `encoding`: same as `textBody`
 - `querystring`: You can pass a custom querystring parser if
    you want. It should have a `parse` method that takes a
    string and a callback. It should return the value in the
    callback or a parsing error

```js
var formBody = require("body/form")
var http = require("http")

http.createServer(function (req, res) {
    formBody(req, res, function (err, body) {
        // err probably means invalid HTTP protocol or some shiz.
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.setHeader("content-type", "application/json")
        res.end(JSON.stringify(body))
    })
}).listen(8080)
```

### `jsonBody(req, res?, opts?, cb<Error, Any>)`

```ocaml
jsonBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String,
        reviver?: (Any) => Any
        JSON?: {
            parse: (String, reviver?: Function, Callback<Error, Any>) => void
        }
    },
    cb: Callback<err: Error, bodyPayload: Any>
) => void
```

`jsonBody` allows you to get the body of a readable stream. It
does the same as `textbody` but assumes the content it a JSON
value and parses it using `JSON.parse`. If `JSON.parse` throws
an exception then it calls the callback with the exception.

 - `limit`: same as `textBody`
 - `encoding`: same as `textBody`
 - `reviver`: A reviver function that will be passed to `JSON.parse`
    as the second argument
 - `JSON`: You can pass a custom JSON parser if you want.
    It should have a `parse` method that takes a string, an
    optional reviver and a callback. It should return the value
    in the callback or a parsing error.

```js
var jsonBody = require("body/json")
var http = require("http")

http.createServer(function (req, res) {
    jsonBody(req, res, function (err, body) {
        // err is probably an invalid json error
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.setHeader("content-type", "application/json")
        res.end(JSON.stringify(body))
    })
}).listen(8080)
```

### `anyBody(req, res?, opts?, cb<Error, Any>)`

```ocaml
anyBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String,
        reviver?: (Any) => Any
        JSON?: {
            parse: (String, reviver?: Function, Callback<Error, Any>) => void
        },
        querystring: {
            parse: (String, Callback<Error, Any>) => void
        }
    },
    cb: Callback<err: Error, bodyPayload: Any>
) => void
```

`anyBody` allows you to get the body of a HTTPRequest. It
does the same as `textBody` except it parses the `content-type`
header and uses either the jsonBody or the formBody function.

This allows you to write POST route handlers that work with
both ajax and html form submits.

 - `limit`: same as `textBody`
 - `encoding`: same as `textBody`
 - `reviver`: same as `jsonBody`
 - `JSON`: same as `jsonBody`
 - `querystring`: same as `formBody`

```js
var anyBody = require("body/any")
var http = require("http")

http.createServer(function (req, res) {
    anyBody(req, res, function (err, body) {
        // err is probably an invalid json error
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.setHeader("content-type", "application/json")
        res.end(JSON.stringify(body))
    })
}).listen(8080)
```

## Installation

`npm install body`

## Tests

`npm test`

## Contributors

 - Raynos

## MIT Licenced

  [1]: https://secure.travis-ci.org/Raynos/body.png
  [2]: http://travis-ci.org/Raynos/body


text:
namespace blink {

bool CSSParser::parseDeclarationList(const CSSParserContext& context, MutableStylePropertySet* propertySet, const String& declaration, CSSParserObserver* observer, StyleSheetContents* styleSheet)
{
    // FIXME: Add inspector observer support in the new CSS parser
    if (!observer && RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseDeclarationList(propertySet, declaration, context);
    return BisonCSSParser(context).parseDeclaration(propertySet, declaration, observer, styleSheet);
}

void CSSParser::parseSelector(const CSSParserContext& context, const String& selector, CSSSelectorList& selectorList)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled()) {
        CSSTokenizer::Scope scope(selector);
        CSSSelectorParser::parseSelector(scope.tokenRange(), context, starAtom, nullptr, selectorList);
        return;
    }
    BisonCSSParser(context).parseSelector(selector, selectorList);
}

PassRefPtrWillBeRawPtr<StyleRuleBase> CSSParser::parseRule(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& rule)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseRule(rule, context, CSSParserImpl::AllowImportRules);
    return BisonCSSParser(context).parseRule(styleSheet, rule);
}

void CSSParser::parseSheet(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& text, const TextPosition& startPosition, CSSParserObserver* observer, bool logErrors)
{
    // FIXME: Add inspector observer support in the new CSS parser
    if (!observer && RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseStyleSheet(text, context, styleSheet);
    BisonCSSParser(context).parseSheet(styleSheet, text, startPosition, observer, logErrors);
}

bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, CSSParserMode parserMode, StyleSheetContents* styleSheet)
{
    if (string.isEmpty())
        return false;
    if (parseFastPath(declaration, propertyID, string, important, parserMode))
        return true;
    CSSParserContext context(parserMode, 0);
    if (styleSheet) {
        context = styleSheet->parserContext();
        context.setMode(parserMode);
    }
    return parseValue(declaration, propertyID, string, important, context);
}

bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const CSSParserContext& context)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseValue(declaration, propertyID, string, important, context);
    return BisonCSSParser::parseValue(declaration, propertyID, string, important, context);
}

bool CSSParser::parseFastPath(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, CSSParserMode parserMode)
{
    RefPtrWillBeRawPtr<CSSValue> value = CSSParserFastPaths::maybeParseValue(propertyID, string, parserMode);
    if (!value)
        return false;
    declaration->addParsedProperty(CSSProperty(propertyID, value.release(), important));
    return true;
}

PassRefPtrWillBeRawPtr<CSSValue> CSSParser::parseSingleValue(CSSPropertyID propertyID, const String& string, const CSSParserContext& context)
{
    if (string.isEmpty())
        return nullptr;
    RefPtrWillBeRawPtr<MutableStylePropertySet> stylePropertySet = MutableStylePropertySet::create();
    bool success = parseFastPath(stylePropertySet.get(), propertyID, string, false, context.mode())
        || parseValue(stylePropertySet.get(), propertyID, string, false, context);
    ASSERT_UNUSED(success, success == stylePropertySet->hasProperty(propertyID));
    return stylePropertySet->getPropertyCSSValue(propertyID);
}

PassRefPtrWillBeRawPtr<ImmutableStylePropertySet> CSSParser::parseInlineStyleDeclaration(const String& styleString, Element* element)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseInlineStyleDeclaration(styleString, element);
    return BisonCSSParser::parseInlineStyleDeclaration(styleString, element);
}

PassOwnPtr<Vector<double>> CSSParser::parseKeyframeKeyList(const String& keyList)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseKeyframeKeyList(keyList);
    return BisonCSSParser(strictCSSParserContext()).parseKeyframeKeyList(keyList);
}

PassRefPtrWillBeRawPtr<StyleRuleKeyframe> CSSParser::parseKeyframeRule(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& rule)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled()) {
        RefPtrWillBeRawPtr<StyleRuleBase> keyframe = CSSParserImpl::parseRule(rule, context, CSSParserImpl::KeyframeRules);
        return toStyleRuleKeyframe(keyframe.get());
    }
    return BisonCSSParser(context).parseKeyframeRule(styleSheet, rule);
}

bool CSSParser::parseSupportsCondition(const String& condition)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled()) {
        CSSTokenizer::Scope scope(condition);
        CSSParserImpl parser(strictCSSParserContext());
        return CSSSupportsParser::supportsCondition(scope.tokenRange(), parser) == CSSSupportsParser::Supported;
    }
    return BisonCSSParser(CSSParserContext(HTMLStandardMode, 0)).parseSupportsCondition(condition);
}

bool CSSParser::parseColor(RGBA32& color, const String& string, bool strict)
{
    if (string.isEmpty())
        return false;

    // First try creating a color specified by name, rgba(), rgb() or "#" syntax.
    if (CSSPropertyParser::fastParseColor(color, string, strict))
        return true;

    // In case the fast-path parser didn't understand the color, try the full parser.
    RefPtrWillBeRawPtr<MutableStylePropertySet> stylePropertySet = MutableStylePropertySet::create();
    // FIXME: The old CSS parser is only working in strict mode ignoring the strict parameter.
    // It needs to be investigated why.
    if (!parseValue(stylePropertySet.get(), CSSPropertyColor, string, false, strictCSSParserContext()))
        return false;

    RefPtrWillBeRawPtr<CSSValue> value = stylePropertySet->getPropertyCSSValue(CSSPropertyColor);
    if (!value || !value->isPrimitiveValue())
        return false;

    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
    if (!primitiveValue->isRGBColor())
        return false;

    color = primitiveValue->getRGBA32Value();
    return true;
}

StyleColor CSSParser::colorFromRGBColorString(const String& string)
{
    // FIXME: Rework css parser so it is more SVG aware.
    RGBA32 color;
    if (parseColor(color, string.stripWhiteSpace()))
        return StyleColor(color);
    // FIXME: This branch catches the string currentColor, but we should error if we have an illegal color value.
    return StyleColor::currentColor();
}

bool CSSParser::parseSystemColor(RGBA32& color, const String& colorString)
{
    CSSParserString cssColor;
    cssColor.init(colorString);
    CSSValueID id = cssValueKeywordID(cssColor);
    if (!CSSPropertyParser::isSystemColor(id))
        return false;

    Color parsedColor = LayoutTheme::theme().systemColor(id);
    color = parsedColor.rgb();
    return true;
}

} // namespace blink


text:
<link rel='import' href='../../bower_components/polymer/polymer.html'>
<link rel="import" href="../../bower_components/iron-flex-layout/classes/iron-flex-layout.html">
<link rel='import' href='../../bower_components/parallax-container/parallax-container.html'>

<link rel='import' href='../overview/overview-behavior.html'>
<link rel="import" href="../software/software-overview-styles.html">
<link rel="import" href="../software/gear-styles.html">

<dom-module id="software-overview">
  <template>

    <parallax-container id="parallaxContainer" on-scroll="handleScroll">

      <parallax-group id="sw-group1" z=2  style="color:white">
        <parallax-layer>

A core focus of the FNNDSC is on software development -- from basic algorithms that analyze raw medical data and tease out valuable information to powerful and intuitive web-based systems that manage medical data and provide for powerful visualization and collaboration techniques.

        </parallax-layer>
        <parallax-layer layer="-1">

        </parallax-layer>
      </parallax-group>

      <parallax-group id="sw-group2" z=3  style="color:white">
        <parallax-layer>

        </parallax-layer>
        <parallax-layer layer=1>

        </parallax-layer>
      </parallax-group>

      <parallax-group id="sw-group3" z=1 style="color:white;">
        <parallax-layer>

        </parallax-layer>
        <parallax-layer layer=-2>

        </parallax-layer>
        <parallax-layer layer=-1>

        </parallax-layer>
      </parallax-group>

      <parallax-group id="sw-group4" z=2>
        <parallax-layer>

            Copyright: FNNDSC 2016

        </parallax-layer>
      </parallax-group>

    </parallax-container>
  </template>

</dom-module>


text:
const fsUtils          = require('./fs-utils');

module.exports = function(gitkeepPath) {
  return fsUtils.write(gitkeepPath, '', { encoding: 'utf8' });
}


text:
require 'spec_helper'
require 'whois/record/parser/whois.centralnic.com.rb'

describe Whois::Record::Parser::WhoisCentralnicCom, "status_registered.expected" do

  subject do
    file = fixture("responses", "whois.centralnic.com/gr.com/status_registered.txt")
    part = Whois::Record::Part.new(:body => File.read(file))
    described_class.new(part)
  end

  describe "#disclaimer" do
    it do
      subject.disclaimer.should == "This whois service is provided by CentralNic Ltd and only contains information pertaining to Internet domain names we have registered for our customers. By using this service you are agreeing (1) not to use any information presented here for any purpose other than determining ownership of domain names, (2) not to store or reproduce this data in any way, (3) not to use any high-volume, automated, electronic processes to obtain data from this service. Abuse of this service is monitored and actions in contravention of these terms will result in being permanently blacklisted. All data is (c) CentralNic Ltd https://www.centralnic.com/"
    end
  end
  describe "#domain" do
    it do
      subject.domain.should == "google.gr.com"
    end
  end
  describe "#domain_id" do
    it do
      subject.domain_id.should == "CNIC-DO735168"
    end
  end
  describe "#status" do
    it do
      subject.status.should == ["OK"]
    end
  end
  describe "#available?" do
    it do
      subject.available?.should == false
    end
  end
  describe "#registered?" do
    it do
      subject.registered?.should == true
    end
  end
  describe "#created_on" do
    it do
      subject.created_on.should be_a(Time)
      subject.created_on.should == Time.parse("2011-02-07 13:10:14 UTC")
    end
  end
  describe "#updated_on" do
    it do
      subject.updated_on.should be_a(Time)
      subject.updated_on.should == Time.parse("2012-06-23 10:38:02 UTC")
    end
  end
  describe "#expires_on" do
    it do
      subject.expires_on.should be_a(Time)
      subject.expires_on.should == Time.parse("2015-02-07 23:59:59 UTC")
    end
  end
  describe "#registrar" do
    it do
      subject.registrar.should == nil
    end
  end
  describe "#registrant_contacts" do
    it do
      subject.registrant_contacts.should be_a(Array)
      subject.registrant_contacts.should have(1).items
      subject.registrant_contacts[0].should be_a(Whois::Record::Contact)
      subject.registrant_contacts[0].type.should          == Whois::Record::Contact::TYPE_REGISTRANT
      subject.registrant_contacts[0].id.should            == "H1346485"
      subject.registrant_contacts[0].name.should          == nil
      subject.registrant_contacts[0].organization.should  == nil
      subject.registrant_contacts[0].address.should       == nil
      subject.registrant_contacts[0].city.should          == nil
      subject.registrant_contacts[0].zip.should           == nil
      subject.registrant_contacts[0].state.should         == nil
      subject.registrant_contacts[0].country.should       == nil
      subject.registrant_contacts[0].country_code.should  == nil
      subject.registrant_contacts[0].phone.should         == nil
      subject.registrant_contacts[0].fax.should           == nil
      subject.registrant_contacts[0].email.should         == nil
    end
  end
  describe "#admin_contacts" do
    it do
      subject.admin_contacts.should be_a(Array)
      subject.admin_contacts.should have(0).items
    end
  end
  describe "#technical_contacts" do
    it do
      subject.technical_contacts.should be_a(Array)
      subject.technical_contacts.should have(1).items
      subject.technical_contacts[0].should be_a(Whois::Record::Contact)
      subject.technical_contacts[0].type.should          == Whois::Record::Contact::TYPE_TECHNICAL
      subject.technical_contacts[0].id.should            == "H1346485"
      subject.technical_contacts[0].name.should          == nil
      subject.technical_contacts[0].organization.should  == nil
      subject.technical_contacts[0].address.should       == nil
      subject.technical_contacts[0].city.should          == nil
      subject.technical_contacts[0].zip.should           == nil
      subject.technical_contacts[0].state.should         == nil
      subject.technical_contacts[0].country.should       == nil
      subject.technical_contacts[0].country_code.should  == nil
      subject.technical_contacts[0].phone.should         == nil
      subject.technical_contacts[0].fax.should           == nil
      subject.technical_contacts[0].email.should         == nil
    end
  end
  describe "#nameservers" do
    it do
      subject.nameservers.should be_a(Array)
      subject.nameservers.should have(2).items
      subject.nameservers[0].should be_a(Whois::Record::Nameserver)
      subject.nameservers[0].name.should == "f1g1ns1.dnspod.net"
      subject.nameservers[1].should be_a(Whois::Record::Nameserver)
      subject.nameservers[1].name.should == "f1g1ns2.dnspod.net"
    end
  end
end


text:
extern libsodium_function_t libsodium_functions_crypto_stream_salsa20[];

#endif


text:
<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController,
    Zend\View\Model\ViewModel,
    Zend\Form\Annotation\AnnotationBuilder,
    Zend\Paginator\Paginator,
    Zend\Json\Json,
    Category\Entity\Item,
    Admin\Form\ItemSearchForm,
    Admin\Model\ItemSearch;

class ItemController extends AbstractActionController {

  public function indexAction() {
    $designerId = $this->params()->fromRoute('page', false);
    $page = (int) $this->params()->fromRoute('page', 1);
    $column = $this->params()->fromQuery('column');
    $order = $this->params()->fromQuery('order');

    $sm = $this->getServiceLocator();
    $itemModel = $sm->get('Item');
    $searchForm = new ItemSearchForm(null, $sm);
    $searchForm->setData($this->getRequest()->getQuery());
    $search = new ItemSearch();
    $searchForm->setInputFilter($search->getInputFilter());

    $action = $this->params()->fromQuery('action');
    $searchParams = array();
    if ($action == 'search') {
      if ($searchForm->isValid()) {
        $searchParams = $searchForm->getData();
      }
    }

    $adapter = $itemModel->getAdapter($column, $order, $searchParams);
    $paginator = new Paginator($adapter);

    $itemsPerPage = 10;
    $paginator->setCurrentPageNumber($page);
    $paginator->setItemCountPerPage($itemsPerPage);
    $totalRecord = $paginator->getTotalItemCount();

    $request = $this->getServiceLocator()->get('ViewHelperManager')->get('RequestHelper');
    $url = $request->getFullUrl();

    return new ViewModel(array(
        'paginator' => $paginator,
        'totoalRecord' => $totalRecord,
        'items_per_page' => $itemsPerPage,
        'url' => $url,
        'column' => $column,
        'order' => $order,
        'form' => $searchForm,
      ));
  }

  public function addAction() {
    $serviceLocator = $this->getServiceLocator();
    $item = new Item();
    $builder = new AnnotationBuilder();
    $form = $builder->createForm($item);
    $form->bind($item);

    $categoryModel = $this->getServiceLocator()->get('Category');
    $categories = $categoryModel->allSelect();
    $form->get('category')->setAttribute('options', $categories);

    // $seasonModel = $serviceLocator->get('Season');
    // $seasons = $seasonModel->allSelect();
    // $form->get('season')->setAttribute('options', $seasons);

    // $designerModel = $serviceLocator->get('Designer');
    // $designers = $designerModel->allSelect();
    // $form->get('designer')->setAttribute('options', $designers);

    $request = $this->getRequest();
    if ($request->isPost()) {
      $form->setData($request->getPost());
      if ($form->isValid()) {
        $data = $request->getPost();
        $itemModel = $serviceLocator->get('Item');
        $item = $itemModel->create($data);

        $designerSeason = $item->designer_season;
        return $this->redirect()->toRoute( 'admin_designer_season_item', array('designer' => $designerSeason->designer->id, 'season' => $designerSeason->id) );
      }
    }

    return array(
      'form' => $form,
    );
  }

  public function editAction() {
    $id = (int) $this->params()->fromRoute('id', 0);
    $serviceLocator = $this->getServiceLocator();
    $itemModel = $serviceLocator->get('Item');
    $item = $itemModel->get($id);
    $builder = new AnnotationBuilder();
    $form = $builder->createForm($item);
    $form->bind($item);

    $categoryModel = $this->getServiceLocator()->get('Category');
    $categories = $categoryModel->allSelect();
    $form->get('category')->setAttribute('options', $categories);

    // $seasonModel = $serviceLocator->get('Season');
    // $seasons = $seasonModel->allSelect();
    // $form->get('season')->setAttribute('options', $seasons);

    // $designerModel = $serviceLocator->get('Designer');
    // $designers = $designerModel->allSelect();
    // $form->get('designer')->setAttribute('options', $designers);

    $request = $this->getRequest();
    if ($request->isPost()) {
      $form->setData($request->getPost());
      if ($form->isValid()) {
        $data = $request->getPost();
        $itemModel->setData($item, $data);
        $itemModel->save($item);
        $designerSeason = $item->designer_season;
        return $this->redirect()->toRoute( 'admin_designer_season_item', array('designer' => $designerSeason->designer->id, 'season' => $designerSeason->id) );
      }
    }
    return array('form' => $form, 'id' => $id, 'item' => $item);
  }

  public function deleteAction() {
    $id = (int) $this->getEvent()->getRouteMatch()->getParam('id');
    if (!$id) {
      return $this->redirect()->toRoute('admin_item');
    }
    $itemModel = $this->getServiceLocator()->get('Item');
    $item = $itemModel->get($id);
    $designerSeason = $item->designer_season;
    if ($item) {
      $itemModel->delete($item);
    }

    return $this->redirect()->toRoute( 'admin_designer_season_item', array('designer' => $designerSeason->designer->id, 'season' => $designerSeason->id) );
  }

  public function bulkDeleteAction() {
    $response = $this->getResponse();
    $ids = $this->params()->fromPost('delIds', '');
    if ($ids == '') {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    $itemsIds = explode(',', $ids);
    $itemModel = $this->getServiceLocator()->get('Item');
    $items = $itemModel->getByIds($itemsIds);

    if (count($items) <= 0) {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    foreach ($items as $item) {
      $itemModel->delete($item);
    }
    $responseData['success'] = true;
    $response->setStatusCode(200);
    $response->setContent(Json::encode($responseData));
    return $response;
  }

  public function bulkShowAction() {
    $response = $this->getResponse();
    $ids = $this->params()->fromPost('ids', '');
    if ($ids == '') {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    $itemsIds = explode(',', $ids);
    $itemModel = $this->getServiceLocator()->get('Item');
    $items = $itemModel->getByIds($itemsIds);

    if (count($items) <= 0) {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    foreach ($items as $item) {
      if(!$item->visible) {
        $item->visible = true;
        $itemModel->save($item);
      }
    }
    $responseData['success'] = true;
    $response->setStatusCode(200);
    $response->setContent(Json::encode($responseData));
    return $response;
  }

  public function bulkHideAction() {
    $response = $this->getResponse();
    $ids = $this->params()->fromPost('ids', '');
    if ($ids == '') {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    $itemsIds = explode(',', $ids);
    $itemModel = $this->getServiceLocator()->get('Item');
    $items = $itemModel->getByIds($itemsIds);

    if (count($items) <= 0) {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    foreach ($items as $item) {
      if($item->visible) {
        $item->visible = false;
        $itemModel->save($item);
      }
    }
    $responseData['success'] = true;
    $response->setStatusCode(200);
    $response->setContent(Json::encode($responseData));
    return $response;
  }

  public function reorderAction() {
    $response = $this->getResponse();
    $ids = $this->params()->fromPost('ids', '');
    if ($ids == '') {
      $response->setStatusCode(404);
      $response->setContent('Not Found');
      return $response;
    }
    $itemsIds = explode(',', $ids);
    $itemModel = $this->getServiceLocator()->get('Item');
    $maxSequence = $itemModel->getMaxSequenceByIds($itemsIds);

    $sequence = $maxSequence;
    foreach ($itemsIds as $itemId) {
      $item = $itemModel->get($itemId);
      $item->sequence = $sequence;
      $itemModel->save($item);
      $sequence--;
    }
    $responseData['success'] = true;
    $response->setStatusCode(200);
    $response->setContent(Json::encode($responseData));
    return $response;
  }

}


text:
/*
 * flavors.js: Instance methods for working with base resources from Openstack CDN
 *
 * (C) 2014 Rackspace
 *      Shaunak Kashyap
 * MIT LICENSE
 */

/**
 * client.getHomeDocument
 *
 * @description gets the home document for the CDN service
 *
 * @param callback
 * @return {*}
 */
exports.getHomeDocument = function(callback) {
  var requestOptions = {
    path: '/'
  };

  return this._request(requestOptions, function (err, body) {
    if (err) {
      return callback(err);
    }

    callback(err, body);
  });
};

/**
 * client.getPing
 *
 * @description gets the server ping response (status response)
 *
 * @param callback
 * @return {*}
 */
exports.getPing = function(callback) {
  var requestOptions = {
    path: '/ping'
  };

  return this._request(requestOptions, function (err) {
    return callback(err);
  });
};


text:
import { ISocketHandler } from "../interfaces/ISocketHandler";

export class DashboardHandler implements ISocketHandler {
    onRegister(io: SocketIO.Server, socket: SocketIO.Socket) {
        socket.join("dashboardLobby");
    }
}


text:
// Copyright (c) 2021-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <compat/compat.h>
#include <test/util/setup_common.h>
#include <util/sock.h>
#include <util/system.h>
#include <util/threadinterrupt.h>

#include <boost/test/unit_test.hpp>

#include <cassert>
#include <thread>

using namespace std::chrono_literals;

BOOST_FIXTURE_TEST_SUITE(sock_tests, BasicTestingSetup)

static bool SocketIsClosed(const SOCKET& s)
{
    // Notice that if another thread is running and creates its own socket after `s` has been
    // closed, it may be assigned the same file descriptor number. In this case, our test will
    // wrongly pretend that the socket is not closed.
    int type;
    socklen_t len = sizeof(type);
    return getsockopt(s, SOL_SOCKET, SO_TYPE, (sockopt_arg_type)&type, &len) == SOCKET_ERROR;
}

static SOCKET CreateSocket()
{
    const SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    BOOST_REQUIRE(s != static_cast<SOCKET>(SOCKET_ERROR));
    return s;
}

BOOST_AUTO_TEST_CASE(constructor_and_destructor)
{
    const SOCKET s = CreateSocket();
    Sock* sock = new Sock(s);
    BOOST_CHECK_EQUAL(sock->Get(), s);
    BOOST_CHECK(!SocketIsClosed(s));
    delete sock;
    BOOST_CHECK(SocketIsClosed(s));
}

BOOST_AUTO_TEST_CASE(move_constructor)
{
    const SOCKET s = CreateSocket();
    Sock* sock1 = new Sock(s);
    Sock* sock2 = new Sock(std::move(*sock1));
    delete sock1;
    BOOST_CHECK(!SocketIsClosed(s));
    BOOST_CHECK_EQUAL(sock2->Get(), s);
    delete sock2;
    BOOST_CHECK(SocketIsClosed(s));
}

BOOST_AUTO_TEST_CASE(move_assignment)
{
    const SOCKET s = CreateSocket();
    Sock* sock1 = new Sock(s);
    Sock* sock2 = new Sock();
    *sock2 = std::move(*sock1);
    delete sock1;
    BOOST_CHECK(!SocketIsClosed(s));
    BOOST_CHECK_EQUAL(sock2->Get(), s);
    delete sock2;
    BOOST_CHECK(SocketIsClosed(s));
}

#ifndef WIN32 // Windows does not have socketpair(2).

static void CreateSocketPair(int s[2])
{
    BOOST_REQUIRE_EQUAL(socketpair(AF_UNIX, SOCK_STREAM, 0, s), 0);
}

static void SendAndRecvMessage(const Sock& sender, const Sock& receiver)
{
    const char* msg = "abcd";
    constexpr ssize_t msg_len = 4;
    char recv_buf[10];

    BOOST_CHECK_EQUAL(sender.Send(msg, msg_len, 0), msg_len);
    BOOST_CHECK_EQUAL(receiver.Recv(recv_buf, sizeof(recv_buf), 0), msg_len);
    BOOST_CHECK_EQUAL(strncmp(msg, recv_buf, msg_len), 0);
}

BOOST_AUTO_TEST_CASE(send_and_receive)
{
    int s[2];
    CreateSocketPair(s);

    Sock* sock0 = new Sock(s[0]);
    Sock* sock1 = new Sock(s[1]);

    SendAndRecvMessage(*sock0, *sock1);

    Sock* sock0moved = new Sock(std::move(*sock0));
    Sock* sock1moved = new Sock();
    *sock1moved = std::move(*sock1);

    delete sock0;
    delete sock1;

    SendAndRecvMessage(*sock1moved, *sock0moved);

    delete sock0moved;
    delete sock1moved;

    BOOST_CHECK(SocketIsClosed(s[0]));
    BOOST_CHECK(SocketIsClosed(s[1]));
}

BOOST_AUTO_TEST_CASE(wait)
{
    int s[2];
    CreateSocketPair(s);

    Sock sock0(s[0]);
    Sock sock1(s[1]);

    std::thread waiter([&sock0]() { (void)sock0.Wait(24h, Sock::RECV); });

    BOOST_REQUIRE_EQUAL(sock1.Send("a", 1, 0), 1);

    waiter.join();
}

BOOST_AUTO_TEST_CASE(recv_until_terminator_limit)
{
    constexpr auto timeout = 1min; // High enough so that it is never hit.
    CThreadInterrupt interrupt;
    int s[2];
    CreateSocketPair(s);

    Sock sock_send(s[0]);
    Sock sock_recv(s[1]);

    std::thread receiver([&sock_recv, &timeout, &interrupt]() {
        constexpr size_t max_data{10};
        bool threw_as_expected{false};
        // BOOST_CHECK_EXCEPTION() writes to some variables shared with the main thread which
        // creates a data race. So mimic it manually.
        try {
            (void)sock_recv.RecvUntilTerminator('\n', timeout, interrupt, max_data);
        } catch (const std::runtime_error& e) {
            threw_as_expected = HasReason("too many bytes without a terminator")(e);
        }
        assert(threw_as_expected);
    });

    BOOST_REQUIRE_NO_THROW(sock_send.SendComplete("1234567", timeout, interrupt));
    BOOST_REQUIRE_NO_THROW(sock_send.SendComplete("89a\n", timeout, interrupt));

    receiver.join();
}

#endif /* WIN32 */

BOOST_AUTO_TEST_SUITE_END()


text:
<!DOCTYPE html>

<meta content="text/html;charset=utf-8" http-equiv="content-type"/>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>pymel.core.animation.blendTwoAttr — PyMEL 1.0.7 documentation</title>
<link href="../../../_static/nature.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../index-2.html" rel="top" title="PyMEL 1.0.7 documentation"/>
<link href="../../pymel.core.animation.html" rel="up" title="pymel.core.animation"/>
<link href="pymel.core.animation.boneLattice.html" rel="next" title="pymel.core.animation.boneLattice"/>
<link href="pymel.core.animation.blendShapePanel.html" rel="prev" title="pymel.core.animation.blendShapePanel"/>
<link href="../../../../style/adsk.cpm.css" rel="stylesheet" type="text/css"/><meta content="expert" name="experiencelevel"/><meta content="programmer" name="audience"/><meta content="enable" name="user-comments"/><meta content="ENU" name="language"/><meta content="MAYAUL" name="product"/><meta content="2016" name="release"/><meta content="Customization" name="book"/><meta content="Maya-Tech-Docs" name="component"/><meta content="/view/MAYAUL/2016/ENU/" name="helpsystempath"/><meta content="04/03/2015" name="created"/><meta content="04/03/2015" name="modified"/><meta content="Navigation

 index

 modules |

 next |

 previous |
 PyMEL 1.0.7 documentation »
 pymel.core.animation »

 pymel.core.animation.blendTwoAttr ¶

 blendTwoAttr ( *args , **kwargs ) ¶
 A blendTwoAttr nodes takes two inputs, and blends the values of the inputs from one to the other, into an output value.
The blending of the two inputs uses a blending function, and the following formula: (1 - blendFunction) * input[0] +
blendFunction * input[1] The..." name="description"/><meta content="__PyMel_generated_functions_pymel_core_animation_pymel_core_animation_blendTwoAttr_html" name="topicid"/>

Navigation

index

modules |

next |

previous |

PyMEL 1.0.7 documentation »

pymel.core.animation »

pymel.core.animation.blendTwoAttr¶

<tt class="descname">blendTwoAttr</tt><big>(</big>*args, **kwargs<big>)</big>¶

A blendTwoAttr nodes takes two inputs, and blends the values of the inputs from one to the other, into an output value.
The blending of the two inputs uses a blending function, and the following formula: (1 - blendFunction) * input[0]  +
blendFunction * input[1] The blendTwoAttr command can be used to blend the animation of an object to transition
smoothly between the animation of two other objects. When the blendTwoAttr command is issued, it creates a blendTwoAttr
node on the specified attributes, and reconnects whatever was previously connected to the attributes to the new blend
nodes. You may also specify which two attributes should be used to blend together. The driver is used when you want to
keyframe an object after it is being animated by a blend node. The current driver index specifies which of the two
blended attributes should be keyframed.

Flags:

<colgroup>
<col width="1%"></col>
<col width="61%"></col>
<col width="19%"></col>
<col width="19%"></col>
</colgroup>

Long Name / Short Name
Argument Types
Properties

<tt class="docutils literal">attribute</tt> / <tt class="docutils literal">at</tt>
unicode

A list of attributes for the selected nodes for which a blendTwoAttr node will be created.

<tt class="docutils literal">attribute0</tt> / <tt class="docutils literal">at0</tt>
PyNode

The attribute that should be connected to the first input of the new blendTwoAttr node. When queried, it returns a string.

<tt class="docutils literal">attribute1</tt> / <tt class="docutils literal">at1</tt>
PyNode

The attribute that should be connected to the second input of the new blendTwoAttr node. When queried, it returns a string.

<tt class="docutils literal">blender</tt> / <tt class="docutils literal">bl</tt>
PyNode

The blender attribute. This is the attribute that will be connected to the newly created blendTwoAttr node(s) blender attribute. This attribute controls how much
of each of the two attributes to use in the blend. If this flag is not specified, a new animation curve is created whose value goes from 1 to 0 throughout the
time range specified by the -t flag. If -t is not specified, an abrupt change from the value of the first to the value of the second attribute will occur at the
current time when this command is issued.

<tt class="docutils literal">controlPoints</tt> / <tt class="docutils literal">cp</tt>
bool

Explicitly specify whether or not to include the control points of a shape (see -sflag) in the list of attributes. Default: false.                        Flag can
have multiple arguments, passed either as a tuple or a list.

<tt class="docutils literal">driver</tt> / <tt class="docutils literal">d</tt>
int

The index of the driver attribute for this blend node (0 or 1) When queried, it returns an integer.

<tt class="docutils literal">name</tt> / <tt class="docutils literal">n</tt>
unicode

name for the new blend node(s)

<tt class="docutils literal">shape</tt> / <tt class="docutils literal">s</tt>
bool

Consider all attributes of shapes below transforms as well, except controlPoints. Default: true

<tt class="docutils literal">time</tt> / <tt class="docutils literal">t</tt>
timerange

The time range between which the blending between the 2 attributes should occur. If a single time is specified, then the blend will cause an abrupt change from
the first to the second attribute at that time.  If a range is specified, a smooth blending will occur over that time range. The default is to make a sudden
transition at the current time.

Derived from mel command <tt class="xref py py-obj docutils literal">maya.cmds.blendTwoAttr</tt>

Example:

import pymel.core as pm

# Assume we have animated a bouncing sphere, sphere1, and we would like
# the sphere to smoothly transition into following a second sphere's,
# sphere2, animation between time 15 and 20.
#
pm.select( 'sphere1' )
pm.blendTwoAttr( at='tx', at1='sphere2.tx', t=(15,20) )
pm.blendTwoAttr( at='ty', at1='sphere2.ty', t=(15,20) )
pm.blendTwoAttr( at='tz', at1='sphere2.tz', t=(15,20) )

# You can use the "-at" flag to narrow the query. For example, if
# you wanted to know the names of the newly created blender curves
# for only the tx and tz attributes of sphere1, you could say:
#
pm.blendTwoAttr( at=['tx','tz'], query=True, blender=True )

# You can now keyframe the sphere2's animation by changing the
# driver on sphere1.
#
pm.blendTwoAttr( at='tx', edit=True, driver=1 )
# setKeyframe ...

# If you already had two objects, sphere1 and sphere2 animated, and
# you wanted to blend between their animation abruptly at time 15,
# you could do:
#
pm.blendTwoAttr( 'newObject.tx', t=(15,15), at0='sphere1.tx', at1='sphere2.tx' )

Previous topic

pymel.core.animation.blendShapePanel

Next topic

pymel.core.animation.boneLattice

Core Modules

<tt class="xref">animation</tt>

<tt class="xref">effects</tt>

<tt class="xref">general</tt>

<tt class="xref">language</tt>

<tt class="xref">modeling</tt>

<tt class="xref">rendering</tt>

<tt class="xref">system</tt>

<tt class="xref">windows</tt>

Type Modules

<tt class="xref">datatypes</tt>

<tt class="xref">nodetypes</tt>

<tt class="xref">uitypes</tt>

Other Modules

<tt class="xref">plugins</tt>

<tt class="xref">mayautils</tt>

<tt class="xref">util</tt>

<tt class="xref">versions</tt>

<tt class="xref">tools</tt>

This Page

Show Source

Quick search

<form action="http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/search.html" class="search" method="get"></form>
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>

    Enter search terms or a module, class or function name.

Navigation

index

modules |

next |

previous |

PyMEL 1.0.7 documentation »

pymel.core.animation »

        © Copyright 2009, Chad Dombrova.
      Created using Sphinx 1.2.3.


text:
require 'spec_helper'

describe HotelsPro::Api::ApiMethod do
  let(:api_method) { HotelsPro::Api::ApiMethod.new }

  it "should raise exception on error response" do
    response = stub(:error? => true, :error => HotelsPro::ErrorResponse.new("Error occured."))
    request  = stub(:perform => response)

    api_method.stub(:request => request)

    lambda { api_method.perform }.should raise_error(HotelsPro::ErrorResponse, "Error occured.")
  end
end


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

using Microsoft.Azure.Commands.ScenarioTest.SqlTests;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;

namespace Microsoft.Azure.Commands.Sql.Test.ScenarioTests
{
    public class ServerCrudTests : SqlTestsBase
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestServerCreate()
        {
            RunPowerShellTest("Test-CreateServer");
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestServerUpdate()
        {
            RunPowerShellTest("Test-UpdateServer");
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestServerGet()
        {
            RunPowerShellTest("Test-GetServer");
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestServerRemove()
        {
            RunPowerShellTest("Test-RemoveServer");
        }
    }
}


text:
// <copyright file="ScenarioTimeoutFeature.cs" company="xBehave.net contributors">
//  Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>

#if !V2
namespace Xbehave.Test.Acceptance
{
    using System;
    using System.Linq;
#if NET40 || NET45
    using System.Threading;
#endif
    using FluentAssertions;
    using Xbehave.Test.Acceptance.Infrastructure;
    using Xunit.Abstractions;

    // In order to prevent very long running tests <-- improve!
    // As a developer
    // I want a feature to fail if a given scenario takes to long to run
    public class ScenarioTimeoutFeature : Feature
    {
#if NET40 || NET45
        private static readonly ManualResetEventSlim @event = new ManualResetEventSlim();
#endif

        [Scenario]
        public void ScenarioExecutesFastEnough()
        {
            var feature = default(Type);
            var results = default(ITestResultMessage[]);

            "Given a feature with a scenario which does not exceed it's timeout"
                .Given(() => feature = typeof(ScenarioFastEnough));

            "When I run the scenarios"
                .When(() => results = this.Run<ITestResultMessage>(feature));

            "Then there should be one result"
                .Then(() => results.Count().Should().Be(1));

            "And the result should be a pass"
                .And(() => results.Should().ContainItemsAssignableTo<ITestPassed>());
        }

#if NET40 || NET45
        [Scenario(Skip = "See https://github.com/xbehave/xbehave.net/issues/93/")]
        public void ScenarioExecutesTooSlowly()
        {
            var feature = default(Type);
            var results = default(ITestResultMessage[]);

            "Given a feature with a scenario which exceeds it's 1ms timeout"
                .Given(() => feature = typeof(ScenarioTooSlow));

            "When I run the scenarios"
                .When(() =>
                {
                    @event.Reset();
                    results = this.Run<ITestResultMessage>(feature);
                })
                .Teardown(() => @event.Set());

            "Then there should be one result"
                .Then(() => results.Count().Should().Be(1));

            "And the result should be a failure"
                .And(() => results.Should().ContainItemsAssignableTo<ITestFailed>());

            "And the result message should be \"Test execution time exceeded: 1ms\""
                .And(() => results.Cast<ITestFailed>().Should().OnlyContain(result =>
                    result.Messages.Single() == "Test execution time exceeded: 1ms"));
        }

        [Scenario(Skip = "See https://github.com/xbehave/xbehave.net/issues/93/")]
        public void ScenarioExecutesTooSlowlyInOneStepAndHasASubsequentPassingStep()
        {
            var feature = default(Type);
            var results = default(ITestResultMessage[]);

            "Given a feature with a scenario which exceeds it's 1ms timeout"
                .Given(() => feature = typeof(ScenarioTooSlowInOneStepAndHasASubsequentPassingStep));

            "When I run the scenarios"
                .When(() =>
                {
                    @event.Reset();
                    results = this.Run<ITestResultMessage>(feature);
                })
                .Teardown(() => @event.Set());

            "Then there should be two result"
                .Then(() => results.Count().Should().Be(2));

            "And the results should be failures"
                .And(() => results.Should().ContainItemsAssignableTo<ITestFailed>());

            "And the first result message should be \"Test execution time exceeded: 1ms\""
                .And(() => results.Cast<ITestFailed>().Should().OnlyContain(result =>
                    result.Messages.Single() == "Test execution time exceeded: 1ms"));
        }
#endif

        private static class ScenarioFastEnough
        {
#pragma warning disable 618
            [Scenario(Timeout = int.MaxValue)]
#pragma warning restore 618
            public static void Scenario()
            {
                "Given something"
                    .Given(() => { });
            }
        }

#if NET40 || NET45
        private static class ScenarioTooSlow
        {
#pragma warning disable 618
            [Scenario(Timeout = 1)]
#pragma warning restore 618
            public static void Scenario()
            {
                "Given something"
                    .Given(() => @event.Wait());
            }
        }

        private static class ScenarioTooSlowInOneStepAndHasASubsequentPassingStep
        {
#pragma warning disable 618
            [Scenario(Timeout = 1)]
#pragma warning restore 618
            public static void Scenario()
            {
                "Given something"
                    .Given(() => @event.Wait());

                "Then true is true"
                    .Then(() => true.Should().BeTrue());
            }
        }
#endif
    }
}
#endif


text:
module FastlaneCore
  VERSION = "0.38.0".freeze
end


text:
/**
 *
 */
package org.latlab.util;

import java.util.Collections;
import java.util.Set;

/**
 * A single dimensional continuous variable.
 *
 * @author leonard
 *
 */
public class SingularContinuousVariable extends ContinuousVariable {

    /**
     * Constructs a singular continuous variable with a default name.
     */
    public SingularContinuousVariable() {

    }

    /**
     * Constructs a singular continuous variable with the given {@code name}.
     *
     * @param name
     *            name of this variable
     */
    public SingularContinuousVariable(String name) {
        super(name);
    }

    /**
     * Returns a sorted set that contains only this variable.
     *
     * @return sorted set containing only this variable
     */
    @Override
    public Set<SingularContinuousVariable> variables() {
        return Collections.singleton(this);
    }

    /**
     * The accept function of the visitor pattern.
     *
     * @param visitor
     *            visits this instance
     */
    public <T> T accept(Visitor<T> visitor) {
        return visitor.visit(this);
    }

    @Override
    public boolean equals(Object o) {
        if (o == this)
            return true;
        else if (o instanceof SingularContinuousVariable) {
            return getName().equals(((SingularContinuousVariable) o).getName());
        } else {
            return false;
        }
    }
}


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

namespace ff.coffee.webapp.Languages.vi {
    using System;

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

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

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

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

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ff.coffee.webapp.Languages.vi.ReportPageResource", typeof(ReportPageResource).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

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

        /// <summary>
        ///   Looks up a localized string similar to Xem chi tiết.
        /// </summary>
        public static string ButtonReportDetailHeader {
            get {
                return ResourceManager.GetString("ButtonReportDetailHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Xem báo cáo.
        /// </summary>
        public static string ReportButtonView {
            get {
                return ResourceManager.GetString("ReportButtonView", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Từ ngày.
        /// </summary>
        public static string ReportDateFromLabel {
            get {
                return ResourceManager.GetString("ReportDateFromLabel", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to đến.
        /// </summary>
        public static string ReportDateToLabel {
            get {
                return ResourceManager.GetString("ReportDateToLabel", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Thu ngân.
        /// </summary>
        public static string ReportSalesCashierHeader {
            get {
                return ResourceManager.GetString("ReportSalesCashierHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Doanh số.
        /// </summary>
        public static string ReportSalesCostHeader {
            get {
                return ResourceManager.GetString("ReportSalesCostHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Ngày.
        /// </summary>
        public static string ReportSalesDateHeader {
            get {
                return ResourceManager.GetString("ReportSalesDateHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Chi tiết hóa đơn.
        /// </summary>
        public static string ReportSalesDetail {
            get {
                return ResourceManager.GetString("ReportSalesDetail", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Chi tiết hóa đơn.
        /// </summary>
        public static string ReportSalesDetailHeader {
            get {
                return ResourceManager.GetString("ReportSalesDetailHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Giảm giá (%).
        /// </summary>
        public static string ReportSalesDiscountHeader {
            get {
                return ResourceManager.GetString("ReportSalesDiscountHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Báo cáo doanh số.
        /// </summary>
        public static string ReportSalesHeader {
            get {
                return ResourceManager.GetString("ReportSalesHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Tên bàn.
        /// </summary>
        public static string ReportSalesTableHeader {
            get {
                return ResourceManager.GetString("ReportSalesTableHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Tổng doanh số.
        /// </summary>
        public static string ReportSalesTotalLabel {
            get {
                return ResourceManager.GetString("ReportSalesTotalLabel", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Thành tiền.
        /// </summary>
        public static string SalesDetailCostHeader {
            get {
                return ResourceManager.GetString("SalesDetailCostHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Đơn giá.
        /// </summary>
        public static string SalesDetailPriceHeader {
            get {
                return ResourceManager.GetString("SalesDetailPriceHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Món.
        /// </summary>
        public static string SalesDetailProductHeader {
            get {
                return ResourceManager.GetString("SalesDetailProductHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Số lượng.
        /// </summary>
        public static string SalesDetailQuantityHeader {
            get {
                return ResourceManager.GetString("SalesDetailQuantityHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Nhân viên Order.
        /// </summary>
        public static string SalesDetailStaffHeader {
            get {
                return ResourceManager.GetString("SalesDetailStaffHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Tổng cộng.
        /// </summary>
        public static string SalesDetailTotalHeader {
            get {
                return ResourceManager.GetString("SalesDetailTotalHeader", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Đơn vị.
        /// </summary>
        public static string SalesDetailUnitHeader {
            get {
                return ResourceManager.GetString("SalesDetailUnitHeader", resourceCulture);
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class MainCameraController : MonoBehaviour
{
	public float movement_velocity = 4f;
	public float movement_modifier = 3f;

	private float speed;
	private float max_x,min_x,max_z,min_z;
	private float min_y = 0.5f;

	public void Start ()
	{
		Cursor.visible = true;
		speed = movement_velocity;
	}

	public void Update ()
	{
		if (!SimulationUIController.is_paused)
		{
			if (Input.GetMouseButtonDown(1))
			{
				Cursor.visible = false;
			}

			if (Input.GetMouseButtonUp(1))
			{
				Cursor.visible = true;
			}

			if (Input.GetKeyDown(KeyCode.LeftShift))
			{
				speed = movement_velocity * movement_modifier;
			}

			if (Input.GetKeyDown(KeyCode.LeftControl))
			{
				speed = movement_velocity / movement_modifier;
			}

			if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.LeftControl))
			{
				speed = movement_velocity;
			}

			this.transform.Translate (Input.GetAxis("Horizontal") * Vector3.right * Time.deltaTime * speed, this.transform);
			this.transform.Translate (Input.GetAxis("Forward" ) * Vector3.forward * Time.deltaTime * speed, this.transform);

			Vector3 new_pos = this.transform.position;

			// If the new position is out of the limits, clamp the position to the limit

			if (new_pos.x > max_x)
			{
				new_pos.x = max_x;
			}
			else if (new_pos.x < min_x)
			{
				new_pos.x = min_x;
			}

			if (new_pos.z > max_z)
			{
				new_pos.z = max_z;
			}
			else if (new_pos.z < min_z)
			{
				new_pos.z = min_z;
			}

			if (new_pos.y < min_y)
			{
				new_pos.y = min_y;
			}

			this.transform.position = new_pos;
		}
	}

	public void goTo (Vector3 pos, Vector3 dir)
	{
		Vector3 v = new Vector3 (pos.x,pos.y,pos.z);
		this.transform.position = v;
		this.transform.rotation = Quaternion.LookRotation(dir,Vector3.up);
	}

	public void setLimits (float max_x,float min_x,float max_z,float min_z)
	{
		this.max_x = max_x;
		this.min_x = min_x;
		this.max_z = max_z;
		this.min_z = min_z;
	}
}


text:
<?php

use Ess_M2ePro_Model_Walmart_Listing_Product as WalmartListingProduct;

class Ess_M2ePro_Block_Adminhtml_Walmart_Listing_Search_Other_Grid
    extends Ess_M2ePro_Block_Adminhtml_Walmart_Listing_Search_Grid
{
    //########################################

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

        // Initialization block
        // ---------------------------------------
        $this->setId('walmartListingSearchOtherGrid');
        // ---------------------------------------

        // Set default values
        // ---------------------------------------
        $this->setDefaultSort(false);
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        // ---------------------------------------
    }

    protected function _prepareColumns()
    {
        parent::_prepareColumns();

        $this->getColumn('name')->setData('header', Mage::helper('M2ePro')->__('Product Title / Product SKU'));
    }

    //########################################

    protected function _prepareCollection()
    {
        $collection = Mage::helper('M2ePro/Component_Walmart')->getCollection('Listing_Other');
        $collection->getSelect()->distinct();

        $stockId = Mage::helper('M2ePro/Magento_Store')->getStockId(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
        $collection->getSelect()->joinLeft(
            array(
                'cisi' => Mage::helper('M2ePro/Module_Database_Structure')
                    ->getTableNameWithPrefix('cataloginventory_stock_item')
            ),
            "(cisi.product_id = `main_table`.product_id AND cisi.stock_id = {$stockId})",
            array('is_in_stock' => 'is_in_stock')
        );

        $collection->getSelect()->joinLeft(
            array(
                'cpe' => Mage::helper('M2ePro/Module_Database_Structure')
                    ->getTableNameWithPrefix('catalog_product_entity')
            ),
            '(cpe.entity_id = `main_table`.product_id)',
            array('sku' => 'sku')
        );

        $collection->getSelect()->reset(Zend_Db_Select::COLUMNS);
        $collection->getSelect()->columns(
            array(
                'sku'                          => 'cpe.sku',
                'name'                         => 'second_table.title',
                'listing_title'                => new Zend_Db_Expr('NULL'),
                'store_id'                     => new Zend_Db_Expr(0),
                'account_id'                   => 'main_table.account_id',
                'marketplace_id'               => 'main_table.marketplace_id',
                'listing_product_id'           => new Zend_Db_Expr('NULL'),
                'listing_other_id'             => 'second_table.listing_other_id',
                'entity_id'                    => 'main_table.product_id',
                'listing_id'                   => new Zend_Db_Expr('NULL'),
                'status'                       => 'main_table.status',
                'is_variation_parent'          => new Zend_Db_Expr('NULL'),
                'variation_child_statuses'     => new Zend_Db_Expr('NULL'),
                'online_sku'                   => 'second_table.sku',
                'gtin'                         => 'second_table.gtin',
                'upc'                          => 'second_table.upc',
                'ean'                          => new Zend_Db_Expr('NULL'),
                'isbn'                         => new Zend_Db_Expr('NULL'),
                'wpid'                         => 'second_table.wpid',
                'channel_url'                  => 'second_table.channel_url',
                'item_id'                      => 'second_table.item_id',
                'online_title'                 => new Zend_Db_Expr('NULL'),
                'online_qty'                   => 'second_table.online_qty',
                'online_price'                 => 'second_table.online_price',
                'online_sale_price'            => new Zend_Db_Expr('NULL'),
                'online_sale_price_start_date' => new Zend_Db_Expr('NULL'),
                'online_sale_price_end_date'   => new Zend_Db_Expr('NULL'),
                'is_in_stock'                  => 'cisi.is_in_stock',
                'is_online_price_invalid'      => 'second_table.is_online_price_invalid',
            )
        );

        $accountId = (int)$this->getRequest()->getParam('walmartAccount', false);
        $marketplaceId = (int)$this->getRequest()->getParam('walmartMarketplace', false);

        if ($accountId) {
            $collection->getSelect()->where('account_id = ?', $accountId);
        }

        if ($marketplaceId) {
            $collection->getSelect()->where('marketplace_id = ?', $marketplaceId);
        }

        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    //########################################

    public function callbackColumnProductTitle($value, $row, $column, $isExport)
    {
        $title = $row->getData('name');

        if ($title === null || $title === '') {
            $value = 'receiving...';
        } else {
            $value = '' .Mage::helper('M2ePro')->escapeHtml($title). '';
        }

        $sku = $row->getData('sku');
        if (!empty($sku)) {
            $sku = Mage::helper('M2ePro')->escapeHtml($sku);
            $skuWord = Mage::helper('M2ePro')->__('SKU');

            $value .= <<<HTML

{$skuWord}:
{$sku}
HTML;
        }

        return $value;
    }

    public function callbackColumnStatus($value, $row, $column, $isExport)
    {
        /** @var Ess_M2ePro_Model_Listing_Other $listingOther */
        $listingOther = Mage::helper('M2ePro/Component_Walmart')
            ->getObject('Listing_Other', $row->getData('listing_other_id'));

        $statusChangeReasons = $listingOther->getChildObject()->getStatusChangeReasons();

        return $this->getProductStatus($row, $row->getData('status')) .
               $this->getStatusChangeReasons($statusChangeReasons);
    }

    public function callbackColumnActions($value, $row, $column, $isExport)
    {
        $altTitle = Mage::helper('M2ePro')->escapeHtml(Mage::helper('M2ePro')->__('Go to Listing'));
        $iconSrc = $this->getSkinUrl('M2ePro/images/goto_listing.png');

        $manageUrl = $this->getUrl(
            '*/adminhtml_walmart_listing_other/view/', array(
            'account'     => $row->getData('account_id'),
            'marketplace' => $row->getData('marketplace_id'),
            'filter'      => base64_encode(
                'title=' . $row->getData('online_sku')
            )
            )
        );

        $html = <<<HTML

HTML;

        return $html;
    }

    public function callbackColumnIsInStock($value, $row, $column, $isExport)
    {
        if ($row->getData('is_in_stock') === null) {
            return Mage::helper('M2ePro')->__('N/A');
        }

        return parent::callbackColumnIsInStock($value, $row, $column, $isExport);
    }

    public function callbackColumnPrice($value, $row, $column, $isExport)
    {
        if ($value === null || $value === '' ||
            ($row->getData('status') == Ess_M2ePro_Model_Listing_Product::STATUS_BLOCKED &&
             !$row->getData('is_online_price_invalid')))
        {
            return Mage::helper('M2ePro')->__('N/A');
        }

        if ((float)$value <= 0) {
            return '0';
        }

        $currency = Mage::helper('M2ePro/Component_Walmart')
            ->getCachedObject('Marketplace', $row->getData('marketplace_id'))
            ->getChildObject()
            ->getDefaultCurrency();

        $priceValue = Mage::app()->getLocale()->currency($currency)->toCurrency($value);

        return $priceValue;
    }

    //########################################

    protected function callbackFilterProductId($collection, $column)
    {
        $cond = $column->getFilter()->getCondition();

        if (empty($cond)) {
            return;
        }

        $collection->addFieldToFilter('main_table.product_id', $cond);
    }

    protected function callbackFilterTitle($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if ($value == null) {
            return;
        }

        $collection->getSelect()->where('second_table.title LIKE ? OR cpe.sku LIKE ?', '%'.$value.'%');
    }

    protected function callbackFilterOnlineSku($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if ($value == null) {
            return;
        }

        $collection->getSelect()->where('second_table.sku LIKE ?', '%'.$value.'%');
    }

    protected function callbackFilterPrice($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if (empty($value)) {
            return;
        }

        $condition = '';

        if (isset($value['from']) || isset($value['to'])) {
            if (isset($value['from']) && $value['from'] != '') {
                $condition = 'second_table.online_price >= \'' . (float)$value['from'] . '\'';
            }

            if (isset($value['to']) && $value['to'] != '') {
                if (isset($value['from']) && $value['from'] != '') {
                    $condition .= ' AND ';
                }

                $condition .= 'second_table.online_price <= \'' . (float)$value['to'] . '\'';
            }
        }

        $collection->getSelect()->where($condition);
    }

    protected function callbackFilterGtin($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if (empty($value)) {
            return;
        }

        $where = <<<SQL
second_table.gtin LIKE '%{$value}%' OR
second_table.upc LIKE '%{$value}%' OR
second_table.wpid LIKE '%{$value}%' OR
second_table.item_id LIKE '%{$value}%'
SQL;

        $collection->getSelect()->where($where);
    }

    protected function callbackFilterQty($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if (empty($value)) {
            return;
        }

        $where = '';

        if (isset($value['from']) && $value['from'] != '') {
            $quoted = $collection->getConnection()->quote($value['from']);
            $where .= 'second_table.online_qty >= ' . $quoted;
        }

        if (isset($value['to']) && $value['to'] != '') {
            if (isset($value['from']) && $value['from'] != '') {
                $where .= ' AND ';
            }

            $quoted = $collection->getConnection()->quote($value['to']);
            $where .= 'second_table.online_qty <= ' . $quoted;
        }

        $collection->getSelect()->where($where);
    }

    protected function callbackFilterStatus($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if ($value == null) {
            return;
        }

        $collection->getSelect()->where('status = ?', $value);
    }

    //########################################
}


text:
'use strict';

var swagger = require('swagger-server'),
    session = require('./sessions'),
    data    = require('@bigstickcarpet/mock-data');

module.exports = {
  init: loadMockData,

  /**
   * GET /employees
   */
  get: [
    session.identifyUser,
    session.mustBeLoggedIn
  ],

  /**
   * POST /employees
   */
  post: [
    session.identifyUser,
    session.adminsOnly,
    verifyUsernameDoesNotExist
  ]
};

/**
 * Loads mock employee data
 *
 * @param {SwaggerServer} server
 * @param {function} next
 */
function loadMockData(server, next) {
  // Create REST resources for each employee
  var resources = data.employees.map(function(employee) {
    return new swagger.Resource('/employees', employee.username, employee);
  });

  // Save the resources to the mock data store
  server.dataStore.save(resources, next);
}

/**
 * Verifies that the new employee's username isn't the same as any existing username.
 */
function verifyUsernameDoesNotExist(req, res, next) {
  var username = req.body.username;
  var dataStore = req.app.dataStore;

  // Check for an existing employee REST resource - /employees/{username}
  var resource = new swagger.Resource('/employees', username, null);
  dataStore.get(resource, function(err, resource) {
    if (resource) {
      // The username already exists, so send an HTTP 409 (Conflict)
      res.sendStatus(409);
    }
    else {
      next();
    }
  });
}