text:
from functools import wraps
import inspect
from textwrap import dedent
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
import warnings

from pandas._libs.properties import cache_readonly  # noqa

def deprecate(
    name: str,
    alternative: Callable,
    version: str,
    alt_name: Optional[str] = None,
    klass: Optional[Type[Warning]] = None,
    stacklevel: int = 2,
    msg: Optional[str] = None,
) -> Callable:
    """
    Return a new function that emits a deprecation warning on use.

    To use this method for a deprecated function, another function
    `alternative` with the same signature must exist. The deprecated
    function will emit a deprecation warning, and in the docstring
    it will contain the deprecation directive with the provided version
    so it can be detected for future removal.

    Parameters
    ----------
    name : str
        Name of function to deprecate.
    alternative : func
        Function to use instead.
    version : str
        Version of pandas in which the method has been deprecated.
    alt_name : str, optional
        Name to use in preference of alternative.__name__.
    klass : Warning, default FutureWarning
    stacklevel : int, default 2
    msg : str
        The message to display in the warning.
        Default is '{name} is deprecated. Use {alt_name} instead.'
    """

    alt_name = alt_name or alternative.__name__
    klass = klass or FutureWarning
    warning_msg = msg or "{} is deprecated, use {} instead".format(name, alt_name)

    @wraps(alternative)
    def wrapper(*args, **kwargs):
        warnings.warn(warning_msg, klass, stacklevel=stacklevel)
        return alternative(*args, **kwargs)

    # adding deprecated directive to the docstring
    msg = msg or "Use `{alt_name}` instead.".format(alt_name=alt_name)
    doc_error_msg = (
        "deprecate needs a correctly formatted docstring in "
        "the target function (should have a one liner short "
        "summary, and opening quotes should be in their own "
        "line). Found:\n{}".format(alternative.__doc__)
    )

    # when python is running in optimized mode (i.e. `-OO`), docstrings are
    # removed, so we check that a docstring with correct formatting is used
    # but we allow empty docstrings
    if alternative.__doc__:
        if alternative.__doc__.count("\n") < 3:
            raise AssertionError(doc_error_msg)
        empty1, summary, empty2, doc = alternative.__doc__.split("\n", 3)
        if empty1 or empty2 and not summary:
            raise AssertionError(doc_error_msg)
        wrapper.__doc__ = dedent(
            """
        {summary}

        .. deprecated:: {depr_version}
            {depr_msg}

        {rest_of_docstring}"""
        ).format(
            summary=summary.strip(),
            depr_version=version,
            depr_msg=msg,
            rest_of_docstring=dedent(doc),
        )

    return wrapper

def deprecate_kwarg(
    old_arg_name: str,
    new_arg_name: Optional[str],
    mapping: Optional[Union[Dict, Callable[[Any], Any]]] = None,
    stacklevel: int = 2,
) -> Callable:
    """
    Decorator to deprecate a keyword argument of a function.

    Parameters
    ----------
    old_arg_name : str
        Name of argument in function to deprecate
    new_arg_name : str or None
        Name of preferred argument in function. Use None to raise warning that
        ``old_arg_name`` keyword is deprecated.
    mapping : dict or callable
        If mapping is present, use it to translate old arguments to
        new arguments. A callable must do its own value checking;
        values not found in a dict will be forwarded unchanged.

    Examples
    --------
    The following deprecates 'cols', using 'columns' instead

    >>> @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
    ... def f(columns=''):
    ...     print(columns)
    ...
    >>> f(columns='should work ok')
    should work ok

    >>> f(cols='should raise warning')
    FutureWarning: cols is deprecated, use columns instead
      warnings.warn(msg, FutureWarning)
    should raise warning

    >>> f(cols='should error', columns="can\'t pass do both")
    TypeError: Can only specify 'cols' or 'columns', not both

    >>> @deprecate_kwarg('old', 'new', {'yes': True, 'no': False})
    ... def f(new=False):
    ...     print('yes!' if new else 'no!')
    ...
    >>> f(old='yes')
    FutureWarning: old='yes' is deprecated, use new=True instead
      warnings.warn(msg, FutureWarning)
    yes!

    To raise a warning that a keyword will be removed entirely in the future

    >>> @deprecate_kwarg(old_arg_name='cols', new_arg_name=None)
    ... def f(cols='', another_param=''):
    ...     print(cols)
    ...
    >>> f(cols='should raise warning')
    FutureWarning: the 'cols' keyword is deprecated and will be removed in a
    future version please takes steps to stop use of 'cols'
    should raise warning
    >>> f(another_param='should not raise warning')
    should not raise warning

    >>> f(cols='should raise warning', another_param='')
    FutureWarning: the 'cols' keyword is deprecated and will be removed in a
    future version please takes steps to stop use of 'cols'
    should raise warning
    """

    if mapping is not None and not hasattr(mapping, "get") and not callable(mapping):
        raise TypeError(
            "mapping from old to new argument values " "must be dict or callable!"
        )

    def _deprecate_kwarg(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            old_arg_value = kwargs.pop(old_arg_name, None)

            if new_arg_name is None and old_arg_value is not None:
                msg = (
                    "the '{old_name}' keyword is deprecated and will be "
                    "removed in a future version. "
                    "Please take steps to stop the use of '{old_name}'"
                ).format(old_name=old_arg_name)
                warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
                kwargs[old_arg_name] = old_arg_value
                return func(*args, **kwargs)

            if old_arg_value is not None:
                if mapping is not None:
                    if hasattr(mapping, "get"):
                        new_arg_value = mapping.get(old_arg_value, old_arg_value)
                    else:
                        new_arg_value = mapping(old_arg_value)
                    msg = (
                        "the {old_name}={old_val!r} keyword is deprecated, "
                        "use {new_name}={new_val!r} instead"
                    ).format(
                        old_name=old_arg_name,
                        old_val=old_arg_value,
                        new_name=new_arg_name,
                        new_val=new_arg_value,
                    )
                else:
                    new_arg_value = old_arg_value
                    msg = (
                        "the '{old_name}' keyword is deprecated, "
                        "use '{new_name}' instead"
                    ).format(old_name=old_arg_name, new_name=new_arg_name)

                warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
                if kwargs.get(new_arg_name, None) is not None:
                    msg = (
                        "Can only specify '{old_name}' or '{new_name}', " "not both"
                    ).format(old_name=old_arg_name, new_name=new_arg_name)
                    raise TypeError(msg)
                else:
                    kwargs[new_arg_name] = new_arg_value
            return func(*args, **kwargs)

        return wrapper

    return _deprecate_kwarg

def rewrite_axis_style_signature(
    name: str, extra_params: List[Tuple[str, Any]]
) -> Callable:
    def decorate(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)

        kind = inspect.Parameter.POSITIONAL_OR_KEYWORD
        params = [
            inspect.Parameter("self", kind),
            inspect.Parameter(name, kind, default=None),
            inspect.Parameter("index", kind, default=None),
            inspect.Parameter("columns", kind, default=None),
            inspect.Parameter("axis", kind, default=None),
        ]

        for pname, default in extra_params:
            params.append(inspect.Parameter(pname, kind, default=default))

        sig = inspect.Signature(params)

        func.__signature__ = sig
        return wrapper

    return decorate

# Substitution and Appender are derived from matplotlib.docstring (1.1.0)
# module http://matplotlib.org/users/license.html

class Substitution:
    """
    A decorator to take a function's docstring and perform string
    substitution on it.

    This decorator should be robust even if func.__doc__ is None
    (for example, if -OO was passed to the interpreter)

    Usage: construct a docstring.Substitution with a sequence or
    dictionary suitable for performing substitution; then
    decorate a suitable function with the constructed object. e.g.

    sub_author_name = Substitution(author='Jason')

    @sub_author_name
    def some_function(x):
        "%(author)s wrote this function"

    # note that some_function.__doc__ is now "Jason wrote this function"

    One can also use positional arguments.

    sub_first_last_names = Substitution('Edgar Allen', 'Poe')

    @sub_first_last_names
    def some_function(x):
        "%s %s wrote the Raven"
    """

    def __init__(self, *args, **kwargs):
        if args and kwargs:
            raise AssertionError("Only positional or keyword args are allowed")

        self.params = args or kwargs

    def __call__(self, func: Callable) -> Callable:
        func.__doc__ = func.__doc__ and func.__doc__ % self.params
        return func

    def update(self, *args, **kwargs) -> None:
        """
        Update self.params with supplied args.

        If called, we assume self.params is a dict.
        """

        self.params.update(*args, **kwargs)

class Appender:
    """
    A function decorator that will append an addendum to the docstring
    of the target function.

    This decorator should be robust even if func.__doc__ is None
    (for example, if -OO was passed to the interpreter).

    Usage: construct a docstring.Appender with a string to be joined to
    the original docstring. An optional 'join' parameter may be supplied
    which will be used to join the docstring and addendum. e.g.

    add_copyright = Appender("Copyright (c) 2009", join='\n')

    @add_copyright
    def my_dog(has='fleas'):
        "This docstring will have a copyright below"
        pass
    """

    def __init__(self, addendum: Optional[str], join: str = "", indents: int = 0):
        if indents > 0:
            self.addendum = indent(addendum, indents=indents)  # type: Optional[str]
        else:
            self.addendum = addendum
        self.join = join

    def __call__(self, func: Callable) -> Callable:
        func.__doc__ = func.__doc__ if func.__doc__ else ""
        self.addendum = self.addendum if self.addendum else ""
        docitems = [func.__doc__, self.addendum]
        func.__doc__ = dedent(self.join.join(docitems))
        return func

def indent(text: Optional[str], indents: int = 1) -> str:
    if not text or not isinstance(text, str):
        return ""
    jointext = "".join(["\n"] + ["    "] * indents)
    return jointext.join(text.split("\n"))


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>GoBlog 后台管理 v{{.version}}</title>
	<meta name="robots" content="all">
	<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
	<link href="/static/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" />
	<link href="/static/themes/admin/css/admin.css" rel="stylesheet" type="text/css"/>

GoBlog 后台管理 您好!{{.adminname}} | 退出登录 | 个人信息 | 站点首页

系统管理

系统设置

系统信息

内容管理

发布文章

文章列表

标签管理

用户管理

添加用户

用户列表

		{{.LayoutContent}}

	Copyright © 2013 lisijie.org. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text: include ../Makefile.simulation-test


text:
function(_filter_unsupported_arch_sources _unsupported_archs_regex _sources _return_var)

    if (NOT "${_unsupported_archs_regex}" STREQUAL "") # Not all architectures are supported
        # Filter sources dependant on unsupported architectures
        list(FILTER _sources EXCLUDE REGEX ${_unsupported_archs_regex})
    endif ()

    set(${_return_var} ${_sources} PARENT_SCOPE)

endfunction()

#=============================================================================#
# Resolves library's architecture-related elements by doing several things:
# 1. Checking whether the platform's architecture is supported by the library
# 2. Filtering out any library sources that relate to unsupported architectures, i.e
#    architectures other than the platform's.
# If the platform's architecture isn't supported by the library, CMake generates an error and stops.
#       _library_sources - List of library's sources to check and potentially filter.
#       [LIB_PROPS_FILE] - Full path to the library's properties file. Optional.
#       _return_var - Name of variable in parent-scope holding the return value.
#       Returns - Filtered list of sources containing only those that don't relate to
#                 any unsupported architecture.
#=============================================================================#
function(resolve_library_architecture _library_sources _return_var)

    if(NOT _library_sources)
        return()
    endif()

    cmake_parse_arguments(parsed_args "" "LIB_PROPS_FILE" "" ${ARGN})

    if (parsed_args_LIB_PROPS_FILE) # Library properties file is given
        set(lib_props_file ${parsed_args_LIB_PROPS_FILE})
    else ()

        # Warn user and assume library is arch-agnostic
        message(STATUS "Library's properties file can't be found under its' root directory.\n\t"
                "Assuming the library is architecture-agnostic (supports all architectures)")
        set(${_return_var} "${_library_sources}" PARENT_SCOPE)
        return()

    endif ()

    get_arduino_library_supported_architectures("${lib_props_file}" lib_archs)

    # Check if the platform's architecture is supported by the library
    is_platform_architecture_supported(${lib_archs} arch_supported_by_lib)

    if (NOT ${arch_supported_by_lib})
        message(SEND_ERROR "The platform's architecture, ${ARDUINO_CMAKE_PLATFORM_ARCHITECTURE}, "
                "isn't supported by the ${_library_name} library")
    endif ()

    get_unsupported_architectures("${lib_archs}" unsupported_archs REGEX)

    # Filter any sources that aren't supported by the platform's architecture
    _filter_unsupported_arch_sources("${unsupported_archs}" "${_library_sources}" valid_sources)

    set(${_return_var} "${valid_sources}" PARENT_SCOPE)

endfunction()


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

namespace DemonSaw.Http
{
	using System.IO;
	using System.Net;

	// Delegates
	public delegate void HttpResponseHandler(HttpResponse httpResponse, object obj = null);

	public class HttpResponse : HttpMessage
	{
		// Constants
		public const string HEADER_COOKIE = "Set-Cookie";

		// Properties
		public HttpCode Code { get; set; }

		// Properties - Helper
		public override string Message
		{
			get
			{
				StringWriter sw = new StringWriter();

				// Http/1.1 200 OK
				sw.Write(Version);
				sw.Write(" ");
				sw.Write((int) Code);
				sw.Write(" ");
				sw.Write(Status);
				sw.Write(EndOfLine);

				// Headers
				foreach (string key in Headers.Keys)
				{
					string value = Headers[key];
					sw.Write(key);
					sw.Write(": ");
					sw.Write(value);
					sw.Write(EndOfLine);
				}

				// Cookies
				foreach (string key in Cookies.Keys)
				{
					string value = Cookies[key];
					sw.Write(HEADER_COOKIE);
					sw.Write(": ");
					sw.Write(key);
					sw.Write("=");
					sw.Write(WebUtility.HtmlEncode(value));
					sw.Write(EndOfLine);
				}

				sw.Write(EndOfLine);

				return sw.ToString();
			}
		}

		public string Status { get { return HttpStatus.GetStatus(Code); } }

		public bool Ok { get { return Code == HttpCode.Ok; } }
		public bool BadRequest { get { return Code == HttpCode.BadRequest; } }
		public bool Unauthorized { get { return Code == HttpCode.Unauthorized; } }
		public bool NotFound { get { return Code == HttpCode.NotFound; } }
		public bool InternalServerError { get { return Code == HttpCode.BadRequest; } }
		public bool Error { get { return !Ok; } }

		// Constructors
		public HttpResponse() { Code = HttpCode.Ok; }
		public HttpResponse(string sessionId) : base(sessionId) { Code = HttpCode.Ok; }
		public HttpResponse(HttpCode code, string sessionId = null) : base(sessionId) { Code = code; }

		// Overrides
		public override string ToString()
		{
			StringWriter sw = new StringWriter();
			sw.Write(Message);
			sw.Write(Data);

			return sw.ToString();
		}

		// Interface
		public override int Parse(string str)
		{
			Clear();

			int size = str.IndexOf(EndOfMessage);
			if (size == -1)
				return 0;

			// Request
			string header = str.Substring(0, size);
			StringReader reader = new StringReader(header);
			Title = reader.ReadLine();

			// Http/1.1 200 OK
			int lpos = 0;
			int rpos = Title.IndexOf(' ');
			Version = Title.Substring(lpos, rpos).Trim();

			lpos = rpos + 1;
			rpos = Title.IndexOf(' ', lpos);
			Code = (HttpCode) int.Parse(Title.Substring(lpos, rpos - lpos).Trim());

			lpos = rpos + 1;
			string status = Title.Substring(lpos, Title.Length - lpos).Trim();

			// Headers
			ParseHeaders(reader, HEADER_COOKIE);

			return size + EndOfMessage.Length;
		}
	}
}


text:
package ch.bfh.ti.ostes2.gossip;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import p2pmpi.mpi.MPI;
import p2pmpi.mpi.IntraComm;
import p2pmpi.mpi.Request;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

/**
 * This class represents the {@link Frontend} in
 * the gossip architecture. It is intended to forward
 * updates and queries from clients (computers, tablets
 * and so on) to a available {@link ReplicationManager}.
 *
 * As this is only a simulation, the {@link Frontend}
 * picks randomly a available {@link ReplicationManager},
 * posts randomly messages and sends randomly queries.
 *
 * The updating and deleting of messages is not yet
 * implemented.
 *
 * For each communication category (updating and querying)
 * the tags from {@link Utils} are used to distinct them.
 *
 * @author sosterwalder
 *
 */
public class Frontend {
	private Logger 					logger = null;
	private IntraComm 				comm = null;
	private int						size = 0;
	private int 					rank = 0;
	private int[]					timestamp = null;
	private int[]					replicaManagerIds = null;
	private ArrayList<LogRecord>	sentMessages = null;
	private ActionMessage[]			answerBuffer = null;
	private Request[]				updateAnswers = null;
	private QueryMessage[]			queryBuffer = null;
	private Request[]				queryAnswers = null;

	/**
	 * Constructor
	 */
	public Frontend() {
		this.setupLogger();

		comm = MPI.COMM_WORLD;
		size = comm.Size();
		rank = comm.Rank();
		this.initializeBuffers();
		this.initializeReplicaManagers();

		logger.info(
			String.format(
				"FE %d: Hej, this is FE %d", rank, rank
			)
		);
	}

	/**
	 * Sets the internal log level
	 * to the given log level.
	 *
	 * @param logLevel		the log level to set
	 */
	public void setLogLevel(Level logLevel) {
		logger.setLevel(logLevel);
		logger.info(
			String.format(
				"FE %d: Set log-level to %s", rank, logLevel.toString()
			)
		);
	}

	/**
	 * Posts the given message (which is a string)
	 * to some random {@link ReplicationManager}.
	 *
	 * @param message		which will be sent
	 */
	public void postMessage(String message) {
		// Pick a random replica manager
		// This gives a random integer between 0 (inclusive) and
		// replicaManagerIds (exclusive)
		Random r = new Random();
		int replicaManagerId = r.nextInt(replicaManagerIds.length);

		// Prepare message and send to some replica manager
		ActionMessage[] msg = new ActionMessage[1];
		msg[0] = new ActionMessage();
		msg[0].setTimestamp(timestamp);
		msg[0].setTitle(message);
		msg[0].setUserId(rank);
		msg[0].setOperation(ActionMessage.Operation.INSERT);
		comm.Isend(msg, 0, msg.length, MPI.OBJECT, replicaManagerIds[replicaManagerId], Utils.UPDATE_TAG);

		// Keep the message for the record
		LogRecord log = new LogRecord();
		log.setMessage(msg[0]);
		log.setReplicationManagerId(replicaManagerIds[replicaManagerId]);
		log.setTimestamp(timestamp);
		sentMessages.add(log);

		logger.info(
			String.format(
				"FE %d: Sending message (ID: %s) to RM %d", rank, msg[0].getId(), replicaManagerIds[replicaManagerId]
			)
		);
	}

	/**
	 * Sends an update-request for the given
	 * {@link ActionMessage} to an available
	 * {@link ReplicationManager}.
	 *
	 * @param msg		the {@link ActionMessage} which
	 * 					should get updated
	 * @param message	the new value of the message
	 */
	public void updateMessage(ActionMessage msg, String message) {
		/*
		 * TODO: Implement
		 *
		 * - Pick randomly some message from sentMessages
		 * - Copy it to a new object
		 * - Change the message-string
		 * - Send it to some RM using the
		 *   ActionMessage.Operation.UPDATE operation
		 * - Save it to the sentMessages-Log
		 */
	}

	/**
	 * Sends a delete-request for the given
	 * {@link ActionMessage} to an available
	 * {@link ReplicationManager}.
	 *
	 * @param msg		the {@link ActionMessage} which
	 * 					should get deleted
	 */
	public void deleteMessage(ActionMessage msg) {
		/*
		 * TODO: Implement
		 *
		 * - Pick randomly some message from sentMessages
		 * - Copy it to a new object
		 * - Send it to some RM using the
		 *   ActionMessage.Operation.DELETE operation
		 * - Save it to the sentMessages-Log
		 */
	}

	/**
	 * Sends a query-request to an available
	 * {@link ReplicationManager}. The query
	 * tells the {@link Frontend} the current
	 * time stamps of all available
	 * replication managers known to the
	 * queried replication manager.
	 */
	public void query() {
		// Get a random replica manager
		Random r = new Random();
		int replicaManagerId = r.nextInt(replicaManagerIds.length);

		// Set up query-message and send it
		// to some replica manager
		QueryMessage[] msg = new QueryMessage[1];
		msg[0] = new QueryMessage();
		msg[0].setTimestamp(timestamp);
		msg[0].setFrontendId(rank);
		comm.Isend(msg, 0, msg.length, MPI.OBJECT, replicaManagerIds[replicaManagerId], Utils.QUERY_TAG);

		// Keep the query for the record
		LogRecord log = new LogRecord();
		log.setMessage(msg[0]);
		log.setReplicationManagerId(replicaManagerIds[replicaManagerId]);
		log.setTimestamp(timestamp);
		sentMessages.add(log);

		logger.info(
			String.format(
				"FE %d: Sending query (ID: %s) to RM %d", rank, msg[0].getId(), replicaManagerIds[replicaManagerId]
			)
		);
	}

	/**
	 * Listens to all available {@link ReplicationManager}s for
	 * possible answers for sent update-requests using
	 * the UPATE-tag from {@link Utils}.
	 */
	public void listenToUpdateAnswers() {
		for (int replicaManagerId = 0; replicaManagerId < replicaManagerIds.length; replicaManagerId++) {
			// If there's no answer yet for
			// current replication manager
			if (updateAnswers[replicaManagerId] == null) {
				// Set up new buffer for reception
				updateAnswers[replicaManagerId] = comm.Irecv(answerBuffer, 0, 1, MPI.OBJECT, replicaManagerIds[replicaManagerId], Utils.UPDATE_TAG);
				logger.trace(
					String.format(
						"FE %d: Listening to RM %d", rank, replicaManagerIds[replicaManagerId]
					)
				);
			}
			else {
				// There seems to be an answer from current
				// replication manager
				if (updateAnswers[replicaManagerId].Test() != null) {
					logger.info(
						String.format(
							"FE %d: Got answer from RM %d: %s", rank, replicaManagerIds[replicaManagerId], Arrays.toString(answerBuffer[0].getTimestamp())
						)
					);

					// Merge the time stamp from the replication manager
					// with the own time stamp
					this.timestamp = Utils.mergeTimestamps(answerBuffer[0].getTimestamp(), this.timestamp);
					logger.debug(
						String.format(
							"FE %d: Merged time stamp from RM %d: %s", rank, replicaManagerIds[replicaManagerId], Arrays.toString(this.timestamp)
						)
					);
					// Re-initialize listening to update-answers
					updateAnswers[replicaManagerId] = comm.Irecv(answerBuffer, 0, 1, MPI.OBJECT, replicaManagerIds[replicaManagerId], Utils.UPDATE_TAG);
				}
				else {
					logger.trace(
						String.format(
							"FE %d: Still listening to RM %d", rank, replicaManagerIds[replicaManagerId]
						)
					);
				}
			}
		}
	}

	/**
	 * Listens to all available {@link ReplicationManager}s for
	 * possible answers for sent query-requests using
	 * the QUERY-tag from {@link Utils}.
	 */
	public void listenToQueryAnswers() {
		for (int replicaManagerId = 0; replicaManagerId < replicaManagerIds.length; replicaManagerId++) {
			// If there's no answer yet for
			// current replication manager
			if (queryAnswers[replicaManagerId] == null) {
				// Set up new buffer for reception
				queryAnswers[replicaManagerId] = comm.Irecv(queryBuffer, 0, 1, MPI.OBJECT, replicaManagerIds[replicaManagerId], Utils.QUERY_TAG);
				logger.trace(
					String.format(
						"FE %d: Listening to RM %d", rank, replicaManagerIds[replicaManagerId]
					)
				);
			}
			else {
				// There seems to be an answer from current
				// replication manager
				if (queryAnswers[replicaManagerId].Test() != null) {
					logger.info(
						String.format(
							"FE %d: Got query-answer from RM %d: %s", rank, replicaManagerIds[replicaManagerId], Arrays.toString(queryBuffer[0].getTimestamp())
						)
					);

					// Set the component-wise maximum
					// from the time stamp returned by the current replication
					// manager and the own time stamp.
					this.timestamp = Utils.getMaximizedTimestamp(queryBuffer[0].getTimestamp(), this.timestamp);

					// Some literature recommends merging
					// the time stamps although. So, at
					// first this was implemented
					// this.timestamp = Utils.mergeTimestamps(queryBuffer[0].getTimestamp(), this.timestamp);

					logger.debug(
						String.format(
							"FE %d: Merged time stamp from RM %d: %s", rank, replicaManagerIds[replicaManagerId], Arrays.toString(this.timestamp)
						)
					);
					// Re-initialize listening to query-answers
					queryAnswers[replicaManagerId] = comm.Irecv(queryBuffer, 0, 1, MPI.OBJECT, replicaManagerIds[replicaManagerId], Utils.QUERY_TAG);
				}
				else {
					logger.trace(
						String.format(
							"FE %d: Still listening to query-answers from RM %d", rank, replicaManagerIds[replicaManagerId]
						)
					);
				}
			}
		}
	}

	/**
	 * Returns all yet sent messages.
	 *
	 * @return		sent messages
	 */
	public ArrayList<LogRecord> getSentMessages() {
		return sentMessages;
	}

	/**
	 * Convenience method for printing all
	 * sent messages within the configured
	 * logger.
	 */
	public void printSentMessages() {

		for (LogRecord msg : this.sentMessages) {
			logger.debug(
				String.format(
					"FE %d - sent messages:	To RM: %d; TS: %s; UUID: %s", rank, msg.getReplicationManagerId(), Arrays.toString(msg.getTimestamp()), msg.getMessage().getId()
				)
			);
		}
	}

	/**
	 * Sets up the logger which
	 * currently appends to the console
	 * (stdout) only.
	 */
	private void setupLogger() {
		SimpleLayout layout = new SimpleLayout();
		ConsoleAppender consoleAppender = new ConsoleAppender( layout );

		logger = LogManager.getLogger(ReplicationManager.class.getName());
		logger.addAppender(consoleAppender);
		// Set a default level, this can
		// get overridden later on although
		logger.setLevel(Level.INFO);
	}

	/**
	 * Sets up all available {@link ReplicationManager}s
	 * to communicate with.
	 * This is kind of hard-coded as this
	 * is only a simulation at the moment.
	 */
	private void initializeReplicaManagers() {
		// Always take the RM with the least distant
		// ID assuming we have always n RM and n FE.
		// E.g.: Size is 6, FE-ID is 6, then
		// RM-ID = FE-ID - (Size / 2) = 3
		for (int i = 0; i < replicaManagerIds.length; i++) {
			replicaManagerIds[i] = rank - (size / 2);
		}
	}

	/**
	 * Initializes all the needed buffers.
	 */
	private void initializeBuffers() {
		timestamp = new int[size / 2];
		replicaManagerIds = new int[size / 2];
		sentMessages = new ArrayList<LogRecord>();
		updateAnswers = new Request[replicaManagerIds.length];
		answerBuffer = new ActionMessage[replicaManagerIds.length];
		queryAnswers = new Request[replicaManagerIds.length];
		queryBuffer = new QueryMessage[replicaManagerIds.length];
	}
}


text:
package com.speedment.generator.translator;

import com.speedment.common.codegen.Meta;
import com.speedment.common.codegen.model.File;
import com.speedment.common.injector.annotation.InjectKey;
import com.speedment.runtime.config.Project;
import java.nio.file.Path;

/**
 *
 * @author Per Minborg
 */
@InjectKey(TranslatorManager.class)
public interface TranslatorManager {

    void accept(Project project);

    void clearExistingFiles();

    void writeToFile(Project project, Meta<File, String> meta, boolean overwriteExisting);

    void writeToFile(Project project, String filename, String content, boolean overwriteExisting);

    void writeToFile(Path location, String content, boolean overwriteExisting);

    int getFilesCreated();
}


text:
import $ from "jquery"

$(require("../components/main_layout/client.coffee"))


text:
'use strict';

var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
var setupTestHooks = blueprintHelpers.setupTestHooks;
var emberNew = blueprintHelpers.emberNew;
var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;

var expect = require('ember-cli-blueprint-test-helpers/chai').expect;
var expectCoffee = require('../helpers/expect-coffee');

describe('Acceptance: ember generate and destroy acceptance-test', function() {
  setupTestHooks(this);

  it('acceptance-test foo', function() {
    var args = ['acceptance-test', 'foo'];

    return emberNew()
      .then(() => emberGenerateDestroy(args, (file) => {
        var acceptanceFile = file('tests/acceptance/foo-test.coffee');

        expect(acceptanceFile)
          .to.contain("import Ember from 'ember'")
          .to.contain("import { module, test } from 'qunit'")
          .to.contain("import startApp from 'my-app/tests/helpers/start-app'")
          .to.contain("module 'Acceptance: Foo',")
          .to.contain("test 'visiting /foo', (assert) ->")
          .to.contain("visit '/foo'")
          .to.contain("andThen ->")
          .to.contain("assert.equal currentURL(), '/foo'");

        expectCoffee(acceptanceFile);
    }));
  });
});


text:
<?php

namespace App\Http\Controllers;

use App\Repositories\CategoryRepository;
use Illuminate\Http\Request;

class CategoryController extends ContentNegotiationController
{
    private $repository;

	/**
	 * CategoryController constructor.
	 */
	public function __construct()
    {
	    $this->repository = new CategoryRepository();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        list($response_array, $status_code) = $this->repository->getAllOfUser();
        return $this->responseWith($response_array, $status_code);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Support\Facades\Response
     */
    public function store(Request $request)
    {
	    list($response_array, $status_code) = $this->repository->createByUser($request->all());
	    return $this->responseWith($response_array, $status_code);
    }

	/**
	 * Display the specified resource.
	 *
	 * @param  int $id
	 *
	 * @return \Illuminate\Support\Facades\Response
	 */
    public function show($id)
    {
	    list($response_array, $status_code) = $this->repository->showCategoryOfUser($id);
	    return $this->responseWith($response_array, $status_code);
    }

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @param  int $id
	 *
	 * @return \Illuminate\Support\Facades\Response
	 */
    public function update(Request $request, $id)
    {
	    list($response_array, $status_code) = $this->repository->updateByUser($request->all(), $id);
	    return $this->responseWith($response_array, $status_code);
    }

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int $id
	 *
	 * @return \Illuminate\Support\Facades\Response
	 * @throws \Exception
	 */
    public function destroy($id)
    {
	    list($response_array, $status_code) = $this->repository->deleteByUser($id);
	    return $this->responseWith($response_array, $status_code);
    }
}


text:
/*
 * Message.cpp
 * -----------
 * Purpose: Various functions for processing song messages (allocating, reading from file...)
 * Notes  : Those functions should offer a rather high level of abstraction compared to
 *          previous ways of reading the song messages. There are still many things to do,
 *          though. Future versions of ReadMessage() could e.g. offer charset conversion
 *          and the code is not yet ready for unicode.
 *          Some functions for preparing the message text to be written to a file would
 *          also be handy.
 * Authors: OpenMPT Devs
 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
 */

#include "stdafx.h"
#include "Message.h"
#include "../common/FileReader.h"

OPENMPT_NAMESPACE_BEGIN

// Read song message from a mapped file.
// [in]  data: pointer to the data in memory that is going to be read
// [in]  length: number of characters that should be read, not including a possible trailing null terminator (it is automatically appended).
// [in]  lineEnding: line ending formatting of the text in memory.
// [out] returns true on success.
bool SongMessage::Read(const mpt::byte *data, size_t length, LineEnding lineEnding)
//---------------------------------------------------------------------------------
{
	const char *str = mpt::byte_cast<const char *>(data);
	while(length != 0 && str[length - 1] == '\0')
	{
		// Ignore trailing null character.
		length--;
	}

	// Simple line-ending detection algorithm. VERY simple.
	if(lineEnding == leAutodetect)
	{
		char cprev = 0;
		size_t nCR = 0, nLF = 0, nCRLF = 0;
		// find CRs, LFs and CRLFs
		for(size_t i = 0; i < length; i++)
		{
			char c = str[i];

			if(c == '\r') nCR++;
			else if(c == '\n') nLF++;

			if(i && cprev == '\r' && c == '\n') nCRLF++;
			cprev = c;
		}
		// evaluate findings
		if(nCR == nLF && nCR == nCRLF)
			lineEnding = leCRLF;
		else if(nCR && !nLF)
			lineEnding = leCR;
		else if(!nCR && nLF)
			lineEnding = leLF;
		else
			lineEnding = leMixed;
	}

	size_t finalLength = 0;
	// calculate the final amount of characters to be allocated.
	for(size_t i = 0; i < length; i++)
	{
		char c = str[i];

		if(c != '\n' || lineEnding != leCRLF)
			finalLength++;
	}

	resize(finalLength);

	size_t cpos = 0;
	for(size_t i = 0; i < length; i++, cpos++)
	{
		char c = str[i];

		switch(c)
		{
		case '\r':
			if(lineEnding != leLF)
				at(cpos) = InternalLineEnding;
			else
				at(cpos) = ' ';
			if(lineEnding == leCRLF) i++;	// skip the LF
			break;
		case '\n':
			if(lineEnding != leCR && lineEnding != leCRLF)
				at(cpos) = InternalLineEnding;
			else
				at(cpos) = ' ';
			break;
		case '\0':
			at(cpos) = ' ';
			break;
		default:
			at(cpos) = c;
			break;
		}
	}

	return true;
}

bool SongMessage::Read(FileReader &file, const size_t length, LineEnding lineEnding)
//----------------------------------------------------------------------------------
{
	FileReader::off_t readLength = std::min(static_cast<FileReader::off_t>(length), file.BytesLeft());
	FileReader::PinnedRawDataView fileView = file.ReadPinnedRawDataView(readLength);
	bool success = Read(fileView.data(), fileView.size(), lineEnding);
	return success;
}

// Read comments with fixed line length from a mapped file.
// [in]  data: pointer to the data in memory that is going to be read
// [in]  length: number of characters that should be read, not including a possible trailing null terminator (it is automatically appended).
// [in]  lineLength: The fixed length of a line.
// [in]  lineEndingLength: The padding space between two fixed lines. (there could for example be a null char after every line)
// [out] returns true on success.
bool SongMessage::ReadFixedLineLength(const mpt::byte *data, const size_t length, const size_t lineLength, const size_t lineEndingLength)
//---------------------------------------------------------------------------------------------------------------------------------------
{
	const char *str = mpt::byte_cast<const char *>(data);
	if(lineLength == 0)
		return false;

	const size_t numLines = (length / (lineLength + lineEndingLength));
	const size_t finalLength = numLines * (lineLength + 1);
	clear();
	reserve(finalLength);

	for(size_t line = 0, fpos = 0, cpos = 0; line < numLines; line++, fpos += (lineLength + lineEndingLength), cpos += (lineLength + 1))
	{
		append(str + fpos, std::min(lineLength, length - fpos));
		append(1, InternalLineEnding);

		// fix weird chars
		for(size_t lpos = 0; lpos < lineLength; lpos++)
		{
			switch(at(cpos + lpos))
			{
			case '\0':
			case '\n':
			case '\r':
				at(cpos + lpos) = ' ';
				break;
			}

		}
	}
	return true;
}

bool SongMessage::ReadFixedLineLength(FileReader &file, const size_t length, const size_t lineLength, const size_t lineEndingLength)
//----------------------------------------------------------------------------------------------------------------------------------
{
	FileReader::off_t readLength = std::min(static_cast<FileReader::off_t>(length), file.BytesLeft());
	FileReader::PinnedRawDataView fileView = file.ReadPinnedRawDataView(readLength);
	bool success = ReadFixedLineLength(fileView.data(), fileView.size(), lineLength, lineEndingLength);
	return success;
}

// Retrieve song message.
// [in]  lineEnding: line ending formatting of the text in memory.
// [out] returns formatted song message.
std::string SongMessage::GetFormatted(const LineEnding lineEnding) const
//----------------------------------------------------------------------
{
	std::string comments;

	if(empty())
	{
		return comments;
	}

	const size_t len = length();
	comments.resize(len);

	size_t writePos = 0;
	for(size_t i = 0; i < len; i++)
	{
		if(at(i) == InternalLineEnding)
		{
			switch(lineEnding)
			{
			case leCR:
			default:
				comments.at(writePos++) = '\r';
				break;
			case leCRLF:
				comments.at(writePos++) = '\r';
				MPT_FALLTHROUGH;
			case leLF:
				comments.at(writePos++) = '\n';
				break;
			}
		} else
		{
			char c = at(i);
			comments.at(writePos++) = c;
		}
	}
	return comments;
}

OPENMPT_NAMESPACE_END


text:
function handles = display_selected_image(handles)
% display_selected_image displays the current image as selected by the
% slider from the current channel. If an ROI has been selected it will be
% displayed as well.
%
% Copyright (c) Molly J. Rossow <molly@mollyrossow.com> August 25 2014

% Get the index selected with the slides.
index = round(get(handles.slImageIndex, 'Value'));

% Display the image
axes(handles.axImage)
hold off
% Multi-frame
if index > 0
    im = handles.data(:,:,index);
else % Single frame
    im = handles.data;
end
imagesc(im) % Display selected image
set(handles.axImage,'XTick',[])
set(handles.axImage,'YTick',[])
axis image
% Draw a box to show the ROI.
if numel(handles.roi) > 0
    handles = draw_roi(handles);
end

end


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=4 sw=4 et tw=99 ft=cpp:
 */

#include <stdio.h>

#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#if IOS
#import <UIKit/UIKit.h>
#else
#import <AppKit/AppKit.h>
#endif
#import <objc/runtime.h>
#import <objc/message.h>

#include "ejs-function.h"
#import "ejs-jsobjc.h"
#include "ejs-objc.h"
#include "ejs-string.h"
#include "ejs-error.h"

#if IOS
#include "ejs-webgl.h"
#endif

#define SPEW(x)

// the keys we use for our associated objects
#define JSCTX_KEY (void*)1
#define JSPEER_KEY (void*)2
#define JSCTOR_KEY (void*)3
#define JSMETHODMAP_KEY (void*)4
#define MONKEYPATCHED_RETAIN_RELEASE (void*)5
#define JSRETAINCOUNT_KEY (void*)6

#define RO_DONT_ENUM_PERMANENT (EJS_PROP_NOT_ENUMERABLE | EJS_PROP_NOT_WRITABLE | EJS_PROP_NOT_CONFIGURABLE)

id
get_objc_id (EJSObjcObject* obj)
{
	EJSObjcObject *handle = [obj objectForPropertyNS:@"_ck_handle"];
	return handle ? ((EJSObjcHandle*)[handle jsObject])->handle : nil;
}

void
set_jspeer (id objc_obj, void*  jspeer)
{
    objc_setAssociatedObject(objc_obj, JSPEER_KEY, jspeer, OBJC_ASSOCIATION_RETAIN);
}

void*
get_jspeer (id objc_obj)
{
    return (void*)objc_getAssociatedObject(objc_obj, JSPEER_KEY);
}

void
set_jsctor (Class cls, void *ctor)
{
    objc_setAssociatedObject(cls, JSCTOR_KEY, ctor, OBJC_ASSOCIATION_RETAIN);
}

void*
get_jsctor (Class cls)
{
    return (void*)objc_getAssociatedObject (cls, JSCTOR_KEY);
}

ejsval _ejs_ObjcHandle;
ejsval _ejs_ObjcHandle_proto;
EJSSpecOps _ejs_objchandle_specops;

static EJS_NATIVE_FUNC(_ejs_ObjcHandle_impl) {
    EJS_NOT_IMPLEMENTED();
}

ejsval
_ejs_objc_handle_new (id handle)
{
    if (handle == nil)
        _ejs_throw_nativeerror_utf8(EJS_ERROR, "_ejs_objc_handle_new passed a nil objc id");

    EJSObjcHandle *rv = _ejs_gc_new(EJSObjcHandle);
    _ejs_init_object ((EJSObject*)rv, _ejs_ObjcHandle_proto, &_ejs_objchandle_specops);

    rv->handle = [handle retain];

    return OBJECT_TO_EJSVAL(rv);
}

EJSObjcObject*
create_objc_handle_object (id objc_id)
{
    ejsval handle = _ejs_objc_handle_new(objc_id);

    return [EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(handle)];
}

id
ejs_objc_handle_get_id (ejsval handleval)
{
    EJSObjcHandle* handleobj = (EJSObjcHandle*)EJSVAL_TO_OBJECT(handleval);
    return handleobj->handle;
}

ejsval _ejs_CoffeeKitObject;
ejsval _ejs_CoffeeKitObject_proto;
EJSSpecOps _ejs_coffeekitobject_specops;

static EJS_NATIVE_FUNC(_ejs_CoffeeKitObject_impl) {
    EJS_NOT_IMPLEMENTED();
}

static EJS_NATIVE_FUNC(_ejs_CoffeeKitObject_setHandle) {
	EJSObjcObject* thisObject = [EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(*_this)];

	SPEW(NSLog (@"made it to coffeekit_object_set_handle, argumentCount = %u", argc);)

    EJSObjcHandle* handleArg = (EJSObjcHandle*)EJSVAL_TO_OBJECT (args[0]);

	if (handleArg->handle == nil) {
        _ejs_throw_nativeerror_utf8(EJS_ERROR, "setHandle called with nil handle");
	}

	[thisObject definePropertyNS:@"_ck_handle"
     object:[EJSObjcObject objectWithJSObject:(EJSObject*)handleArg]
		    attributes:EJS_PROP_NOT_WRITABLE | EJS_PROP_NOT_CONFIGURABLE];

	set_jspeer (handleArg->handle, thisObject);

    return _ejs_undefined;
}

static EJS_NATIVE_FUNC(_ejs_CoffeeKitObject_prototype_toString) {
	EJSObjcObject* thisObject = [EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(*_this)];
    NSString* desc = [NSString stringWithFormat:@"%@",  get_objc_id(thisObject)];
    return STRING_TO_EJSVAL([[EJSObjcString stringWithNSString:desc] jsString]);
}

void
_ejs_objc_init(ejsval global)
{
    _ejs_objchandle_specops =  _ejs_Object_specops;
    _ejs_objchandle_specops.class_name = "ObjcHandle";

    _ejs_gc_add_root (&_ejs_ObjcHandle_proto);
    _ejs_ObjcHandle_proto = _ejs_object_new(_ejs_Object_prototype, &_ejs_objchandle_specops);

    _ejs_ObjcHandle = _ejs_function_new_native (_ejs_null, _ejs_atom_ObjcHandle, _ejs_ObjcHandle_impl);

    _ejs_object_setprop (_ejs_ObjcHandle, _ejs_atom_prototype,  _ejs_ObjcHandle_proto);
    _ejs_object_setprop (_ejs_ObjcHandle_proto, _ejs_atom_constructor,  _ejs_ObjcHandle);

    _ejs_object_setprop (global, _ejs_atom_ObjcHandle, _ejs_ObjcHandle);

    _ejs_coffeekitobject_specops =  _ejs_Object_specops;
    _ejs_coffeekitobject_specops.class_name = "PirouetteObject";

    _ejs_gc_add_root (&_ejs_CoffeeKitObject_proto);
    _ejs_CoffeeKitObject_proto = _ejs_object_new(_ejs_Object_prototype, &_ejs_coffeekitobject_specops);

    _ejs_CoffeeKitObject = _ejs_function_new_native (_ejs_null, _ejs_atom_PirouetteObject, (EJSClosureFunc)_ejs_CoffeeKitObject_impl);

    _ejs_object_setprop (_ejs_CoffeeKitObject, _ejs_atom_prototype,  _ejs_CoffeeKitObject_proto);
    _ejs_object_setprop (_ejs_CoffeeKitObject_proto, _ejs_atom_constructor,  _ejs_CoffeeKitObject);

    EJS_INSTALL_ATOM_FUNCTION(_ejs_CoffeeKitObject, setHandle, _ejs_CoffeeKitObject_setHandle);
    EJS_INSTALL_ATOM_FUNCTION(_ejs_CoffeeKitObject_proto, toString, _ejs_CoffeeKitObject_prototype_toString);

    _ejs_object_setprop (global, _ejs_atom_PirouetteObject, _ejs_CoffeeKitObject);
}

static EJS_NATIVE_FUNC(_ejs_objc_requireFramework) {
    // this needs to go away, replaced by a pragma that the compiler can react to
    return _ejs_undefined;
}

static EJS_NATIVE_FUNC(_ejs_objc_allocInstance) {
    if (argc == 0)
        return _ejs_null;

    ejsval clsname = args[0];

    if (!EJSVAL_IS_STRING(clsname))
        _ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "args0 for allocInstance must be a string");

    char *clsname_utf8 = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(args[0]));
    Class cls = objc_getClass (clsname_utf8);
    NSLog (@"allocating instance of %s/%p\n", clsname_utf8, cls);
    free (clsname_utf8);

    id instance = class_createInstance (cls, 0);
    NSLog (@"class_createInstance returned %@\n", instance);
    ejsval rv = _ejs_objc_handle_new (instance); // this retains
    [instance release]; // so we release instance here

    return rv;
}

static id (*PerformReturningId)(id performOn, SEL selector) = (id (*)(id, SEL))objc_msgSend;

static EJS_NATIVE_FUNC(_ejs_objc_staticCall) {
    const char *clsname_cstr = [[EJSObjcString stringWithJSString:EJSVAL_TO_STRING(args[0])] UTF8String];
    const char *selector_cstr = [[EJSObjcString stringWithJSString:EJSVAL_TO_STRING(args[1])] UTF8String];

    Class cls = objc_getClass (clsname_cstr);
    SEL sel = sel_getUid (selector_cstr);

	return OBJECT_TO_EJSVAL([create_objc_handle_object (PerformReturningId(cls, sel)) jsObject]);
}

static EJS_NATIVE_FUNC(_ejs_objc_getInstanceVariable) {
	SPEW(NSLog (@"in _icall_objc_getInstanceVariable");)
	if (argc != 2) {
		NSLog (@"getInstanceVariable requires 2 args");
		// XXX throw an exception here
		abort();
	}

	id handle = get_objc_id ([EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(args[0])]);

	if (!handle) {
		NSLog (@"getInstanceVariable first parameter has no handle");
		// XXX throw an exception here
		abort();
	}
    char* ivar_utf8 = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(args[1]));
	id ivar_value = nil;

	SPEW(NSLog (@"    %@:%s", handle, ivar_utf8););

	object_getInstanceVariable (handle, ivar_utf8, (void**)&ivar_value);
	free (ivar_utf8);

	SPEW(NSLog (@"    returning value = %@", ivar_value);)

	if (ivar_value)
		return OBJECT_TO_EJSVAL([create_objc_handle_object (ivar_value) jsObject]);
	else
		return _ejs_null;
}

static EJS_NATIVE_FUNC(_ejs_objc_setInstanceVariable) {
	SPEW(NSLog (@"in _icall_objc_setInstanceVariable");)
	if (argc != 3) {
		NSLog (@"setInstanceVariable requires 3 args");
		// XXX throw an exception here
		abort();
	}

	id handle = get_objc_id ([[EJSObjcValue valueWithJSValue:args[0]] objectValue]);
	if (!handle) {
		NSLog (@"setInstanceVariable first parameter has no handle");
		// XXX throw an exception here
		abort();
	}
    char* ivar_utf8 = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(args[1]));

	id value_handle = get_objc_id ([[EJSObjcValue valueWithJSValue:args[2]] objectValue]);

	SPEW(NSLog (@"  setting %s on %@ to %@ ", ivar_utf8, handle, value_handle);)

	object_setInstanceVariable (handle, ivar_utf8, value_handle);
	free (ivar_utf8);

    return _ejs_undefined;
}

static EJS_NATIVE_FUNC(invokeSelectorFromJS);

static EJS_NATIVE_FUNC(_ejs_objc_selectorInvoker) {
    if (!EJSVAL_IS_STRING(args[0])) {
        _ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "non-string passed to objc.selectorInvoker");
    }

    char *selname_utf8 = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(args[0]));

    //NSLog (@"in _ejs_objc_selectorInvoker (%s)", selname_utf8);

    EJSObjcObject* func = [EJSObjcObject makeFunctionNS:[NSString stringWithFormat:@"__ejs_invoke_%s_from_js", selname_utf8] withCallback:(EJSClosureFunc)invokeSelectorFromJS argCount:0];

    free (selname_utf8);

    [func definePropertyNS:@"_ck_sel"
          value:[EJSObjcValue valueWithJSValue:args[0]]
          attributes:RO_DONT_ENUM_PERMANENT];

    return OBJECT_TO_EJSVAL([func jsObject]);
}

static EJS_NATIVE_FUNC(_ejs_objc_getTypeEncoding) {
    EJS_NOT_IMPLEMENTED();
}

@interface MethodInfo : NSObject {
    NSString* _name;
    SEL _sel;
    NSString* _sig;
    NSMethodSignature* _methodSig;
}

-(id) initWithName:(NSString*)name_str selector:(SEL)selector typeSig:(const char*)type_str;
-(NSMethodSignature*) resolveSigWithClass:(Class)cls staticMethod:(BOOL)static_method;
-(NSString*) name;
-(SEL) sel;
-(NSString*) sig;
-(NSString*) description;

@end

@implementation MethodInfo
-(id) initWithName:(NSString*)name_str selector:(SEL)selector typeSig:(const char*)type_str
{
    self = [super init];
    _name = [name_str retain];
    _sel = selector;
    _sig = [[NSString alloc] initWithUTF8String:type_str];
    return self;
}

-(NSMethodSignature*) resolveSigWithClass:(Class)cls staticMethod:(BOOL)static_method
{
    if (_methodSig)
        return _methodSig;

    //  NSLog (@"resolveSigWithClass %@ (static = %s)", _name, static_method ? "YES" : "NO");
    Method meth = static_method ? class_getClassMethod (cls, _sel) : class_getInstanceMethod (cls, _sel);

    if (!meth) {
        NSString* str = [NSString stringWithFormat:@"failed to locate method `%s' on class %@", sel_getName(_sel), cls];
        _ejs_throw_nativeerror_utf8(EJS_ERROR, [str UTF8String]);
    }

    //  NSLog (@"method type encoding = %s", method_getTypeEncoding (meth));

    _methodSig = [[NSMethodSignature signatureWithObjCTypes:method_getTypeEncoding (meth)] retain];

    return _methodSig;
}

-(NSString*) name
{
    return _name;
}

-(SEL) sel
{
    return _sel;
}

-(NSString*) sig
{
    return _sig;
}

-(NSString*) description
{
    return [NSString stringWithFormat:@"<MethodInfo name=%@ sel=%s sig=%@>", _name, sel_getName(_sel), _sig];
}
@end

static const char*
get_selector_name_from_function (EJSObjcObject* function)
{
    return [function utf8StringForPropertyNS:@"_ck_sel"];
}

static const char*
get_type_sig_from_function (EJSObjcObject* function)
{
    return [function utf8StringForPropertyNS:@"_ck_typeSig"];
}

static const char*
get_type_encoding_from_function (EJSObjcObject* function)
{
    return [function utf8StringForPropertyNS:@"_ck_typeEncoding"];
}

static SEL
get_selector_from_function (EJSObjcObject* function)
{
    return sel_getUid(get_selector_name_from_function (function));
}

static bool
is_function_exported (EJSObjcObject* func)
{
    EJSObjcValue* propval = [func valueForPropertyNS:@"_ck_exported"];

    return [propval isBool] && [propval boolValue];
}

static EJSObjcObject*
get_object_prototype_method ( NSString *name)
{
    EJS_NOT_IMPLEMENTED();
#if notyet
	EJSObjcObject* object_proto = [[[ctx globalObject] objectForPropertyNS:@"Object"] prototype];
	return [object_proto objectForPropertyNS:name];
#endif
}

static EJSObjcValue*
marshal_id_as_jsvalue (id objc_id, BOOL protect)
{
    if (objc_id == nil) {
        SPEW(NSLog (@"returning null");)
        return [EJSObjcValue nullValue];
    }

    if ([objc_id isKindOfClass:[NSString class]]) {
        return [EJSObjcValue nsStringValue:(NSString*)objc_id];
    }

    EJSObjcObject* ctor_obj = NULL;
    Class return_class = object_getClass (objc_id);

    do {
        SPEW(NSLog (@"return_class = %@", return_class);)

        ctor_obj = get_jsctor(return_class);

        //          NSLog (@"ctor_obj = %p", ctor_obj);

        if (!ctor_obj) {
            return_class = class_getSuperclass (return_class);
            if (return_class == NULL) {
                NSLog (@"no further superclasses, bailing...");
                abort();
            }
        }

    } while (ctor_obj == NULL);

    // this will retain objc_id
    EJSObjcObject* handle = create_objc_handle_object (objc_id);
    EJSObjcValue* handle_val = [EJSObjcValue objectValue:handle];
    //        NSLog (@"handle = %p", handle);

    EJSObjcInvocation *inv = [EJSObjcInvocation invocationWithConstructor:ctor_obj argCount:1];

    [inv setArgument:handle_val atIndex:0];

    // and this will create a ref to the handle_val so that the lifetime of the objc_id will be at least
    // as long as the lifetime of jspeer.
    EJSObjcValue* rv = [inv invoke];
    EJSObjcObject* jspeer = [rv objectValue];
    if (jspeer == NULL)
        [NSException raise:@"Exception marshaling id as jsvalue" format:@"%@", [inv exception]];

    //        NSLog (@"peer = %p", jspeer);
    set_jspeer (objc_id, jspeer);

    return rv;
}

static EJSObjcValue*
marshal_cgrect_as_jsvalue (CGRect *rect)
{
	EJSObjcString* x_ = [EJSObjcString stringWithUTF8CString:"x"];
	EJSObjcString* y_ = [EJSObjcString stringWithUTF8CString:"y"];
	EJSObjcString* width_ = [EJSObjcString stringWithUTF8CString:"width"];
	EJSObjcString* height_ = [EJSObjcString stringWithUTF8CString:"height"];

    EJSObjcObject* peer = [EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(_ejs_object_create(_ejs_null))];

    [peer defineProperty:x_ value:[EJSObjcValue numberValue:rect->origin.x]
          attributes:RO_DONT_ENUM_PERMANENT];

    [peer defineProperty:y_ value:[EJSObjcValue numberValue:rect->origin.y]
          attributes:RO_DONT_ENUM_PERMANENT];

    [peer defineProperty:width_ value:[EJSObjcValue numberValue:rect->size.width]
          attributes:RO_DONT_ENUM_PERMANENT];

    [peer defineProperty:height_ value:[EJSObjcValue numberValue:rect->size.height]
          attributes:RO_DONT_ENUM_PERMANENT];

    return [EJSObjcValue objectValue:peer];
}

static NSArray*
marshal_jsarray_as_nsarray (EJSObjcObject *o)
{
	int length = [o arrayLength];
        int i;

        NSMutableArray *nsarray = [NSMutableArray arrayWithCapacity:length];

        for (i = 0; i < length; i ++) {
                EJSObjcObject* el = [o objectForPropertyNS:[NSString stringWithFormat:@"%d", i]];
                [nsarray addObject:get_objc_id(el)];
        }

        return [NSArray arrayWithArray:nsarray];
}

static EJS_NATIVE_FUNC(invokeSelectorFromJS) {
    EJSObjcObject *thisObj = [EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(*_this)];

#if old
    SEL sel = get_selector_from_function (func);
#else
    SEL sel = sel_getUid([[EJSObjcValue valueWithJSValue:args[0]] utf8StringValue]);
#endif
    id handle = get_objc_id (thisObj);
    Method meth = NULL;
    const char *typeEncoding = NULL;
    void** free_ptrs = NULL;

    if (handle == nil) {
        const char *register_cstr = [thisObj utf8StringForPropertyNS:@"_ck_register"];

        if (register_cstr) {
            Class cls = objc_getClass (register_cstr);
            meth = class_getClassMethod (cls, sel);
            if (meth != NULL)
                handle = cls;
        }
    }
    else {
        meth = class_getInstanceMethod (object_getClass (handle), sel);
    }

    if (!meth) {
        abort();
    }

    SPEW(NSLog (@"invoking %s on %@\n", sel_getName (sel), handle);)

#if false
    typeEncoding = get_type_encoding_from_function (func);
#endif
    if (!typeEncoding) {
        SPEW(NSLog (@"getting type encoding from objc");)
        typeEncoding = method_getTypeEncoding (meth);
        SPEW(NSLog (@" it was %s", typeEncoding);)
        if (!typeEncoding) {
            NSString* str = [NSString stringWithFormat:@"failed to locate selector `%s'.  this is usually due to a framework not being linked against.", sel_getName (sel)];
            _ejs_throw_nativeerror_utf8(EJS_ERROR, [str UTF8String]);
        }
    }
    SPEW(NSLog (@"  type = %s", typeEncoding);)

        if (handle == NULL) {
        _ejs_throw_nativeerror_utf8(EJS_ERROR, "NULL handle in invokeSelectorFromJS");
    }

    if (sel == NULL) {
        _ejs_throw_nativeerror_utf8(EJS_ERROR, "NULL selector in invokeSelectorFromJS");
    }

    NSMethodSignature *sig = [NSMethodSignature signatureWithObjCTypes:typeEncoding];
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];

    if ((argc + 2 - 1 /* the -1 to get rid of the selector passed as arg0 */) != [sig numberOfArguments]) {
        NSLog (@"Incorrect number of arguments to objective-C method %s on %@ (type encoding %s).  expected = %lu, offered = %u", sel_getName(sel), handle, typeEncoding, (unsigned long)[sig numberOfArguments], argc + 2);
        return _ejs_null;
    }

    free_ptrs = (void**)calloc(sizeof(void*), argc);
    [inv setTarget:handle];
    [inv setSelector:sel];

    int i;
    for (i = 0; i < argc-1; i ++) {
        int objc_arg_num = i+2;
        const char* arg_type = [sig getArgumentTypeAtIndex:objc_arg_num];
        EJSObjcValue* val = [EJSObjcValue valueWithJSValue:args[i+1]];

		SPEW(NSLog(@"marshaling arg[%d], type %s", i, arg_type);)

        switch (arg_type[0]) {
        case _C_ID: {
            void* arg_ptr = NULL;

            if ([val isString]) {
                // create an NSString for this arg
                arg_ptr = [[val stringValue] nsString];
                //            NSLog (@"arg %d: string marshalling of %@", i, arg_ptr);
            }
            else if ([val isNull] || [val isUndefined]) {
                arg_ptr = nil;
                //            NSLog (@"arg %d: object marshalling of %@", i, arg_ptr);
            }
            else if ([val isObject]) {
                // fetch the objc handle from this arg
                EJSObjcObject* o = [val objectValue];
                arg_ptr = get_objc_id (o);
                if (arg_ptr == NULL) {
                    if ([o isArray]) {
                        // let's assume we marshal this as an NSArray for now... XXX
                        arg_ptr = marshal_jsarray_as_nsarray (o);
                    }
                }
				SPEW(NSLog (@"arg %d: object marshalling of %@", i, arg_ptr);)
            }
            else {
#if notyet_spidermonkey
                NSLog (@"arg %d: skipping @ marshaling arg (unhandled JS type %d)", i, JSValueGetType (cx, JS_ARGV(cx,vp)[i]));
                NSLog (@"selector: %s", sel_getName (sel));
                int j;
                for (j = 0; j < argc; j ++) {
                    NSLog (@"arg %d: JS type %d", j, JSValueGetType (cx, JS_ARGV(cx,vp)[i]));
                }
#else
				NSLog (@"error marshaling 1");
#endif
                abort();
            }

            [inv setArgument:&arg_ptr atIndex:objc_arg_num];
            break;
        }

        case _C_SEL: {
            if ([val isObject] && [[val objectValue] isFunction]) {
                SEL sel = get_selector_from_function ([val objectValue]);
                SPEW(NSLog (@"arg %d: marshaling selector %s", i, sel ? sel_getName (sel) : "<NULL>");)
                [inv setArgument:&sel atIndex:objc_arg_num];
            }
            else if ([val isString]) {
                const char *sel_str = [[val stringValue] UTF8String];
                SPEW(NSLog (@"arg %d: marshaling selector %s", i, sel_str);)
                SEL sel = sel_getUid (sel_str);
                [inv setArgument:&sel atIndex:objc_arg_num];
            }
            else {
#if notyet_spidermonkey
                NSLog (@"arg %d: skipping selector marshaling arg (unhandled JS type %d)", i, JSValueGetType (cx, JS_ARGV(cx,vp)[i]));
#else
				NSLog (@"error marshaling 2");
#endif
                abort();
            }
            break;
        }

        case _C_FLT: {
            float v = (float)[val numberValue];
			SPEW(NSLog (@"arg %d: marshaling float = %g", i, v);)
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_DBL: {
            double v = (double)[val numberValue];
			SPEW(NSLog (@"arg %d: marshaling double = %g", i, v);)
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_INT: {
            int32_t v = (int32_t)[val numberValue];
			SPEW(NSLog (@"arg %d: marshaling int = %d", i, v);)
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_UINT: {
            uint32_t v = (uint32_t)[val numberValue];
			SPEW(NSLog (@"arg %d: marshaling uint = %u", i, v);)
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_LNG_LNG: {
            int64_t v = (int64_t)[val numberValue];
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_ULNG_LNG: {
            uint64_t v = (uint64_t)[val numberValue];
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_CHR: {
#if !IOS
            char v = (char)[val numberValue];
#else
            int32_t v = (int32_t)[val numberValue];
#endif
            [inv setArgument:&v atIndex:objc_arg_num];
            break;
        }

        case _C_CHARPTR: {
            const char* jsstr = [[val stringValue] UTF8String];
            [inv setArgument:&jsstr atIndex:objc_arg_num];
            break;
        }

        case _C_STRUCT_B: {
            // marshal by duck typing, not by the JS type, so we can accept object literals

            if (!strncmp (&arg_type[1], "CGRect", strlen ("CGRect"))
                || !strncmp (&arg_type[1], "NSRect", strlen ("NSRect"))) {
                // FIXME: handle both x,y,width,height and position,size?
                //JSValueRef* js_exc = NULL;

                EJSObjcObject* rectobj = [val objectValue];
                CGRect *rect = (CGRect*)malloc (sizeof (CGRect));

                rect->origin.x = [rectobj floatForPropertyNS:@"x"];
                rect->origin.y = [rectobj floatForPropertyNS:@"y"];
                rect->size.width = [rectobj floatForPropertyNS:@"width"];
                rect->size.height = [rectobj floatForPropertyNS:@"height"];

                NSLog (@"marshaling rectangle %g %g %g %g", rect->origin.x, rect->origin.y, rect->size.width, rect->size.height);

                free_ptrs[i] = rect;

                [inv setArgument:rect atIndex:objc_arg_num];
            }
#if IOS
            else if (!strncmp (&arg_type[1], "UIEdgeInsets", strlen ("UIEdgeInsets"))) {

                EJSObjcObject* insetsobj = [val objectValue];

                UIEdgeInsets *insets = (UIEdgeInsets*)malloc (sizeof (UIEdgeInsets));
                insets->top = [insetsobj floatForPropertyNS:@"top"];
                insets->left = [insetsobj floatForPropertyNS:@"left"];;
                insets->bottom = [insetsobj floatForPropertyNS:@"bottom"];;
                insets->right = [insetsobj floatForPropertyNS:@"right"];;

                free_ptrs[i] = insets;

                [inv setArgument:insets atIndex:objc_arg_num];
            }
            else if (!strncmp (&arg_type[1], "UIOffset", strlen ("UIOffset"))) {

                EJSObjcObject* offsetobj = [val objectValue];

                UIOffset *offset = (UIOffset*)malloc (sizeof (UIOffset));
                offset->horizontal = [offsetobj floatForPropertyNS:@"horizontal"];
                offset->vertical = [offsetobj floatForPropertyNS:@"vertical"];

                free_ptrs[i] = offset;

                [inv setArgument:offset atIndex:objc_arg_num];
            }
#endif
            else {
                NSLog (@"skipping marshaling arg %d (unhandled struct type %s)", objc_arg_num, arg_type);
                abort();
            }
            break;
        }

        default:
            NSLog (@"skipping marshaling arg %d (unhandled objc type %s)", objc_arg_num, arg_type);
            abort();
            break;
        }
    }

    SPEW(NSLog (@" start objc invoke");)
    [inv invoke];
    SPEW(NSLog (@" end objc invoke");)

    // free the marshaled structs
    for (i = 0; i < argc; i ++)
        if (free_ptrs[i])
            free (free_ptrs[i]);
    free(free_ptrs);

    const char *return_type = [sig methodReturnType];
    // bail early if the return type is void
    if (return_type[0] == _C_VOID) {
		return _ejs_undefined;
	}

    NSUInteger return_length = [sig methodReturnLength];
    void* return_buffer = (void *)malloc(return_length);
    EJSObjcValue* rv;

    [inv getReturnValue:return_buffer];

    // marshal the rv
    switch (return_type[0]) {
    case _C_ID: {
        SPEW(NSLog (@"@ return type, creating JS peer, return_buffer = %p, value = %p", return_buffer, *(id*)return_buffer);)
        rv = marshal_id_as_jsvalue(*(id*)return_buffer, YES);
        break;
    }

    case _C_STRUCT_B: {
        if (!strncmp (&return_type[1], "CGRect", strlen ("CGRect"))
            || !strncmp (&return_type[1], "NSRect", strlen ("NSRect"))) {
            // XXX this should return an instance of foundation.NSRect
            // but for now we just return a new empty object with the
            // right fields set.
            rv = marshal_cgrect_as_jsvalue ((CGRect*)return_buffer);
        }
        else {
            NSString* str = [NSString stringWithFormat:@"unhandled struct return type `%s'", return_type];
            _ejs_throw_nativeerror_utf8(EJS_ERROR, [str UTF8String]);
        }
        break;
    }

    case _C_CHR:
        rv = [EJSObjcValue numberValue:*(int8_t*)return_buffer];
        break;
    case _C_UCHR:
        rv = [EJSObjcValue numberValue:*(uint8_t*)return_buffer];
        break;
    case _C_SHT:
        rv = [EJSObjcValue numberValue:*(int16_t*)return_buffer];
        break;
    case _C_USHT:
        rv = [EJSObjcValue numberValue:*(uint16_t*)return_buffer];
        break;
    case _C_INT:
        rv = [EJSObjcValue numberValue:*(int32_t*)return_buffer];
        break;
    case _C_UINT:
        rv = [EJSObjcValue numberValue:*(uint32_t*)return_buffer];
        break;
    case _C_LNG_LNG:
        rv = [EJSObjcValue numberValue:*(int64_t*)return_buffer];
        break;
    case _C_ULNG_LNG:
        rv = [EJSObjcValue numberValue:*(uint64_t*)return_buffer];
        break;
    case _C_FLT:
	rv = [EJSObjcValue numberValue:*(float*)return_buffer];
	break;
    case _C_DBL:
	rv = [EJSObjcValue numberValue:*(double*)return_buffer];
	break;

    default: {
        NSString* str = [NSString stringWithFormat:@"unhandled return type `%s'", return_type];
        _ejs_throw_nativeerror_utf8(EJS_ERROR, [str UTF8String]);
    }
    }

    free (return_buffer);
    return [rv jsValue];
}

static EJSObjcObject*
get_js_peer (id obj, id *class_out, BOOL *static_method)
{
    EJSObjcObject* jspeer = get_jspeer (obj);
    if (jspeer == NULL) {
        jspeer = get_jsctor (obj);
        if (jspeer == NULL) {
            SPEW(NSLog (@"null peer somehow made it to the method tramp...");)
            abort ();
        }
        else {
            *class_out = obj;
            *static_method = YES;
        }
    }
    else {
        *class_out = [obj class];
        *static_method = NO;
    }

    return jspeer;
}

static void*
coffeekit_method_tramp (id obj, SEL sel, ...)
{
    const char *sel_name = sel_getName(sel);
    id cls;
    BOOL static_method = false;
    va_list ap;

    SPEW(NSLog (@"coffeekit_method_tramp (%@, %s)", obj, sel_name);)

    EJSObjcObject* jspeer = get_js_peer (obj, &cls, &static_method);

    NSString* sel_nsstr = [NSString stringWithUTF8String:sel_name];
    NSMutableDictionary *method_map = objc_getAssociatedObject (cls, JSMETHODMAP_KEY);
    if (method_map == NULL) {
        SPEW(NSLog (@"null method_map somehow made it to the method tramp...");)
        abort ();
    }

    MethodInfo* meth_info = [method_map objectForKey:sel_nsstr];
    NSString* name_nsstr = [meth_info name];
    NSMethodSignature* sig = [meth_info resolveSigWithClass:cls staticMethod:static_method];

    SPEW(NSLog (@"method_map[%@] = %@, looking up on jspeer %@", sel_nsstr, name_nsstr, jspeer);)

    EJSObjcObject* func = [jspeer objectForPropertyNS:name_nsstr];

    SPEW(NSLog (@"found it!");)

    if (!func || ![func isFunction]) {
        SPEW(NSLog (@"it's not a function, returning");)
        return NULL;
    }

#if notyet
    int func_arity = [func functionArity];
    int jsarg_count = MIN(func_arity, [sig numberOfArguments] - 2);
#else
    int jsarg_count = [sig numberOfArguments] - 2;
#endif
    int jsarg_num;

    EJSObjcInvocation* inv = [EJSObjcInvocation invocationWithFunction:func argCount:jsarg_count thisObject:jspeer];

    [inv setThisObject:jspeer];
    [inv setFunction:func];

    va_start (ap, sel);

    for (jsarg_num = 0; jsarg_num < jsarg_count; jsarg_num++) {
        const char *arg_type = [sig getArgumentTypeAtIndex:jsarg_num + 2];
        switch (arg_type[0]) {
            case _C_ID: {
                id objc_id = va_arg (ap, id);
                [inv setArgument:marshal_id_as_jsvalue(objc_id, YES) atIndex:jsarg_num];
                break;
            }
            case _C_STRUCT_B: {
                if (!strncmp (&arg_type[1], "CGRect", strlen ("CGRect")) || !strncmp (&arg_type[1], "NSRect", strlen ("NSRect"))) {
                    CGRect rect = va_arg (ap, CGRect);
                    [inv setArgument:marshal_cgrect_as_jsvalue(&rect) atIndex:jsarg_num];
                }
                else {
                    NSString* str = [NSString stringWithFormat:@"unhandled tramp arg marshalling for struct type `%s'", arg_type];
                    _ejs_throw_nativeerror_utf8(EJS_ERROR, [str UTF8String]);
                }
                break;
            }
            case _C_INT: {
                int32_t i = va_arg(ap, int32_t);
                [inv setArgument:[EJSObjcValue numberValue:i] atIndex:jsarg_num];
                break;
            }
            case _C_UINT: {
                uint32_t i = va_arg(ap, uint32_t);
                [inv setArgument:[EJSObjcValue numberValue:i] atIndex:jsarg_num];
                break;
            }
            case _C_LNG_LNG: {
                int64_t i = va_arg(ap, int64_t);
                [inv setArgument:[EJSObjcValue numberValue:i] atIndex:jsarg_num];
                break;
            }
            case _C_ULNG_LNG: {
                uint64_t i = va_arg(ap, uint64_t);
                [inv setArgument:[EJSObjcValue numberValue:i] atIndex:jsarg_num];
                break;
            }
            default: {
                /*id objc_id =*/ va_arg (ap, id);

                NSLog (@"unhandled tramp arg marshaling for type %s", arg_type);
                [inv setArgument:[EJSObjcValue undefinedValue] atIndex:jsarg_num];
                break;
            }
        }
    }

    va_end(ap);

    EJSObjcValue* rv = [inv invoke];

    if (rv == NULL) {
      NSLog(@"WTF");
      NSLog(@"WTF");
      NSLog(@"WTF");
      NSLog(@"WTF");
      NSLog(@"WTF");
      NSLog(@"WTF");
      NSLog(@"WTF");
      NSLog(@"WTF");
        [NSException raise:@"Exception calling JS method" format:@"%@", [inv exception]];
    }

    // marshal the JS return value to objective-c
    const char *return_type = [sig methodReturnType];

    // bail out early (and ignore the JS return value) if the return type is void
    if (return_type[0] == _C_VOID) return NULL;

    switch (return_type[0]) {
        case _C_ID: {
            if ([rv isString]) return [[rv stringValue] nsString];
            return [rv isObject] ? get_objc_id([rv objectValue]) : NULL;
        }
        case _C_CHR: {
            return [rv isBool] ? (void*)(NSInteger)[rv boolValue] : (void*)(NSInteger)[rv numberValue];
        }
        case _C_INT:
        case _C_LNG:
        case _C_LNG_LNG: {
            return [rv isNumber] ? (void*)(NSInteger)[rv numberValue] : (void*)(NSInteger)0;
        }
        case _C_UINT:
        case _C_ULNG:
        case _C_ULNG_LNG: {
            return [rv isNumber] ? (void*)(NSUInteger)[rv numberValue] : (void*)(NSUInteger)0;
        }
        case _C_CLASS: {
            //    NSLog (@"_C_CLASS return value marshalling");

            EJSObjcObject* o = [rv objectValue];

            const char* register_cstr = [o utf8StringForPropertyNS:@"_ck_register"];

            if (!register_cstr) {
                NSLog (@"invalid or missing _ck_register on a object returned for where Class JS->objc marshalling was assumed");
                return NULL;
            }

            SPEW(NSLog (@"objective C class for return value is %s", register_cstr);)

            Class cls = objc_getClass (register_cstr);

            return cls;
        }
    }

    // XXX
    NSLog (@"XXX");
    abort();
    return nil;
}

static id
coffeekit_ctor_tramp (id obj, SEL sel, ...)
{
    SPEW(NSLog (@"coffeekit_ctor_tramp (%@, %s)", obj, sel_getName(sel));)

    Class cls = [obj class];

    EJSObjcObject* js_ctor = get_jsctor(cls);

    EJSObjcInvocation* inv = [EJSObjcInvocation invocationWithConstructor:js_ctor argCount:1];

	EJSObjcObject* handle = create_objc_handle_object(obj);
	EJSObjcValue* handle_val = [EJSObjcValue objectValue:handle];

    [inv setArgument:handle_val atIndex:0];

    EJSObjcValue* rv = [inv invoke];
    if (rv == NULL) {
        [NSException raise:@"Exception creating new JS wrapper" format:@"%@", [inv exception]];
    }
	if (![rv isObject]) {
        [NSException raise:@"Constructor returned something other than an object" format:@"%@", [inv exception]];
    }

    EJSObjcObject* peer = [rv objectValue];

	SPEW(NSLog (@"ctor created peer %@", peer);)

    set_jspeer (obj, peer);

    return obj;
}

static EJSObjcObject*
register_members (Class cls, EJSObjcObject* obj, NSMutableDictionary* method_map)
{
	EJSObjcObject* ctor = NULL;
    EJSObject* _obj = [obj jsObject];

    for (_EJSPropertyMapEntry* s = _obj->map->head_insert; s; s = s->next_insert) {
        if (_ejs_property_desc_has_getter(s->desc) ||
            _ejs_property_desc_has_setter(s->desc)) {
			if (_ejs_property_desc_has_getter(s->desc)) {

                char *utf8 = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(s->name));
                EJSObjcString* name = [EJSObjcString stringWithUTF8CString:utf8];

                EJSObjcObject *getter = [EJSObjcObject objectWithJSObject:EJSVAL_TO_OBJECT(s->desc->getter)];
                NSLog (@"there was a getter for %@", [name nsString]);
				EJSObjcValue* ck_ivar = [getter valueForPropertyNS:@"_ck_ivar"];

				if ([ck_ivar isString]) {
                    const char *ivar_name = [[ck_ivar stringValue] UTF8String];
                    NSLog (@" and there's an ivar named %s", ivar_name);
                    if (NO == class_addIvar (cls, ivar_name, sizeof(id), log2(sizeof(id)), "@")) {
                        NSLog (@"failed to add ivar");
                    }
                }
			}
		}
		else {
            char *utf8 = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(s->name));
            EJSObjcString* name = [EJSObjcString stringWithUTF8CString:utf8];
            free (utf8);
            NSString* name_nsstr = [name nsString];

			EJSObjcObject* propobj = [obj objectForProperty:name];

			if (!propobj || ![propobj isFunction]) {
                SPEW (NSLog (@"property %@ isn't a function, skipping for now", name_nsstr);)
				continue;
			}

			if (NSOrderedSame == [name_nsstr compare:@"constructor"]) {
				ctor = propobj;

				[method_map setObject:name_nsstr forKey:@"init"];

				class_addMethod (cls, sel_getUid ("init"), (IMP)coffeekit_ctor_tramp, "@@:");
			}
			else {
				if (!is_function_exported (propobj)) {
                    SPEW(NSLog (@"function %@ isn't exported, skipping", name_nsstr);)
					continue;
				}

				const char *sel_name = get_selector_name_from_function (propobj);
				const char *type_sig = get_type_sig_from_function (propobj);

				SEL sel = sel_getUid(sel_name);

				SPEW(NSLog (@"adding method %s/%s in class %s", sel_name, type_sig, class_getName(cls));)

				MethodInfo *info = [[MethodInfo alloc] initWithName:name_nsstr selector:sel typeSig:type_sig];
				[method_map setObject:info forKey:[NSString stringWithUTF8String:sel_name]];
				[info release];

				class_addMethod (cls, sel, (IMP)coffeekit_method_tramp, type_sig);
			}
		}
	}

	return ctor;
}

static Class
register_js_class (EJSObjcObject* proto,
                   const char *register_name,
                   const char *super_register_name)
{
	id cls = objc_getClass (register_name);

	if (cls) {
		// if the class was already registered (it's builtin),
		// just add the corresponding ctor
	        if (objc_getAssociatedObject (cls, MONKEYPATCHED_RETAIN_RELEASE) == NULL) {
//                      Method retain = class_getInstanceMethod (cls, sel_getUid ("retain"));
//                      Method release = class_getInstanceMethod (cls, sel_getUid ("release"));

			objc_setAssociatedObject (cls, MONKEYPATCHED_RETAIN_RELEASE, (id)1, OBJC_ASSOCIATION_ASSIGN);

//                      class_replaceMethod(cls, sel_getUid("retainCount"), (IMP)monkey_retainCount, "I@:");
//                      class_replaceMethod(cls, sel_getUid("retain"), (IMP)monkey_retain, "@@:");
//                      class_replaceMethod(cls, sel_getUid("release"), (IMP)monkey_release, "v@:");
		}

		if (get_jsctor(cls) == NULL) {
			EJSObjcObject* propobj = [proto objectForPropertyNS:@"constructor"];
			if (!propobj || ![propobj isFunction]) {
				NSLog (@"constructor is missing or is not a function");
				return cls;
			}

			// 	  NSLog (@"storing ctor in builtin class");
			set_jsctor(cls, propobj);
		}
		return cls;
	}

	cls = objc_getProtocol(register_name);
	if (cls) {
		SPEW(NSLog (@"%s is not a class, it's a protocol", register_name);)
		// XXX we really need to throw an exception here...
		return cls;
	}

	SPEW(NSLog (@"register_name = %s, super_name = %s", register_name, super_register_name);)

	id sup = objc_lookUpClass (super_register_name);

	cls = objc_allocateClassPair (sup, register_name, 0);

	Class metaclass = object_getClass (cls);

	NSMutableDictionary* method_map = [NSMutableDictionary dictionary];

    SPEW(NSLog (@"registering instance members");)
	// register the instance methods and properties
	EJSObjcObject* ctor = register_members (cls, proto, method_map);

    SPEW(NSLog (@"registering static members");)
	// register the static methods and properties
	if (ctor)
		register_members (metaclass, ctor, method_map);

	objc_registerClassPair (cls);

#if notyet
	objc_setAssociatedObject (cls, JSCTX_KEY, ctx, OBJC_ASSOCIATION_RETAIN);
#endif
	if (ctor)
		set_jsctor(cls, ctor);

	objc_setAssociatedObject (cls, JSMETHODMAP_KEY, method_map, OBJC_ASSOCIATION_RETAIN);

	/*
	  class_addMethod(cls, sel_getUid("retain"), (IMP)monkey_retain, "@@:");
	  class_addMethod(cls, sel_getUid("release"), (IMP)monkey_release, "v@:");
	*/

	SPEW(NSLog (@"associated ctor %p with class %s/%p", ctor, register_name, cls);)

	return cls;
}

static EJS_NATIVE_FUNC(_ejs_objc_registerJSClass) {
    // unused ejsval ctor = args[0]
    EJSObjcObject* proto = [[EJSObjcValue valueWithJSValue:args[1]] objectValue];
    char *register_cstr = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(args[2]));
    char *super_register_cstr = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(args[3]));

    register_js_class (proto, register_cstr, super_register_cstr);

    free (register_cstr);
    free (super_register_cstr);

    return _ejs_undefined;
}

#if IOS
static EJS_NATIVE_FUNC(_ejs_objc_UIApplicationMain) {
    NSString* delegate_name = [[EJSObjcString stringWithJSString:EJSVAL_TO_STRING(args[2])] nsString];

    SPEW(NSLog (@"About to call UIApplicationMain (..., %@)!", delegate_name);)
     // XXX get argv/argc/principal from @args
    static char *argv[] = { "ejs", NULL };
    UIApplicationMain(0, argv, nil, delegate_name);
    exit(0);
}

#else
static EJS_NATIVE_FUNC(_ejs_objc_NSApplicationMain) {
    SPEW(NSLog (@"About to call NSApplicationMain!");)
    // XXX get argv from args
    static char *argv[] = { "ejs", NULL };
    NSApplicationMain(0, argv);
    exit(0);
}
#endif

ejsval
_ejs_objc_module_func (ejsval exports)
{
    EJS_INSTALL_FUNCTION(exports, "requireFramework", _ejs_objc_requireFramework);
    EJS_INSTALL_FUNCTION(exports, "allocInstance", _ejs_objc_allocInstance);
    EJS_INSTALL_FUNCTION(exports, "staticCall", _ejs_objc_staticCall);
    EJS_INSTALL_FUNCTION(exports, "getInstanceVariable", _ejs_objc_getInstanceVariable);
    EJS_INSTALL_FUNCTION(exports, "setInstanceVariable", _ejs_objc_setInstanceVariable);
    EJS_INSTALL_FUNCTION(exports, "selectorInvoker", _ejs_objc_selectorInvoker);
    EJS_INSTALL_FUNCTION(exports, "getTypeEncoding", _ejs_objc_getTypeEncoding);
    EJS_INSTALL_FUNCTION(exports, "registerJSClass", _ejs_objc_registerJSClass);
#if IOS
    EJS_INSTALL_FUNCTION(exports, "allocateWebGLRenderingContext", _ejs_objc_allocateWebGLRenderingContext);
    EJS_INSTALL_FUNCTION(exports, "UIApplicationMain", _ejs_objc_UIApplicationMain);
#else
    EJS_INSTALL_FUNCTION(exports, "NSApplicationMain", _ejs_objc_NSApplicationMain);
#endif

    _ejs_objc_init (exports);

    return _ejs_undefined;
}


text:
/**
 * @filename
 * @copyright (c) Copyright 2014 SD-Team HTWK
 * @author dhecht
 * @details
 */
#include "stdafx.h"
#include "ImageCutter.h"

ADTF_FILTER_PLUGIN(FILTER_NAME, OID_NEW_LANE_DETECTION, ImageCutter);

ImageCutter::ImageCutter(const char *__info) : cFilter(__info)
{
	this->isFirstFrame = true;
}

ImageCutter::~ImageCutter(void)
{}

tResult ImageCutter::Init(tInitStage eStage, __exception)
{
	RETURN_IF_FAILED(cFilter::Init(eStage, __exception_ptr));

	switch (eStage)
	{
	case StageFirst:
		RETURN_IF_FAILED(createInputPin("videoInput", this->videoInput));
		RETURN_IF_FAILED(createVideoOutputPin("cuttedVideo", this->cuttedVideoOutputPin));
		break;

	case StageNormal:
		break;

	case StageGraphReady:
		break;
	}

	RETURN_NOERROR;
}

tResult ImageCutter::createInputPin(const tChar *pinName, cVideoPin &pin)
{
	pin.Create(pinName, IPin::PD_Input, static_cast<IPinEventSink*>(this));
	RETURN_IF_FAILED(RegisterPin(&pin));

	RETURN_NOERROR;
}

tResult ImageCutter::createVideoOutputPin(const tChar *pinName, cVideoPin &pin)
{
	pin.Create(pinName, IPin::PD_Output, static_cast<IPinEventSink*>(this));
	RETURN_IF_FAILED(RegisterPin(&pin));

	RETURN_NOERROR;
}

tResult ImageCutter::Start(__exception)
{
	RETURN_IF_FAILED(cFilter::Start(__exception_ptr));

	RETURN_NOERROR;
}

tResult ImageCutter::Stop(__exception)
{
	RETURN_IF_FAILED(cFilter::Stop(__exception_ptr));

	RETURN_NOERROR;
}

tResult ImageCutter::Shutdown(tInitStage eStage, __exception)
{
	RETURN_IF_FAILED(cFilter::Shutdown(eStage, __exception_ptr));

	RETURN_NOERROR;
}

tResult ImageCutter::OnPinEvent(IPin *source, tInt eventCore, tInt param1, tInt param2, IMediaSample *mediaSample)
{
	RETURN_IF_POINTER_NULL(source);
	RETURN_IF_POINTER_NULL(mediaSample);

	if (eventCore == IPinEventSink::PE_MediaSampleReceived)
	{
		if (source == &this->videoInput)
		{
			if (this->isFirstFrame)
			{
				//Read media type
				cObjectPtr<IMediaType> type;
				RETURN_IF_FAILED(this->videoInput.GetMediaType(&type));

				cObjectPtr<IMediaTypeVideo> typeVideo;
				RETURN_IF_FAILED(type->GetInterface(IID_ADTF_MEDIA_TYPE_VIDEO, (tVoid**)(&typeVideo)));

				const tBitmapFormat *format = typeVideo->GetFormat();
				RETURN_IF_POINTER_NULL(format);

				//Set media type
				setBitmapFormat(format);
				this->isFirstFrame = false;
			}
			else {
				RETURN_IF_FAILED(processImage(mediaSample));
			}

		}
	}

	RETURN_NOERROR;
}

tVoid ImageCutter::setBitmapFormat(const tBitmapFormat *format)
{
	this->videoInputInfo.nBitsPerPixel = format->nBitsPerPixel;
	this->videoInputInfo.nBytesPerLine = format->nBytesPerLine;
	this->videoInputInfo.nPaletteSize = format->nPaletteSize;
	this->videoInputInfo.nPixelFormat = format->nPixelFormat;
	this->videoInputInfo.nHeight = format->nHeight;
	this->videoInputInfo.nWidth = format->nWidth;
	this->videoInputInfo.nSize = format->nSize;

	// Output format
	this->videoOutputInfo = this->videoInputInfo;
	this->videoOutputInfo.nWidth = 640;
	this->videoOutputInfo.nHeight = 240;
	// just needed the half size, because the height has 240px instead of 480px
	this->videoOutputInfo.nSize /= 2;

	this->cuttedVideoOutputPin.SetFormat(&this->videoOutputInfo, NULL);
}

tResult ImageCutter::processImage(IMediaSample *mediaSample)
{
	const tVoid *buffer;

	if (IS_OK(mediaSample->Lock(&buffer)))
	{
		//Receive the image
		Mat image(Size(this->videoInputInfo.nWidth, this->videoInputInfo.nHeight), CV_8UC3, (char*)buffer);

		mediaSample->Unlock(buffer);

		static Mat cuttedImage;
		//Extract region of interest
		cuttedImage = image(Range(240, this->videoInputInfo.nHeight), Range(0, this->videoInputInfo.nWidth)).clone();
		// extractROI(image);

		//Send it to the output pin
		transmitVideoOutput(cuttedImage, this->cuttedVideoOutputPin);
	}

	RETURN_NOERROR;
}

Mat ImageCutter::extractROI(const Mat& inImage){
	Mat outImage(240, 640, inImage.type());

	for (tInt row = 240, rowOutImage = 0; row < 480 /*&& rowOutImage < 240*/; row++, rowOutImage++)
	{
		for (tInt col = 0; col < 640; col++)
		{
			outImage.at<Vec3b>(rowOutImage, col) = inImage.at<Vec3b>(row, col);
		}
	}

	return outImage;
}

tResult ImageCutter::transmitVideoOutput(Mat &image, cVideoPin &pin)
{
	if (!pin.IsConnected())
	{
		RETURN_NOERROR;
	}

	// Create new IMediaSample
	cObjectPtr<IMediaSample> sample;

	if (IS_OK(AllocMediaSample(&sample)))
	{
		tTimeStamp time = _clock ? _clock->GetStreamTime() : cHighResTimer::GetTime();
		RETURN_IF_FAILED(sample->Update(time, image.data, this->videoOutputInfo.nSize, 0));
		RETURN_IF_FAILED(pin.Transmit(sample));
	}

	RETURN_NOERROR;
}


text:
#ifndef __G_LOCAL_FILE_INFO_H__
#define __G_LOCAL_FILE_INFO_H__

#include <gio/gfileinfo.h>
#include <gio/gfile.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

G_BEGIN_DECLS

typedef struct
{
  gboolean writable;
  gboolean is_sticky;
  gboolean has_trash_dir;
  int      owner;
  dev_t    device;
  gpointer extra_data;
  GDestroyNotify free_extra_data;
} GLocalParentFileInfo;

#ifdef G_OS_WIN32
/* We want 64-bit file size support */
#define GLocalFileStat struct _stati64
#else
#define GLocalFileStat struct stat
#endif

#define G_LOCAL_FILE_INFO_NOSTAT_ATTRIBUTES \
    G_FILE_ATTRIBUTE_STANDARD_NAME "," \
    G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," \
    G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME "," \
    G_FILE_ATTRIBUTE_STANDARD_COPY_NAME

gboolean   _g_local_file_has_trash_dir        (const char             *dirname,
                                               dev_t                   dir_dev);
#ifdef G_OS_UNIX
gboolean   _g_local_file_is_lost_found_dir    (const char             *path,
                                               dev_t                   path_dev);
#endif
void       _g_local_file_info_get_parent_info (const char             *dir,
                                               GFileAttributeMatcher  *attribute_matcher,
                                               GLocalParentFileInfo   *parent_info);
void       _g_local_file_info_free_parent_info (GLocalParentFileInfo   *parent_info);
void       _g_local_file_info_get_nostat      (GFileInfo              *info,
                                               const char             *basename,
                                               const char             *path,
                                               GFileAttributeMatcher  *attribute_matcher);
GFileInfo *_g_local_file_info_get             (const char             *basename,
                                               const char             *path,
                                               GFileAttributeMatcher  *attribute_matcher,
                                               GFileQueryInfoFlags     flags,
                                               GLocalParentFileInfo   *parent_info,
                                               GError                **error);
GFileInfo *_g_local_file_info_get_from_fd     (int                     fd,
                                               const char             *attributes,
                                               GError                **error);
char *     _g_local_file_info_create_etag     (GLocalFileStat         *statbuf);
gboolean   _g_local_file_info_set_attribute   (char                   *filename,
                                               const char             *attribute,
                                               GFileAttributeType      type,
                                               gpointer                value_p,
                                               GFileQueryInfoFlags     flags,
                                               GCancellable           *cancellable,
                                               GError                **error);
gboolean   _g_local_file_info_set_attributes  (char                   *filename,
                                               GFileInfo              *info,
                                               GFileQueryInfoFlags     flags,
                                               GCancellable           *cancellable,
                                               GError                **error);

G_END_DECLS

#endif /* __G_FILE_LOCAL_FILE_INFO_H__ */


text:
SRCM4="${HOME}/bin/cflags/acinclude.m4"

cp $SRCM4 .
autoreconf --force


text:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();

if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}

console.log("Computer Picked: " + computerChoice);
console.log("")
console.log("User Picked: " + userChoice);
console.log("")
var compare = function(choice1, choice2)

{   if(choice1 === choice2) {
        return "The result is a tie!";
    }
    else if(choice1 === "rock") {
        if(choice2 === "scissors") {
            return "rock wins";
        }
        else {
            return "paper wins";
        }
    }
    else if(choice1 === "paper") {
        if(choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors wins";
        }
    }
    else(choice1 === "scissors");
        if(choice2 === "rock") {
            return "rock wins";
        }
        else {
            return "scissors win";
        }
};

compare(userChoice,computerChoice);


text:
{{define "title"}}Torrents List{{end}}
{{define "contclass"}}cont-view{{end}}
{{define "content"}}

  <form method="post" action="">
    {{ range (index $.Infos "infos")}}

× {{ . }}

    {{end}}
    {{ range (index $.Errors "errors")}}

× {{ . }}

    {{end}}

          <select class="form-control" name="action">
            <option value="">Action...</option>
            <option value="move">Move</option>
            <option value="delete">Delete</option>
          </select>
          <select class="form-control" style="display: none;" name="moveto">
            <option value="">To...</option>
            <option value="0">{{call $.T "torrent_status_hidden"}}</option>
            <option value="1">{{call $.T "torrent_status_normal"}}</option>
            <option value="2">{{call $.T "torrent_status_remake"}}</option>
            <option value="3">{{call $.T "trusted"}}</option>
            <option value="4">A+</option>
          </select>

        <input type="submit" class="btn btn-success" value="Apply">
        <input type="reset" class="btn btn-danger" value="Reset">

        <input type="checkbox" name="checkall" data-selectall="checkbox">
        Torrent Name
        Uploader
        Action

    {{ range .Torrents}}

        <input type="checkbox" name="torrent_id" value="{{.ID }}">
        {{ .Name }} (Edit)
        {{ if gt .UploaderID 0 }}{{ .Uploader.Username }}{{ else }}れんちょん{{end}}
         {{ call $.T "delete" }}

    {{end}}

  </form>

              {{ genNav .Navigation .URL 5 }}

{{end}}
{{ define "js_footer"}}

{{end}}


text:
package com.lynbrookrobotics.potassium.commons.flywheel

import com.lynbrookrobotics.potassium.streams.Stream
import com.lynbrookrobotics.potassium.{Component, Signal}
import com.lynbrookrobotics.potassium.streams.Stream
import com.lynbrookrobotics.potassium.control.{PIDF, PIDFConfig}
import com.lynbrookrobotics.potassium.tasks.{ContinuousTask, FiniteTask, WrapperTask}
import com.lynbrookrobotics.potassium.units.{GenericDerivative, GenericValue}
import squants.{Angle, Dimensionless, Percent}
import squants.motion.AngularVelocity
import squants.time.Frequency
trait FlywheelProperties {
  def velocityGains
    : PIDFConfig[Frequency, GenericValue[Frequency], Frequency, GenericDerivative[Frequency], Dimensionless, Dimensionless]
}

trait FlywheelHardware {
  def velocity: Stream[Frequency]
}

abstract class Flywheel {
  type Properties <: FlywheelProperties
  type Hardware <: FlywheelHardware

  object velocityControllers {
    def velocityControl(
      target: Stream[Frequency]
    )(implicit properties: Signal[Properties], hardware: Hardware): (Stream[Frequency], Stream[Dimensionless]) = {
      val error = hardware.velocity.zipAsync(target).map(t => t._2 - t._1)
      (
        error,
        PIDF
          .pidf(
            hardware.velocity,
            target,
            properties.map(_.velocityGains)
          )
          .map(_ max Percent(0))
      )
    }
  }

  object velocityTasks {
    class WhileAtVelocity(vel: Stream[Frequency], tolerance: Frequency)(flywheel: Comp)(
      implicit properties: Signal[Properties],
      hardware: Hardware
    ) extends WrapperTask {
      override def onStart(): Unit = {
        val (error, control) = velocityControllers.velocityControl(vel)
        flywheel.setController(control.withCheckZipped(error) { error =>
          if (error.abs < tolerance) {
            readyToRunInner()
          }
        })
      }

      override def onEnd(): Unit = {
        flywheel.resetToDefault()
      }
    }
  }

  type Comp <: Component[Dimensionless]
}


text:
FROM biocontainers/biocontainers:debian-stretch-backports
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="discosnp" \
    container="discosnp" \
    about.summary="discovering Single Nucleotide Polymorphism from raw set(s) of reads" \
    about.home="http://colibread.inria.fr/discosnp/" \
    software.version="1.2.6-1b2-deb" \
    version="1" \
    about.license_file="/usr/share/doc/discosnp/copyright" \
    extra.binaries="/usr/bin/discoSnp_to_csv,/usr/bin/discoSnp_to_genotypes,/usr/bin/kissnp2,/usr/bin/kissreads" \
    about.tags=""

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install -y discosnp && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker