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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.0"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>EmbASP-Python v7.1.0: parsers.asp.asp_parser.ASPParser Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

EmbASP-Python v7.1.0

parsers

asp

asp_parser

ASPParser

Public Member Functions |
Static Public Member Functions |
List of all members

parsers.asp.asp_parser.ASPParser Class Reference

Inheritance diagram for parsers.asp.asp_parser.ASPParser:

  <map id="parsers.asp.asp_5Fparser.ASPParser_map" name="parsers.asp.asp_5Fparser.ASPParser_map">
<area href="classparsers_1_1asp_1_1asp__parser__base_1_1ASPGrammarVisitor_1_1ASPGrammarVisitor.html" alt="parsers.asp.asp_parser_base.ASPGrammarVisitor.ASPGrammarVisitor" shape="rect" coords="0,56,413,80"/>
  </map>

Public Member Functions

def 	__init__ (self)

def 	get_parameters (self)

def 	visitTerm (self, ctx)

 Public Member Functions inherited from parsers.asp.asp_parser_base.ASPGrammarVisitor.ASPGrammarVisitor

def 	visitOutput (self, ctx)

def 	visitPredicate_atom (self, ctx)

Static Public Member Functions

def 	parse (atom)

Constructor & Destructor Documentation

◆ __init__()

          def parsers.asp.asp_parser.ASPParser.__init__
          (

          self	)

Member Function Documentation

◆ get_parameters()

          def parsers.asp.asp_parser.ASPParser.get_parameters
          (

          self	)

◆ parse()

          def parsers.asp.asp_parser.ASPParser.parse
          (

          atom	)

static

◆ visitTerm()

          def parsers.asp.asp_parser.ASPParser.visitTerm
          (

          self,

          ctx

          )

Reimplemented from parsers.asp.asp_parser_base.ASPGrammarVisitor.ASPGrammarVisitor.

The documentation for this class was generated from the following file:

embasp-python/parsers/asp/asp_parser.py

<address class="footer">
Generated by  1.9.0
</address>


text:
"""Provides device automations for MQTT."""
from __future__ import annotations

from collections.abc import Callable
import logging
from typing import cast

import attr
import voluptuous as vol

from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    CONF_DEVICE,
    CONF_DEVICE_ID,
    CONF_DOMAIN,
    CONF_PLATFORM,
    CONF_TYPE,
    CONF_VALUE_TEMPLATE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
from homeassistant.helpers.typing import ConfigType

from . import debug_info, trigger as mqtt_trigger
from .config import MQTT_BASE_SCHEMA
from .const import (
    ATTR_DISCOVERY_HASH,
    CONF_ENCODING,
    CONF_PAYLOAD,
    CONF_QOS,
    CONF_TOPIC,
    DOMAIN,
)
from .discovery import MQTT_DISCOVERY_DONE
from .mixins import (
    MQTT_ENTITY_DEVICE_INFO_SCHEMA,
    MqttDiscoveryDeviceUpdate,
    send_discovery_done,
    update_device,
)
from .util import get_mqtt_data

_LOGGER = logging.getLogger(__name__)

CONF_AUTOMATION_TYPE = "automation_type"
CONF_DISCOVERY_ID = "discovery_id"
CONF_SUBTYPE = "subtype"
DEFAULT_ENCODING = "utf-8"
DEVICE = "device"

MQTT_TRIGGER_BASE = {
    # Trigger when MQTT message is received
    CONF_PLATFORM: DEVICE,
    CONF_DOMAIN: DOMAIN,
}

TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
    {
        vol.Required(CONF_PLATFORM): DEVICE,
        vol.Required(CONF_DOMAIN): DOMAIN,
        vol.Required(CONF_DEVICE_ID): str,
        vol.Required(CONF_DISCOVERY_ID): str,
        vol.Required(CONF_TYPE): cv.string,
        vol.Required(CONF_SUBTYPE): cv.string,
    }
)

TRIGGER_DISCOVERY_SCHEMA = MQTT_BASE_SCHEMA.extend(
    {
        vol.Required(CONF_AUTOMATION_TYPE): str,
        vol.Required(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
        vol.Optional(CONF_PAYLOAD, default=None): vol.Any(None, cv.string),
        vol.Required(CONF_SUBTYPE): cv.string,
        vol.Required(CONF_TOPIC): cv.string,
        vol.Required(CONF_TYPE): cv.string,
        vol.Optional(CONF_VALUE_TEMPLATE, default=None): vol.Any(None, cv.string),
    },
    extra=vol.REMOVE_EXTRA,
)

LOG_NAME = "Device trigger"

@attr.s(slots=True)
class TriggerInstance:
    """Attached trigger settings."""

    action: TriggerActionType = attr.ib()
    trigger_info: TriggerInfo = attr.ib()
    trigger: Trigger = attr.ib()
    remove: CALLBACK_TYPE | None = attr.ib(default=None)

    async def async_attach_trigger(self) -> None:
        """Attach MQTT trigger."""
        mqtt_config = {
            CONF_PLATFORM: DOMAIN,
            CONF_TOPIC: self.trigger.topic,
            CONF_ENCODING: DEFAULT_ENCODING,
            CONF_QOS: self.trigger.qos,
        }
        if self.trigger.payload:
            mqtt_config[CONF_PAYLOAD] = self.trigger.payload
        if self.trigger.value_template:
            mqtt_config[CONF_VALUE_TEMPLATE] = self.trigger.value_template
        mqtt_config = mqtt_trigger.TRIGGER_SCHEMA(mqtt_config)

        if self.remove:
            self.remove()
        self.remove = await mqtt_trigger.async_attach_trigger(
            self.trigger.hass,
            mqtt_config,
            self.action,
            self.trigger_info,
        )

@attr.s(slots=True)
class Trigger:
    """Device trigger settings."""

    device_id: str = attr.ib()
    discovery_data: dict | None = attr.ib()
    hass: HomeAssistant = attr.ib()
    payload: str | None = attr.ib()
    qos: int | None = attr.ib()
    subtype: str = attr.ib()
    topic: str | None = attr.ib()
    type: str = attr.ib()
    value_template: str | None = attr.ib()
    trigger_instances: list[TriggerInstance] = attr.ib(factory=list)

    async def add_trigger(
        self, action: TriggerActionType, trigger_info: TriggerInfo
    ) -> Callable:
        """Add MQTT trigger."""
        instance = TriggerInstance(action, trigger_info, self)
        self.trigger_instances.append(instance)

        if self.topic is not None:
            # If we know about the trigger, subscribe to MQTT topic
            await instance.async_attach_trigger()

        @callback
        def async_remove() -> None:
            """Remove trigger."""
            if instance not in self.trigger_instances:
                raise HomeAssistantError("Can't remove trigger twice")

            if instance.remove:
                instance.remove()
            self.trigger_instances.remove(instance)

        return async_remove

    async def update_trigger(self, config: ConfigType) -> None:
        """Update MQTT device trigger."""
        self.type = config[CONF_TYPE]
        self.subtype = config[CONF_SUBTYPE]
        self.payload = config[CONF_PAYLOAD]
        self.qos = config[CONF_QOS]
        topic_changed = self.topic != config[CONF_TOPIC]
        self.topic = config[CONF_TOPIC]
        self.value_template = config[CONF_VALUE_TEMPLATE]

        # Unsubscribe+subscribe if this trigger is in use and topic has changed
        # If topic is same unsubscribe+subscribe will execute in the wrong order
        # because unsubscribe is done with help of async_create_task
        if topic_changed:
            for trig in self.trigger_instances:
                await trig.async_attach_trigger()

    def detach_trigger(self) -> None:
        """Remove MQTT device trigger."""
        # Mark trigger as unknown
        self.topic = None

        # Unsubscribe if this trigger is in use
        for trig in self.trigger_instances:
            if trig.remove:
                trig.remove()
                trig.remove = None

class MqttDeviceTrigger(MqttDiscoveryDeviceUpdate):
    """Setup a MQTT device trigger with auto discovery."""

    def __init__(
        self,
        hass: HomeAssistant,
        config: ConfigType,
        device_id: str,
        discovery_data: dict,
        config_entry: ConfigEntry,
    ) -> None:
        """Initialize."""
        self._config = config
        self._config_entry = config_entry
        self.device_id = device_id
        self.discovery_data = discovery_data
        self.hass = hass
        self._mqtt_data = get_mqtt_data(hass)

        MqttDiscoveryDeviceUpdate.__init__(
            self,
            hass,
            discovery_data,
            device_id,
            config_entry,
            LOG_NAME,
        )

    async def async_setup(self) -> None:
        """Initialize the device trigger."""
        discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
        discovery_id = discovery_hash[1]
        if discovery_id not in self._mqtt_data.device_triggers:
            self._mqtt_data.device_triggers[discovery_id] = Trigger(
                hass=self.hass,
                device_id=self.device_id,
                discovery_data=self.discovery_data,
                type=self._config[CONF_TYPE],
                subtype=self._config[CONF_SUBTYPE],
                topic=self._config[CONF_TOPIC],
                payload=self._config[CONF_PAYLOAD],
                qos=self._config[CONF_QOS],
                value_template=self._config[CONF_VALUE_TEMPLATE],
            )
        else:
            await self._mqtt_data.device_triggers[discovery_id].update_trigger(
                self._config
            )
        debug_info.add_trigger_discovery_data(
            self.hass, discovery_hash, self.discovery_data, self.device_id
        )

    async def async_update(self, discovery_data: dict) -> None:
        """Handle MQTT device trigger discovery updates."""
        discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
        discovery_id = discovery_hash[1]
        debug_info.update_trigger_discovery_data(
            self.hass, discovery_hash, discovery_data
        )
        config = TRIGGER_DISCOVERY_SCHEMA(discovery_data)
        update_device(self.hass, self._config_entry, config)
        device_trigger: Trigger = self._mqtt_data.device_triggers[discovery_id]
        await device_trigger.update_trigger(config)

    async def async_tear_down(self) -> None:
        """Cleanup device trigger."""
        discovery_hash = self.discovery_data[ATTR_DISCOVERY_HASH]
        discovery_id = discovery_hash[1]
        if discovery_id in self._mqtt_data.device_triggers:
            _LOGGER.info("Removing trigger: %s", discovery_hash)
            trigger: Trigger = self._mqtt_data.device_triggers[discovery_id]
            trigger.detach_trigger()
            debug_info.remove_trigger_discovery_data(self.hass, discovery_hash)

async def async_setup_trigger(
    hass, config: ConfigType, config_entry: ConfigEntry, discovery_data: dict
) -> None:
    """Set up the MQTT device trigger."""
    config = TRIGGER_DISCOVERY_SCHEMA(config)
    discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]

    if (device_id := update_device(hass, config_entry, config)) is None:
        async_dispatcher_send(hass, MQTT_DISCOVERY_DONE.format(discovery_hash), None)
        return

    mqtt_device_trigger = MqttDeviceTrigger(
        hass, config, device_id, discovery_data, config_entry
    )
    await mqtt_device_trigger.async_setup()
    send_discovery_done(hass, discovery_data)

async def async_removed_from_device(hass: HomeAssistant, device_id: str) -> None:
    """Handle Mqtt removed from a device."""
    mqtt_data = get_mqtt_data(hass)
    triggers = await async_get_triggers(hass, device_id)
    for trig in triggers:
        device_trigger: Trigger = mqtt_data.device_triggers.pop(trig[CONF_DISCOVERY_ID])
        if device_trigger:
            device_trigger.detach_trigger()
            discovery_data = cast(dict, device_trigger.discovery_data)
            discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]
            debug_info.remove_trigger_discovery_data(hass, discovery_hash)

async def async_get_triggers(
    hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
    """List device triggers for MQTT devices."""
    mqtt_data = get_mqtt_data(hass)
    triggers: list[dict[str, str]] = []

    if not mqtt_data.device_triggers:
        return triggers

    for discovery_id, trig in mqtt_data.device_triggers.items():
        if trig.device_id != device_id or trig.topic is None:
            continue

        trigger = {
            **MQTT_TRIGGER_BASE,
            "device_id": device_id,
            "type": trig.type,
            "subtype": trig.subtype,
            "discovery_id": discovery_id,
        }
        triggers.append(trigger)

    return triggers

async def async_attach_trigger(
    hass: HomeAssistant,
    config: ConfigType,
    action: TriggerActionType,
    trigger_info: TriggerInfo,
) -> CALLBACK_TYPE:
    """Attach a trigger."""
    mqtt_data = get_mqtt_data(hass)
    device_id = config[CONF_DEVICE_ID]
    discovery_id = config[CONF_DISCOVERY_ID]

    if discovery_id not in mqtt_data.device_triggers:
        mqtt_data.device_triggers[discovery_id] = Trigger(
            hass=hass,
            device_id=device_id,
            discovery_data=None,
            type=config[CONF_TYPE],
            subtype=config[CONF_SUBTYPE],
            topic=None,
            payload=None,
            qos=None,
            value_template=None,
        )
    return await mqtt_data.device_triggers[discovery_id].add_trigger(
        action, trigger_info
    )

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "tscore/ink_platform.h"
#include "records/I_RecHttp.h"
#include "P_EventSystem.h"
#include "HttpConfig.h"
#include "HTTP.h"
#include "I_Net.h"
#include <records/I_RecHttp.h>

namespace detail
{
/** Options for @c HttpSessionAccept.

    @internal This is done as a separate class for two reasons.

    The first is that in current usage many instances are created
    with the same options so (for the client) this is easier and
    more efficient than passing options directly to the @c
    HttpSessionAccept or calling setters.

    The second is that @c HttpSessionAccept is not provided with any thread
    safety because it is intended as an immutable object. Putting
    the setters here and not there makes that clearer.

    We don't do this directly as nested class because we want to
    inherit the data members rather than duplicate the declarations
    and initializations.
 */
class HttpSessionAcceptOptions
{
private:
  typedef HttpSessionAcceptOptions self; ///< Self reference type.
public:
  HttpSessionAcceptOptions();

  // Connection type (HttpProxyPort::TransportType)
  int transport_type = 0;
  /// Set the transport type.
  self &setTransportType(int);
  /// Local address to bind for outbound connections.
  IpAddr outbound_ip4;
  /// Local address to bind for outbound connections.
  IpAddr outbound_ip6;
  /// Set the outbound IP address to @a ip.
  self &setOutboundIp(IpAddr &ip);
  /// Set the outbound IP address to @a ip.
  self &setOutboundIp(IpEndpoint *ip);
  /// Local port for outbound connection.
  uint16_t outbound_port = 0;
  /// Set outbound port.
  self &setOutboundPort(uint16_t);
  /// Outbound transparent.
  bool f_outbound_transparent = false;
  /// Set outbound transparency.
  self &setOutboundTransparent(bool);
  /// Transparent pass-through.
  bool f_transparent_passthrough = false;
  /// Set transparent passthrough.
  self &setTransparentPassthrough(bool);
  /// Host address resolution preference order.
  HostResPreferenceOrder host_res_preference;
  /// Set the host query preference.
  self &setHostResPreference(HostResPreferenceOrder const);
  /// Acceptable session protocols.
  SessionProtocolSet session_protocol_preference;
  /// Set the session protocol preference.
  self &setSessionProtocolPreference(SessionProtocolSet const &);
};

inline HttpSessionAcceptOptions::HttpSessionAcceptOptions()

{
  memcpy(host_res_preference, host_res_default_preference_order, sizeof(host_res_preference));
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setTransportType(int type)
{
  transport_type = type;
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setOutboundIp(IpAddr &ip)
{
  if (ip.isIp4())
    outbound_ip4 = ip;
  else if (ip.isIp6())
    outbound_ip6 = ip;
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setOutboundIp(IpEndpoint *ip)
{
  if (ip->isIp4())
    outbound_ip4 = *ip;
  else if (ip->isIp6())
    outbound_ip6 = *ip;
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setOutboundPort(uint16_t port)
{
  outbound_port = port;
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setOutboundTransparent(bool flag)
{
  f_outbound_transparent = flag;
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setTransparentPassthrough(bool flag)
{
  f_transparent_passthrough = flag;
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setHostResPreference(HostResPreferenceOrder const order)
{
  memcpy(host_res_preference, order, sizeof(host_res_preference));
  return *this;
}

inline HttpSessionAcceptOptions &
HttpSessionAcceptOptions::setSessionProtocolPreference(SessionProtocolSet const &sp_set)
{
  session_protocol_preference = sp_set;
  return *this;
}
} // namespace detail

/**
   The continuation mutex is NULL to allow parellel accepts in NT. No
   state is recorded by the handler and values are required to be set
   during construction via the @c Options struct and never changed. So
   a NULL mutex is safe.

   Most of the state is simply passed on to the @c ClientSession after
   an accept. It is done here because this is the least bad pathway
   from the top level configuration to the HTTP session.
*/

class HttpSessionAccept : public SessionAccept, private detail::HttpSessionAcceptOptions
{
private:
  typedef HttpSessionAccept self; ///< Self reference type.
public:
  /** Construction options.
      Provide an easier to remember typedef for clients.
  */
  typedef detail::HttpSessionAcceptOptions Options;

  /** Default constructor.
      @internal We don't use a static default options object because of
      initialization order issues. It is important to pick up data that is read
      from the config file and a static is initialized long before that point.
  */
  HttpSessionAccept(Options const &opt = Options()) : SessionAccept(nullptr), detail::HttpSessionAcceptOptions(opt) // copy these.
  {
    SET_HANDLER(&HttpSessionAccept::mainEvent);
    return;
  }

  ~HttpSessionAccept() override { return; }
  bool accept(NetVConnection *, MIOBuffer *, IOBufferReader *) override;
  int mainEvent(int event, void *netvc) override;

  // noncopyable
  HttpSessionAccept(const HttpSessionAccept &) = delete;
  HttpSessionAccept &operator=(const HttpSessionAccept &) = delete;
};


text:
<?php
namespace models\rights;

class Realm {

	const SITE			= 'site';
	const PROJECT		= 'project';

	public static $realms = array(
			self::SITE,
			self::PROJECT
	);

}

?>


text:
package org.apache.druid.server.coordinator;

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import org.apache.druid.client.indexing.IndexingServiceClient;
import org.apache.druid.indexer.TaskStatusPlus;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.guava.Comparators;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.server.coordinator.helper.DruidCoordinatorHelper;
import org.joda.time.DateTime;
import org.joda.time.Period;

import java.util.ArrayList;
import java.util.List;

public class DruidCoordinatorCleanupPendingSegments implements DruidCoordinatorHelper
{
  private static final Logger log = new Logger(DruidCoordinatorCleanupPendingSegments.class);
  private static final Period KEEP_PENDING_SEGMENTS_OFFSET = new Period("P1D");

  private final IndexingServiceClient indexingServiceClient;

  @Inject
  public DruidCoordinatorCleanupPendingSegments(IndexingServiceClient indexingServiceClient)
  {
    this.indexingServiceClient = indexingServiceClient;
  }

  @Override
  public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
  {
    final List<DateTime> createdTimes = new ArrayList<>();
    createdTimes.add(
        indexingServiceClient
            .getActiveTasks()
            .stream()
            .map(TaskStatusPlus::getCreatedTime)
            .min(Comparators.naturalNullsFirst())
            .orElse(DateTimes.nowUtc()) // If there are no active tasks, this returns the current time.
    );

    final TaskStatusPlus completeTaskStatus = indexingServiceClient.getLastCompleteTask();
    if (completeTaskStatus != null) {
      createdTimes.add(completeTaskStatus.getCreatedTime());
    }
    createdTimes.sort(Comparators.naturalNullsFirst());

    // There should be at least one createdTime because the current time is added to the 'createdTimes' list if there
    // is no running/pending/waiting tasks.
    Preconditions.checkState(!createdTimes.isEmpty(), "Failed to gather createdTimes of tasks");

    // If there is no running/pending/waiting/complete tasks, stalePendingSegmentsCutoffCreationTime is
    // (DateTimes.nowUtc() - KEEP_PENDING_SEGMENTS_OFFSET).
    final DateTime stalePendingSegmentsCutoffCreationTime = createdTimes.get(0).minus(KEEP_PENDING_SEGMENTS_OFFSET);
    for (String dataSource : params.getUsedSegmentsTimelinesPerDataSource().keySet()) {
      if (!params.getCoordinatorDynamicConfig().getDataSourcesToNotKillStalePendingSegmentsIn().contains(dataSource)) {
        log.info(
            "Killed [%d] pendingSegments created until [%s] for dataSource[%s]",
            indexingServiceClient.killPendingSegments(dataSource, stalePendingSegmentsCutoffCreationTime),
            stalePendingSegmentsCutoffCreationTime,
            dataSource
        );
      }
    }
    return params;
  }
}


text:
namespace indoo.tools {

    using System;
    using System.Collections.Generic;
    using System.Text;

    public class LookupEventArgs : EventArgs {

        string _ipAddress;
        string _consoleOutput;
        bool _timedOut;
        bool _skippedExternalIP;
        bool _alwaysSkip;

        public string IpAddress { get { return _ipAddress; } }
        public string ConsoleOutput { get { return _consoleOutput; } }
        public bool TimedOut { get { return _timedOut; } }
        public bool SkippedExternalIP { get { return _skippedExternalIP; } }
        /// <summary>
        /// True if the ini file is indicating to always skip the external ip
        /// </summary>
        public bool AlwaysSkip { get { return _alwaysSkip; } }

        /// <summary>
        ///
        /// </summary>
        /// <param name="ipAddress">quad-dotted external ip address, if lookup was successful</param>
        /// <param name="consoleOutput">Text such as errors and status that externalIP would have written to the console</param>
        /// <param name="timedOut">true if the lookup failed</param>
        /// <param name="skipExternalIP">true if the lookup was skipped (whether due to -s command, or settings in the .ini file)</param>
        /// <param name="alwaysSkip">true if the .ini file currently indicates to always skip the lookup</param>
        public LookupEventArgs(string ipAddress, string consoleOutput, bool timedOut, bool skipExternalIP, bool alwaysSkip) {
            _ipAddress = ipAddress;
            _timedOut = timedOut;
            _skippedExternalIP = skipExternalIP;
            _alwaysSkip = alwaysSkip;
            _consoleOutput = consoleOutput;
        }
    }
}


text:
set -e

#
# Input validation
if [[ -z "${xamarin_solution}" ]] ; then
  echo "Missing required input: xamarin_solution"
  exit 1
fi

if [[ ! -e "${xamarin_solution}" ]] ; then
  echo "File not exist at: ${xamarin_solution}"
  exit 1
fi

#
# Print configs
echo
echo '========== Configs =========='
echo " * xamarin_solution: ${xamarin_solution}"

#
# Xamarin Components restore
xamarin_components="$COMPONENT_PATH/xamarin-component.exe"

echo
echo mono "${xamarin_components}" restore "${xamarin_solution}"
mono "${xamarin_components}" restore "${xamarin_solution}"


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

using System;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;

namespace FakeSign
{
    /// <summary>
    /// Takes a delay-signed assembly and flips its CLI header "strong-name signed" bit without
    /// adding a correct signature. This creates an assembly that can be loaded in full trust
    /// without registering for verification skipping. The assembly cannot be installed to the
    /// GAC.
    /// </summary>
    /// <remarks>
    /// This code is taken largely from the Microsoft.BuildTools project and their OSS signing
    /// process.
    ///
    /// https://github.com/dotnet/buildtools/blob/master/src/Microsoft.DotNet.Build.Tasks/OpenSourceSign.cs
    /// </remarks>
    internal static class Program
    {
        /// <summary>
        /// The number of bytes from the start of the <see cref="CorHeader"/> to its <see cref="CorFlags"/>.
        /// </summary>
        private const int OffsetFromStartOfCorHeaderToFlags =
           sizeof(Int32)  // byte count
         + sizeof(Int16)  // major version
         + sizeof(Int16)  // minor version
         + sizeof(Int64); // metadata directory

        private static bool ExecuteCore(string assemblyPath, bool unSign = false, bool force = false)
        {
            if (Directory.Exists(assemblyPath))
            {
                Console.Error.WriteLine($"Expected file, not a directory: {assemblyPath}");
                return false;
            }

            if (!File.Exists(assemblyPath))
            {
                Console.Error.WriteLine($"File not found: {assemblyPath}");
                return false;
            }

            using (var stream = OpenFile(assemblyPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
            using (var reader = new PEReader(stream))
            using (var writer = new BinaryWriter(stream))
            {
                var mdReader = ValidateManagedAssemblyAndGetMetadataReader(reader);
                if (mdReader == null)
                {
                    Console.Error.WriteLine($"Cannot {(unSign ? "un-sign" : "sign")} {assemblyPath}.");
                    return false;
                }

                if (!force && !Validate(reader, mdReader, unSign))
                {
                    Console.Error.WriteLine($"Use the -f (force) option to {(unSign ? "un-sign" : "sign")} {assemblyPath} anyway.");
                    return false;
                }

                stream.Position = reader.PEHeaders.CorHeaderStartOffset + OffsetFromStartOfCorHeaderToFlags;

                var flags = reader.PEHeaders.CorHeader.Flags;
                if (unSign)
                {
                    flags &= ~CorFlags.StrongNameSigned;
                }
                else
                {
                    flags |= CorFlags.StrongNameSigned;
                }

                writer.Write((UInt32)flags);
            }

            return true;
        }

        private static MetadataReader ValidateManagedAssemblyAndGetMetadataReader(PEReader peReader)
        {
            if (!peReader.HasMetadata)
            {
                Console.Error.WriteLine("PE file is not a managed module.");
                return null;
            }

            var mdReader = peReader.GetMetadataReader();
            if (!mdReader.IsAssembly)
            {
                Console.Error.WriteLine("PE file is not an assembly.");
                return null;
            }

            return mdReader;
        }

        /// <summary>
        /// Returns true if the PE file meets all of the pre-conditions to be Open Source Signed.
        /// Returns false and logs msbuild errors otherwise.
        /// </summary>
        private static bool Validate(PEReader peReader, MetadataReader mdReader, bool unSign)
        {
            CorHeader header = peReader.PEHeaders.CorHeader;
            var expectedStrongNameFlag = unSign ? CorFlags.StrongNameSigned : 0;
            var actualStrongNameFlag = header.Flags & CorFlags.StrongNameSigned;

            if (expectedStrongNameFlag != actualStrongNameFlag)
            {
                Console.Error.WriteLine($"PE file is {(unSign ? "not" : "already")} strong-name signed.");
                return false;
            }

            if ((header.StrongNameSignatureDirectory.Size <= 0) || mdReader.GetAssemblyDefinition().PublicKey.IsNil)
            {
                Console.Error.WriteLine("PE file is not a delay-signed assembly.");
                return false;
            }

            return true;
        }

        /// <summary>
        /// Wraps FileStream constructor to normalize all unpreventable exceptions to IOException.
        /// </summary>
        private static FileStream OpenFile(string path, FileMode mode, FileAccess access, FileShare share)
        {
            try
            {
                return new FileStream(path, mode, access, share);
            }
            catch (ArgumentException ex)
            {
                throw new IOException(ex.Message, ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                throw new IOException(ex.Message, ex);
            }
            catch (NotSupportedException ex)
            {
                throw new IOException(ex.Message, ex);
            }
        }

        internal static int Main(string[] args)
        {
            string file = null;
            bool unSign = false;
            bool force = false;

            foreach (string arg in args)
            {
                if (arg.Length >= 2 && (arg[0] == '-' || arg[0] == '/'))
                {
                    switch (arg[1])
                    {
                        case '?':
                            goto Help;

                        case 'u':
                        case 'U':
                            unSign = true;
                            break;

                        case 'f':
                        case 'F':
                            force = true;
                            break;

                        default:
                            Console.Error.WriteLine($"Unrecognized switch {arg}");
                            goto Help;
                    }
                }
                else if (file != null)
                {
                    Console.Error.WriteLine("Too many arguments.");
                    goto Help;
                }
                else
                {
                    file = arg;
                }
            }

            if (file == null)
            {
                Console.Error.WriteLine("Missing assemblyPath.");
                goto Help;
            }

            return ExecuteCore(file, unSign, force) ? 0 : 1;

        Help:
            Console.Error.Write(
@"Sets or removes the ""strong name signed"" flag in a managed assembly. This
creates an assembly that can be loaded in full trust without registering for
verification skipping.

FakeSign [-u] [-f] assemblyPath
    -u (unsign) Clears the strong name flag (default is to set the flag).
    -f (force) Updates even if nothing would change.
");
            return 1;
        }
    }
}


text:
from flask import request
from marshmallow import ValidationError

from bms_app.models import (
    BMSServer, Mapping, Operation, OperationDetails, SourceDB, SourceDBType,
    Wave, db
)
from bms_app.schema import AddWaveSchema, WaveSchema
from bms_app.services.utils import generate_target_gcp_logs_link
from bms_app.wave import bp
from bms_app.wave.services import (
    GetWaveService, list_waves_service, validate_wave_name_is_unique
)
from bms_app.wave.services.waves import assign_source_db_wave

@bp.route('', methods=['GET'])
def list_waves():
    """Return all available waves."""
    project_id = request.args.get('project_id', type=int)

    data = list_waves_service(project_id)

    return {
        'data': data
    }

@bp.route('/<int:wave_id>', methods=['GET'])
def get_wave(wave_id):
    """Return wave."""
    return GetWaveService.run(
        wave_id=wave_id,
        return_details=request.args.get('details')
    )

@bp.route('/<int:wave_id>/operations/<int:operation_id>/details', methods=['GET'])
def get_operation_details(wave_id, operation_id):
    """Return details/histories of the particular operation."""
    query = db.session.query(OperationDetails, SourceDB, BMSServer) \
        .join(Mapping, OperationDetails.mapping_id == Mapping.id) \
        .join(SourceDB, Mapping.db_id == SourceDB.id) \
        .join(BMSServer, Mapping.bms_id == BMSServer.id) \
        .filter(OperationDetails.operation_id == operation_id) \
        .all()

    response = {}
    for op_details, source_db, bms_server in query:
        db_id = source_db.id
        if db_id not in response:
            response[db_id] = {
                'status': op_details.status.value,
                'operation_id': op_details.operation_id,
                'operation_type': op_details.operation_type.value,
                'wave_id': op_details.wave_id,
                'source_db': {
                    'source_hostname': source_db.server,
                    'db_name': source_db.db_name,
                    'db_type': source_db.db_type.value,
                    'is_rac': source_db.db_type == SourceDBType.RAC,
                    'oracle_version': source_db.oracle_version,
                },
                'bms': []
            }
        logs_url = generate_target_gcp_logs_link(op_details, bms_server)
        response[db_id]['bms'].append({
            'id': bms_server.id,
            'name': bms_server.name,
            'logs_url': logs_url,
            'started_at': op_details.started_at.strftime("%a, %d %b %Y %H:%M:%S GMT"),
            'completed_at': op_details.completed_at.strftime("%a, %d %b %Y %H:%M:%S GMT"),
            'step': op_details.step,
            'mapping_id': op_details.mapping_id
        })

    return {'data': list(response.values())}

@bp.route('/<int:wave_id>', methods=['DELETE'])
def delete_wave(wave_id):
    """Delete wave."""
    operation_exists = db.session.query(Wave, Operation) \
        .filter(Operation.wave_id == Wave.id) \
        .filter(Wave.id == wave_id).count()
    if operation_exists:
        raise ValidationError({'wave_id': ['wave is not empty']})

    SourceDB.query.filter(SourceDB.wave_id == wave_id).update({'wave_id': None})

    wave = Wave.query.get_or_404(wave_id)
    db.session.delete(wave)
    db.session.commit()

    return {}, 204

@bp.route('/<int:wave_id>', methods=['PUT'])
def edit_wave(wave_id):
    """Update wave."""
    validated_data = WaveSchema(only=['name', 'project_id']).load(request.json)
    wave = Wave.query.get_or_404(wave_id)

    validate_wave_name_is_unique(
        validated_data['name'],
        wave.project_id,
        exclude_wave_id=wave_id
    )

    wave.name = validated_data['name']

    db.session.add(wave)
    db.session.commit()

    return WaveSchema().dump(wave)

@bp.route('', methods=['POST'])
def add_wave():
    """Add wave."""
    validated_data = AddWaveSchema().load(request.json)

    wave = db.session.query(Wave).filter(
        Wave.name == validated_data['name'],
        Wave.project_id == validated_data['project_id']
    ).first()

    if not wave:
        wave = Wave(
            name=validated_data['name'],
            project_id=validated_data['project_id']
        )

        db.session.add(wave)
        db.session.commit()

    response = {}

    if validated_data.get('db_ids'):
        assigment_result = assign_source_db_wave(
            wave=wave,
            db_ids=validated_data['db_ids']
        )
        response.update(assigment_result)

    return response, 201


text:
<?php namespace Ganymed\Auth;

/*
 * This file is part of the Ganymed Package.
 *
 * (c) Swen Gorschewski <swen.gorschewski@gmail.com>
 *
 * The Package is distributed under the MIT License
 */

use Ganymed\Exceptions\ModelNotFoundException;
use Ganymed\Services\Session;

class Auth {

    /**
     * Session implementation.
     *
     * @var Session
     */
    protected $session;

    /**
     * User model.
     *
     * @var User
     */
    protected $user;

    function __construct(Session $session, User $user)
    {
        $this->session = $session;
        $this->user = $user;
    }

    /**
     * Check if a user is authenticated.
     * @return bool
     */
    public function check()
    {
        return $this->session->get('auth') != null ? true : false;
    }

    /**
     * Validate the supplied login credentials.
     *
     * @param $email
     * @param $password
     * @return bool
     */
    public function validate($email, $password)
    {

        try {
            if ($this->user = \User::getByEmail($email)) {

                if (password_verify($password, $this->user->password)) {
                    return true;
                }

            }
        } catch(ModelNotFoundException $e) {

            // Handle errors on failed authentication.
            $errors = [
                'error' => 'Wrong email or password.'
            ];

            $this->session->put('errors', serialize($errors));

            return false;

        }

    }

    /**
     * Register a user session if the supplied credentials are valid.
     *
     * @param $email
     * @param $password
     * @return bool
     */
    public function attempt($email, $password)
    {
        if ($this->validate($email, $password)) {
            $this->session->put('email', $email);
            $this->session->put('auth', true);
            return true;
        }

        return false;
    }

    public function logout()
    {
        $this->session->remove('email');
        $this->session->remove('auth');
    }

}


text:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbmongoose', function(error){
         if(error){
	        throw error;
	     }
	     //else{
	        //console.log('Conectado a MongoDB');
	     //}
});

var movieSchema = new mongoose.Schema({

	_id: String,
	      criticisms: {

	      	color: String,
	      	journalist: String,
	      	media: String,
	      	url: String,

	      	color: String,
	      	journalist: String,
	      	media: String,
},
	director_id : String,
	genre: String,
	      prizes: {

	      	event: String,
	      	names: [],
	      	year: Number,
},
	title: String,
	type: String,
	year: Number,

	      prizes: {

	      	event: String,
	      	names: [],
	      	year: Number,
},

	      criticisms: {

	      	color: String,
	      	journalist: String,
	      	media: String,
	      	url: String,

	      	color: String,
	      	journalist: String,
	      	media: String,
},

	genres: [],
	writers: [],
},
{collection: 'movie'});
var Movie = mongoose.model('Movie',movieSchema);

Movie.find(function(err,movie){
	if (err) return console.error(err);
	var stringVar="\nMovie:";
	console.log(stringVar);
	console.log(movie);
});

var directorSchema = new mongoose.Schema({

	_id: String,
	actor_movies: [],
	directed_movies: [],
	name: String,
	type: String,

},
{collection: 'director'});
var Director = mongoose.model('Director',directorSchema);

Director.find(function(err,director){
	if (err) return console.error(err);
	var stringVar="\nDirector:";
	console.log(stringVar);
	console.log(director);
	mongoose.disconnect();
});


text:
1. Go to https://baas-dev.10gen.cc/ and log in.
2. Click on "Create a new app" and give it a name.
3. Go to "Clients" on the left side nav and take note of the App ID for your app.

### Set up authentication providers

Now that the app exists, you need to set up a way for new users to log in.
Go to the **Authentication** link in the left-side panel. Anonymous login is
already supported so if this good enough, you can skip past Facebook and Google
setup. Otherwise, follow the instructions for at least one of the providers listed below:

##### Facebook

1. Create an app on Facebook (See: [Facebook - Register and Configure an App](https://developers.facebook.com/docs/apps/register))
2. On your app dashboard, click Add Product.
3. Add the Facebook Login product.
4. Go to the settings for Facebook Login.
5. Under "Valid OAuth redirect URIs" add the following entry:
	`https://baas-dev.10gen.cc/api/client/v1.0/auth/callback`

Return back to the Stitch authentication settings page, and enter your App ID and App Secret as client ID and client secret respectively from the Facebook app dashboard. Add `http://localhost:8000/` to the list of redirect URIs, and save it.

##### Google
1. Get your client ID and client secret (See: [Google - Setting up OAuth 2.0](https://support.google.com/cloud/answer/6158849?hl=en))
2. Click the edit button for your credentials on the Google API Manager.
3. For Authorized redirect URIs, add the following entry:
	`https://baas-dev.10gen.cc/api/client/v1.0/auth/callback`
4. On the Stitch admin site

Return back to the Stitch authentication settings page, and enter your client ID and client Secret in the Google auth settings panel. Add `http://localhost:8000/` to the list of redirect URIs, and save it.

### Set up a MongoDB service

1. Choose the `mongodb1` service on the left nav panel.
2. Under the "Config" tab for the `mongodb1` service, put in the URI for your MongoDB cluster found by clicking connect on your cluster in Atlas.
3. Click save.

### Find your default namespace

In the "Rules" tab of the MongoDB service, look for a rule that corresponds to a MongoDB database and collection. It should look like app-<characters>.items. Take note of this as this is the MongoDB namespace you'll use for this example.

### Serve the app

Edit "index.js" and change the lines near the top of the file `const APP_ID = "..."` and `const DB_NAME = "..."` so that they contain the ID of the app you took note of earlier on the Clients page and the DB portion of the namespace of the rule you found.
Then install the necessary dependencies and serve the app.
```
npm install
webpack-dev-server
```

Open your browser and go to `https://localhost:8080/`.


text:
package scaladelray.clustering

import java.net._
import akka.actor.{Props, ActorSystem}
import akka.pattern.ask
import com.typesafe.config.ConfigFactory
import scala.swing._
import scala.swing.GridBagPanel.{Anchor, Fill}
import java.awt.Dimension
import scala.collection.mutable
import java.util.Date
import scala.swing.event.ButtonClicked
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.Await

/**
 * The render node application. It opens a windows where the user can configure the interface, the port, and the number
 * of cores that are provided. The service can be started and stopped in the UI.
 */
object RenderNode extends SimpleSwingApplication {

  /**
   * The actor system where the rendering actors run in.
   */
  private var remoteActorSystem : Option[ActorSystem] = None

  /**
   * The socket of the [[scaladelray.clustering.BeaconActor]]. It is used to close the multicast socket and shutdown
   * the BeaconNActor properly.
   */
  private var beaconSocket : Option[MulticastSocket] = None

  Logging.loggingActor ! LogMessage( new Date, "Application started" )

  override def top = new MainFrame {
    title = "ScalaDelRay rendering node"
    contents = ui
    size = new Dimension( 320, 480 )
    resizable = false
  }

  /**
   * The UI.
   */
  private lazy val ui = new GridBagPanel {

    val c = new Constraints
    val interfaceLabel = new Label( "Interface: " )
    c.fill = Fill.Horizontal
    c.weightx = 0.5
    c.gridx = 0
    c.gridy = 0
    layout( interfaceLabel ) = c

    val addresses = mutable.MutableList[String]()
    val nets = NetworkInterface.getNetworkInterfaces
    while( nets.hasMoreElements ) {
      val net = nets.nextElement
      val iNetAddresses = net.getInetAddresses
      while( iNetAddresses.hasMoreElements ) {
        val iNetAddress = iNetAddresses.nextElement
        addresses += iNetAddress.getHostAddress
      }

    }

    val interfaceComboBox = new ComboBox( addresses )
    c.gridx = 1
    layout( interfaceComboBox ) = c

    val portLabel = new Label( "Port:" )
    c.gridx = 0
    c.gridy = 1
    layout( portLabel ) = c

    val portTextField = new TextField( "7983" )
    c.gridx = 1
    layout( portTextField ) = c

    val threadsLabel = new Label( "Threads:" )
    c.gridx = 0
    c.gridy = 2
    layout( threadsLabel ) = c

    val threadsTextField = new TextField( Runtime.getRuntime.availableProcessors().toString )
    c.gridx = 1
    layout( threadsTextField ) = c

    val startStopButton = new Button( "Start" )
    startStopButton.reactions += {
      case ButtonClicked(_) =>

        if( remoteActorSystem.isEmpty ) {
          startStopButton.enabled = false
          startStopButton.text = "Stop"
          interfaceComboBox.enabled = false
          portTextField.enabled = false
          threadsTextField.enabled = false
          val config = ConfigFactory.parseString("""
            akka {
              actor {
                provider = "akka.remote.RemoteActorRefProvider"
              }
              remote {
                enabled-transports = ["akka.remote.netty.tcp"]
                netty.tcp {
                  hostname = """ + '"' + interfaceComboBox.selection.item + '"' + """
                  port = """ + portTextField.text + """
                }
              }
            }""")

          remoteActorSystem = Some( ActorSystem( "renderNode", config ) )
          Logging.loggingActor ! LogMessage( new Date(), "Started rendering node service" )

          val beaconActor = remoteActorSystem.get.actorOf( Props[BeaconActor] )
          implicit val timeout = Timeout(5 seconds)

          val future = beaconActor ? StartBeacon( 12345, interfaceComboBox.selection.item, portTextField.text.toInt, threadsTextField.text.toInt )
          val bs = Await.result(future, timeout.duration).asInstanceOf[BeaconSocket]
          beaconSocket = Some( bs.socket )

          startStopButton.enabled = true
        } else {
          startStopButton.enabled = false
          beaconSocket.get.close()
          beaconSocket = None
          remoteActorSystem.get.shutdown()
          remoteActorSystem = None
          startStopButton.text = "Start"
          interfaceComboBox.enabled = true
          portTextField.enabled = true
          threadsTextField.enabled = true
          Logging.loggingActor ! LogMessage( new Date(), "Stopped rendering node service" )
          startStopButton.enabled = true

        }
    }
    c.gridx = 0
    c.gridy = 3
    c.gridwidth = 2
    layout( startStopButton ) = c

    val logTable = new Table
    Logging.loggingActor ! PromoteTable( logTable )
    val logTableScrollPane = new ScrollPane {
      contents = logTable
    }

    c.gridy = 4
    c.ipady = 200
    c.weighty = 1.0
    c.anchor = Anchor.PageEnd
    c.fill = Fill.Both
    layout( logTableScrollPane ) = c

    val dummyLabel = new Label( "" )
    c.fill = Fill.Horizontal
    c.ipady = 0
    c.weighty = 0.0
    c.gridx = 1
    c.gridwidth = 1
    c.gridy = 5
    layout(dummyLabel) = c

  }
}


text:
var actions = require('./actions');
var dispatcher = require('./dispatcher');
var constants = require('./constants');

var API = module.exports = {
    fetchChirps: function () {
        get('/api/chirps').then(actions.gotChirps.bind(actions));
    },
    fetchUsers: function () {
        get('/api/users').then(actions.gotUsers.bind(actions));
    },
    startFetchingChirps: function () {
        this.fetchChirps();
        return setInterval(this.fetchChirps, 1000);
    },
    startFetchingUsers: function (){
        this.fetchUsers();
        return setInterval(this.fetchUsers, 5000);
    },
    saveChirp: function (text) {
        text = text.trim();
        if(text === '') return;

        post('/api/chirps', { text: text }).then(actions.chirped.bind(actions));
    },
    follow: function (id) {
        post('/api/follow/' + id).then(actions.followed.bind(actions));
    },
    unfollow: function (id) {
        post('/api/unfollow/' + id).then(actions.unfollowed.bind(actions));
    }
};

function get(url) {
    return fetch(url, {
        credentials: 'same-origin'
    }).then(function (res) {
        return res.json();
    });
}

function post(url, body) {
    return fetch(url, {
        method: 'POST',
        credentials: 'include',
        body: JSON.stringify(body || {}),
        headers: {
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        }
    }).then(function (res) {
        return res.json();
    });
}

dispatcher.register(function (action) {
    switch (action.actionType) {
        case constants.CHIRP:
            API.saveChirp(action.data);
            break;
        case constants.FOLLOW:
            API.follow(action.data);
            break;
        case constants.UNFOLLOW:
            API.unfollow(action.data);
    }

});


text:
typealias AbstractUniform Union{DiscreteUniform, Uniform}

immutable NumberStrategy{D <: AbstractUniform, T} <: AbstractStrategy
    dist::D
    specialvalues::Vector{T}
    p::Bernoulli
    shrinker::NoShrinker
end
Base.minimum(strategy::NumberStrategy) = dist.params(strategy.dist)[1]
shrinker(strategy::NumberStrategy) = strategy.shrinker
returntype{D, T}(::Type{NumberStrategy{D, T}}) = T

# ----- Float -----
function _specialvalues{T <: AbstractFloat}(::Type{T}, min::T, max::T)
    specialvalues = [convert(T, NaN)]
    append!(specialvalues, [min, max])
    if (min < zero(T)) && (max > zero(T))
        push!(specialvalues, zero(T))
    end
    if (min < one(T)) && (max > one(T))
        push!(specialvalues, one(T))
    end
    if (min < -one(T)) && (max > -one(T))
        push!(specialvalues, -one(T))
    end
    return specialvalues
end

"""
Generate arbitrary float values between a desired range
"""
function floats{T <: AbstractFloat}(
    min::T, max::T;
    specialvalues::Vector{T}=_specialvalues(T, min, max),
    p::Bernoulli=Bernoulli(0.1),
    shrinker=NoShrinker())

    NumberStrategy(Uniform(min, max), specialvalues, p, shrinker)
end

# ----- Int -----
function _specialvalues{T <: Signed}(::Type{T}, min::T, max::T)
    specialvalues = [min, max]
    if (min < zero(T)) && (max > zero(T))
        push!(specialvalues, zero(T))
    end
    if (min < one(T)) && (max > one(T))
        push!(specialvalues, one(T))
    end
    if (min < -one(T)) && (max > -one(T))
        push!(specialvalues, -one(T))
    end
    return specialvalues
end
"""
Generate arbitrary signed values between a desired range
"""
function signeds{T <: Signed}(
    min::T, max::T;
    specialvalues::Vector{T}=_specialvalues(T, min, max),
    p::Bernoulli=Bernoulli(0.1),
    shrinker=NoShrinker())

    NumberStrategy(DiscreteUniform(min, max), specialvalues, p, shrinker)
end

function _specialvalues{T <: Unsigned}(::Type{T}, min::T, max::T)
    specialvalues = [min, max]
    if (min < one(T)) && (max > one(T))
        push!(specialvalues, one(T))
    end
    return specialvalues
end
"""
Generate arbitrary unsigned values between a desired range
"""
function unsigneds{T <: Unsigned}(
    min::T, max::T;
    specialvalues::Vector{T}=_specialvalues(T, min, max),
    p::Bernoulli=Bernoulli(0.1),
    shrinker=NoShrinker())

    NumberStrategy(DiscreteUniform(min, max), specialvalues, p, shrinker)
end

function arbitrary{D, T}(strategy::NumberStrategy{D, T})
    if Bool(rand(strategy.p))
        if length(strategy.specialvalues) > 0
            return convert(T, rand(strategy.specialvalues))
        end
    end
    return convert(T, rand(strategy.dist))
end
shrink{T <: Number}(x::T, strategy::NumberStrategy) = Task(() -> nothing)

# ----- Booleans -----
immutable BoolStrategy <: AbstractStrategy
    bernoulli::Bernoulli
end
BoolStrategy(p::Float64) = BoolStrategy(Bernoulli(p))

bools(; p=0.5) = BoolStrategy(p)

arbitrary(strategy::BoolStrategy) = rand(strategy.bernoulli)
shrink(x::Bool, strategy::BoolStrategy) = Bool[]


text:
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, throws:false*/
(function($) {
"use strict";

var linkedlist = $.mediawiki.utils.linkedlist;
var ListIsEmptyError = $.mediawiki.utils.ListIsEmptyError;

function linkedlistEqual(lst, expected) {
	var result1 = [];
	lst.foreach(function(data) { result1.push(data); });
	deepEqual(result1, expected);

	var result2 = [];
	lst.reverse_foreach(function(data) { result2.push(data); });
	expected.reverse();
	deepEqual(result2, expected);
}

test("linkedlist, constructor", function() {
	var lst = $.mediawiki.utils.LinkedList();
	ok(lst.next === lst);
	ok(lst.prev === lst);
	ok(lst.length === 0);
	ok(lst.push !== null);
	ok(lst.pop !== null);
	ok(lst.foreach !== null);
	ok(lst.reverse_foreach !== null);
	ok(lst.unshift !== null);
	ok(lst.peek !== null);
});

test("linkedlist, foreach", function() {
	var lst = $.mediawiki.utils.LinkedList();

	var item1 = {data: 1, prev: lst};
	lst.next = item1;
	var item2 = {data: 2, prev: item1, next: lst};
	item1.next = item2;

	var result = [];
	lst.foreach(function(data) { result.push(data); });
	deepEqual(result, [1, 2]);
});

test("linkedlist, reverse_foreach", function() {
	var lst = $.mediawiki.utils.LinkedList();

	var item1 = {data: 1, prev: lst};
	lst.next = item1;
	var item2 = {data: 2, prev: item1, next: lst};
	item1.next = item2;
	lst.prev = item2;

	var result = [];
	lst.reverse_foreach(function(data) { result.push(data); });
	deepEqual(result, [2, 1]);
});

test("linkedlist, peek", function() {
	var lst = $.mediawiki.utils.LinkedList();

	equal(lst.peek(), null);
	lst.push(1);
	equal(lst.peek(), 1);
	lst.push(2);
	equal(lst.peek(), 2);
});

test("linkedlist, pop", function() {
	var lst = $.mediawiki.utils.LinkedList();

	throws(function() { lst.pop(); }, ListIsEmptyError);

	lst.push(1);
	lst.push(2);
	linkedlistEqual(lst, [1, 2]);
	equal(lst.length, 2);

	equal(lst.pop(), 2);
	linkedlistEqual(lst, [1]);
	equal(lst.length, 1);

	equal(lst.pop(), 1);
	linkedlistEqual(lst, []);
	equal(lst.length, 0);
});

test("linkedlist, push after specified item", function() {
	var lst = $.mediawiki.utils.LinkedList();
	equal(lst.length, 0);

	var item = lst.push(1);
	lst.push(3);
	linkedlistEqual(lst, [1, 3]);
	equal(lst.length, 2);

	lst.push(2, item);
	linkedlistEqual(lst, [1, 2, 3]);
	equal(lst.length, 3);
});

test("linkedlist, push after tail", function() {
	var lst = $.mediawiki.utils.LinkedList();
	equal(lst.length, 0);

	lst.push(1);
	linkedlistEqual(lst, [1]);
	equal(lst.length, 1);

	lst.push(2);
	linkedlistEqual(lst, [1, 2]);
	equal(lst.length, 2);

	lst.push(3);
	linkedlistEqual(lst, [1, 2, 3]);
	equal(lst.length, 3);
});

test("linkedlist, unshift", function() {
	var lst = $.mediawiki.utils.LinkedList();
	equal(lst.length, 0);

	lst.unshift(1);
	linkedlistEqual(lst, [1]);
	equal(lst.length, 1);

	lst.unshift(2);
	linkedlistEqual(lst, [2, 1]);
	equal(lst.length, 2);
});

test("linkedlist, object independance", function() {
	var lst1 = $.mediawiki.utils.LinkedList();
	var lst2 = $.mediawiki.utils.LinkedList();
	ok(lst1 !== lst2);

	lst1.push(1);
	ok(lst1.length === 1);
	ok(lst2.length === 0);
});

test("linkedlist, is last", function() {
	var lst = $.mediawiki.utils.LinkedList();

	var item1 = lst.push(1);
	ok(lst.is_last(item1) === true);

	lst.push(2);
	ok(lst.is_last(item1) === false);
});

}(jQuery));


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Index (Abstract Service Library)</title>
<meta name="date" content="2013-12-08">
<link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

A C D E F G I L M O Q R S T W

A

addWorkerFactory(WorkerFactory, String) - Method in class org.nise.ux.asl.run.ServiceServerBuilder

Adds workers generated from this factory right after library listener, as first layer of workers

addWorkerFactory(WorkerFactory, String, String) - Method in class org.nise.ux.asl.run.ServiceServerBuilder

Adds workers generated from this factory right after workers of name {parentName}

aslListeners - Variable in class org.nise.ux.asl.run.ServiceServerImpl

aslRequestFetchers - Variable in class org.nise.ux.asl.run.ServiceServerImpl

C

ChainException - Exception in org.nise.ux.asl.data

ChainException(String) - Constructor for exception org.nise.ux.asl.data.ChainException

close() - Method in interface org.nise.ux.asl.face.ServiceServer

Closes service-server by ending all client requests gracefully.

close() - Method in class org.nise.ux.asl.lib.DataStream

close() - Method in class org.nise.ux.asl.run.ServiceClient

close() - Method in class org.nise.ux.asl.run.ServiceServerImpl

create() - Method in class org.nise.ux.asl.run.ServiceServerBuilder

D

data - Variable in class org.nise.ux.asl.data.ServiceResponse

data - Variable in class org.nise.ux.asl.lib.IndexedData

DataConnection - Interface in org.nise.ux.asl.data

DataStream - Class in org.nise.ux.asl.lib

DataStream(String, int) - Constructor for class org.nise.ux.asl.lib.DataStream

DataStream(Socket) - Constructor for class org.nise.ux.asl.lib.DataStream

E

exit(boolean) - Method in interface org.nise.ux.asl.face.ServiceServer

Closes service-server by ending all client requests if 'exit process' is not forced.

exit(boolean) - Method in class org.nise.ux.asl.run.ServiceServerImpl

extractCommand() - Method in class org.nise.ux.asl.lib.DataStream

F

FETCHER_NO - Static variable in interface org.nise.ux.asl.face.ServiceServer

constant value equal to "FETCHER_NO"

G

getAllStats() - Method in interface org.nise.ux.asl.face.ServiceServer

Gives all system status in a Map of "{Status name}" -> "{Status value}"

getAllStats(String) - Method in interface org.nise.ux.asl.face.ServiceServer

Gives all system status in a Map of "{prefix}{Status name}" -> "{Status value}"

getAllStats() - Method in class org.nise.ux.asl.run.ServiceServerImpl

getAllStats(String) - Method in class org.nise.ux.asl.run.ServiceServerImpl

Gives all system status in a Map of "{prefix}{Status name}" -> "{Status value}"

getBooleanConfiguration(String) - Method in interface org.nise.ux.asl.face.ServiceServer

Get boolean value of a configuration using its name

getClients() - Method in interface org.nise.ux.asl.face.ServiceServer

getCommand() - Method in interface org.nise.ux.asl.data.DataConnection

getConfiguration(String) - Method in interface org.nise.ux.asl.face.ServiceServer

Get value of a configuration using its name

getConfigurationKeys() - Method in interface org.nise.ux.asl.face.ServiceServer

Get boolean value of a configuration using its name

getIndex() - Method in interface org.nise.ux.asl.data.DataConnection

getInSystem() - Method in interface org.nise.ux.asl.face.ServiceServer

getIntegerConfiguration(String) - Method in interface org.nise.ux.asl.face.ServiceServer

Get integer value of a configuration using its name

getListeningPort() - Method in interface org.nise.ux.asl.face.ServiceServer

Get value of configuration ServiceServer.LISTENING_PORT equal to getIntegerConfiguration(ServiceServer.LISTENING_PORT)

getMax_clients() - Method in interface org.nise.ux.asl.face.ServiceServer

Get value of configuration ServiceServer.MAX_CLIENTS equal to getIntegerConfiguration(ServiceServer.MAX_CLIENTS)

getRequestArgs(Type[]) - Method in interface org.nise.ux.asl.data.DataConnection

getRequestArgs(Class<?>[]) - Method in interface org.nise.ux.asl.data.DataConnection

getWorker() - Method in interface org.nise.ux.asl.face.WorkerFactory

Create a new instance of Worker

getWorkerNames() - Method in interface org.nise.ux.asl.face.ServiceServer

Get a list of Workers.

getWorkerNames() - Method in class org.nise.ux.asl.run.ServiceServerImpl

getWorkerNo(String) - Method in interface org.nise.ux.asl.face.ServiceServer

Get number of ServiceServer Workers of name 'worker' configured.

getWorkerNo(String) - Method in class org.nise.ux.asl.run.ServiceServerImpl

I

index - Variable in class org.nise.ux.asl.lib.IndexedData

IndexedData<T> - Class in org.nise.ux.asl.lib

IndexedData(T, int) - Constructor for class org.nise.ux.asl.lib.IndexedData

invokeServiceCommand(<any>, String, Object...) - Method in class org.nise.ux.asl.run.ServiceClient

isClosed() - Method in class org.nise.ux.asl.lib.DataStream

isTest_mode() - Method in interface org.nise.ux.asl.face.ServiceServer

Get value of configuration ServiceServer.TEST_MODE equal to getBooleanConfiguration(ServiceServer.TEST_MODE)

L

LISTENING_PORT - Static variable in interface org.nise.ux.asl.face.ServiceServer

constant value equal to "LISTENING_PORT"

M

MapCommand - Annotation Type in org.nise.ux.asl.data

MAX_CLIENTS - Static variable in interface org.nise.ux.asl.face.ServiceServer

constant value equal to "MAX_CLIENTS"

O

org.nise.ux.asl.data - package org.nise.ux.asl.data

org.nise.ux.asl.face - package org.nise.ux.asl.face

org.nise.ux.asl.lib - package org.nise.ux.asl.lib

org.nise.ux.asl.run - package org.nise.ux.asl.run

Q

QUEUE_LENGTH_CONST - Static variable in interface org.nise.ux.asl.face.ServiceServer

constant value equal to "QUEUE_LENGTH_CONST"

R

recieve(<any>) - Method in class org.nise.ux.asl.lib.DataStream

recieveReturn() - Method in class org.nise.ux.asl.lib.DataStream

refreshAll() - Method in class org.nise.ux.asl.run.ServiceServerImpl

Re-Constructs or Destroys ServiceServer Threads based on numbers defined in configuration parameters

refreshConfig(String, String) - Method in class org.nise.ux.asl.run.ServiceServerImpl

Re-Constructs or Destroys ServiceServer Threads of given configuration parameter.

restart() - Method in class org.nise.ux.asl.run.ServiceClient

run() - Method in class org.nise.ux.asl.run.ServiceClient

S

send(SD) - Method in interface org.nise.ux.asl.data.DataConnection

send(Object, int) - Method in class org.nise.ux.asl.lib.DataStream

sendCommand(int, String, Object...) - Method in class org.nise.ux.asl.lib.DataStream

sendReturn(int, Object) - Method in class org.nise.ux.asl.lib.DataStream

sendReturn(int, Throwable) - Method in class org.nise.ux.asl.lib.DataStream

ServiceClient<D,R> - Class in org.nise.ux.asl.run

ServiceClient(String, int, int) - Constructor for class org.nise.ux.asl.run.ServiceClient

ServiceResponse - Class in org.nise.ux.asl.data

ServiceResponse(Object) - Constructor for class org.nise.ux.asl.data.ServiceResponse

ServiceResponse(Throwable) - Constructor for class org.nise.ux.asl.data.ServiceResponse

ServiceResponse(Object, Throwable) - Constructor for class org.nise.ux.asl.data.ServiceResponse

ServiceServer - Interface in org.nise.ux.asl.face

ServiceServerBuilder - Class in org.nise.ux.asl.run

This is the Main Constructor Class of this service library.

ServiceServerBuilder(int) - Constructor for class org.nise.ux.asl.run.ServiceServerBuilder

ServiceServerImpl - Class in org.nise.ux.asl.run

ServiceServerImpl(List<WorkersTreeDecriptor>) - Constructor for class org.nise.ux.asl.run.ServiceServerImpl

ServiceServerImpl(List<WorkersTreeDecriptor>, Map<String, String>) - Constructor for class org.nise.ux.asl.run.ServiceServerImpl

setAutoWorkerNo(String, int, int) - Method in class org.nise.ux.asl.run.ServiceServerBuilder

Set value of configuration for {worker}_no with automatic management with lower/upper bands specified.

setConfiguration(String, String) - Method in interface org.nise.ux.asl.face.ServiceServer

Set value of a configuration

setConstantWorkerNo(String, int) - Method in class org.nise.ux.asl.run.ServiceServerBuilder

Set value of configuration for {worker}_no as a constant factor

setMax_clients(int) - Method in interface org.nise.ux.asl.face.ServiceServer

Set value of configuration for ServiceServer.MAX_CLIENTS equal to setConfiguration("MAX_CLIENTS", String.valueOf(max_clients))

setTest_mode(boolean) - Method in interface org.nise.ux.asl.face.ServiceServer

Set value of configuration for ServiceServer.TEST_MODE equal to setConfiguration("TEST_MODE", String.valueOf(test_mode))

start() - Method in class org.nise.ux.asl.run.ServiceServerImpl

T

TEST_MODE - Static variable in interface org.nise.ux.asl.face.ServiceServer

constant value equal to "TEST_MODE"

throwable - Variable in class org.nise.ux.asl.data.ServiceResponse

toString() - Method in class org.nise.ux.asl.data.ServiceResponse

W

Worker - Interface in org.nise.ux.asl.face

Worker_iQueues - Variable in class org.nise.ux.asl.run.ServiceServerImpl

WorkerFactory - Interface in org.nise.ux.asl.face

Interface used to create Worker instances.

workersListMap - Variable in class org.nise.ux.asl.run.ServiceServerImpl

workersNameList - Variable in class org.nise.ux.asl.run.ServiceServerImpl

A C D E F G I L M O Q R S T W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

				This library is a work of NISE organization User-eXperience team.


text:
These settings apply only when `--nodejs` is specified on the command line.
Please also specify `--node-sdks-folder=<path to root folder of your azure-sdk-for-node clone>`.

``` yaml $(nodejs)
nodejs:
  azure-arm: true
  package-name: azure-arm-hdinsight
  output-folder: $(node-sdks-folder)/lib/services/hdInsightManagement/lib
```


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * Attach Internet Gateway Request Marshaller
 */
public class AttachInternetGatewayRequestMarshaller implements Marshaller<Request<AttachInternetGatewayRequest>, AttachInternetGatewayRequest> {

    public Request<AttachInternetGatewayRequest> marshall(AttachInternetGatewayRequest attachInternetGatewayRequest) {

        if (attachInternetGatewayRequest == null) {
		    throw new AmazonClientException("Invalid argument passed to marshall(...)");
		}

        Request<AttachInternetGatewayRequest> request = new DefaultRequest<AttachInternetGatewayRequest>(attachInternetGatewayRequest, "AmazonEC2");
        request.addParameter("Action", "AttachInternetGateway");
        request.addParameter("Version", "2012-10-01");

        if (attachInternetGatewayRequest.getInternetGatewayId() != null) {
            request.addParameter("InternetGatewayId", StringUtils.fromString(attachInternetGatewayRequest.getInternetGatewayId()));
        }
        if (attachInternetGatewayRequest.getVpcId() != null) {
            request.addParameter("VpcId", StringUtils.fromString(attachInternetGatewayRequest.getVpcId()));
        }

        return request;
    }
}


text:
--------------------------------
-- @module TransitionSlideInR
-- @extend TransitionSlideInL
-- @parent_module cc

--------------------------------
--  Creates a transition with duration and incoming scene.

-- param t Duration time, in seconds.

-- param scene A given scene.

-- return A autoreleased TransitionSlideInR object.
-- @function [parent=#TransitionSlideInR] create
-- @param self
-- @param #float t
-- @param #cc.Scene scene
-- @return TransitionSlideInR#TransitionSlideInR ret (return value: cc.TransitionSlideInR)

--------------------------------
--  Returns the action that will be performed by the incoming and outgoing scene.
-- @function [parent=#TransitionSlideInR] action
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)

return nil


text:
Limit.sec={Limit.Mutual.sec}

Void.sec={Void.MutualExceptMerger.sec}

Benefit.sec={Benefit.Mutual.sec}


text:
This directory includes subdirectories for rubygems required by rbeapi.  The
packaging definitions, herein, are ONLY to be used when packaging for
Arista EOS.   For all other platform, native platform packages or the
'gem install' command should be used.


text:
package buildinfo

import (
	"bytes"
	"debug/elf"
	"debug/macho"
	"debug/pe"
	"debug/plan9obj"
	"encoding/binary"
	"errors"
	"fmt"
	"internal/xcoff"
	"io"
	"io/fs"
	"os"
	"runtime/debug"
)

// Type alias for build info. We cannot move the types here, since
// runtime/debug would need to import this package, which would make it
// a much larger dependency.
type BuildInfo = debug.BuildInfo

var (
	// errUnrecognizedFormat is returned when a given executable file doesn't
	// appear to be in a known format, or it breaks the rules of that format,
	// or when there are I/O errors reading the file.
	errUnrecognizedFormat = errors.New("unrecognized file format")

	// errNotGoExe is returned when a given executable file is valid but does
	// not contain Go build information.
	errNotGoExe = errors.New("not a Go executable")

	// The build info blob left by the linker is identified by
	// a 16-byte header, consisting of buildInfoMagic (14 bytes),
	// the binary's pointer size (1 byte),
	// and whether the binary is big endian (1 byte).
	buildInfoMagic = []byte("\xff Go buildinf:")
)

// ReadFile returns build information embedded in a Go binary
// file at the given path. Most information is only available for binaries built
// with module support.
func ReadFile(name string) (info *BuildInfo, err error) {
	defer func() {
		if pathErr := (*fs.PathError)(nil); errors.As(err, &pathErr) {
			err = fmt.Errorf("could not read Go build info: %w", err)
		} else if err != nil {
			err = fmt.Errorf("could not read Go build info from %s: %w", name, err)
		}
	}()

	f, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return Read(f)
}

// Read returns build information embedded in a Go binary file
// accessed through the given ReaderAt. Most information is only available for
// binaries built with module support.
func Read(r io.ReaderAt) (*BuildInfo, error) {
	vers, mod, err := readRawBuildInfo(r)
	if err != nil {
		return nil, err
	}
	bi, err := debug.ParseBuildInfo(mod)
	if err != nil {
		return nil, err
	}
	bi.GoVersion = vers
	return bi, nil
}

type exe interface {
	// ReadData reads and returns up to size bytes starting at virtual address addr.
	ReadData(addr, size uint64) ([]byte, error)

	// DataStart returns the virtual address of the segment or section that
	// should contain build information. This is either a specially named section
	// or the first writable non-zero data segment.
	DataStart() uint64
}

// readRawBuildInfo extracts the Go toolchain version and module information
// strings from a Go binary. On success, vers should be non-empty. mod
// is empty if the binary was not built with modules enabled.
func readRawBuildInfo(r io.ReaderAt) (vers, mod string, err error) {
	// Read the first bytes of the file to identify the format, then delegate to
	// a format-specific function to load segment and section headers.
	ident := make([]byte, 16)
	if n, err := r.ReadAt(ident, 0); n < len(ident) || err != nil {
		return "", "", errUnrecognizedFormat
	}

	var x exe
	switch {
	case bytes.HasPrefix(ident, []byte("\x7FELF")):
		f, err := elf.NewFile(r)
		if err != nil {
			return "", "", errUnrecognizedFormat
		}
		x = &elfExe{f}
	case bytes.HasPrefix(ident, []byte("MZ")):
		f, err := pe.NewFile(r)
		if err != nil {
			return "", "", errUnrecognizedFormat
		}
		x = &peExe{f}
	case bytes.HasPrefix(ident, []byte("\xFE\xED\xFA")) || bytes.HasPrefix(ident[1:], []byte("\xFA\xED\xFE")):
		f, err := macho.NewFile(r)
		if err != nil {
			return "", "", errUnrecognizedFormat
		}
		x = &machoExe{f}
	case bytes.HasPrefix(ident, []byte{0x01, 0xDF}) || bytes.HasPrefix(ident, []byte{0x01, 0xF7}):
		f, err := xcoff.NewFile(r)
		if err != nil {
			return "", "", errUnrecognizedFormat
		}
		x = &xcoffExe{f}
	case hasPlan9Magic(ident):
		f, err := plan9obj.NewFile(r)
		if err != nil {
			return "", "", errUnrecognizedFormat
		}
		x = &plan9objExe{f}
	default:
		return "", "", errUnrecognizedFormat
	}

	// Read the first 64kB of dataAddr to find the build info blob.
	// On some platforms, the blob will be in its own section, and DataStart
	// returns the address of that section. On others, it's somewhere in the
	// data segment; the linker puts it near the beginning.
	// See cmd/link/internal/ld.Link.buildinfo.
	dataAddr := x.DataStart()
	data, err := x.ReadData(dataAddr, 64*1024)
	if err != nil {
		return "", "", err
	}
	const (
		buildInfoAlign = 16
		buildInfoSize  = 32
	)
	for {
		i := bytes.Index(data, buildInfoMagic)
		if i < 0 || len(data)-i < buildInfoSize {
			return "", "", errNotGoExe
		}
		if i%buildInfoAlign == 0 && len(data)-i >= buildInfoSize {
			data = data[i:]
			break
		}
		data = data[(i+buildInfoAlign-1)&^(buildInfoAlign-1):]
	}

	// Decode the blob.
	// The first 14 bytes are buildInfoMagic.
	// The next two bytes indicate pointer size in bytes (4 or 8) and endianness
	// (0 for little, 1 for big).
	// Two virtual addresses to Go strings follow that: runtime.buildVersion,
	// and runtime.modinfo.
	// On 32-bit platforms, the last 8 bytes are unused.
	// If the endianness has the 2 bit set, then the pointers are zero
	// and the 32-byte header is followed by varint-prefixed string data
	// for the two string values we care about.
	ptrSize := int(data[14])
	if data[15]&2 != 0 {
		vers, data = decodeString(data[32:])
		mod, data = decodeString(data)
	} else {
		bigEndian := data[15] != 0
		var bo binary.ByteOrder
		if bigEndian {
			bo = binary.BigEndian
		} else {
			bo = binary.LittleEndian
		}
		var readPtr func([]byte) uint64
		if ptrSize == 4 {
			readPtr = func(b []byte) uint64 { return uint64(bo.Uint32(b)) }
		} else {
			readPtr = bo.Uint64
		}
		vers = readString(x, ptrSize, readPtr, readPtr(data[16:]))
		mod = readString(x, ptrSize, readPtr, readPtr(data[16+ptrSize:]))
	}
	if vers == "" {
		return "", "", errNotGoExe
	}
	if len(mod) >= 33 && mod[len(mod)-17] == '\n' {
		// Strip module framing: sentinel strings delimiting the module info.
		// These are cmd/go/internal/modload.infoStart and infoEnd.
		mod = mod[16 : len(mod)-16]
	} else {
		mod = ""
	}

	return vers, mod, nil
}

func hasPlan9Magic(magic []byte) bool {
	if len(magic) >= 4 {
		m := binary.BigEndian.Uint32(magic)
		switch m {
		case plan9obj.Magic386, plan9obj.MagicAMD64, plan9obj.MagicARM:
			return true
		}
	}
	return false
}

func decodeString(data []byte) (s string, rest []byte) {
	u, n := binary.Uvarint(data)
	if n <= 0 || u >= uint64(len(data)-n) {
		return "", nil
	}
	return string(data[n : uint64(n)+u]), data[uint64(n)+u:]
}

// readString returns the string at address addr in the executable x.
func readString(x exe, ptrSize int, readPtr func([]byte) uint64, addr uint64) string {
	hdr, err := x.ReadData(addr, uint64(2*ptrSize))
	if err != nil || len(hdr) < 2*ptrSize {
		return ""
	}
	dataAddr := readPtr(hdr)
	dataLen := readPtr(hdr[ptrSize:])
	data, err := x.ReadData(dataAddr, dataLen)
	if err != nil || uint64(len(data)) < dataLen {
		return ""
	}
	return string(data)
}

// elfExe is the ELF implementation of the exe interface.
type elfExe struct {
	f *elf.File
}

func (x *elfExe) ReadData(addr, size uint64) ([]byte, error) {
	for _, prog := range x.f.Progs {
		if prog.Vaddr <= addr && addr <= prog.Vaddr+prog.Filesz-1 {
			n := prog.Vaddr + prog.Filesz - addr
			if n > size {
				n = size
			}
			data := make([]byte, n)
			_, err := prog.ReadAt(data, int64(addr-prog.Vaddr))
			if err != nil {
				return nil, err
			}
			return data, nil
		}
	}
	return nil, errUnrecognizedFormat
}

func (x *elfExe) DataStart() uint64 {
	for _, s := range x.f.Sections {
		if s.Name == ".go.buildinfo" {
			return s.Addr
		}
	}
	for _, p := range x.f.Progs {
		if p.Type == elf.PT_LOAD && p.Flags&(elf.PF_X|elf.PF_W) == elf.PF_W {
			return p.Vaddr
		}
	}
	return 0
}

// peExe is the PE (Windows Portable Executable) implementation of the exe interface.
type peExe struct {
	f *pe.File
}

func (x *peExe) imageBase() uint64 {
	switch oh := x.f.OptionalHeader.(type) {
	case *pe.OptionalHeader32:
		return uint64(oh.ImageBase)
	case *pe.OptionalHeader64:
		return oh.ImageBase
	}
	return 0
}

func (x *peExe) ReadData(addr, size uint64) ([]byte, error) {
	addr -= x.imageBase()
	for _, sect := range x.f.Sections {
		if uint64(sect.VirtualAddress) <= addr && addr <= uint64(sect.VirtualAddress+sect.Size-1) {
			n := uint64(sect.VirtualAddress+sect.Size) - addr
			if n > size {
				n = size
			}
			data := make([]byte, n)
			_, err := sect.ReadAt(data, int64(addr-uint64(sect.VirtualAddress)))
			if err != nil {
				return nil, errUnrecognizedFormat
			}
			return data, nil
		}
	}
	return nil, errUnrecognizedFormat
}

func (x *peExe) DataStart() uint64 {
	// Assume data is first writable section.
	const (
		IMAGE_SCN_CNT_CODE               = 0x00000020
		IMAGE_SCN_CNT_INITIALIZED_DATA   = 0x00000040
		IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
		IMAGE_SCN_MEM_EXECUTE            = 0x20000000
		IMAGE_SCN_MEM_READ               = 0x40000000
		IMAGE_SCN_MEM_WRITE              = 0x80000000
		IMAGE_SCN_MEM_DISCARDABLE        = 0x2000000
		IMAGE_SCN_LNK_NRELOC_OVFL        = 0x1000000
		IMAGE_SCN_ALIGN_32BYTES          = 0x600000
	)
	for _, sect := range x.f.Sections {
		if sect.VirtualAddress != 0 && sect.Size != 0 &&
			sect.Characteristics&^IMAGE_SCN_ALIGN_32BYTES == IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_MEM_READ|IMAGE_SCN_MEM_WRITE {
			return uint64(sect.VirtualAddress) + x.imageBase()
		}
	}
	return 0
}

// machoExe is the Mach-O (Apple macOS/iOS) implementation of the exe interface.
type machoExe struct {
	f *macho.File
}

func (x *machoExe) ReadData(addr, size uint64) ([]byte, error) {
	for _, load := range x.f.Loads {
		seg, ok := load.(*macho.Segment)
		if !ok {
			continue
		}
		if seg.Addr <= addr && addr <= seg.Addr+seg.Filesz-1 {
			if seg.Name == "__PAGEZERO" {
				continue
			}
			n := seg.Addr + seg.Filesz - addr
			if n > size {
				n = size
			}
			data := make([]byte, n)
			_, err := seg.ReadAt(data, int64(addr-seg.Addr))
			if err != nil {
				return nil, err
			}
			return data, nil
		}
	}
	return nil, errUnrecognizedFormat
}

func (x *machoExe) DataStart() uint64 {
	// Look for section named "__go_buildinfo".
	for _, sec := range x.f.Sections {
		if sec.Name == "__go_buildinfo" {
			return sec.Addr
		}
	}
	// Try the first non-empty writable segment.
	const RW = 3
	for _, load := range x.f.Loads {
		seg, ok := load.(*macho.Segment)
		if ok && seg.Addr != 0 && seg.Filesz != 0 && seg.Prot == RW && seg.Maxprot == RW {
			return seg.Addr
		}
	}
	return 0
}

// xcoffExe is the XCOFF (AIX eXtended COFF) implementation of the exe interface.
type xcoffExe struct {
	f *xcoff.File
}

func (x *xcoffExe) ReadData(addr, size uint64) ([]byte, error) {
	for _, sect := range x.f.Sections {
		if sect.VirtualAddress <= addr && addr <= sect.VirtualAddress+sect.Size-1 {
			n := sect.VirtualAddress + sect.Size - addr
			if n > size {
				n = size
			}
			data := make([]byte, n)
			_, err := sect.ReadAt(data, int64(addr-sect.VirtualAddress))
			if err != nil {
				return nil, err
			}
			return data, nil
		}
	}
	return nil, errors.New("address not mapped")
}

func (x *xcoffExe) DataStart() uint64 {
	if s := x.f.SectionByType(xcoff.STYP_DATA); s != nil {
		return s.VirtualAddress
	}
	return 0
}

// plan9objExe is the Plan 9 a.out implementation of the exe interface.
type plan9objExe struct {
	f *plan9obj.File
}

func (x *plan9objExe) DataStart() uint64 {
	if s := x.f.Section("data"); s != nil {
		return uint64(s.Offset)
	}
	return 0
}

func (x *plan9objExe) ReadData(addr, size uint64) ([]byte, error) {
	for _, sect := range x.f.Sections {
		if uint64(sect.Offset) <= addr && addr <= uint64(sect.Offset+sect.Size-1) {
			n := uint64(sect.Offset+sect.Size) - addr
			if n > size {
				n = size
			}
			data := make([]byte, n)
			_, err := sect.ReadAt(data, int64(addr-uint64(sect.Offset)))
			if err != nil {
				return nil, err
			}
			return data, nil
		}
	}
	return nil, errors.New("address not mapped")

}


text:
var OPPORTUNITY_STAGE_NAMES = [
    'Evaluation',
    'Contract Negotiation',
    'Closed Won'
];

module.exports = {
    OPPORTUNITY_STAGE_NAMES,
}


text:
package monix.reactive.observers

import monix.execution.Ack.{Continue, Stop}
import monix.execution.{Ack, CancelableFuture, Scheduler}
import monix.reactive.Observable

import scala.collection.mutable
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}

/** Wraps a [[Subscriber]] into an implementation that abstains from emitting items until the call
  * to `connect()` happens. Prior to `connect()` you can enqueue
  * events for delivery once `connect()` happens, but before any items
  * emitted by `onNext` / `onComplete` and `onError`.
  *
  * Example: {{{
  *   import monix.execution.Ack.Continue
  *   import monix.execution.Scheduler.Implicits.global
  *
  *   val subscriber = new Subscriber[String] {
  *     val scheduler = global
  *     def onNext(a: String) = {
  *       println(s"Received: $$a")
  *       Continue
  *     }
  *     def onError(e: Throwable) =
  *       println(s"Error: $$e")
  *     def onComplete() =
  *       println("Completed!")
  *   }
  *
  *   val out = ConnectableSubscriber(subscriber)
  *
  *   // schedule onNext event, after connect()
  *   out.onNext("c")
  *
  *   // schedule event "a" to be emitted first
  *   out.pushFirst("a")
  *   // schedule event "b" to be emitted second
  *   out.pushFirst("b")
  *
  *   // underlying observer now gets events "a", "b", "c" in order
  *   out.connect()
  * }}}
  *
  * Example of an observer ended in error: {{{
  *   val out2 = ConnectableSubscriber(subscriber)
  *
  *   // schedule onNext event, after connect()
  *   out2.onNext("c")
  *
  *   out2.pushFirst("a") // event "a" to be emitted first
  *   out2.pushFirst("b") // event "b" to be emitted second
  *
  *   // schedule an onError sent downstream, once connect()
  *   // happens, but after "a" and "b"
  *   out2.pushError(new RuntimeException())
  *
  *   // underlying observer receives ...
  *   // onNext("a") -> onNext("b") -> onError(RuntimeException)
  *   out2.connect()
  *
  *   // NOTE: that onNext("c") never happens
  * }}}
  */
final class ConnectableSubscriber[-A] private (underlying: Subscriber[A]) extends Subscriber[A] { self =>

  implicit val scheduler: Scheduler =
    underlying.scheduler

  // MUST BE synchronized by `self`, only available if isConnected == false
  private[this] var queue = mutable.ArrayBuffer.empty[A]
  // MUST BE synchronized by `self`, only available if isConnected == false
  private[this] var scheduledDone = false
  // MUST BE synchronized by `self`, only available if isConnected == false
  private[this] var scheduledError = null: Throwable
  // MUST BE synchronized by `self`
  private[this] var isConnectionStarted = false
  // MUST BE synchronized by `self`, as long as isConnected == false
  private[this] var wasCanceled = false

  // Promise guaranteed to be fulfilled once isConnected is
  // seen as true and used for back-pressure.
  // MUST BE synchronized by `self`, only available if isConnected == false
  private[this] var connectedPromise = Promise[Ack]()
  private[this] var connectedFuture = connectedPromise.future

  // Volatile that is set to true once the buffer is drained.
  // Once visible as true, it implies that the queue is empty
  // and has been drained and thus the onNext/onError/onComplete
  // can take the fast path
  @volatile private[this] var isConnected = false

  // Only accessible in `connect()`
  private[this] var connectionRef: CancelableFuture[Ack] = _

  /** Connects the underling observer to the upstream publisher.
    *
    * This function should be idempotent. Calling it multiple times
    * should have the same effect as calling it once.
    */
  def connect(): CancelableFuture[Ack] =
    self.synchronized {
      if (!isConnected && !isConnectionStarted) {
        isConnectionStarted = true
        val bufferWasDrained = Promise[Ack]()

        val cancelable = Observable
          .fromIterable(queue)
          .unsafeSubscribeFn(new Subscriber[A] {
            implicit val scheduler = underlying.scheduler
            private[this] var ack: Future[Ack] = Continue

            bufferWasDrained.future.onComplete {
              case Success(Continue) =>
                connectedPromise.success(Continue)
                isConnected = true
                // GC relief
                queue = null
                connectedPromise = null
                // This might be a race condition problem, but it only
                // matters for GC relief purposes
                connectionRef = CancelableFuture.successful(Continue)

              case Success(Stop) =>
                wasCanceled = true
                connectedPromise.success(Stop)
                isConnected = true
                // GC relief
                queue = null
                connectedPromise = null
                // This might be a race condition problem, but it only
                // matters for GC relief purposes
                connectionRef = CancelableFuture.successful(Stop)

              case Failure(ex) =>
                wasCanceled = true
                connectedPromise.failure(ex)
                isConnected = true
                // GC relief
                queue = null
                connectedPromise = null
                // This might be a race condition problem, but it only
                // matters for GC relief purposes
                connectionRef = CancelableFuture.failed(ex)
            }

            def onNext(elem: A): Future[Ack] = {
              ack = underlying.onNext(elem).syncOnStopFollow(bufferWasDrained, Stop)
              ack
            }

            def onComplete(): Unit = {
              if (!scheduledDone) {
                ack.syncOnContinue { bufferWasDrained.trySuccess(Continue); () }
              } else if (scheduledError ne null) {
                if (bufferWasDrained.trySuccess(Stop))
                  underlying.onError(scheduledError)
              } else if (bufferWasDrained.trySuccess(Stop))
                underlying.onComplete()
              ()
            }

            def onError(ex: Throwable): Unit = {
              if (scheduledError ne null)
                scheduler.reportFailure(ex)
              else {
                scheduledDone = true
                scheduledError = ex

                if (bufferWasDrained.trySuccess(Stop))
                  underlying.onError(ex)
                else
                  scheduler.reportFailure(ex)
              }
            }
          })

        connectionRef = CancelableFuture(bufferWasDrained.future, cancelable)
      }

      connectionRef
    }

  /** Schedule one element to be pushed to the underlying subscriber
    * when [[connect]] happens.
    *
    * The given elements are appended to a queue that will be
    * drained on [[connect]]. Afterwards no more elements are
    * allowed to be pushed in the queue.
    *
    * These elements are streamed before any elements that will
    * eventually get streamed with [[onNext]], because of
    * the applied back-pressure from `onNext`.
    */
  def pushFirst(elem: A): Unit =
    self.synchronized {
      if (isConnected || isConnectionStarted)
        throw new IllegalStateException("Observer was already connected, so cannot pushFirst")
      else if (!scheduledDone)
        queue += elem
      ()
    }

  /** Schedule elements to be pushed to the underlying subscriber
    * when [[connect]] happens.
    *
    * The given elements are appended to a queue that will be
    * drained on [[connect]]. Afterwards no more elements are
    * allowed to be pushed in the queue.
    *
    * These elements are streamed before any elements that will
    * eventually get streamed with [[onNext]], because of
    * the applied back-pressure from `onNext`.
    */
  def pushFirstAll[U <: A](xs: Iterable[U]): Unit =
    self.synchronized {
      if (isConnected || isConnectionStarted)
        throw new IllegalStateException("Observer was already connected, so cannot pushFirst")
      else if (!scheduledDone)
        queue.appendAll(xs)
      ()
    }

  /** Schedule a complete event when [[connect]] happens,
    * but before any elements scheduled with [[pushFirst]]
    * or [[pushFirstAll]].
    *
    * After `pushComplete` no more [[pushFirst]] or [[onNext]]
    * events are accepted.
    */
  def pushComplete(): Unit =
    self.synchronized {
      if (isConnected || isConnectionStarted)
        throw new IllegalStateException("Observer was already connected, so cannot pushFirst")
      else if (!scheduledDone) {
        scheduledDone = true
      }
    }

  /** Schedule an error event when [[connect]] happens,
    * but before any elements scheduled with [[pushFirst]]
    * or [[pushFirstAll]].
    *
    * After `pushError` no more [[pushFirst]] or [[onNext]]
    * events are accepted.
    */
  def pushError(ex: Throwable): Unit =
    self.synchronized {
      if (isConnected || isConnectionStarted)
        throw new IllegalStateException("Observer was already connected, so cannot pushFirst")
      else if (!scheduledDone) {
        scheduledDone = true
        scheduledError = ex
      }
    }

  /** The [[Subscriber.onNext]] method that pushes events to
    * the underlying subscriber.
    *
    * It will back-pressure by means of its `Future[Ack]` result
    * until [[connect]] happens and the underlying queue of
    * scheduled events have been drained.
    */
  def onNext(elem: A): Future[Ack] = {
    if (!isConnected) {
      // no need for synchronization here, since this reference is initialized
      // before the subscription happens and because it gets written only in
      // onNext / onComplete, which are non-concurrent clauses
      connectedFuture = connectedFuture.flatMap {
        case Continue => underlying.onNext(elem)
        case Stop => Stop
      }
      connectedFuture
    } else if (!wasCanceled) {
      // taking fast path
      underlying.onNext(elem)
    } else {
      // was canceled either during connect, or the upstream publisher
      // sent an onNext event after onComplete / onError
      Stop
    }
  }

  /** The [[Subscriber.onComplete]] method that pushes the
    * complete event to the underlying observer.
    *
    * It will wait for [[connect]] to happen and the queue of
    * scheduled events to be drained.
    */
  def onComplete(): Unit = {
    // we cannot take a fast path here
    connectedFuture.syncTryFlatten
      .syncOnContinue(underlying.onComplete())
    ()
  }

  /** The [[Subscriber.onError]] method that pushes an
    * error event to the underlying observer.
    *
    * It will wait for [[connect]] to happen and the queue of
    * scheduled events to be drained.
    */
  def onError(ex: Throwable): Unit = {
    // we cannot take a fast path here
    connectedFuture.syncTryFlatten
      .syncOnContinue(underlying.onError(ex))
    ()
  }
}

object ConnectableSubscriber {
  /** `ConnectableSubscriber` builder */
  def apply[A](subscriber: Subscriber[A]): ConnectableSubscriber[A] = {
    new ConnectableSubscriber[A](subscriber)
  }
}


text:
class AddColumnsToBonus < ActiveRecord::Migration
  def change
    add_column :bonus, :project_id, :integer
    add_column :bonus, :user_id, :integer
  end
end


text:
import Ember from 'ember';
import { module, test } from 'qunit';
import FlexberryMapModelApiMixin from 'ember-flexberry-gis/mixins/flexberry-map-model-api';
import sinon from 'sinon';

module('Unit | Mixin | test method setVisibilityObjects');

let mapApiMixinObject = Ember.Object.extend(FlexberryMapModelApiMixin);

let layerModel = Ember.A({
  settingsAsObject: {
    labelSettings: {
      signMapObjects: true
    }
  }
});
let _labelsLayer = L.featureGroup();
let leafletObject = L.featureGroup();
leafletObject.options = {
  showExisting: false,
  continueLoading: false
};
leafletObject._labelsLayer = _labelsLayer;
let firstTestLayer = L.polygon([[1, 2], [4, 2], [4, 4], [1, 2]]).addTo(leafletObject);
firstTestLayer.id = '1';
let secondTestLayer = L.polygon([[10, 20], [40, 20], [40, 40], [10, 20]]).addTo(leafletObject);
secondTestLayer.id = '2';
let thirdTestLayer = L.polygon([[0.1, 0.2], [0.4, 0.2], [0.4, 0.4], [0.1, 0.2]]).addTo(leafletObject);
thirdTestLayer.id = '3';
let firstTestLabelLayer = L.marker([1, 2]).addTo(_labelsLayer);
firstTestLabelLayer.id = '1';
let secondTestLabelLayer = L.marker([40, 20]).addTo(_labelsLayer);
secondTestLabelLayer.id = '2';
let thirdTestLabelLayer = L.marker([20, 40]).addTo(_labelsLayer);
thirdTestLabelLayer.id = '3';

test('Test to check fail message', function(assert) {
  //Arrange
  assert.expect(4);
  let map = L.map(document.createElement('div'), {
    center: [51.505, -0.09],
    zoom: 13
  });
  let done = assert.async(1);
  let subject = mapApiMixinObject.create({
    _getModelLeafletObject() { return [layerModel, leafletObject]; },
    mapApi: {
      getFromApi() { return map; }
    },
    _getLayerFeatureId(layer, shape) { return shape.id; },
  });
  let getModelLeafletObjSpy = sinon.spy(subject, '_getModelLeafletObject');

  //Act
  let result = subject._setVisibilityObjects('1', ['1', '2'], true);

  //Assert
  assert.ok(result instanceof Ember.RSVP.Promise, 'Equals result = Promise');
  result.catch((res)=> {
    assert.equal(res, 'Layer type not supported');
    assert.equal(getModelLeafletObjSpy.callCount, 1, 'Check call count to method _getModelLeafletObject');
    assert.equal(getModelLeafletObjSpy.args[0][0], '1', 'Check call first arg to method _getModelLeafletObject');
    done();
    getModelLeafletObjSpy.restore();
  });
});