text:
"""
This module provides GSS-API / SSPI  authentication as defined in :rfc:`4462`.

.. note:: Credential delegation is not supported in server mode.

.. seealso:: :doc:`/api/kex_gss`

.. versionadded:: 1.15
"""

import struct
import os
import sys

#: A boolean constraint that indicates if GSS-API / SSPI is available.
GSS_AUTH_AVAILABLE = True

#: A tuple of the exception types used by the underlying GSSAPI implementation.
GSS_EXCEPTIONS = ()

#: :var str _API: Constraint for the used API
_API = "MIT"

try:
    import gssapi

    GSS_EXCEPTIONS = (gssapi.GSSException,)
except (ImportError, OSError):
    try:
        import pywintypes
        import sspicon
        import sspi

        _API = "SSPI"
        GSS_EXCEPTIONS = (pywintypes.error,)
    except ImportError:
        GSS_AUTH_AVAILABLE = False
        _API = None

from paramiko.common import MSG_USERAUTH_REQUEST
from paramiko.ssh_exception import SSHException

def GSSAuth(auth_method, gss_deleg_creds=True):
    """
    Provide SSH2 GSS-API / SSPI authentication.

    :param str auth_method: The name of the SSH authentication mechanism
                            (gssapi-with-mic or gss-keyex)
    :param bool gss_deleg_creds: Delegate client credentials or not.
                                 We delegate credentials by default.
    :return: Either an `._SSH_GSSAPI` (Unix) object or an
             `_SSH_SSPI` (Windows) object

    :raises: ``ImportError`` -- If no GSS-API / SSPI module could be imported.

    :see: `RFC 4462 <http://www.ietf.org/rfc/rfc4462.txt>`_
    :note: Check for the available API and return either an `._SSH_GSSAPI`
           (MIT GSSAPI) object or an `._SSH_SSPI` (MS SSPI) object. If you
           get python-gssapi working on Windows, python-gssapi
           will be used and a `._SSH_GSSAPI` object will be returned.
           If there is no supported API available,
           ``None`` will be returned.
    """
    if _API == "MIT":
        return _SSH_GSSAPI(auth_method, gss_deleg_creds)
    elif _API == "SSPI" and os.name == "nt":
        return _SSH_SSPI(auth_method, gss_deleg_creds)
    else:
        raise ImportError("Unable to import a GSS-API / SSPI module!")

class _SSH_GSSAuth(object):
    """
    Contains the shared variables and methods of `._SSH_GSSAPI` and
    `._SSH_SSPI`.
    """

    def __init__(self, auth_method, gss_deleg_creds):
        """
        :param str auth_method: The name of the SSH authentication mechanism
                                (gssapi-with-mic or gss-keyex)
        :param bool gss_deleg_creds: Delegate client credentials or not
        """
        self._auth_method = auth_method
        self._gss_deleg_creds = gss_deleg_creds
        self._gss_host = None
        self._username = None
        self._session_id = None
        self._service = "ssh-connection"
        """
        OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication,
        so we also support the krb5 mechanism only.
        """
        self._krb5_mech = "1.2.840.113554.1.2.2"

        # client mode
        self._gss_ctxt = None
        self._gss_ctxt_status = False

        # server mode
        self._gss_srv_ctxt = None
        self._gss_srv_ctxt_status = False
        self.cc_file = None

    def set_service(self, service):
        """
        This is just a setter to use a non default service.
        I added this method, because RFC 4462 doesn't specify "ssh-connection"
        as the only service value.

        :param str service: The desired SSH service
        """
        if service.find("ssh-"):
            self._service = service

    def set_username(self, username):
        """
        Setter for C{username}. If GSS-API Key Exchange is performed, the
        username is not set by C{ssh_init_sec_context}.

        :param str username: The name of the user who attempts to login
        """
        self._username = username

    def ssh_gss_oids(self, mode="client"):
        """
        This method returns a single OID, because we only support the
        Kerberos V5 mechanism.

        :param str mode: Client for client mode and server for server mode
        :return: A byte sequence containing the number of supported
                 OIDs, the length of the OID and the actual OID encoded with
                 DER
        :note: In server mode we just return the OID length and the DER encoded
               OID.
        """
        from pyasn1.type.univ import ObjectIdentifier
        from pyasn1.codec.der import encoder

        OIDs = self._make_uint32(1)
        krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech))
        OID_len = self._make_uint32(len(krb5_OID))
        if mode == "server":
            return OID_len + krb5_OID
        return OIDs + OID_len + krb5_OID

    def ssh_check_mech(self, desired_mech):
        """
        Check if the given OID is the Kerberos V5 OID (server mode).

        :param str desired_mech: The desired GSS-API mechanism of the client
        :return: ``True`` if the given OID is supported, otherwise C{False}
        """
        from pyasn1.codec.der import decoder

        mech, __ = decoder.decode(desired_mech)
        if mech.__str__() != self._krb5_mech:
            return False
        return True

    # Internals
    # -------------------------------------------------------------------------
    def _make_uint32(self, integer):
        """
        Create a 32 bit unsigned integer (The byte sequence of an integer).

        :param int integer: The integer value to convert
        :return: The byte sequence of an 32 bit integer
        """
        return struct.pack("!I", integer)

    def _ssh_build_mic(self, session_id, username, service, auth_method):
        """
        Create the SSH2 MIC filed for gssapi-with-mic.

        :param str session_id: The SSH session ID
        :param str username: The name of the user who attempts to login
        :param str service: The requested SSH service
        :param str auth_method: The requested SSH authentication mechanism
        :return: The MIC as defined in RFC 4462. The contents of the
                 MIC field are:
                 string    session_identifier,
                 byte      SSH_MSG_USERAUTH_REQUEST,
                 string    user-name,
                 string    service (ssh-connection),
                 string    authentication-method
                           (gssapi-with-mic or gssapi-keyex)
        """
        mic = self._make_uint32(len(session_id))
        mic += session_id
        mic += struct.pack("B", MSG_USERAUTH_REQUEST)
        mic += self._make_uint32(len(username))
        mic += username.encode()
        mic += self._make_uint32(len(service))
        mic += service.encode()
        mic += self._make_uint32(len(auth_method))
        mic += auth_method.encode()
        return mic

class _SSH_GSSAPI(_SSH_GSSAuth):
    """
    Implementation of the GSS-API MIT Kerberos Authentication for SSH2.

    :see: `.GSSAuth`
    """

    def __init__(self, auth_method, gss_deleg_creds):
        """
        :param str auth_method: The name of the SSH authentication mechanism
                                (gssapi-with-mic or gss-keyex)
        :param bool gss_deleg_creds: Delegate client credentials or not
        """
        _SSH_GSSAuth.__init__(self, auth_method, gss_deleg_creds)

        if self._gss_deleg_creds:
            self._gss_flags = (
                gssapi.C_PROT_READY_FLAG,
                gssapi.C_INTEG_FLAG,
                gssapi.C_MUTUAL_FLAG,
                gssapi.C_DELEG_FLAG,
            )
        else:
            self._gss_flags = (
                gssapi.C_PROT_READY_FLAG,
                gssapi.C_INTEG_FLAG,
                gssapi.C_MUTUAL_FLAG,
            )

    def ssh_init_sec_context(
        self, target, desired_mech=None, username=None, recv_token=None
    ):
        """
        Initialize a GSS-API context.

        :param str username: The name of the user who attempts to login
        :param str target: The hostname of the target to connect to
        :param str desired_mech: The negotiated GSS-API mechanism
                                 ("pseudo negotiated" mechanism, because we
                                 support just the krb5 mechanism :-))
        :param str recv_token: The GSS-API token received from the Server
        :raises:
            `.SSHException` -- Is raised if the desired mechanism of the client
            is not supported
        :return: A ``String`` if the GSS-API has returned a token or
            ``None`` if no token was returned
        """
        from pyasn1.codec.der import decoder

        self._username = username
        self._gss_host = target
        targ_name = gssapi.Name(
            "host@" + self._gss_host, gssapi.C_NT_HOSTBASED_SERVICE
        )
        ctx = gssapi.Context()
        ctx.flags = self._gss_flags
        if desired_mech is None:
            krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
        else:
            mech, __ = decoder.decode(desired_mech)
            if mech.__str__() != self._krb5_mech:
                raise SSHException("Unsupported mechanism OID.")
            else:
                krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
        token = None
        try:
            if recv_token is None:
                self._gss_ctxt = gssapi.InitContext(
                    peer_name=targ_name,
                    mech_type=krb5_mech,
                    req_flags=ctx.flags,
                )
                token = self._gss_ctxt.step(token)
            else:
                token = self._gss_ctxt.step(recv_token)
        except gssapi.GSSException:
            message = "{} Target: {}".format(sys.exc_info()[1], self._gss_host)
            raise gssapi.GSSException(message)
        self._gss_ctxt_status = self._gss_ctxt.established
        return token

    def ssh_get_mic(self, session_id, gss_kex=False):
        """
        Create the MIC token for a SSH2 message.

        :param str session_id: The SSH session ID
        :param bool gss_kex: Generate the MIC for GSS-API Key Exchange or not
        :return: gssapi-with-mic:
                 Returns the MIC token from GSS-API for the message we created
                 with ``_ssh_build_mic``.
                 gssapi-keyex:
                 Returns the MIC token from GSS-API with the SSH session ID as
                 message.
        """
        self._session_id = session_id
        if not gss_kex:
            mic_field = self._ssh_build_mic(
                self._session_id,
                self._username,
                self._service,
                self._auth_method,
            )
            mic_token = self._gss_ctxt.get_mic(mic_field)
        else:
            # for key exchange with gssapi-keyex
            mic_token = self._gss_srv_ctxt.get_mic(self._session_id)
        return mic_token

    def ssh_accept_sec_context(self, hostname, recv_token, username=None):
        """
        Accept a GSS-API context (server mode).

        :param str hostname: The servers hostname
        :param str username: The name of the user who attempts to login
        :param str recv_token: The GSS-API Token received from the server,
                               if it's not the initial call.
        :return: A ``String`` if the GSS-API has returned a token or ``None``
                if no token was returned
        """
        # hostname and username are not required for GSSAPI, but for SSPI
        self._gss_host = hostname
        self._username = username
        if self._gss_srv_ctxt is None:
            self._gss_srv_ctxt = gssapi.AcceptContext()
        token = self._gss_srv_ctxt.step(recv_token)
        self._gss_srv_ctxt_status = self._gss_srv_ctxt.established
        return token

    def ssh_check_mic(self, mic_token, session_id, username=None):
        """
        Verify the MIC token for a SSH2 message.

        :param str mic_token: The MIC token received from the client
        :param str session_id: The SSH session ID
        :param str username: The name of the user who attempts to login
        :return: None if the MIC check was successful
        :raises: ``gssapi.GSSException`` -- if the MIC check failed
        """
        self._session_id = session_id
        self._username = username
        if self._username is not None:
            # server mode
            mic_field = self._ssh_build_mic(
                self._session_id,
                self._username,
                self._service,
                self._auth_method,
            )
            self._gss_srv_ctxt.verify_mic(mic_field, mic_token)
        else:
            # for key exchange with gssapi-keyex
            # client mode
            self._gss_ctxt.verify_mic(self._session_id, mic_token)

    @property
    def credentials_delegated(self):
        """
        Checks if credentials are delegated (server mode).

        :return: ``True`` if credentials are delegated, otherwise ``False``
        """
        if self._gss_srv_ctxt.delegated_cred is not None:
            return True
        return False

    def save_client_creds(self, client_token):
        """
        Save the Client token in a file. This is used by the SSH server
        to store the client credentials if credentials are delegated
        (server mode).

        :param str client_token: The GSS-API token received form the client
        :raises:
            ``NotImplementedError`` -- Credential delegation is currently not
            supported in server mode
        """
        raise NotImplementedError

class _SSH_SSPI(_SSH_GSSAuth):
    """
    Implementation of the Microsoft SSPI Kerberos Authentication for SSH2.

    :see: `.GSSAuth`
    """

    def __init__(self, auth_method, gss_deleg_creds):
        """
        :param str auth_method: The name of the SSH authentication mechanism
                                (gssapi-with-mic or gss-keyex)
        :param bool gss_deleg_creds: Delegate client credentials or not
        """
        _SSH_GSSAuth.__init__(self, auth_method, gss_deleg_creds)

        if self._gss_deleg_creds:
            self._gss_flags = (
                sspicon.ISC_REQ_INTEGRITY
                | sspicon.ISC_REQ_MUTUAL_AUTH
                | sspicon.ISC_REQ_DELEGATE
            )
        else:
            self._gss_flags = (
                sspicon.ISC_REQ_INTEGRITY | sspicon.ISC_REQ_MUTUAL_AUTH
            )

    def ssh_init_sec_context(
        self, target, desired_mech=None, username=None, recv_token=None
    ):
        """
        Initialize a SSPI context.

        :param str username: The name of the user who attempts to login
        :param str target: The FQDN of the target to connect to
        :param str desired_mech: The negotiated SSPI mechanism
                                 ("pseudo negotiated" mechanism, because we
                                 support just the krb5 mechanism :-))
        :param recv_token: The SSPI token received from the Server
        :raises:
            `.SSHException` -- Is raised if the desired mechanism of the client
            is not supported
        :return: A ``String`` if the SSPI has returned a token or ``None`` if
                 no token was returned
        """
        from pyasn1.codec.der import decoder

        self._username = username
        self._gss_host = target
        error = 0
        targ_name = "host/" + self._gss_host
        if desired_mech is not None:
            mech, __ = decoder.decode(desired_mech)
            if mech.__str__() != self._krb5_mech:
                raise SSHException("Unsupported mechanism OID.")
        try:
            if recv_token is None:
                self._gss_ctxt = sspi.ClientAuth(
                    "Kerberos", scflags=self._gss_flags, targetspn=targ_name
                )
            error, token = self._gss_ctxt.authorize(recv_token)
            token = token[0].Buffer
        except pywintypes.error as e:
            e.strerror += ", Target: {}".format(e, self._gss_host)
            raise

        if error == 0:
            """
            if the status is GSS_COMPLETE (error = 0) the context is fully
            established an we can set _gss_ctxt_status to True.
            """
            self._gss_ctxt_status = True
            token = None
            """
            You won't get another token if the context is fully established,
            so i set token to None instead of ""
            """
        return token

    def ssh_get_mic(self, session_id, gss_kex=False):
        """
        Create the MIC token for a SSH2 message.

        :param str session_id: The SSH session ID
        :param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not
        :return: gssapi-with-mic:
                 Returns the MIC token from SSPI for the message we created
                 with ``_ssh_build_mic``.
                 gssapi-keyex:
                 Returns the MIC token from SSPI with the SSH session ID as
                 message.
        """
        self._session_id = session_id
        if not gss_kex:
            mic_field = self._ssh_build_mic(
                self._session_id,
                self._username,
                self._service,
                self._auth_method,
            )
            mic_token = self._gss_ctxt.sign(mic_field)
        else:
            # for key exchange with gssapi-keyex
            mic_token = self._gss_srv_ctxt.sign(self._session_id)
        return mic_token

    def ssh_accept_sec_context(self, hostname, username, recv_token):
        """
        Accept a SSPI context (server mode).

        :param str hostname: The servers FQDN
        :param str username: The name of the user who attempts to login
        :param str recv_token: The SSPI Token received from the server,
                               if it's not the initial call.
        :return: A ``String`` if the SSPI has returned a token or ``None`` if
                 no token was returned
        """
        self._gss_host = hostname
        self._username = username
        targ_name = "host/" + self._gss_host
        self._gss_srv_ctxt = sspi.ServerAuth("Kerberos", spn=targ_name)
        error, token = self._gss_srv_ctxt.authorize(recv_token)
        token = token[0].Buffer
        if error == 0:
            self._gss_srv_ctxt_status = True
            token = None
        return token

    def ssh_check_mic(self, mic_token, session_id, username=None):
        """
        Verify the MIC token for a SSH2 message.

        :param str mic_token: The MIC token received from the client
        :param str session_id: The SSH session ID
        :param str username: The name of the user who attempts to login
        :return: None if the MIC check was successful
        :raises: ``sspi.error`` -- if the MIC check failed
        """
        self._session_id = session_id
        self._username = username
        if username is not None:
            # server mode
            mic_field = self._ssh_build_mic(
                self._session_id,
                self._username,
                self._service,
                self._auth_method,
            )
            # Verifies data and its signature.  If verification fails, an
            # sspi.error will be raised.
            self._gss_srv_ctxt.verify(mic_field, mic_token)
        else:
            # for key exchange with gssapi-keyex
            # client mode
            # Verifies data and its signature.  If verification fails, an
            # sspi.error will be raised.
            self._gss_ctxt.verify(self._session_id, mic_token)

    @property
    def credentials_delegated(self):
        """
        Checks if credentials are delegated (server mode).

        :return: ``True`` if credentials are delegated, otherwise ``False``
        """
        return self._gss_flags & sspicon.ISC_REQ_DELEGATE and (
            self._gss_srv_ctxt_status or self._gss_flags
        )

    def save_client_creds(self, client_token):
        """
        Save the Client token in a file. This is used by the SSH server
        to store the client credentails if credentials are delegated
        (server mode).

        :param str client_token: The SSPI token received form the client
        :raises:
            ``NotImplementedError`` -- Credential delegation is currently not
            supported in server mode
        """
        raise NotImplementedError


text:
package java.security;

import java.net.URI;
import java.util.*;
import static java.security.KeyStore.*;

/**
 * Configuration data that specifies the keystores in a keystore domain.
 * A keystore domain is a collection of keystores that are presented as a
 * single logical keystore. The configuration data is used during
 * {@code KeyStore}
 * {@link KeyStore#load(KeyStore.LoadStoreParameter) load} and
 * {@link KeyStore#store(KeyStore.LoadStoreParameter) store} operations.
 *

 * The following syntax is supported for configuration data:
 *
{@code
 *     domain <domainName> [<property> ...] {
 *         keystore <keystoreName> [<property> ...] ;
 *         ...
 *     };
 *     ...
 * }

 * where {@code domainName} and {@code keystoreName} are identifiers
 * and {@code property} is a key/value pairing. The key and value are
 * separated by an 'equals' symbol and the value is enclosed in double
 * quotes. A property value may be either a printable string or a binary
 * string of colon-separated pairs of hexadecimal digits. Multi-valued
 * properties are represented as a comma-separated list of values,
 * enclosed in square brackets.
 * See {@link Arrays#toString(java.lang.Object[])}.
 *

 * To ensure that keystore entries are uniquely identified, each
 * entry's alias is prefixed by its {@code keystoreName} followed
 * by the entry name separator and each {@code keystoreName} must be
 * unique within its domain. Entry name prefixes are omitted when
 * storing a keystore.
 *

 * Properties are context-sensitive: properties that apply to
 * all the keystores in a domain are located in the domain clause,
 * and properties that apply only to a specific keystore are located
 * in that keystore's clause.
 * Unless otherwise specified, a property in a keystore clause overrides
 * a property of the same name in the domain clause. All property names
 * are case-insensitive. The following properties are supported:
 *

 *
 {@code keystoreType="<type>"}

 *
 The keystore type.

 *
 {@code keystoreURI="<url>"}

 *
 The keystore location.

 *
 {@code keystoreProviderName="<name>"}

 *
 The name of the keystore's JCE provider.

 *
 {@code keystorePasswordEnv="<environment-variable>"}

 *
 The environment variable that stores a keystore password.
 *          Alternatively, passwords may be supplied to the constructor
 *          method in a {@code Map<String, ProtectionParameter>}.

 *
 {@code entryNameSeparator="<separator>"}

 *
 The separator between a keystore name prefix and an entry name.
 *          When specified, it applies to all the entries in a domain.
 *          Its default value is a space.

 *

 *

 * For example, configuration data for a simple keystore domain
 * comprising three keystores is shown below:
 *

 *
 * domain app1 {
 *     keystore app1-truststore
 *         keystoreURI="file:///app1/etc/truststore.jks";
 *
 *     keystore system-truststore
 *         keystoreURI="${java.home}/lib/security/cacerts";
 *
 *     keystore app1-keystore
 *         keystoreType="PKCS12"
 *         keystoreURI="file:///app1/etc/keystore.p12";
 * };
 *
 *

 * @since 1.8
 */
public final class DomainLoadStoreParameter implements LoadStoreParameter {

    private final URI configuration;
    private final Map<String,ProtectionParameter> protectionParams;

    /**
     * Constructs a DomainLoadStoreParameter for a keystore domain with
     * the parameters used to protect keystore data.
     *
     * @param configuration identifier for the domain configuration data.
     *     The name of the target domain should be specified in the
     *     {@code java.net.URI} fragment component when it is necessary
     *     to distinguish between several domain configurations at the
     *     same location.
     *
     * @param protectionParams the map from keystore name to the parameter
     *     used to protect keystore data.
     *     A {@code java.util.Collections.EMPTY_MAP} should be used
     *     when protection parameters are not required or when they have
     *     been specified by properties in the domain configuration data.
     *     It is cloned to prevent subsequent modification.
     *
     * @exception NullPointerException if {@code configuration} or
     *     {@code protectionParams} is {@code null}
     */
    public DomainLoadStoreParameter(URI configuration,
        Map<String,ProtectionParameter> protectionParams) {
        if (configuration == null || protectionParams == null) {
            throw new NullPointerException("invalid null input");
        }
        this.configuration = configuration;
        this.protectionParams =
            Collections.unmodifiableMap(new HashMap<>(protectionParams));
    }

    /**
     * Gets the identifier for the domain configuration data.
     *
     * @return the identifier for the configuration data
     */
    public URI getConfiguration() {
        return configuration;
    }

    /**
     * Gets the keystore protection parameters for keystores in this
     * domain.
     *
     * @return an unmodifiable map of keystore names to protection
     *     parameters
     */
    public Map<String,ProtectionParameter> getProtectionParams() {
        return protectionParams;
    }

    /**
     * Gets the keystore protection parameters for this domain.
     * Keystore domains do not support a protection parameter.
     *
     * @return always returns {@code null}
     */
    @Override
    public KeyStore.ProtectionParameter getProtectionParameter() {
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'json'

require_relative 'redis_base'

module Collectr
  class RedisHash < RedisBase
    attr_reader :store

    def initialize(name, options={})
      @title = name
      # Use raw only when both the keys and values are strings.
      @raw = options.fetch(:raw) { false }
      @store = Redis.current
      @expires_in = options[:expires_in]
    end

    def [](key)
      deserialize @store.hget(@title, serialize(key))
    end

    def []=(key, val)
      @store.hset @title, serialize(key), serialize(val)
    end

    def fetch(key, options={})
      result = self[key]
      if result.nil?
        return nil if has_key?(key)
        if block_given?
          result = yield key
        else
          raise KeyError
        end
      end
      result
    end

    def cache(key, options={})
      result = self[key]
      if result.nil? and block_given?
        result = yield key
        self[key] = result
      else
        raise KeyError
      end
      result
    end

    def destroy
      @store.del @title
    end

    def delete(key)
      @store.hdel @title, serialize(key)
    end

    def empty?
      size == 0
    end

    def size
      @store.hlen @title
    end

    def has_key?(key)
      key? key
    end
    def key?(key)
      @store.hexists @title, serialize(key)
    end

    def keys
      @store.hkeys(@title).collect{ |key| deserialize key }
    end

    def values
      keys.collect{ |key| self[key] }
    end

    def to_hash
      hash = {}
      @store.hgetall(@title).each do |key, val|
        hash[deserialize(key)] = deserialize(val)
      end
      hash
    end

    def clear
      destroy
      # keys.each{ |key| delete key }
    end
  end
end


text:
using System;
using System.Data.SqlClient;
using Accidis.Sjoslaget.WebService.Db;
using Accidis.WebServices.Db;
using Dapper;

namespace Accidis.Sjoslaget.Test.Db
{
	static class SjoslagetDbExtensions
	{
		static SjoslagetDbExtensions()
		{
			SqlMapper.AddTypeHandler(new SubCruiseCodeTypeHandler());
		}

		static Guid _cabinTypeId;
		static Guid _cabinTypeBId;
		static Guid _cruiseId;
		static Guid _productId;

		public static Guid CabinTypeId => _cabinTypeId;
		public static Guid CabinTypeBId => _cabinTypeBId;
		public static Guid CruiseId => _cruiseId;
		public static Guid ProductId => _productId;

		// Use from [TestInitialize] or [ClassInitialize]
		public static void InitializeForTest(SjoslagetDbTestConfig config = null)
		{
			using(var db = DbUtil.Open())
				db.InitializeForTest(config);
		}

		// Use from [TestInitialize] or [ClassInitialize]
		public static void InitializeForTest(this SqlConnection db, SjoslagetDbTestConfig config = null)
		{
			if(null == config)
				config = SjoslagetDbTestConfig.Default;

			db.Execute("delete from [Cruise]");
			db.Execute("delete from [CabinType]");
			db.Execute("delete from [ProductType]");

			_cabinTypeId = db.ExecuteScalar<Guid>("insert into [CabinType] ([Name], [Description], [Capacity], [Order]) output inserted.[Id] values ('A4', '', 4, 0)");
			_cabinTypeBId = db.ExecuteScalar<Guid>("insert into [CabinType] ([SubCruise], [Name], [Description], [Capacity], [Order]) output inserted.[Id] values ('B', 'B4', '', 4, 0)");
			_cruiseId = db.ExecuteScalar<Guid>("insert into [Cruise] ([Name], [IsActive]) output inserted.[Id] values ('Test', 1)");
			_productId = db.ExecuteScalar<Guid>("insert into [ProductType] ([Name], [Order]) output inserted.[Id] values ('Produkt', 0)");

			db.Execute("insert into [CruiseCabin] ([CruiseId], [CabinTypeId], [Count], [PricePerPax]) values (@CruiseId, @CabinTypeId, @NumberOfCabins, @PricePerPax)",
				new {CruiseId = _cruiseId, CabinTypeId = _cabinTypeId, NumberOfCabins = config.NumberOfCabins, PricePerPax = config.PricePerPax});
			db.Execute("insert into [CruiseCabin] ([CruiseId], [CabinTypeId], [Count], [PricePerPax]) values (@CruiseId, @CabinTypeId, @NumberOfCabins, @PricePerPax)",
				new {CruiseId = _cruiseId, CabinTypeId = _cabinTypeBId, NumberOfCabins = config.NumberOfCabins, PricePerPax = config.PricePerPax});
			db.Execute("insert into [CruiseProduct] ([CruiseId], [ProductTypeId], [Description], [Price]) values (@CruiseId, @ProductTypeId, '', @Price)",
				new {CruiseId = _cruiseId, ProductTypeId = _productId, Price = config.ProductPrice});
		}
	}
}


text:
#ifndef ICONV_H_ /* minimal iconv.h header based on public knowledge */
#define ICONV_H_

#include <stddef.h> /* size_t */
#include <errno.h>

typedef void *iconv_t;

#ifdef __cplusplus
extern "C" {
#endif

extern iconv_t iconv_open(const char *, const char *);
extern size_t iconv(iconv_t, char **, size_t *, char **, size_t *);
extern int iconv_close(iconv_t);

#ifdef __cplusplus
}
#endif

#endif /* ICONV_H_ */


text:
module VagrantPlugins
  module BoxUpdater
    class Config < Vagrant.plugin('2', :config)
      attr_accessor :disable, :autoupdate

      def initialize
        @disable = false
        @autoupdate = false
      end

      def finalize!
        @disable = false if @disable == UNSET_VALUE
        @autoupdate = false if @autoupdate == UNSET_VALUE
      end

      def validate(machine)
        {}
      end
    end
  end
end


text:
.. Copyright 2017 Covata Limited or its affiliates

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Identity
========

An Identity is an entity (such as user, device, or another service) registered
with Delta and is comprised of a number of attributes, of which two rely on
cryptographic primitives. These are the long-lived key pairs:

- Encryption key pair - An asymmetric key pair, associated with an identity
  for the purposes of encrypting and decrypting secret encryption keys:
   - Public encryption key - The public key that functions as a key encryption
     key, to encrypt a secret encryption key. The public encryption key is
     stored in Delta as part of the identity creation process.
   - Private decryption key - The private key used to decrypt a secret
    encryption key. The private decryption key must be managed outside of Delta.

- Signing key pair - An asymmetric key pair, associated with an identity for
  the purpose of request signing and authentication:
   - Public signing verification key - The public key used to verify request
     authenticity and ownership. The public signing verification key is stored
     in Delta as part of the identity creation process and is not publicly
     visible (unlike the public encryption key).
   - Private signing key - The private key used to sign requests as required by
     Delta so that the requests can be verified. The private signing key must be
     managed outside of Delta.

.. currentmodule:: covata.delta

.. autoclass:: Identity
   :members:


text:
// This code is a -*- C++ -*- header file

#ifndef _position_h
#define _position_h

#include <iosfwd>
#include <vector>
//++ELS
class  mappedFile;
struct location;
struct mapline;
//--ELS

class position
{
public:
  static void *operator new(size_t);
  static void  operator delete(void *);

public:
  // Public Enum
  enum extractflag { START, END };

  // Constructor(s) / Destructor(s)
  position(void);
  position(unsigned int, mappedFile *);
  position(unsigned int, unsigned int, mappedFile *);
  position(const location *, extractflag);
  position(const mapline *, extractflag, const char *);
  virtual ~position(void);

  // Copy Constructor
  position(const position &);

  // Public Interface
  virtual position *next(unsigned int increment = 1) const;
  virtual position *prev(unsigned int decrement = 1) const;

  virtual int               valid() const;
  virtual int               exists() const;
  virtual void              invalidate();
  virtual void              dumpTo(ostream &) const;
  virtual int               toLocation(location *, extractflag) const;
  virtual position         *offsetWith(const position *, const position *) const;
  inline  const mappedFile *fromFile(void) const;

  // Position Comparasion Operators
  inline int operator != (const position &) const;
  inline int operator <  (const position &) const;
  inline int operator <= (const position &) const;
  inline int operator == (const position &) const;
  inline int operator >= (const position &) const;
  inline int operator >  (const position &) const;

private:

  // remove assignment operator from public scope
  inline position &operator = (const position &);

  // Private Enum
  enum datatype { BP, RC };

  // Private Statics
  static datatype initType(const location *, extractflag);
  static vector<position *> freePositions;
  static const int blockSize;

  // Private Methods
  inline int compareBP(const position &) const;
  inline int compareRC(const position &) const;
  inline int compare(const position &) const;

  int computeBP(unsigned int &) const;
  int computeRC(unsigned int &, unsigned int &) const;
  int computeBP(unsigned int, unsigned int, unsigned int &) const;
  int computeRC(unsigned int, unsigned int &, unsigned int &) const;

  int initWithLocation(const location *, extractflag);

  // Private Members
  unsigned int    bp;
  unsigned int    row;
  unsigned int    col;
  const datatype  type;
  mappedFile     *file;
};

const mappedFile *position::fromFile(void) const
{
  return file;
}

position &position::operator = (const position &other)
{
  if ( this != &other )
    {
      bp  = other.bp;
      row = other.row;
      col = other.col;
      file= other.file;
    }
  return *this;
}

int position::compareBP(const position &other) const
{
  int retval = -2; // -2 says can't tell (so don't ask... ;-) )

  if ( bp < other.bp )
    retval = -1;
  else if ( bp > other.bp )
    retval = 1;
  else
    retval = 0;

  return retval;
}

int position::compareRC(const position &other) const
{
  int retval = -2; // Can't Tell

  if ( row < other.row )
    retval = -1;
  else if ( row > other.row )
    retval = 1;
  else if ( col < other.col )
    retval = -1;
  else if ( col > other.col )
    retval = 1;
  else
    retval = 0;

  return retval;
}

int position::compare(const position &other) const
{
  int retval = -2; // Once again, can't tell

  // can only compare from same file
  if ( file == other.file )
    {
      if ( type == BP && other.type == BP )
	retval = compareBP(other);
      else if ( type == RC && other.type == RC )
	retval = compareRC(other);
      else
	{
	  if ( type == BP )
	    {
	      unsigned int otherBP;
	      other.computeBP(otherBP);
	      position p(otherBP, file);
	      retval = compareBP(p);
	    }
	  else
	    {
	      unsigned int thisBP;
	      computeBP(thisBP);
	      position p(thisBP, file);
	      retval = p.compareBP(other);
	    }
	}
    }

  return retval;
}

int position::operator < ( const position &other ) const
{
  int retval = 0;

  if (compare(other) == -1 )
    retval = 1;

  return retval;
}

int position::operator > ( const position &other ) const
{
  int retval = 0;

  if (compare(other) == 1 )
    retval = 1;

  return retval;
}

int position::operator == ( const position &other ) const
{
  int retval = 0;

  if (compare(other) == 0 )
    retval = 1;

  return retval;
}

int position::operator != ( const position &other ) const
{
  int retval = 0;

  int cmp = compare(other);
  if ( cmp == 1 || cmp == -1 )
    retval = 1;

  return retval;
}

int position::operator <= ( const position &other ) const
{
  int retval = 0;

  int cmp = compare(other);
  if ( cmp == -1 || cmp == 0 )
    retval = 1;

  return retval;
}

int position::operator >= ( const position &other ) const
{
  int retval = 0;

  int cmp = compare(other);
  if ( cmp == 0 || cmp == 1 )
    retval = 1;

  return retval;
}
#endif
// _position_h


text:
DELIMITER ENDROUTINE
CREATE PROCEDURE resume_create
(
      IN  arg_person_id  ${PERSON_ID_TYPE}
    , OUT arg_resume_id  ${ASSET_ID_TYPE}
)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN
    START TRANSACTION
    ;
    CALL nextval ('seq_asset_id', @var_resume_id)
    ;
    CALL asset_create_with_meta ('resume', CONCAT('resume', @var_resume_id), arg_resume_id)
    ;
    INSERT INTO person_resume (person_id, resume_id) VALUES
    (arg_person_id, arg_resume_id)
    ;
    COMMIT
    ;
END
ENDROUTINE
DELIMITER ;


text:
"""
A spider that generate light requests to meassure QPS troughput

usage:

    scrapy runspider qpsclient.py --loglevel=INFO --set RANDOMIZE_DOWNLOAD_DELAY=0 --set CONCURRENT_REQUESTS=50 -a qps=10 -a latency=0.3

"""

from ants.spider import Spider
from ants.http import Request

class QPSSpider(Spider):

    name = 'qps'
    benchurl = 'http://localhost:8880/'

    # Max concurrency is limited by global CONCURRENT_REQUESTS setting
    max_concurrent_requests = 8
    # Requests per second goal
    qps = None # same as: 1 / download_delay
    download_delay = None
    # time in seconds to delay server responses
    latency = None
    # number of slots to create
    slots = 1

    def __init__(self, *a, **kw):
        super(QPSSpider, self).__init__(*a, **kw)
        if self.qps is not None:
            self.qps = float(self.qps)
            self.download_delay = 1 / self.qps
        elif self.download_delay is not None:
            self.download_delay = float(self.download_delay)

    def start_requests(self):
        url = self.benchurl
        if self.latency is not None:
            url += '?latency={0}'.format(self.latency)

        slots = int(self.slots)
        if slots > 1:
            urls = [url.replace('localhost', '127.0.0.%d' % (x + 1)) for x in xrange(slots)]
        else:
            urls = [url]

        idx = 0
        while True:
            url = urls[idx % len(urls)]
            yield Request(url, dont_filter=True)
            idx += 1

    def parse(self, response):
        pass


text:
<?php

namespace Wei\Model;

use ArrayIterator;
use BadMethodCallException;
use Wei\Ret;

/**
 * Add collection functions to the model
 *
 * @internal Expected to be used only by ModelTrait
 */
trait CollTrait
{
    /**
     * Whether it contains multiple or single row data
     *
     * @var bool
     */
    protected $coll = false;

    /**
     * Create a new model collection
     *
     * @param iterable $attributes
     * @param array $options
     * @return $this|$this[]
     * @phpstan-return $this
     */
    public static function newColl(iterable $attributes = [], array $options = []): self
    {
        return static::new($attributes, ['coll' => true] + $options);
    }

    /**
     * Returns whether it contains multiple or single row data
     *
     * @return bool
     */
    public function isColl(): bool
    {
        return $this->coll;
    }

    /**
     * Clear the default attribute values and convert to a collection
     *
     * @return $this|$this[]
     * @phpstan-return $this
     */
    public function beColl(): self
    {
        $this->attributes = [];
        $this->coll = true;

        return $this;
    }

    /**
     * Merges attributes into collection and save to database, including insert, update and delete
     *
     * @param array $attributes A two-dimensional array
     * @param array $extra The extra attributes for new rows
     * @param string|null $sortColumn
     * @return $this
     */
    public function saveColl(array $attributes, array $extra = [], string $sortColumn = null): self
    {
        // 1. Uses primary key as data index
        $newAttributes = [];
        $primaryKey = $this->getPrimaryKey();
        foreach ($this->attributes as $key => $record) {
            unset($this->attributes[$key]);
            // Ignore default data
            if ($record instanceof $this) {
                $newAttributes[$record[$primaryKey]] = $record;
            }
        }
        $this->attributes = $newAttributes;

        // 2. Removes empty rows from data
        foreach ($attributes as $index => $row) {
            if (empty($row)) {
                unset($attributes[$index]);
            }
        }

        // 3. Removes missing rows
        $existIds = [];
        foreach ($attributes as $row) {
            if (is_object($row)) {
                $row = (array) $row;
            }

            if (isset($row[$primaryKey]) && null !== $row[$primaryKey]) {
                $existIds[] = $row[$primaryKey];
            }
        }
        /** @var static $record */
        foreach ($this->attributes as $key => $record) {
            if (!in_array($record[$primaryKey], $existIds, true)) {
                $record->destroy();
                unset($this->attributes[$key]);
            }
        }

        // 4. Merges existing rows or create new rows
        foreach ($attributes as $index => $row) {
            if (is_object($row)) {
                $row = (array) $row;
            }

            if ($sortColumn) {
                $row[$sortColumn] = $index;
            }
            if (isset($row[$primaryKey], $this->attributes[$row[$primaryKey]])) {
                $this->attributes[$row[$primaryKey]]->fromArray($row);
            } else {
                $this->offsetSet(null, static::new()->fromArray($extra + $row));
            }
        }
        $this->attributes = array_values($this->attributes);

        // 5. Save and return
        return $this->save();
    }

    /**
     * Set field value for every record in the collection
     *
     * @param string $name
     * @param mixed $value
     * @return $this
     */
    public function setAll(string $name, $value): self
    {
        foreach ($this->attributes as $i => $item) {
            $this->attributes[$i][$name] = $value;
        }
        return $this;
    }

    /**
     * Return the value of field from every record in the collection
     *
     * @param string $name
     * @return array
     */
    public function getAll(string $name): array
    {
        $items = [];
        foreach ($this->attributes as $item) {
            $items[] = $item[$name];
        }
        return $items;
    }

    /**
     * Filters elements of the collection using a callback function
     *
     * @param callable $fn
     * @return $this|$this[]
     * @phpstan-return $this
     */
    public function filter(callable $fn)
    {
        $this->ensureColl();

        $attributes = array_filter($this->attributes, $fn);
        return static::newColl($attributes)->setOption([
            'new' => $this->new,
        ]);
    }

    /**
     * Returns the record number in collection
     *
     * @return int
     */
    public function count(): int
    {
        return count($this->attributes);
    }

    /**
     * Retrieve an array iterator
     *
     * @return ArrayIterator
     */
    public function getIterator(): ArrayIterator
    {
        return new ArrayIterator($this->attributes);
    }

    /**
     * Check if the key name exists in the collection
     *
     * @param string|int $name
     * @return bool
     */
    protected function hasColl($name): bool
    {
        return array_key_exists($name, $this->attributes);
    }

    /**
     * Set the value of the specified key name in the collection
     *
     * @param string|int|null $name
     * @param self $value
     * @return $this
     */
    protected function setCollValue($name, self $value): self
    {
        // Support $coll[] = $value;
        if (null === $name) {
            $this->attributes[] = $value;
        } else {
            $this->attributes[$name] = $value;
        }
        return $this;
    }

    /**
     * Get the value of the specified key name in the collection
     *
     * @param string|int $name
     * @return self
     */
    protected function &getCollValue($name): self
    {
        return $this->attributes[$name];
    }

    /**
     * Apply the specified method to the attribute of the collection
     *
     * @param string $method
     * @param array $args
     * @return array
     * @internal
     */
    protected function mapColl(string $method, array $args = []): array
    {
        $results = [];
        foreach ($this->attributes as $key => $model) {
            $results[$key] = $model->{$method}(...$args);
        }
        return $results;
    }

    /**
     * Throw an exception if the current object is not a collection
     *
     * @internal
     */
    protected function ensureColl(): void
    {
        if (!$this->coll) {
            $traces = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 2);
            throw new BadMethodCallException(sprintf(
                'Method "%s" can be called when the object is a collection',
                $traces[1]['function']
            ));
        }
    }

    /**
     * Convert the collection to list data
     *
     * @param array $merge
     * @return Ret
     * @internal
     */
    protected function collToRet(array $merge = []): Ret
    {
        $this->ensureColl();
        return $this->suc(array_merge([
            'data' => $this,
            'page' => $this->getQueryPart('page'),
            'limit' => $this->getQueryPart('limit'),
            'total' => $this->cnt(),
        ], $merge));
    }
}


text:
layout: post
title:  "Why is my d3.js chart not displaying my data correctly?"
date:   2017-03-13 00:07:44 -0400
---

FYI: This is for folks who are already familar with d3.js but have encounterred the fustrating problem with there data plotting incorrectly.
After wokring on web applications for some time. I recently had the time to venture into data visualization. I've always wanted to explore this realm given my background in Electronic Design and Multimedia. As a designer we learn to display information that is beautiful, minimal and easy to understand but not interactive by a user. That part is left up to the developers. Now that I am a developer I am able to turn my designs into an interactive playground that is both dynamic and interactive. Something that could not be done only with design.

My project was to make an interactive weather chart where the user could hover over dots that marked every change in temperature throughout the 7 day week startinng with "today". There are several apis and frameworks one can use such as : HTML5 svg and canvas for instance. Given it's popularity amongst tech companys and developers I decided to go with d3.js.

According to the website D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3's emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework. What this means is that it allows you to write code that is no different from writting code without the framework. It's the same tools (svg, canvas, css) that we would normally used to draw graphics in a website that is used in d3.js.

At first the docs can seem intimidating but once you get to the part that you need applying the code seems simple. In my case I needed to draw a multichart graph so I watched a lynda.com [tutorial](https://www.lynda.com/D3js-tutorials/Data-Visualization-D3js/162449-2.html/) on d3.js. I also read some of the docs on d3.js [github-wiki](https://github.com/d3/d3/wiki) page.

It's simple, you have to download the js file for d3. To organize my files I used bower.js and saved the framework iin my project. The following are instructions for how to use bower.js [Here](https://github.com/bower/bower)

Enter the necessary js links in your index.html page.

To area for the chart to actually show up in the DOM you have to include this script in a js file and link it to your index.html file as well.

```
d3.select("element")
```

The important part is the d3.select. This selects any element you put on your page such as a div for instance.

Now to the meat of the story. Since I created a multiline chart I needed x and y coordinates to plot the line.
In the DOM the points are plotted from left to right for the x-axis and top to bottom for the y-axis.

So to draw a straight line you would write x = 0 y = 0 for the starting point, and for the ending point x = 100 y = -100.
Easy enough right?

I had to plot a total of 0 - 100 on the y-axis and 1 - 7 (days) on the x-axis
It turns out whenever you are plotting the lines on the y-axis you with positive values you must minus the positve values from 100. This is the only way  the values will show up as positive values. Because remember the y-axis goes down, so by default it will plot the points downwalrd from 0 to -100 and not updwards from 0 to 100.

So if the values were 10, 20, 44, 55, I would have to minus 100 from 10 = 90, 100 - 20 = 80, 100 - 44 = 56, 100 - 55 = 45 to get teh correct values so that the values do not appear inverted. So 10 would plot on the grpah 90 pixels down which is equal to 10 pixels upward. Get it? That's positive 10 on the chart!

Here is the part of the code where I minus the values (High and Lows) from 100.

```
  var lows = weatherData.map((e,i)=>{  return 100 - Number(e.low);})
        var highs = weatherData.map((e,i)=>{  return 100 - Number(e.high);})
```

Then poltted them onto the graph with the d3.js function for a line d3.line/

```
 line = d3.line()
            .x(function(d, i){;return d.x*60;})
            .y(function(d, i){return d.y*5;})
            .curve(d3.curveCardinal);

       //  Create d3 line generator
       //  highs
       lineTwo = d3.line()
            .x(function(d, i){return d.x*60;})
            .y(function(d, i){return d.y*5;})
            .curve(d3.curveCardinal);
```

You can see my chart live [here](https://rocky-garden-18908.herokuapp.com/)


text:
        <title>Security Alerts</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="shortcut icon" href="">
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/c3.min.css"/>
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
        <link rel="stylesheet" type="text/css" href="css/MarkerCluster.css" />
        <link rel="stylesheet" type="text/css" href="css/MarkerCluster.Default.css" />
        <link rel="stylesheet" type="text/css" href="css/site.css" />

Security Alerts

Security Alerts by the IFRC Security Unit. Use the map to zoom and pan to the area of interest. Select a pin on the map for more information. Or click on an item in the list of alert on the right of the map. Use the slider to go back in time.

 Security Incidents in last 30 days

Use the slider to look at past events.


text:
Basic Pipeline for Exome Variant Analysis

More information to come ;-)


text:
package com.keithpower.gekmlib;

public class Units
{
    public static final String FRACTION = "fraction";
    public static final String PIXELS = "pixels";
    public static final String INSET_PIXELS = "insetPixels";
}


text:
require 'configliere'
require 'json'

Settings.use :commandline
Settings.use :config_block
Settings.define :es_index, default: nil
Settings.define :fields, default: nil
Settings.define :one_index, default: false, flag: 'o'
Settings.define :composite_key, default: nil
Settings.define :es_type
Settings.finally do |settings|
  settings.es_index ||= settings.one_index ? [settings.es_type, "cnt"].join : 'ad_activity'
end
Settings.resolve!

puts "using es index #{Settings.es_index} and type #{Settings.es_type}"

index = Settings.es_index
type = Settings.es_type

response = `curl localhost:9200/#{Settings.es_index}/_mapping/`
puts JSON.parse(response)["#{index}"]["#{type}"]#["properties"]
fields = JSON.parse(response)["#{index}"]["#{type}"]["properties"].keys#.select{|x| x.end_with?("_id")}
#fields += %w[metric feature]# browser_ua]
#fields = JSON.parse(response)["#{type}_legacy"][type]["properties"].keys.select{|x| x.end_with?("_id")}

puts "got fields #{Settings.fields || fields}"

# site_count => site_composite
# placement_count => pl_composite
# flight_count => metric_feature

composite_key = case Settings.es_type
                when "site_count" then "site_composite"
                when "placement_count" then "pl_composite"
                when "flight_count" then "metric_feature"
                else nil
                end

doc = {
  "query"=> {
    "match_all"=> {}
  },
  "facets"=> {
    # "ignz"=> {
    #   "statistical"=> {
    #     "field" => "cnt"
    #   }
    # },
    "igna"=> {
      "date_histogram"=> {
        "field"=> "tb_h",
	"interval" => "day"
      }
    },
    "ignb"=> {
      "terms"=> {
        "fields"=> [Settings.fields || fields].flatten
      }
    },
  }
}

fields.each do |field|
  doc["facets"]["ign_#{field}"] = {
    "terms_stats" => {
      "key_field" => field,
      "value_field" => "cnt"
    }
  }
end

if not composite_key.nil?
  doc["facets"]["ignc"] = {
    "terms_stats" => {
      "key_field" => Settings.composite_key || composite_key,
      "value_field" => "cnt"
    }
  }
end

puts "about to query with " + doc.to_s

results = `curl localhost:9200/#{Settings.es_index}/#{Settings.es_type}/_search/?pretty=true -d '#{JSON.generate(doc)}'`
term_hash = {}
resultsLineArray = results.split( /\r?\n/ )
copy_resultsLineArray = resultsLineArray - []
copy_resultsLineArray.each_with_index do |line, index|
  if line.include?("\"term\" : \"")
	term_hash[line] = index
  end
end
puts `curl localhost:9200/#{Settings.es_index}/#{Settings.es_type}/_search/?pretty=true -d '#{JSON.generate(doc)}'`
puts "from command: \n curl localhost:9200/#{Settings.es_index}/#{Settings.es_type}/_search/ -d '#{JSON.generate(doc)}'"
puts "number of terms: #{term_hash.keys.size()}"


text:
<?xml version="1.0" encoding="utf-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
        id="cordova-plugin-fb-accountkit"
        version="0.1.0-beta">

  <name>Cordova Fb Account Kit</name>
  <description>Cordova plugin to integrate Facebook Account Kit, which allows passwordless SMS/email authentication</description>
  <license>MIT</license>

  <engines>
    <engine name="cordova-android" version=">=3.5.0" />
  </engines>

  <preference name="FB_APP_NAME" />
  <preference name="FB_APP_ID" />
  <preference name="FB_CLIENT_TOKEN" />

  <asset src="www/fb-account-kit.js" target="js/fb-account-kit.js"/>

  <js-module src="www/fb-account-kit.js" name="fbAccountKit">
    <clobbers target="fbAccountKit" />
  </js-module>

  <platform name="android">

    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="FbAccountKit">
        <param name="android-package" value="in.confest.fbaccountkit.FbAccountKit"/>
      </feature>
      <access origin="https://m.facebook.com" />
      <access origin="https://graph.facebook.com" />
      <access origin="https://api.facebook.com" />
      <access origin="https://*.fbcdn.net" />
      <preference name="android-minSdkVersion" value="15" />
    </config-file>

    <source-file src="src/android/fbaccountkit.xml" target-dir="res/values" />
    <config-file target="res/values/fbaccountkit.xml" parent="/*">
      <string name="fb_app_name">$FB_APP_NAME</string>
      <string name="fb_app_id">$FB_APP_ID</string>
      <string name="account_kit_token">$FB_CLIENT_TOKEN</string>
    </config-file>

    <config-file target="AndroidManifest.xml" parent="application">
      <uses-permission android:name="android.permission.RECEIVE_SMS" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      <uses-permission android:name="android.permission.GET_ACCOUNTS" />

      <activity
              android:name="com.facebook.accountkit.ui.AccountKitActivity" >
      </activity>

      <meta-data android:name="com.facebook.accountkit.ApplicationName" android:value="@string/fb_app_name" />
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/fb_app_id" />
      <meta-data android:name="com.facebook.accountkit.ClientToken" android:value="@string/account_kit_token" />
      <meta-data android:name="com.facebook.accountkit.FacebookAppEventsEnabled" android:value="false"/>

    </config-file>

    <framework src="com.facebook.android:account-kit-sdk:4.16.1"/>
    <framework src="com.android.support:appcompat-v7:24.2.1"/>
    <framework src="com.google.code.gson:gson:2.7"/>

    <source-file src="src/android/FbAccountKit.java" target-dir="src/in/confest/fbaccountkit/"/>
  </platform>

</plugin>


text:
class Fiddle {
    public static void main(String[] args) {
        System.out.println("template compiled!");
    }
}


text:
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
import { test as qunitTest } from 'qunit';

export default function test(testName, callback) {
  function wrapper(assert) {
    var context = getContext();

    var result = callback.call(context, assert);

    function failTestOnPromiseRejection(reason) {
      var message;
      if (reason instanceof Error) {
        message = reason.stack;
        if (reason.message && message.indexOf(reason.message) < 0) {
          // PhantomJS has a `stack` that does not contain the actual
          // exception message.
          message = Ember.inspect(reason) + "\n" + message;
        }
      } else {
        message = Ember.inspect(reason);
      }
      ok(false, message);
    }

    Ember.run(function(){
      QUnit.stop();
      Ember.RSVP.Promise.resolve(result)['catch'](failTestOnPromiseRejection)['finally'](QUnit.start);
    });
  }

  qunitTest(testName, wrapper);
}


text:
package org.apache.isis.viewer.wicket.ui.components.entity.selector.links;

import org.apache.wicket.Component;
import org.apache.wicket.model.IModel;

import org.apache.isis.applib.layout.grid.bootstrap3.BS3Grid;
import org.apache.isis.applib.layout.component.Grid;
import org.apache.isis.core.metamodel.facets.object.grid.GridFacet;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.viewer.wicket.model.models.EntityModel;
import org.apache.isis.viewer.wicket.ui.ComponentFactory;
import org.apache.isis.viewer.wicket.ui.ComponentType;
import org.apache.isis.viewer.wicket.ui.components.entity.EntityComponentFactoryAbstract;
import org.apache.isis.viewer.wicket.ui.components.layout.bs3.BS3GridPanel;

/**
 * {@link ComponentFactory} for {@link EntityLinksSelectorPanel}.
 */
public class EntityLinksSelectorPanelFactory extends EntityComponentFactoryAbstract {

    private static final long serialVersionUID = 1L;

    public EntityLinksSelectorPanelFactory() {
        super(ComponentType.ENTITY, EntityLinksSelectorPanel.class);
    }

    @Override
    public Component createComponent(final String id, final IModel<?> model) {
        final EntityModel entityModel = (EntityModel) model;

        final ObjectSpecification specification = entityModel.getTypeOfSpecification();
        final GridFacet facet = specification.getFacet(GridFacet.class);

        final Grid grid = facet.getGrid();
        if (grid != null) {
            if(grid instanceof BS3Grid) {
                final BS3Grid bs3Grid = (BS3Grid) grid;
                return new BS3GridPanel(id, entityModel, bs3Grid);
            }
        }
        return new EntityLinksSelectorPanel(id, entityModel, this);
    }
}


text:
from django import forms
from django.forms import Media
from django.utils.functional import cached_property
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

from geoposition.forms import GeopositionWidget

# Standard zoom ends at 20, but some satellite image pushes it even further.
# See: https://developers.google.com/maps/documentation/javascript/maxzoom
# and http://www.wolfpil.de/v3/deep-zoom.html for examples
MAX_MAP_ZOOM = 23  # Deep zoom

class ZoomRangeWidget(forms.TextInput):
    """
    Range widget
    """
    input_type = 'range'
    min_value = 0
    max_value = MAX_MAP_ZOOM

    def build_attrs(self, *args, **kwargs):
        # Signature changed significantly in Django 1.11,
        # can only edit return value now for reliable compatibility.
        attrs = super().build_attrs(*args, **kwargs)
        attrs['min'] = self.min_value
        attrs['max'] = self.max_value
        attrs['onchange'] = 'this.nextSibling.innerHTML = this.value;'
        return attrs

    def render(self, name, value, *args, **kwargs):
        input = super().render(name, value, *args, **kwargs)
        return format_html('{0}{1}', input, value)

    class Media:
        css = {'all': ('fluentcms_googlemaps/admin/zoomrangewidget.css',)}

class InlineGeopositionWidget(GeopositionWidget):
    """
    Hide the Google Maps inline for now.
    """

    def format_output(self, rendered_widgets):
        return (
            u'
'
            u' {0}: {1}
'
            u' {2}: {3}'
            u'
'
        ).format(
            _("latitude"), rendered_widgets[0],
            _("longitude"), rendered_widgets[1],
        )

    class Media:
        css = {'all': ('fluentcms_googlemaps/admin/geopositionwidget.css',)}
        js = ()

    @cached_property
    def media(self):
        # Avoid the base class media, no need to load google maps in the admin page.
        return Media(self.Media)


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

using System;
using System.Diagnostics.Contracts;

namespace MsgPack.Serialization.AbstractSerializers
{
	partial class SerializerBuilder<TContext, TConstruct, TObject>
	{
		private void BuildEnumSerializer( TContext context )
		{
			Contract.Assert( typeof( TObject ).GetIsEnum() );
			var underlyingType = Enum.GetUnderlyingType( typeof( TObject ) );
			Contract.Assert( underlyingType != null, "Underlying type of " + typeof( TObject ) + " is null." );

			this.BuildPackUnderlyingValueTo( context, underlyingType );
			this.BuildUnpackFromUnderlyingValue( context, underlyingType );
		}

		private void BuildPackUnderlyingValueTo( TContext context, Type underlyingType )
		{
			this.EmitMethodPrologue(
				context,
				EnumSerializerMethod.PackUnderlyingValueTo
			);

			TConstruct construct = null;
			try
			{
				construct =
					this.EmitInvokeVoidMethod(
						context,
						this.ReferArgument( context, typeof( Packer ), "packer", 1 ),
						typeof( Packer ).GetMethod( "Pack", new[] { underlyingType } ),
						this.EmitEnumToUnderlyingCastExpression( context, underlyingType, this.ReferArgument( context, typeof( TObject ), "enumValue", 2 ) )
					);
			}
			finally
			{
				this.EmitMethodEpilogue(
					context,
					EnumSerializerMethod.PackUnderlyingValueTo,
					construct
				);
			}
		}

		private void BuildUnpackFromUnderlyingValue( TContext context, Type underlyingType )
		{
			this.EmitMethodPrologue(
				context,
				EnumSerializerMethod.UnpackFromUnderlyingValue
			);

			TConstruct construct = null;
			try
			{
				construct =
					this.EmitRetrunStatement(
						context,
						this.EmitEnumFromUnderlyingCastExpression(
							context,
							typeof( TObject ),
							this.EmitInvokeMethodExpression(
								context,
								this.ReferArgument( context, typeof( MessagePackObject ), "messagePackObject", 1 ),
								typeof( MessagePackObject ).GetMethod( "As" + underlyingType.Name, ReflectionAbstractions.EmptyTypes )
							)
						)
					);
			}
			finally
			{
				this.EmitMethodEpilogue(
					context,
					EnumSerializerMethod.UnpackFromUnderlyingValue,
					construct
				);
			}
		}

		protected abstract TConstruct EmitEnumToUnderlyingCastExpression( TContext context, Type underlyingType, TConstruct enumValue );

		protected abstract TConstruct EmitEnumFromUnderlyingCastExpression( TContext context, Type enumType, TConstruct underlyingValue );
	}
}


text:
package net.runelite.client.plugins.timestamp;

import java.awt.Color;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;

@ConfigGroup("timestamp")
public interface TimestampConfig extends Config
{
	@ConfigItem(
		keyName = "opaqueTimestamp",
		name = "Timestamps (opaque)",
		position = 1,
		description = "Colour of Timestamps from the Timestamps plugin (opaque)"
	)
	Color opaqueTimestamp();

	@ConfigItem(
		keyName = "transparentTimestamp",
		name = "Timestamps (transparent)",
		position = 2,
		description = "Colour of Timestamps from the Timestamps plugin (transparent)"
	)
	Color transparentTimestamp();

	@ConfigItem(
		keyName = "format",
		name = "Timestamp Format",
		position = 3,
		description = "Customize your timestamp format by using the following characters
" +
			"'yyyy' : year
" +
			"'MM' : month
" +
			"'dd' : day
" +
			"'HH' : hour in 24 hour format
" +
			"'hh' : hour in 12 hour format
" +
			"'mm' : minute
" +
			"'ss' : second
" +
			"'a'  : AM/PM"
	)
	default String timestampFormat()
	{
		return "[HH:mm]";
	}
}


text:
<?php

namespace PommProject\Foundation\Converter;

/**
 * PgTsRange
 *
 * Range for timestamps.
 *
 * @package Foundation
 * @copyright 2014 Grégoire HUBERT
 * @author Grégoire HUBERT
 * @license X11 {@link http://opensource.org/licenses/mit-license.php}
 *
 *
 * @see PgNumRange
 */
class PgTsRange extends PgNumRange
{
    public function getTypeClassName()
    {
        return '\PommProject\Foundation\Converter\Type\TsRange';
    }
}


text:
using namespace csapex;

RewiringDialog::RewiringDialog(NodeFacade* node, CsApexViewCore& view_core, QWidget* parent, Qt::WindowFlags f)
  : QDialog(parent, f)
  , view_core_(view_core)
  ,

  view_core_old_(std::make_shared<CsApexViewCoreImplementation>(view_core_, view_core_.getExceptionHandler()))
  , view_core_new_(std::make_shared<CsApexViewCoreImplementation>(view_core_, view_core_.getExceptionHandler()))
  , node_facade_(node)
{
    root_uuid_provider_ = std::make_shared<UUIDProvider>();
}

RewiringDialog::~RewiringDialog()
{
}

std::string RewiringDialog::getType() const
{
    return type_new_;
}

std::vector<ConnectionDescription> RewiringDialog::getConnections(const UUID& new_node_uuid)
{
    for (const SlotPtr& slot_new : nf_new->getNodeHandle()->getSlots()) {
        for (const ConnectionPtr& connection : slot_new->getConnections()) {
            UUID to_uuid = UUIDProvider::makeDerivedUUID_forced(new_node_uuid, slot_new->getUUID().id().getFullName());
            connections_.push_back(ConnectionDescription(new_target_uuid_to_old_uuid_.at(connection->from()->getUUID()), to_uuid, slot_new->getType(), connection->getSeq(), connection->id(), connection->isActive(),
                                                         connection->getFulcrumsCopy()));
        }
    }
    for (const InputPtr& input_new : nf_new->getNodeHandle()->getExternalInputs()) {
        for (const ConnectionPtr& connection : input_new->getConnections()) {
            UUID to_uuid = UUIDProvider::makeDerivedUUID_forced(new_node_uuid, input_new->getUUID().id().getFullName());
            connections_.push_back(ConnectionDescription(new_target_uuid_to_old_uuid_.at(connection->from()->getUUID()), to_uuid, input_new->getType(), connection->getSeq(), connection->id(), connection->isActive(),
                                                         connection->getFulcrumsCopy()));
        }
    }

    for (const EventPtr& event_new : nf_new->getNodeHandle()->getEvents()) {
        for (const ConnectionPtr& connection : event_new->getConnections()) {
            UUID from_uuid = UUIDProvider::makeDerivedUUID_forced(new_node_uuid, event_new->getUUID().id().getFullName());
            connections_.push_back(ConnectionDescription(from_uuid, new_target_uuid_to_old_uuid_.at(connection->to()->getUUID()), event_new->getType(), connection->getSeq(), connection->id(), connection->isActive(),
                                                         connection->getFulcrumsCopy()));
        }
    }
    for (const OutputPtr& output_new : nf_new->getNodeHandle()->getExternalOutputs()) {
        for (const ConnectionPtr& connection : output_new->getConnections()) {
            UUID from_uuid = UUIDProvider::makeDerivedUUID_forced(new_node_uuid, output_new->getUUID().id().getFullName());
            connections_.push_back(ConnectionDescription(from_uuid, new_target_uuid_to_old_uuid_.at(connection->to()->getUUID()), output_new->getType(), connection->getSeq(), connection->id(), connection->isActive(),
                                                         connection->getFulcrumsCopy()));
        }
    }

    return connections_;
}

void RewiringDialog::makeUI(const QString& stylesheet)
{
    BoxDialog diag("Please enter the new node type.", *view_core_.getNodeFactory(), view_core_.getSnippetFactory());
    diag.setWindowTitle("Select new node type.");

    int r = diag.exec();

    if (!r) {
        return;
    }

    type_new_ = diag.getName();

    createGraphs(type_new_);
    createConnections();

    createUI(stylesheet);
}

void RewiringDialog::createGraphs(const std::string& type)
{
    NodeFactoryImplementationPtr nfl = std::dynamic_pointer_cast<NodeFactoryImplementation>(view_core_.getNodeFactory());
    if (!nfl) {
        throw std::runtime_error("currently not supported");
    }
    NodeFactoryImplementation& node_factory = *nfl;

    // old graph
    graph_facade_old_ = view_core_old_->getLocalRoot();
    apex_assert_hard(graph_facade_old_);
    NodeFacadeImplementationPtr gnf_old = std::dynamic_pointer_cast<NodeFacadeImplementation>(graph_facade_old_->getNodeFacade());
    apex_assert_hard(gnf_old);
    graph_node_old = std::dynamic_pointer_cast<SubgraphNode>(gnf_old->getNodeHandle()->getNode().lock());
    apex_assert_hard(graph_node_old);
    graph_old = graph_facade_old_->getLocalGraph();
    apex_assert_hard(graph_old);

    nf_old = node_factory.makeNode(node_facade_->getType(), node_facade_->getUUID(), graph_old);
    nf_old->setNodeState(node_facade_->getNodeStateCopy());
    graph_old->addNode(nf_old);

    // new graph
    graph_facade_new_ = view_core_new_->getLocalRoot();
    apex_assert_hard(graph_facade_new_);
    NodeFacadeImplementationPtr gnf_new = std::dynamic_pointer_cast<NodeFacadeImplementation>(graph_facade_new_->getNodeFacade());
    apex_assert_hard(gnf_new);
    graph_node_new = std::dynamic_pointer_cast<SubgraphNode>(gnf_new->getNodeHandle()->getNode().lock());
    apex_assert_hard(graph_node_new);
    graph_new = graph_facade_new_->getLocalGraph();
    apex_assert_hard(graph_new);

    nf_new = node_factory.makeNode(type, graph_new->generateUUID(type), graph_new);
    graph_new->addNode(nf_new);
}

void RewiringDialog::createConnections()
{
    for (const ConnectorDescription& slot_original : node_facade_->getSlots()) {
        for (const ConnectorDescription::Target& target : slot_original.targets) {
            SlotPtr slot_old = nf_old->getNodeHandle()->getSlot(slot_original.id);
            apex_assert_hard(slot_old);
            updateConnection(slot_old, slot_original, target.auuid, target.active);
        }
    }
    for (const ConnectorDescription& input_original : node_facade_->getExternalInputs()) {
        for (const ConnectorDescription::Target& target : input_original.targets) {
            InputPtr input_old = nf_old->getNodeHandle()->getInput(input_original.id);
            apex_assert_hard(input_old);
            updateConnection(input_old, input_original, target.auuid, target.active);
        }
    }

    for (const ConnectorDescription& event_original : node_facade_->getEvents()) {
        for (const ConnectorDescription::Target& target : event_original.targets) {
            EventPtr event_old = nf_old->getNodeHandle()->getEvent(event_original.id);
            apex_assert_hard(event_old);
            updateConnection(event_old, event_original, target.auuid, target.active);
        }
    }
    for (const ConnectorDescription& output_original : node_facade_->getExternalOutputs()) {
        for (const ConnectorDescription::Target& target : output_original.targets) {
            OutputPtr output_old = nf_old->getNodeHandle()->getOutput(output_original.id);
            updateConnection(output_old, output_original, target.auuid, target.active);
        }
    }
}

void RewiringDialog::createUI(const QString& stylesheet)
{
    setStyleSheet(stylesheet);
    setWindowIcon(QIcon(":/pencil.png"));
    setWindowTitle(QString("Change Node to ") + QString::fromStdString(type_new_));

    setFocusPolicy(Qt::StrongFocus);
    setModal(true);

    QVBoxLayout* layout = new QVBoxLayout;
    setLayout(layout);

    layout->addWidget(new QLabel("Current node:"));

    GraphView* view_old = new GraphView(graph_facade_old_, *view_core_old_);
    view_old->overwriteStyleSheet(stylesheet);
    view_old->setMinimumSize(500, 350);
    view_old->setInteractive(false);
    layout->addWidget(view_old);

    layout->addWidget(new QLabel("New node:"));

    GraphView* view_new = new GraphView(graph_facade_new_, *view_core_new_);
    view_new->overwriteStyleSheet(stylesheet);
    view_new->setMinimumSize(500, 350);
    layout->addWidget(view_new);

    QDialogButtonBox* buttons = new QDialogButtonBox;
    buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    layout->addWidget(buttons);

    QObject::connect(buttons, SIGNAL(accepted()), this, SLOT(finish()));
    QObject::connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
}

void RewiringDialog::updateConnection(InputPtr input, const ConnectorDescription& connector, const AUUID& target, bool active)
{
    UUID original_uuid = target;
    UUID uuid_old;
    if (uuid_cache_.find(original_uuid) != uuid_cache_.end()) {
        uuid_old = uuid_cache_.at(original_uuid);
    } else {
        uuid_old = graph_old->generateUUID(original_uuid.id().type());
        uuid_cache_[original_uuid] = uuid_old;
        new_target_uuid_to_old_uuid_[uuid_old] = original_uuid;
    }

    UUID uuid_new = UUID::NONE;
    OutputPtr source_old = graph_old->findTypedConnectorNoThrow<Output>(uuid_old);
    OutputPtr source_new = graph_new->findTypedConnectorNoThrow<Output>(uuid_old);
    if (target.type() == "event" || target.type() == "relayevent") {
        if (!source_old) {
            source_old = graph_node_old->createInternalEvent(connector.token_type, uuid_old, connector.label);
        }
        if (!source_new) {
            source_new = graph_node_new->createInternalEvent(connector.token_type, uuid_old, connector.label);
        }
    } else {
        if (!source_old) {
            source_old = graph_node_old->createInternalOutput(connector.token_type, uuid_old, connector.label);
        }
        if (!source_new) {
            source_new = graph_node_new->createInternalOutput(connector.token_type, uuid_old, connector.label);
        }
    }

    graph_old->addConnection(DirectConnection::connect(source_old, input));

    uuid_new = UUIDProvider::makeDerivedUUID_forced(nf_new->getUUID(), input->getUUID().id().getFullName());

    ConnectionPtr c;
    if (InputPtr in_new = nf_new->getNodeHandle()->getInput(uuid_new)) {
        if (!Connection::isCompatibleWith(source_new.get(), in_new.get())) {
            return;
        }
        c = DirectConnection::connect(source_new, in_new);
    } else if (SlotPtr slot_new = nf_new->getNodeHandle()->getSlot(uuid_new)) {
        if (!Connection::isCompatibleWith(source_new.get(), slot_new.get())) {
            return;
        }
        c = DirectConnection::connect(source_new, slot_new);
    }
    if (c) {
        c->setActive(active);
        graph_new->addConnection(c);
    }
}

void RewiringDialog::updateConnection(OutputPtr output, const ConnectorDescription& connector, const AUUID& target, bool active)
{
    UUID uuid_old;
    UUID original_uuid = target;
    if (uuid_cache_.find(original_uuid) != uuid_cache_.end()) {
        uuid_old = uuid_cache_.at(original_uuid);
    } else {
        uuid_old = graph_old->generateUUID(original_uuid.id().type());
        uuid_cache_[original_uuid] = uuid_old;
        new_target_uuid_to_old_uuid_[uuid_old] = original_uuid;
    }

    UUID uuid_new = UUID::NONE;
    InputPtr sink_old = graph_old->findTypedConnectorNoThrow<Input>(uuid_old);
    InputPtr sink_new = graph_new->findTypedConnectorNoThrow<Input>(uuid_old);
    if (target.type() == "slot" || target.type() == "relayslot") {
        if (!sink_old) {
            sink_old = graph_node_old->createInternalSlot(connector.token_type, uuid_old, connector.label, [](const TokenPtr&) {});
        }
        if (!sink_new) {
            sink_new = graph_node_new->createInternalSlot(connector.token_type, uuid_old, connector.label, [](const TokenPtr&) {});
        }
    } else {
        if (!sink_old) {
            sink_old = graph_node_old->createInternalInput(connector.token_type, uuid_old, connector.label, connector.optional);
        }
        if (!sink_new) {
            sink_new = graph_node_new->createInternalInput(connector.token_type, uuid_old, connector.label, connector.optional);
        }
    }

    graph_old->addConnection(DirectConnection::connect(output, sink_old));

    uuid_new = UUIDProvider::makeDerivedUUID_forced(nf_new->getUUID(), output->getUUID().id().getFullName());

    ConnectionPtr c;
    if (OutputPtr out_new = nf_new->getNodeHandle()->getOutput(uuid_new)) {
        c = DirectConnection::connect(out_new, sink_new);
    } else if (EventPtr event_new = nf_new->getNodeHandle()->getEvent(uuid_new)) {
        c = DirectConnection::connect(event_new, sink_new);
    }

    if (c) {
        c->setActive(active);
        graph_new->addConnection(c);
    }
}

void RewiringDialog::finish()
{
    Q_EMIT accept();
}

/// MOC
#include "../../../include/csapex/view/widgets/moc_rewiring_dialog.cpp"


text:
@interface DownloadOperation () <NSURLConnectionDataDelegate, NSURLConnectionDelegate>

@property (nonatomic, readwrite, getter = isExecuting) BOOL executing;
@property (nonatomic, readwrite, getter = isFinished)  BOOL finished;

@property (nonatomic, strong) NSOutputStream *outputStream;
@property (nonatomic, weak)   NSURLConnection *connection;
@property (nonatomic, strong) NSString *tempPath;
@property (nonatomic, strong) NSError *error;

@end

@implementation DownloadOperation

@synthesize executing = _executing;
@synthesize finished  = _finished;

- (id)initWithURL:(NSURL *)url path:(NSString *)path {
    self = [super init];
    if (self) {
        _url = url;
        _path = [path copy];

        _executing = NO;
        _finished = NO;

        _expectedContentLength = 0;
        _progressContentLength = 0;
    }
    return self;
}

- (id)initWithURL:(NSURL *)url {
    return [self initWithURL:url path:nil];
}

#pragma mark - NSOperation methods

- (void)start {
    if ([self isCancelled]) {
        self.finished = YES;
        return;
    }

    if (!self.path) {
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        self.path = [docsPath stringByAppendingPathComponent:[self.url lastPathComponent]];
    }

    self.tempPath = [self pathForTemporaryFileWithPrefix:@"download"];

    self.executing = YES;

    [self performSelector:@selector(startInNetworkThread) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO];
}

- (void)startInNetworkThread {
    NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [connection start];
    self.connection = connection;
}

- (BOOL)isConcurrent {
    return YES;
}

- (void)setExecuting:(BOOL)executing {
    if (executing != _executing) {
        [self willChangeValueForKey:@"isExecuting"];
        _executing = executing;
        [self didChangeValueForKey:@"isExecuting"];
    }
}

- (void)setFinished:(BOOL)finished {
    if (finished != _finished) {
        [self willChangeValueForKey:@"isFinished"];
        _finished = finished;
        [self didChangeValueForKey:@"isFinished"];
    }
}

#pragma mark - Download thread methods

+ (void)networkRequestThreadEntryPoint:(id __unused)object {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"com.robertmryan.networkthread"];

        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

+ (NSThread *)networkRequestThread {
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });

    return _networkRequestThread;
}

#pragma mark - Private methods

- (NSString *)pathForTemporaryFileWithPrefix:(NSString *)prefix {
    NSString *uuidString = [[NSUUID UUID] UUIDString];
    return [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@", prefix, uuidString]];
}

- (BOOL)createFolderForPath:(NSString *)filePath
{
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folder = [filePath stringByDeletingLastPathComponent];
    BOOL isDirectory;

    if (![fileManager fileExistsAtPath:folder isDirectory:&isDirectory]) {
        // if folder doesn't exist, try to create it

        [fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];

        // if fail, report error

        if (error) {
            self.error = error;

            return FALSE;
        }

        // directory successfully created

        return TRUE;
    } else if (!isDirectory) {
        self.error = [NSError errorWithDomain:[NSBundle mainBundle].bundleIdentifier
                                         code:-1
                                     userInfo:@{
                      @"message"  : @"Unable to create directory; file exists by that name",
                      @"function" : @(__FUNCTION__),
                      @"folder"   : folder
                      }];

        return FALSE;
    }

    // directory already existed

    return TRUE;
}

- (BOOL)completeWithSuccess:(BOOL)success
{
    // clean up connection and download steam

    if (!success)
        [self.connection cancel];
    self.connection = nil;

    [self.outputStream close];
    self.outputStream = nil;

    // if download successful, let's save the result, otherwise just get rid of temporary file

    if (success)
        success = [self saveDownloadedFile];
    else
        success = [self removeTemporaryFile];

    // if caller wanted to know about success or failure, then inform it

    if (self.downloadCompletionBlock) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.downloadCompletionBlock(self, success, self.error);
        });
    }

    // finish this operation

    self.executing = NO;
    self.finished = YES;

    return success;
}

- (BOOL)removeTemporaryFile
{
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (self.tempPath) {
        if ([fileManager fileExistsAtPath:self.tempPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:self.tempPath error:&error];
            if (error)  {
                self.error = error;

                return NO;
            }
        }
    }

    return YES;
}

- (BOOL)saveDownloadedFile {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    if (![self createFolderForPath:self.path]) {
        return NO;
    }

    if ([fileManager fileExistsAtPath:self.path]) {
        [fileManager removeItemAtPath:self.path error:&error];
        if (error) {
            self.error = error;

            return NO;
        }
    }

    [fileManager moveItemAtPath:self.tempPath toPath:self.path error:&error];
    if (error) {
        self.error = error;

        return NO;
    }

    return YES;
}

#pragma mark - NSURLConnectionDataDelegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([self isCancelled]) {
        [self completeWithSuccess:NO];
        return;
    }

    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (id)response;

        NSInteger statusCode = [httpResponse statusCode];

        if (statusCode == 200) {
            self.expectedContentLength = [response expectedContentLength];
        } else if (statusCode >= 400) {
            self.error = [NSError errorWithDomain:[NSBundle mainBundle].bundleIdentifier
                                             code:statusCode
                                         userInfo:@{
                                                      @"message" : @"bad HTTP response status code",
                                                      @"function": @(__FUNCTION__),
                                                      @"NSHTTPURLResponse" : response
                                                  }];

            [self completeWithSuccess:NO];

            return;
        }
    } else {
        self.expectedContentLength = -1;
    }

    self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.tempPath append:NO];
    [self.outputStream open];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    const uint8_t *buffer = [data bytes];
    NSUInteger bytesRemaining = [data length];
    NSInteger bytesWritten;

    if ([self isCancelled]) {
        [self completeWithSuccess:NO];
        return;
    }

    while (bytesRemaining != 0) {
        bytesWritten = [self.outputStream write:buffer maxLength:bytesRemaining];
        if (bytesWritten < 0) {

            self.error = [NSError errorWithDomain:[NSBundle mainBundle].bundleIdentifier
                                             code:-1
                                         userInfo:@{
                                                    @"message"  : @"Unable to write bytes",
                                                    @"function" : @(__FUNCTION__),
                                                    @"url"      : [self.url absoluteString]
                                                    }];

            [self completeWithSuccess:NO];

            return;
        }

        bytesRemaining -= bytesWritten;
        buffer += bytesWritten;
    }

    self.progressContentLength += [data length];

    if (self.downloadProgressBlock) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.downloadProgressBlock(self, self.progressContentLength, self.expectedContentLength);
        });
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    self.error = error;

    [self completeWithSuccess:NO];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.error = nil;

    [self completeWithSuccess:YES];
}

@end