text:
from __future__ import unicode_literals, division, absolute_import, print_function

from .._errors import pretty_message
from .._ffi import (
    buffer_from_bytes,
    bytes_from_buffer,
    deref,
    new,
    null,
    pointer_set,
    struct,
    struct_bytes,
    unwrap,
    write_to_buffer,
)
from .util import rand_bytes
from .. import backend
from .._types import type_name, byte_cls

_backend = backend()

if _backend == 'winlegacy':
    from ._advapi32 import advapi32, Advapi32Const, handle_error, open_context_handle, close_context_handle
else:
    from ._cng import bcrypt, BcryptConst, handle_error, open_alg_handle, close_alg_handle

__all__ = [
    'aes_cbc_no_padding_decrypt',
    'aes_cbc_no_padding_encrypt',
    'aes_cbc_pkcs7_decrypt',
    'aes_cbc_pkcs7_encrypt',
    'des_cbc_pkcs5_decrypt',
    'des_cbc_pkcs5_encrypt',
    'rc2_cbc_pkcs5_decrypt',
    'rc2_cbc_pkcs5_encrypt',
    'rc4_decrypt',
    'rc4_encrypt',
    'tripledes_cbc_pkcs5_decrypt',
    'tripledes_cbc_pkcs5_encrypt',
]

def aes_cbc_no_padding_encrypt(key, data, iv):
    """
    Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and
    no padding. This means the ciphertext must be an exact multiple of 16 bytes
    long.

    :param key:
        The encryption key - a byte string either 16, 24 or 32 bytes long

    :param data:
        The plaintext - a byte string

    :param iv:
        The initialization vector - either a byte string 16-bytes long or None
        to generate an IV

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A tuple of two byte strings (iv, ciphertext)
    """

    if len(key) not in [16, 24, 32]:
        raise ValueError(pretty_message(
            '''
            key must be either 16, 24 or 32 bytes (128, 192 or 256 bits)
            long - is %s
            ''',
            len(key)
        ))

    if not iv:
        iv = rand_bytes(16)
    elif len(iv) != 16:
        raise ValueError(pretty_message(
            '''
            iv must be 16 bytes long - is %s
            ''',
            len(iv)
        ))

    if len(data) % 16 != 0:
        raise ValueError(pretty_message(
            '''
            data must be a multiple of 16 bytes long - is %s
            ''',
            len(data)
        ))

    return (iv, _encrypt('aes', key, data, iv, False))

def aes_cbc_no_padding_decrypt(key, data, iv):
    """
    Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
    padding.

    :param key:
        The encryption key - a byte string either 16, 24 or 32 bytes long

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector - a byte string 16-bytes long

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if len(key) not in [16, 24, 32]:
        raise ValueError(pretty_message(
            '''
            key must be either 16, 24 or 32 bytes (128, 192 or 256 bits)
            long - is %s
            ''',
            len(key)
        ))

    if len(iv) != 16:
        raise ValueError(pretty_message(
            '''
            iv must be 16 bytes long - is %s
            ''',
            len(iv)
        ))

    return _decrypt('aes', key, data, iv, False)

def aes_cbc_pkcs7_encrypt(key, data, iv):
    """
    Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and
    PKCS#7 padding.

    :param key:
        The encryption key - a byte string either 16, 24 or 32 bytes long

    :param data:
        The plaintext - a byte string

    :param iv:
        The initialization vector - either a byte string 16-bytes long or None
        to generate an IV

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A tuple of two byte strings (iv, ciphertext)
    """

    if len(key) not in [16, 24, 32]:
        raise ValueError(pretty_message(
            '''
            key must be either 16, 24 or 32 bytes (128, 192 or 256 bits)
            long - is %s
            ''',
            len(key)
        ))

    if not iv:
        iv = rand_bytes(16)
    elif len(iv) != 16:
        raise ValueError(pretty_message(
            '''
            iv must be 16 bytes long - is %s
            ''',
            len(iv)
        ))

    return (iv, _encrypt('aes', key, data, iv, True))

def aes_cbc_pkcs7_decrypt(key, data, iv):
    """
    Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key

    :param key:
        The encryption key - a byte string either 16, 24 or 32 bytes long

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector - a byte string 16-bytes long

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if len(key) not in [16, 24, 32]:
        raise ValueError(pretty_message(
            '''
            key must be either 16, 24 or 32 bytes (128, 192 or 256 bits)
            long - is %s
            ''',
            len(key)
        ))

    if len(iv) != 16:
        raise ValueError(pretty_message(
            '''
            iv must be 16 bytes long - is %s
            ''',
            len(iv)
        ))

    return _decrypt('aes', key, data, iv, True)

def rc4_encrypt(key, data):
    """
    Encrypts plaintext using RC4 with a 40-128 bit key

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The plaintext - a byte string

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the ciphertext
    """

    if len(key) < 5 or len(key) > 16:
        raise ValueError(pretty_message(
            '''
            key must be 5 to 16 bytes (40 to 128 bits) long - is %s
            ''',
            len(key)
        ))

    return _encrypt('rc4', key, data, None, None)

def rc4_decrypt(key, data):
    """
    Decrypts RC4 ciphertext using a 40-128 bit key

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The ciphertext - a byte string

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if len(key) < 5 or len(key) > 16:
        raise ValueError(pretty_message(
            '''
            key must be 5 to 16 bytes (40 to 128 bits) long - is %s
            ''',
            len(key)
        ))

    return _decrypt('rc4', key, data, None, None)

def rc2_cbc_pkcs5_encrypt(key, data, iv):
    """
    Encrypts plaintext using RC2 with a 64 bit key

    :param key:
        The encryption key - a byte string 8 bytes long

    :param data:
        The plaintext - a byte string

    :param iv:
        The 8-byte initialization vector to use - a byte string - set as None
        to generate an appropriate one

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A tuple of two byte strings (iv, ciphertext)
    """

    if len(key) < 5 or len(key) > 16:
        raise ValueError(pretty_message(
            '''
            key must be 5 to 16 bytes (40 to 128 bits) long - is %s
            ''',
            len(key)
        ))

    if not iv:
        iv = rand_bytes(8)
    elif len(iv) != 8:
        raise ValueError(pretty_message(
            '''
            iv must be 8 bytes long - is %s
            ''',
            len(iv)
        ))

    return (iv, _encrypt('rc2', key, data, iv, True))

def rc2_cbc_pkcs5_decrypt(key, data, iv):
    """
    Decrypts RC2 ciphertext using a 64 bit key

    :param key:
        The encryption key - a byte string 8 bytes long

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector used for encryption - a byte string

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if len(key) < 5 or len(key) > 16:
        raise ValueError(pretty_message(
            '''
            key must be 5 to 16 bytes (40 to 128 bits) long - is %s
            ''',
            len(key)
        ))

    if len(iv) != 8:
        raise ValueError(pretty_message(
            '''
            iv must be 8 bytes long - is %s
            ''',
            len(iv)
        ))

    return _decrypt('rc2', key, data, iv, True)

def tripledes_cbc_pkcs5_encrypt(key, data, iv):
    """
    Encrypts plaintext using 3DES in either 2 or 3 key mode

    :param key:
        The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode)

    :param data:
        The plaintext - a byte string

    :param iv:
        The 8-byte initialization vector to use - a byte string - set as None
        to generate an appropriate one

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A tuple of two byte strings (iv, ciphertext)
    """

    if len(key) != 16 and len(key) != 24:
        raise ValueError(pretty_message(
            '''
            key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s
            ''',
            len(key)
        ))

    if not iv:
        iv = rand_bytes(8)
    elif len(iv) != 8:
        raise ValueError(pretty_message(
            '''
            iv must be 8 bytes long - is %s
            ''',
            len(iv)
        ))

    cipher = 'tripledes_3key'
    if len(key) == 16:
        cipher = 'tripledes_2key'

    return (iv, _encrypt(cipher, key, data, iv, True))

def tripledes_cbc_pkcs5_decrypt(key, data, iv):
    """
    Decrypts 3DES ciphertext in either 2 or 3 key mode

    :param key:
        The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode)

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector used for encryption - a byte string

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if len(key) != 16 and len(key) != 24:
        raise ValueError(pretty_message(
            '''
            key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s
            ''',
            len(key)
        ))

    if len(iv) != 8:
        raise ValueError(pretty_message(
            '''
            iv must be 8 bytes long - is %s
            ''',
            len(iv)
        ))

    cipher = 'tripledes_3key'
    if len(key) == 16:
        cipher = 'tripledes_2key'

    return _decrypt(cipher, key, data, iv, True)

def des_cbc_pkcs5_encrypt(key, data, iv):
    """
    Encrypts plaintext using DES with a 56 bit key

    :param key:
        The encryption key - a byte string 8 bytes long (includes error
        correction bits)

    :param data:
        The plaintext - a byte string

    :param iv:
        The 8-byte initialization vector to use - a byte string - set as None
        to generate an appropriate one

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A tuple of two byte strings (iv, ciphertext)
    """

    if len(key) != 8:
        raise ValueError(pretty_message(
            '''
            key must be 8 bytes (56 bits + 8 parity bits) long - is %s
            ''',
            len(key)
        ))

    if not iv:
        iv = rand_bytes(8)
    elif len(iv) != 8:
        raise ValueError(pretty_message(
            '''
            iv must be 8 bytes long - is %s
            ''',
            len(iv)
        ))

    return (iv, _encrypt('des', key, data, iv, True))

def des_cbc_pkcs5_decrypt(key, data, iv):
    """
    Decrypts DES ciphertext using a 56 bit key

    :param key:
        The encryption key - a byte string 8 bytes long (includes error
        correction bits)

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector used for encryption - a byte string

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if len(key) != 8:
        raise ValueError(pretty_message(
            '''
            key must be 8 bytes (56 bits + 8 parity bits) long - is %s
            ''',
            len(key)
        ))

    if len(iv) != 8:
        raise ValueError(pretty_message(
            '''
            iv must be 8 bytes long - is %s
            ''',
            len(iv)
        ))

    return _decrypt('des', key, data, iv, True)

def _advapi32_create_handles(cipher, key, iv):
    """
    Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
    HCRYPTPROV must be released by close_context_handle() and the
    HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        A byte string of the symmetric key

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :return:
        A tuple of (HCRYPTPROV, HCRYPTKEY)
    """

    context_handle = None

    if cipher == 'aes':
        algorithm_id = {
            16: Advapi32Const.CALG_AES_128,
            24: Advapi32Const.CALG_AES_192,
            32: Advapi32Const.CALG_AES_256,
        }[len(key)]
    else:
        algorithm_id = {
            'des': Advapi32Const.CALG_DES,
            'tripledes_2key': Advapi32Const.CALG_3DES_112,
            'tripledes_3key': Advapi32Const.CALG_3DES,
            'rc2': Advapi32Const.CALG_RC2,
            'rc4': Advapi32Const.CALG_RC4,
        }[cipher]

    provider = Advapi32Const.MS_ENH_RSA_AES_PROV
    context_handle = open_context_handle(provider, verify_only=False)

    blob_header_pointer = struct(advapi32, 'BLOBHEADER')
    blob_header = unwrap(blob_header_pointer)
    blob_header.bType = Advapi32Const.PLAINTEXTKEYBLOB
    blob_header.bVersion = Advapi32Const.CUR_BLOB_VERSION
    blob_header.reserved = 0
    blob_header.aiKeyAlg = algorithm_id

    blob_struct_pointer = struct(advapi32, 'PLAINTEXTKEYBLOB')
    blob_struct = unwrap(blob_struct_pointer)
    blob_struct.hdr = blob_header
    blob_struct.dwKeySize = len(key)

    blob = struct_bytes(blob_struct_pointer) + key

    flags = 0
    if cipher in set(['rc2', 'rc4']) and len(key) == 5:
        flags = Advapi32Const.CRYPT_NO_SALT

    key_handle_pointer = new(advapi32, 'HCRYPTKEY *')
    res = advapi32.CryptImportKey(
        context_handle,
        blob,
        len(blob),
        null(),
        flags,
        key_handle_pointer
    )
    handle_error(res)

    key_handle = unwrap(key_handle_pointer)

    if cipher == 'rc2':
        buf = new(advapi32, 'DWORD *', len(key) * 8)
        res = advapi32.CryptSetKeyParam(
            key_handle,
            Advapi32Const.KP_EFFECTIVE_KEYLEN,
            buf,
            0
        )
        handle_error(res)

    if cipher != 'rc4':
        res = advapi32.CryptSetKeyParam(
            key_handle,
            Advapi32Const.KP_IV,
            iv,
            0
        )
        handle_error(res)

        buf = new(advapi32, 'DWORD *', Advapi32Const.CRYPT_MODE_CBC)
        res = advapi32.CryptSetKeyParam(
            key_handle,
            Advapi32Const.KP_MODE,
            buf,
            0
        )
        handle_error(res)

        buf = new(advapi32, 'DWORD *', Advapi32Const.PKCS5_PADDING)
        res = advapi32.CryptSetKeyParam(
            key_handle,
            Advapi32Const.KP_PADDING,
            buf,
            0
        )
        handle_error(res)

    return (context_handle, key_handle)

def _bcrypt_create_key_handle(cipher, key):
    """
    Creates a BCRYPT_KEY_HANDLE for symmetric encryption/decryption. The
    handle must be released by bcrypt.BCryptDestroyKey() when done.

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        A byte string of the symmetric key

    :return:
        A BCRYPT_KEY_HANDLE
    """

    alg_handle = None

    alg_constant = {
        'aes': BcryptConst.BCRYPT_AES_ALGORITHM,
        'des': BcryptConst.BCRYPT_DES_ALGORITHM,
        'tripledes_2key': BcryptConst.BCRYPT_3DES_112_ALGORITHM,
        'tripledes_3key': BcryptConst.BCRYPT_3DES_ALGORITHM,
        'rc2': BcryptConst.BCRYPT_RC2_ALGORITHM,
        'rc4': BcryptConst.BCRYPT_RC4_ALGORITHM,
    }[cipher]

    try:
        alg_handle = open_alg_handle(alg_constant)
        blob_type = BcryptConst.BCRYPT_KEY_DATA_BLOB

        blob_struct_pointer = struct(bcrypt, 'BCRYPT_KEY_DATA_BLOB_HEADER')
        blob_struct = unwrap(blob_struct_pointer)
        blob_struct.dwMagic = BcryptConst.BCRYPT_KEY_DATA_BLOB_MAGIC
        blob_struct.dwVersion = BcryptConst.BCRYPT_KEY_DATA_BLOB_VERSION1
        blob_struct.cbKeyData = len(key)

        blob = struct_bytes(blob_struct_pointer) + key

        if cipher == 'rc2':
            buf = new(bcrypt, 'DWORD *', len(key) * 8)
            res = bcrypt.BCryptSetProperty(
                alg_handle,
                BcryptConst.BCRYPT_EFFECTIVE_KEY_LENGTH,
                buf,
                4,
                0
            )
            handle_error(res)

        key_handle_pointer = new(bcrypt, 'BCRYPT_KEY_HANDLE *')
        res = bcrypt.BCryptImportKey(
            alg_handle,
            null(),
            blob_type,
            key_handle_pointer,
            null(),
            0,
            blob,
            len(blob),
            0
        )
        handle_error(res)

        return unwrap(key_handle_pointer)

    finally:
        if alg_handle:
            close_alg_handle(alg_handle)

def _encrypt(cipher, key, data, iv, padding):
    """
    Encrypts plaintext

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The plaintext - a byte string

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :param padding:
        Boolean, if padding should be used - unused for RC4

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the ciphertext
    """

    if not isinstance(key, byte_cls):
        raise TypeError(pretty_message(
            '''
            key must be a byte string, not %s
            ''',
            type_name(key)
        ))

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    if cipher != 'rc4' and not isinstance(iv, byte_cls):
        raise TypeError(pretty_message(
            '''
            iv must be a byte string, not %s
            ''',
            type_name(iv)
        ))

    if cipher != 'rc4' and not padding:
        # AES in CBC mode can be allowed with no padding if
        # the data is an exact multiple of the block size
        if not (cipher == 'aes' and len(data) % 16 == 0):
            raise ValueError('padding must be specified')

    if _backend == 'winlegacy':
        return _advapi32_encrypt(cipher, key, data, iv, padding)
    return _bcrypt_encrypt(cipher, key, data, iv, padding)

def _advapi32_encrypt(cipher, key, data, iv, padding):
    """
    Encrypts plaintext via CryptoAPI

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The plaintext - a byte string

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :param padding:
        Boolean, if padding should be used - unused for RC4

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the ciphertext
    """

    context_handle = None
    key_handle = None

    try:
        context_handle, key_handle = _advapi32_create_handles(cipher, key, iv)

        out_len = new(advapi32, 'DWORD *', len(data))
        res = advapi32.CryptEncrypt(
            key_handle,
            null(),
            True,
            0,
            null(),
            out_len,
            0
        )
        handle_error(res)

        buffer_len = deref(out_len)
        buffer = buffer_from_bytes(buffer_len)
        write_to_buffer(buffer, data)

        pointer_set(out_len, len(data))
        res = advapi32.CryptEncrypt(
            key_handle,
            null(),
            True,
            0,
            buffer,
            out_len,
            buffer_len
        )
        handle_error(res)

        output = bytes_from_buffer(buffer, deref(out_len))

        # Remove padding when not required. CryptoAPI doesn't support this, so
        # we just manually remove it.
        if cipher == 'aes' and not padding and len(output) == len(data) + 16:
            output = output[:-16]

        return output

    finally:
        if key_handle:
            advapi32.CryptDestroyKey(key_handle)
        if context_handle:
            close_context_handle(context_handle)

def _bcrypt_encrypt(cipher, key, data, iv, padding):
    """
    Encrypts plaintext via CNG

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The plaintext - a byte string

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :param padding:
        Boolean, if padding should be used - unused for RC4

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the ciphertext
    """

    key_handle = None

    try:
        key_handle = _bcrypt_create_key_handle(cipher, key)

        if iv is None:
            iv_len = 0
        else:
            iv_len = len(iv)

        flags = 0
        if padding is True:
            flags = BcryptConst.BCRYPT_BLOCK_PADDING

        out_len = new(bcrypt, 'ULONG *')
        res = bcrypt.BCryptEncrypt(
            key_handle,
            data,
            len(data),
            null(),
            null(),
            0,
            null(),
            0,
            out_len,
            flags
        )
        handle_error(res)

        buffer_len = deref(out_len)
        buffer = buffer_from_bytes(buffer_len)
        iv_buffer = buffer_from_bytes(iv) if iv else null()

        res = bcrypt.BCryptEncrypt(
            key_handle,
            data,
            len(data),
            null(),
            iv_buffer,
            iv_len,
            buffer,
            buffer_len,
            out_len,
            flags
        )
        handle_error(res)

        return bytes_from_buffer(buffer, deref(out_len))

    finally:
        if key_handle:
            bcrypt.BCryptDestroyKey(key_handle)

def _decrypt(cipher, key, data, iv, padding):
    """
    Decrypts AES/RC4/RC2/3DES/DES ciphertext

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :param padding:
        Boolean, if padding should be used - unused for RC4

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    if not isinstance(key, byte_cls):
        raise TypeError(pretty_message(
            '''
            key must be a byte string, not %s
            ''',
            type_name(key)
        ))

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    if cipher != 'rc4' and not isinstance(iv, byte_cls):
        raise TypeError(pretty_message(
            '''
            iv must be a byte string, not %s
            ''',
            type_name(iv)
        ))

    if cipher not in set(['rc4', 'aes']) and not padding:
        raise ValueError('padding must be specified')

    if _backend == 'winlegacy':
        return _advapi32_decrypt(cipher, key, data, iv, padding)
    return _bcrypt_decrypt(cipher, key, data, iv, padding)

def _advapi32_decrypt(cipher, key, data, iv, padding):
    """
    Decrypts AES/RC4/RC2/3DES/DES ciphertext via CryptoAPI

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :param padding:
        Boolean, if padding should be used - unused for RC4

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    context_handle = None
    key_handle = None

    try:
        context_handle, key_handle = _advapi32_create_handles(cipher, key, iv)

        if cipher == 'aes' and not padding and len(data) % 16 != 0:
            raise ValueError('Invalid data - ciphertext length must be a multiple of 16')

        buffer = buffer_from_bytes(data)
        out_len = new(advapi32, 'DWORD *', len(data))
        res = advapi32.CryptDecrypt(
            key_handle,
            null(),
            # To skip padding, we have to tell the API that this is not
            # the final block
            False if cipher == 'aes' and not padding else True,
            0,
            buffer,
            out_len
        )
        handle_error(res)

        return bytes_from_buffer(buffer, deref(out_len))

    finally:
        if key_handle:
            advapi32.CryptDestroyKey(key_handle)
        if context_handle:
            close_context_handle(context_handle)

def _bcrypt_decrypt(cipher, key, data, iv, padding):
    """
    Decrypts AES/RC4/RC2/3DES/DES ciphertext via CNG

    :param cipher:
        A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
        "rc2", "rc4"

    :param key:
        The encryption key - a byte string 5-16 bytes long

    :param data:
        The ciphertext - a byte string

    :param iv:
        The initialization vector - a byte string - unused for RC4

    :param padding:
        Boolean, if padding should be used - unused for RC4

    :raises:
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library

    :return:
        A byte string of the plaintext
    """

    key_handle = None

    try:
        key_handle = _bcrypt_create_key_handle(cipher, key)

        if iv is None:
            iv_len = 0
        else:
            iv_len = len(iv)

        flags = 0
        if padding is True:
            flags = BcryptConst.BCRYPT_BLOCK_PADDING

        out_len = new(bcrypt, 'ULONG *')
        res = bcrypt.BCryptDecrypt(
            key_handle,
            data,
            len(data),
            null(),
            null(),
            0,
            null(),
            0,
            out_len,
            flags
        )
        handle_error(res)

        buffer_len = deref(out_len)
        buffer = buffer_from_bytes(buffer_len)
        iv_buffer = buffer_from_bytes(iv) if iv else null()

        res = bcrypt.BCryptDecrypt(
            key_handle,
            data,
            len(data),
            null(),
            iv_buffer,
            iv_len,
            buffer,
            buffer_len,
            out_len,
            flags
        )
        handle_error(res)

        return bytes_from_buffer(buffer, deref(out_len))

    finally:
        if key_handle:
            bcrypt.BCryptDestroyKey(key_handle)


text:
published: false
---
A couple years ago I had the opportunity to attend a talk by [John Wilkes](https://research.google.com/pubs/JohnWilkes.html). Before he began his talk on [Borg](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43438.pdf), Google's cluster scheduler, he began with an un-scheduled lecture on how to sell your research.

The night before, John attended the PhD Poster session Google and told us in his own way that he found us lacking in the art of the elevator pitch. The line stuck with me was: **You need to be able to summarize your research and your work in under 30 seconds and be in a place where someone is interested in asking you more questions**. Citing a [panel discussion](https://dl.acm.org/citation.cfm?id=165934) from OOPSLA '93, specifically  [Kent Beck's](https://en.wikipedia.org/wiki/Kent_Beck) comments on how to write an abstract, John proceeded to outline for us a simple formula for how to summarize and engage audiences in 4 sentences.

Sentence ❶ : State the problem

Sentence ❷  : Why is the problem is a problem?

Sentence ❸ : A "starling" sentence

Sentence ❹ : Implications of the startling sentence.

This was Kent's example from the panel:

_The rejection rate for OOPSLA papers in near 90% _❶_. Most papers are rejected not because of a lack of good ideas, but because they are poorly structured _❷_. Following four simple steps in writing a paper will dramatically increase your chances of acceptance _❸_. If everyone followed these steps, the amount of communication in the object community would increase, improving the rate of progress _❹_._

### Case Study #1

That's a pretty good synthetic example, but I wanted to see if John followed his own advice. Let's take a look at [Large-scale cluster management at Google with Borg](https://dl.acm.org/citation.cfm?id=2741964) which he [presented himself](https://www.youtube.com/watch?v=7MwxA4Fj2l4) at EuroSys '15:

![borg_abs.png]({{site.baseurl}}/_drafts/borg_abs.PNG)

### Analysis

The first sentence states the problem that Google faces - cluster management for a large datacenter spanning a diverse set of both applications and machines. ❶

_Google's Borg system is a cluster manager that runs hundreds
of thousands of jobs, from many thousands of different
applications, across a number of clusters each with up to
tens of thousands of machines._

The problem is a problem because efficient task packing, over-commitment, performance isolation, and admission control are needed to achieve high utilization. We also get a bonus sentence about challenges of fault tolerence. ❷

_It achieves high utilization by combining admission control,
efficient task-packing, over-commitment, and machine
sharing with process-level performance isolation. It supports high-availability applications with runtime features that minimize fault-recovery time, and scheduling policies that reduce
the probability of correlated failures._

Startling sentence? A suite of tools and a job spec language at the cluster level. ❸

_Borg simplifies life for its users by offering a declarative job specification language, name service integration, real-time job monitoring, and tools to analyze and simulate system behavior._

The implications are "we built it" and leared some interesting lessons along the way. ❹

_We present a summary of the Borg system architecture
and features, important design decisions, a quantitative analysis
of some of its policy decisions, and a qualitative examination
of lessons learned from a decade of operational
experience with it._

This paper is unconventional in that it is a retrospective of a production system but it still ahderes to the outline format.

### Case Study #2
Much of the security work done at UC San Diego involves measurement studies such as [reverse engineering emissions defeat devices](https://cseweb.ucsd.edu/~klevchen/diesel-sp17.pdf) in Volkswagen and Fiat cars or [map the internals of cloud infrastures](https://cseweb.ucsd.edu/~hovav/dist/cloudsec.pdf) based on VM side-channel attacks. This is a little different from systems buildling papers but we seek to find if Kent Beck's structure applys to these cases as well.

![cloud_abs.PNG]({{site.baseurl}}/_drafts/cloud_abs.PNG)

The problem (opportunity) is people outsourcing compute to public clouds. ❶

_Third-party cloud computing represents the promise of outsourcing
as applied to computation._

This is a problem because the business model of cloud providers requires
the use of virtual machines for users to run their job on. The virtual machine will represents a shared
physical infrastructure. ❷

_Services, such as Microsoft's Azure and Amazon's EC2, allow users to instantiate
virtual machines (VMs) on demand and thus purchase
precisely the capacity they require when they require it.
In turn, the use of virtualization allows third-party cloud
providers to maximize the utilization of their sunk capital
costs by multiplexing many customer VMs across a shared
physical infrastructure. _

The shared physical infrastrucutre is vulnerable to new VM based side-channel attacks can leak data to both map the internal cloud infrastructure and disrupt user performance. ❸

_However, in this paper, we show
that this approach can also introduce new vulnerabilities.
Using the Amazon EC2 service as a case study, we show that
it is possible to map the internal cloud infrastructure, identify
where a particular target VM is likely to reside, and then
instantiate new VMs until one is placed co-resident with the
target. _

The implication is that it is possible to mount cross-VM side channel attacks that can extract information
from a VM. ❹

_We explore how such placement can then be used to
mount cross-VM side-channel attacks to extract information
from a target VM on the same machine._

## Why Writing an Abstract is Hard?

Of course it is not as easy as this. One has to have the right starting point.

When I was a first year PhD, I found writing the abstract and introduction of my own papers the most daunting aspect of the paper. I was consoled to hear from my felllow graduate students "don't worry the professor will take care of it".

This seemed to be the common theme in most labs. The student writes the background, design, evaluation, and spends a few cycles working on an abstract and introdcution which is eventually completely scrapped by the adivsor and rewritten.

As a more senior PhD now, I understand why the professors always seemed to have an infallable talent for abstract writing - **they understand the big picture**. There is tendency to lose sight of the forest from the trees working long hours in the weeds of a narrow research thread. The thread can seem magnified and the abstract starts to be about all about the details of the contribution rather than the insight that the contribution enables.

I find that the earlier involvement I have in the beginning of the project the more comfortable I am with writing the abstract. That being said, not everyone joins a project in the beginning. I believe it is the responsilbity of both the PI and the student to sync and realign what the big picture of the project is every now and again. Not only does it focus the efforts of the group, but I find it to be a huge morale boost to remember that the scope of the work is far bigger than the bug I was trying to debug this week.

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <title>YeomanTutorial</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="styles/main.css">

'Allo, 'Allo!


text:
const referer = "/room/x887dfffd";

const roomId = referer
    .split('/')[referer.split('/').length - 1]
    .replace(/\?.+/, '');

console.log(roomId);
console.log(referer.split('/'));
console.log(referer.split('/')[referer.split('/').length - 1]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectTasksOptions">
    <TaskOptions isEnabled="true">
      <option name="arguments" value="-w $FileName$" />
      <option name="checkSyntaxErrors" value="true" />
      <option name="description" value="Do GoImport on file save" />
      <option name="exitCodeBehavior" value="ERROR" />
      <option name="fileExtension" value="go" />
      <option name="immediateSync" value="false" />
      <option name="name" value="GoImport" />
      <option name="output" value="" />
      <option name="outputFilters">
        <array />
      </option>
      <option name="outputFromStdout" value="false" />
      <option name="program" value="$PROJECT_DIR$/../../../../bin/goimports" />
      <option name="scopeName" value="Project Files" />
      <option name="trackOnlyRoot" value="false" />
      <option name="workingDir" value="$FileDir$" />
      <envs />
    </TaskOptions>
  </component>
</project>


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

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * ScalingAction JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ScalingActionJsonUnmarshaller implements Unmarshaller<ScalingAction, JsonUnmarshallerContext> {

    public ScalingAction unmarshall(JsonUnmarshallerContext context) throws Exception {
        ScalingAction scalingAction = new ScalingAction();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Market", targetDepth)) {
                    context.nextToken();
                    scalingAction.setMarket(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SimpleScalingPolicyConfiguration", targetDepth)) {
                    context.nextToken();
                    scalingAction.setSimpleScalingPolicyConfiguration(SimpleScalingPolicyConfigurationJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return scalingAction;
    }

    private static ScalingActionJsonUnmarshaller instance;

    public static ScalingActionJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new ScalingActionJsonUnmarshaller();
        return instance;
    }
}


text:
package org.sagebionetworks.web.client.place;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;
import com.google.gwt.place.shared.Prefix;

public class ErrorPlace extends Place {

  private String token;

  public ErrorPlace(String token) {
    this.token = token;
  }

  public String toToken() {
    return token;
  }

  @Prefix("!Error")
  public static class Tokenizer implements PlaceTokenizer<ErrorPlace> {

    @Override
    public String getToken(ErrorPlace place) {
      return place.toToken();
    }

    @Override
    public ErrorPlace getPlace(String token) {
      return new ErrorPlace(token);
    }
  }
}


text:
module Crowdin
  module Tool
    class ConfigurationManager
      require 'yaml'

      SETUP_COMMAND_DESC = {
          'init' => 'initializes crowdin-cli configuration for the current project'
      }

      def self.setup_task_descriptions
        SETUP_COMMAND_DESC
      end

      def self.setup_commands
        SETUP_COMMAND_DESC.keys
      end

      def self.run_setup_tasks(commands)
        (self.setup_commands & [commands].flatten).each do |task|
          self.send(task)
        end
      end

      def self.configure_crowdin
        init unless File.exist?(configuration_filename)
      end

      def self.init
        configuration = default_configuration
        raise "Cannot load default configuration" unless configuration.is_a?(Hash)
        configuration['base_path'] = Dir.pwd
        save_configuration(configuration)
      end

      def self.save_configuration(configuration)
        puts "Writing crowdin configuration to '#{configuration_filename}'"
        File.open(configuration_filename, 'w+') do |file|
          file << YAML::dump(configuration)
        end
      end

      def self.default_configuration
        YAML::load_file(default_configuration_filename)
      rescue Exception => e
        raise "Unable to read default configuration from '#{default_configuration_filename}'"
      end

      def self.default_configuration_filename
        'crowdin_default.yaml'
      end

      def self.configuration_filename
        'crowdin.yaml'
      end

    end
  end
end


text:
package ru.job4j.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import ru.job4j.model.Persistent;

/**
 * @author Hincu Andrei (andreih1981@gmail.com)on 16.03.2018.
 * @version $Id$.
 * @since 0.1.
 */
public abstract class AbstractController<E extends Persistent, K> implements Dao<E, K> {
//    private static final Logger LOG = LogManager.getLogger(AbstractController.class);
//    private SessionFactory sessionFactory = HibernateService.getSessionFactory();
//    private Session currentSession;
//    private Transaction currentTransaction;
//
//    public Session getCurrentSession() {
//        return currentSession;
//    }
//
//    public Session openCurrentSession() {
//        this.currentSession = sessionFactory.openSession();
//        return currentSession;
//    }
//    public void closeCurrentSession() {
//        this.currentSession.close();
//    }
//    public Session openCurrentSessionWithTransaction() {
//        this.currentSession = sessionFactory.openSession();
//        this.currentTransaction = currentSession.beginTransaction();
//        return currentSession;
//    }
//    public void closeSessionWithTransaction() {
//        this.currentTransaction.commit();
//        this.currentSession.close();
//    }
//    public void addTransactionToCurrentSession() {
//        this.currentTransaction = currentSession.beginTransaction();
//    }

}


text:
require 'test_helper'

class NBTJSONTest < Minitest::Test
  def test_setblock_encodes_nbt
    # top level
    commands = assert_valid do
      setblock 1, 2, 3, 'minecraft:command_block', 0, :replace, {'Command'=>'say Hello'}
    end
    assert_includes commands[1], '{Command:"say Hello"}'

    # in initial block
    commands = assert_valid do
      initial do
        setblock 1, 2, 3, 'minecraft:command_block', 0, :replace, {'Command'=>'say Hello'}
      end
    end
    assert_includes commands[0], '{Command:"say Hello"}'
  end

  def test_blockdata_encodes_nbt
    commands = assert_valid do
      initial do
        blockdata 1, 2, 3, {'Command'=>'say Hello'}
      end
    end
    assert_equal ['blockdata 1 2 3 {Command:"say Hello"}'], commands
  end

  def test_replaceitem_encodes_nbt
    commands = assert_valid do
      initial do
        replaceitem :entity, @a[team: 'Blue'], 'slot.armor.chest', 'minecraft:leather_chestplate', 1, 0, {display:{color:3361970}}
      end
    end
    assert_equal [
      'replaceitem entity @a[team=Blue] slot.armor.chest minecraft:leather_chestplate 1 0 {display:{color:3361970}}'
    ], commands
  end

  def test_tellraw_encodes_json
    commands = assert_valid do
      initial do
        tellraw @a, {text: 'Hello'}, {text: 'World'}
      end
    end
    assert_equal ['tellraw @a [{"text":"Hello"},{"text":"World"}]'], commands

    commands = assert_valid do
      initial do
        tellraw @a, [{text: 'Hello'}, {text: 'World'}]
      end
    end
    assert_equal ['tellraw @a [{"text":"Hello"},{"text":"World"}]'], commands
  end

  def test_title_encodes_json
    commands = assert_valid do
      initial do
        title @a, :title, {text: "Score", color: "red"}
      end
    end
    assert_equal ['title @a title [{"text":"Score","color":"red"}]'], commands
  end

  def test_nested_nbt
    assert_equal '{tag:{display:{Name:"Bob"}}}', McBlocky::DSL.to_nbt(
      {tag: {display: {'Name'=>'Bob'}}}
    )
    assert_equal '[{slot:0,id:"minecraft:diamond"},{slot:1,id:"minecraft:iron_ingot"}]',
      McBlocky::DSL.to_nbt([
        {slot: 0, id: 'minecraft:diamond'},
        {slot: 1, id: 'minecraft:iron_ingot'}
      ])
  end

  def test_to_json
    assert_equal '"Hello"', McBlocky::DSL.to_json("Hello")
    assert_equal '42', McBlocky::DSL.to_json(42)
    assert_equal '{"foo":"bar"}', McBlocky::DSL.to_json({foo: 'bar'})
    assert_equal '[42]', McBlocky::DSL.to_json([42])
    assert_equal '[1,2,"foo"]', McBlocky::DSL.to_json(1, 2, "foo")
  end
end


text: module.exports = require('./dist/decompiler.js');


text:
namespace Friends.Core
{
    public class LoggingEvents
    {
        public const int k_GenerateItems = 1000;
        public const int k_ListItems = 1001;
        public const int k_GetItem = 1002;
        public const int k_InsertItem = 1003;
        public const int k_UpdateItem = 1004;
        public const int k_DeleteItem = 1005;
        public const int k_GetItemNotfound = 4000;
        public const int k_UpdateItemNotfound = 4001;
    }
}


text:
<connectorDefinition label="Send Cursor on Target message"
	name="cot-out" type="outbound">
	<adapter uri="com.esri.geoevent.solutions.adapter.cot.outbound/CursorOnTargetOut/10.5.0" />
	<transport uri="com.esri.geoevent.solutions.transport.tcpsquirt.outbound/TCPSquirt/10.5.0" />
	<defaultName>CoT-out</defaultName>
	<description>Send a Cursor on Target message out over tcp socket that opens on demand</description>
	<properties>
		<advanced>
			<property label="Host (Client Mode)" name="host" source="transport" />
			<property label="Connection Timeout (Client Mode)" name="clientConnectionTimeout" source="transport" />
			<property label="Mode" name="mode" source="transport" />
		</advanced>
		<hidden>

		</hidden>
		<shown>
			<property label="Server Port" name="port" default="5565" source="transport" />
		</shown>
	</properties>
</connectorDefinition>


text:
class FoursquareWrapper

  FOURSQUARE_CLIENT_ID = ENV["foursquare_client_id"]
  FOURSQUARE_SECRET = ENV["foursquare_secret"]

  def self.request(request_url)
    base_url = "https://api.foursquare.com/v2/"
    api_request = URI(URI.encode(base_url+request_url))
    api_response = Net::HTTP.get(api_request)
    JSON.parse(api_response)["response"]
  end

  def self.checkins
    result = self.request("venues/explore?near=New York NY&client_id=#{FOURSQUARE_CLIENT_ID}&client_secret=#{FOURSQUARE_SECRET}&v=20130815&limit=50")
    venue = Struct.new(:latitude, :longitude, :weight)
    result["groups"][0]["items"].collect do |location|
      venue_hash = location["venue"]
      venue.new(venue_hash["location"]["lat"],venue_hash["location"]["lng"],venue_hash["stats"]["checkinsCount"])
    end
  end

  def self.linear_transform_weight(venue)
    1 + (venue.weight-min) * (3-1) / (max-min)
  end

  def self.max
    @@checkins.max_by do |venue|
      venue.weight
    end.weight
  end

  def self.min
    @@checkins.min_by do |venue|
      venue.weight
    end.weight
  end

  @@checkins = self.checkins

  def self.all
    @@checkins.each do |venue|
      venue.weight = linear_transform_weight(venue)
    end
  end

  @@all = self.all

  def self.all_hourly
    (0..23).collect do |hour|
      @@all
    end
  end

end


text:
module org.mobilitydata.gtfsvalidator.app.pkg {
  requires org.mobilitydata.gtfsvalidator.app.gui;
}


text:
#include <difont/difont.h>

#ifndef _DIFONT_BUFFER_GLYPH_H_
#define _DIFONT_BUFFER_GLYPH_H_

/**
 * BufferGlyph is a specialisation of Glyph for memory buffer rendering.
 */
namespace difont {
    class BufferGlyph : public Glyph {
    public:
        /**
         * Constructor
         *
         * @param glyph The Freetype glyph to be processed
         * @param buffer  An Buffer object in which to render the glyph.
         */
        BufferGlyph(FT_GlyphSlot glyph, difont::Buffer *buffer);

        /**
         * Destructor
         */
        virtual ~BufferGlyph();

        /**
         * Render this glyph at the current pen position.
         *
         * @param pen  The current pen position.
         * @param renderMode  Render mode to display
         * @return  The advance distance for this glyph.
         */
        virtual const difont::Point& Render(const difont::Point& pen, int renderMode);
    };
}

#endif  //  __BufferGlyph__


text:
echo ""
echo "========================================="
echo "Initializing CloudStore database..."
echo ""

psql -U postgres -f roles.sql
createdb -U cf_cloudstore cf_cloudstore
psql -U postgres -c 'create extension hstore;' cf_cloudstore
psql -U cf_cloudstore -f scheme.sql

echo ""
echo "DONE initializing"
echo ""


text:
Puppet::Type.type(:rabbitmq_exchange).provide(:default) do

  def self.instances
    []
  end

  def create
    default_fail
  end

  def destroy
    default_fail
  end

  def exists?
    default_fail
  end

  def default_fail
    fail('This is just the default provider for rabbitmq_exchange, all it does is fail')
  end
end


text:
<?php

/**
 * Handles interfaces to Magento products or product pages.
 *
 * @author Andrew Kenney <akenney@onesite.com>
 */
class Onesite_SSO_Helper_Product extends Mage_Core_Helper_Abstract
{
	/**
	 * Return the current product being viewed.
	 *
	 * @return void
	 */
	public function getCurrent()
	{
		return Mage::registry('current_product');
	}

	/**
	 * Get the unique key for a product, typically its SKU.
	 *
	 * @return string
	 */
	public function getUniqueKey()
	{
		$product = $this->getCurrent();

		if (is_null($product)) {
			return false;
		}

		$sku = $product->getSku();
		Mage::log("Got SKU: $sku");

		return $sku;
	}
}


text:
/**
 * @unrestricted
 */
TextUtils.TextRange = class {
  /**
   * @param {number} startLine
   * @param {number} startColumn
   * @param {number} endLine
   * @param {number} endColumn
   */
  constructor(startLine, startColumn, endLine, endColumn) {
    this.startLine = startLine;
    this.startColumn = startColumn;
    this.endLine = endLine;
    this.endColumn = endColumn;
  }

  /**
   * @param {number} line
   * @param {number} column
   * @return {!TextUtils.TextRange}
   */
  static createFromLocation(line, column) {
    return new TextUtils.TextRange(line, column, line, column);
  }

  /**
   * @param {!Object} serializedTextRange
   * @return {!TextUtils.TextRange}
   */
  static fromObject(serializedTextRange) {
    return new TextUtils.TextRange(
        serializedTextRange.startLine, serializedTextRange.startColumn, serializedTextRange.endLine,
        serializedTextRange.endColumn);
  }

  /**
   * @param {!TextUtils.TextRange} range1
   * @param {!TextUtils.TextRange} range2
   * @return {number}
   */
  static comparator(range1, range2) {
    return range1.compareTo(range2);
  }

  /**
   * @param {!TextUtils.TextRange} oldRange
   * @param {string} newText
   * @return {!TextUtils.TextRange}
   */
  static fromEdit(oldRange, newText) {
    let endLine = oldRange.startLine;
    let endColumn = oldRange.startColumn + newText.length;
    const lineEndings = newText.computeLineEndings();
    if (lineEndings.length > 1) {
      endLine = oldRange.startLine + lineEndings.length - 1;
      const len = lineEndings.length;
      endColumn = lineEndings[len - 1] - lineEndings[len - 2] - 1;
    }
    return new TextUtils.TextRange(oldRange.startLine, oldRange.startColumn, endLine, endColumn);
  }

  /**
   * @return {boolean}
   */
  isEmpty() {
    return this.startLine === this.endLine && this.startColumn === this.endColumn;
  }

  /**
   * @param {!TextUtils.TextRange} range
   * @return {boolean}
   */
  immediatelyPrecedes(range) {
    if (!range)
      return false;
    return this.endLine === range.startLine && this.endColumn === range.startColumn;
  }

  /**
   * @param {!TextUtils.TextRange} range
   * @return {boolean}
   */
  immediatelyFollows(range) {
    if (!range)
      return false;
    return range.immediatelyPrecedes(this);
  }

  /**
   * @param {!TextUtils.TextRange} range
   * @return {boolean}
   */
  follows(range) {
    return (range.endLine === this.startLine && range.endColumn <= this.startColumn) || range.endLine < this.startLine;
  }

  /**
   * @return {number}
   */
  get linesCount() {
    return this.endLine - this.startLine;
  }

  /**
   * @return {!TextUtils.TextRange}
   */
  collapseToEnd() {
    return new TextUtils.TextRange(this.endLine, this.endColumn, this.endLine, this.endColumn);
  }

  /**
   * @return {!TextUtils.TextRange}
   */
  collapseToStart() {
    return new TextUtils.TextRange(this.startLine, this.startColumn, this.startLine, this.startColumn);
  }

  /**
   * @return {!TextUtils.TextRange}
   */
  normalize() {
    if (this.startLine > this.endLine || (this.startLine === this.endLine && this.startColumn > this.endColumn))
      return new TextUtils.TextRange(this.endLine, this.endColumn, this.startLine, this.startColumn);
    else
      return this.clone();
  }

  /**
   * @return {!TextUtils.TextRange}
   */
  clone() {
    return new TextUtils.TextRange(this.startLine, this.startColumn, this.endLine, this.endColumn);
  }

  /**
   * @return {!{startLine: number, startColumn: number, endLine: number, endColumn: number}}
   */
  serializeToObject() {
    const serializedTextRange = {};
    serializedTextRange.startLine = this.startLine;
    serializedTextRange.startColumn = this.startColumn;
    serializedTextRange.endLine = this.endLine;
    serializedTextRange.endColumn = this.endColumn;
    return serializedTextRange;
  }

  /**
   * @param {!TextUtils.TextRange} other
   * @return {number}
   */
  compareTo(other) {
    if (this.startLine > other.startLine)
      return 1;
    if (this.startLine < other.startLine)
      return -1;
    if (this.startColumn > other.startColumn)
      return 1;
    if (this.startColumn < other.startColumn)
      return -1;
    return 0;
  }

  /**
   * @param {number} lineNumber
   * @param {number} columnNumber
   * @return {number}
   */
  compareToPosition(lineNumber, columnNumber) {
    if (lineNumber < this.startLine || (lineNumber === this.startLine && columnNumber < this.startColumn))
      return -1;
    if (lineNumber > this.endLine || (lineNumber === this.endLine && columnNumber > this.endColumn))
      return 1;
    return 0;
  }

  /**
   * @param {!TextUtils.TextRange} other
   * @return {boolean}
   */
  equal(other) {
    return this.startLine === other.startLine && this.endLine === other.endLine &&
        this.startColumn === other.startColumn && this.endColumn === other.endColumn;
  }

  /**
   * @param {number} line
   * @param {number} column
   * @return {!TextUtils.TextRange}
   */
  relativeTo(line, column) {
    const relative = this.clone();

    if (this.startLine === line)
      relative.startColumn -= column;
    if (this.endLine === line)
      relative.endColumn -= column;

    relative.startLine -= line;
    relative.endLine -= line;
    return relative;
  }

  /**
   * @param {number} line
   * @param {number} column
   * @return {!TextUtils.TextRange}
   */
  relativeFrom(line, column) {
    const relative = this.clone();

    if (this.startLine === 0)
      relative.startColumn += column;
    if (this.endLine === 0)
      relative.endColumn += column;

    relative.startLine += line;
    relative.endLine += line;
    return relative;
  }

  /**
   * @param {!TextUtils.TextRange} originalRange
   * @param {!TextUtils.TextRange} editedRange
   * @return {!TextUtils.TextRange}
   */
  rebaseAfterTextEdit(originalRange, editedRange) {
    console.assert(originalRange.startLine === editedRange.startLine);
    console.assert(originalRange.startColumn === editedRange.startColumn);
    const rebase = this.clone();
    if (!this.follows(originalRange))
      return rebase;
    const lineDelta = editedRange.endLine - originalRange.endLine;
    const columnDelta = editedRange.endColumn - originalRange.endColumn;
    rebase.startLine += lineDelta;
    rebase.endLine += lineDelta;
    if (rebase.startLine === editedRange.endLine)
      rebase.startColumn += columnDelta;
    if (rebase.endLine === editedRange.endLine)
      rebase.endColumn += columnDelta;
    return rebase;
  }

  /**
   * @override
   * @return {string}
   */
  toString() {
    return JSON.stringify(this);
  }

  /**
   * @param {number} lineNumber
   * @param {number} columnNumber
   * @return {boolean}
   */
  containsLocation(lineNumber, columnNumber) {
    if (this.startLine === this.endLine)
      return this.startLine === lineNumber && this.startColumn <= columnNumber && columnNumber <= this.endColumn;
    if (this.startLine === lineNumber)
      return this.startColumn <= columnNumber;
    if (this.endLine === lineNumber)
      return columnNumber <= this.endColumn;
    return this.startLine < lineNumber && lineNumber < this.endLine;
  }
};

/**
 * @unrestricted
 */
TextUtils.SourceRange = class {
  /**
   * @param {number} offset
   * @param {number} length
   */
  constructor(offset, length) {
    this.offset = offset;
    this.length = length;
  }
};

/**
 * @unrestricted
 */
TextUtils.SourceEdit = class {
  /**
   * @param {string} sourceURL
   * @param {!TextUtils.TextRange} oldRange
   * @param {string} newText
   */
  constructor(sourceURL, oldRange, newText) {
    this.sourceURL = sourceURL;
    this.oldRange = oldRange;
    this.newText = newText;
  }

  /**
   * @param {!TextUtils.SourceEdit} edit1
   * @param {!TextUtils.SourceEdit} edit2
   * @return {number}
   */
  static comparator(edit1, edit2) {
    return TextUtils.TextRange.comparator(edit1.oldRange, edit2.oldRange);
  }

  /**
   * @return {!TextUtils.TextRange}
   */
  newRange() {
    return TextUtils.TextRange.fromEdit(this.oldRange, this.newText);
  }
};


text:
import React, { Component } from "react";

import Badge from "material-ui/Badge";
import Avatar from "material-ui/Avatar";
import Grid from "material-ui/Grid";

export default class MemCoworker extends Component {
  render() {
    const coworkers = this.props.checkedUsers,
      users = this.props.users,
      taskOwner = this.props.taskOwner;

    const coworkerId = coworkers.map(worker => {
      return worker.id;
    });

    const filteredOwner = users.filter(user => {
      return user.id === taskOwner.id;
    });

    const filteredUser = users.map(user => {
      if (coworkerId.includes(user.id)) {
        return user;
      }
    });

    return (
      <Grid container justify={"flex-start"}>
        {filteredUser.map(worker => {
          return (
            worker !== undefined && (
              <Grid key={worker.id} item xs={1}>
                <Avatar alt={worker.username} src={worker.pic} />
              </Grid>
            )
          );
        })}

        <Grid key={"owner"} item xs={1}>
          {filteredOwner[0] !== undefined && (
            <Badge
              badgeContent={filteredOwner[0].username.charAt(0)}
              color="primary"
            >
              <Avatar
                alt={filteredOwner[0].username}
                src={filteredOwner[0].pic}
                id="task-owner"
              />
            </Badge>
          )}
        </Grid>
      </Grid>
    );
  }
}


text:
var util = require('util'),
    exec = require('child_process').exec,
    fs = require("fs"),
    pathlib = require("path"),
    helpers = require("./helpers");

module.exports.findLemmas = findLemmas;

module.exports.config = {
    morfdir: pathlib.join("C:","lemma", "morf"),
    tempdir: "R:"
};

function findLemmas(words, callback){
    var word, fname, fpath, output;

    if(typeof words == "string"){
        words = [words];
    }

    if(!Array.isArray(words) || !words.length){
        return callback();
    }

    for(i=words.length-1; i>=0; i--){
        word = (words[i] || "").toString("utf-8").trim();
        if(!word.length){
            words.splice(i,1);
        }else{
            words[i] = word;
        }
    }

    if(!words.length){
        return callback();
    }

    fname = helpers.genFName();
    fpath = pathlib.join(module.exports.config.tempdir, fname);

    output = helpers.convertToWin1257(words.join("\n"));

    fs.writeFile(fpath+".txt", output, function(err){
        if(err){
            return callback(err);
        }
        makeLemma(fpath, callback);
    });
}

function makeLemma(fpath, callback){
    var morfpath = pathlib.join(module.exports.config.morfdir, "ESTMORF.EXE");

    exec(morfpath + ' -B "' + fpath+'.txt"',{
            cwd: module.exports.config.morfdir
        },
        function (err, stdout, stderr) {
            if(err){
                fs.unlink(fpath+".txt");
                return callback(err);
            }
            fs.readFile(fpath+".mrf", function(err, data){
                fs.unlink(fpath+".txt");
                fs.unlink(fpath+".mrf");

                var lemmatxt = (helpers.convertFromWin1257(data) || "").toString("utf-8").trim();

                parseLemma(lemmatxt, callback);
            });
        });

}

function parseLemma(lemmatxt, callback){
    var lines = lemmatxt.split("\n"),
        words = {}, curword, lemma;

    for(var i=0, len=lines.length; i<len; i++){
        if(lines[i].match(/^\S/)){
            curword = lines[i].trim();
        }else{
            if(curword){
                if(!words[curword]){
                    words[curword] = [];
                }
                if((lemma = lines[i].trim()) && !lemma.match(/#/)){
                    words[curword].push(lemma);
                }
            }
        }
    }

    callback(null, words);
}


text:
declare module 'webpack-node-externals' {
}


text:
<?php

namespace RcmAdmin\Factory;

use RcmAdmin\Form\NewPageForm;
use Zend\Di\ServiceLocator;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Service Factory for the Admin Page Controller
 *
 * Factory for the Admin Page Controller.
 *
 * @category  Reliv
 * @package   RcmAdmin
 * @author    Westin Shafer <wshafer@relivinc.com>
 * @copyright 2012 Reliv International
 * @license   License.txt New BSD License
 * @version   Release: 1.0
 * @link      https://github.com/reliv
 *
 */
class NewPageFormFactory implements FactoryInterface
{

    /**
     * Create Service
     *
     * @param ServiceLocatorInterface $formElementManager Zend Controler Manager
     *
     * @return NewPageForm
     */
    public function createService(ServiceLocatorInterface $formElementManager)
    {
        /** @var \Zend\Form\FormElementManager $formElementMgr For IDE */
        $formElementMgr = $formElementManager;

        /** @var \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator */
        $serviceLocator = $formElementMgr->getServiceLocator();

        /** @var \Rcm\Entity\Site $currentSite */
        $currentSite = $serviceLocator->get('Rcm\Service\CurrentSite');

        /** @var \Doctrine\ORM\EntityManagerInterface $entityManager */
        $entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');

        /** @var \Rcm\Repository\Page $pageRepo */
        $pageRepo = $entityManager->getRepository('\Rcm\Entity\Page');

        /** @var \Rcm\Service\LayoutManager $layoutManager */
        $layoutManager = $serviceLocator->get('Rcm\Service\LayoutManager');

        /** @var \Rcm\Validator\MainLayout $layoutValidator */
        $layoutValidator = $serviceLocator->get('Rcm\Validator\MainLayout');

        /** @var \Rcm\Validator\Page $pageValidator */
        $pageValidator = $serviceLocator->get('Rcm\Validator\Page');

        /** @var \Rcm\Validator\PageTemplate $templateValidator */
        $templateValidator = $serviceLocator->get('Rcm\Validator\PageTemplate');

        return new NewPageForm(
            $currentSite,
            $pageRepo,
            $layoutManager,
            $layoutValidator,
            $pageValidator,
            $templateValidator
        );
    }
}


text:
namespace Microsoft.PowerShell.Commands.Internal
{
    using System;
    using System.Runtime.InteropServices;
    using System.Transactions;
    using Microsoft.Win32.SafeHandles;
    using System.Management.Automation;

    [Guid("79427A2B-F895-40e0-BE79-B57DC82ED231"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IKernelTransaction
    {
        int GetHandle(out IntPtr pHandle);
    }

    [System.Security.SuppressUnmanagedCodeSecurity]
    internal sealed class SafeTransactionHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private const string resBaseName = "RegistryProviderStrings";

        private SafeTransactionHandle(IntPtr handle)
            : base(true)
        {
            this.handle = handle;
        }

        internal static SafeTransactionHandle Create()
        {
            return SafeTransactionHandle.Create(Transaction.Current);
        }

        internal static SafeTransactionHandle Create(Transaction managedTransaction)
        {
            if (managedTransaction == null)
            {
                throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NeedTransaction);
            }

            // MSDTC is not available on WinPE machine.
            // CommitableTransaction will use DTC APIs under the covers to get KTM transaction manager interface.
            // KTM is kernel Transaction Manager to handle file, registry etc and MSDTC provides an integration support
            // with KTM to handle transaction across kernel resources and MSDTC resources like SQL, MSMQ etc.
            // We need KTMRM service as well. WinPE doesn't have these services installed
            if (Utils.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM())
            {
                throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions);
            }

            IDtcTransaction dtcTransaction = TransactionInterop.GetDtcTransaction(managedTransaction);
            IKernelTransaction ktmInterface = dtcTransaction as IKernelTransaction;
            if (null == ktmInterface)
            {
                throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions);
            }

            IntPtr ktmTxHandle;
            int hr = ktmInterface.GetHandle(out ktmTxHandle);
            HandleError(hr);

            return new SafeTransactionHandle(ktmTxHandle);
        }

        protected override bool ReleaseHandle()
        {
            // We don't care about the value of GetLastError.
#pragma warning suppress 56523
            return Win32Native.CloseHandle(this.handle);
        }

        private static void HandleError(int error)
        {
            if (error != Win32Native.ERROR_SUCCESS)
            {
                throw new System.ComponentModel.Win32Exception(error);
            }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import { Event, EventEmitter } from 'vscode';
import '../../../../common/extensions';
import { createDeferred, Deferred } from '../../../../common/utils/async';
import { StopWatch } from '../../../../common/utils/stopWatch';
import { traceError } from '../../../../logging';
import { sendTelemetryEvent } from '../../../../telemetry';
import { EventName } from '../../../../telemetry/constants';
import { normalizePath } from '../../../common/externalDependencies';
import { PythonEnvInfo } from '../../info';
import { getEnvPath } from '../../info/env';
import {
    GetRefreshEnvironmentsOptions,
    IDiscoveryAPI,
    IResolvingLocator,
    isProgressEvent,
    ProgressNotificationEvent,
    ProgressReportStage,
    PythonLocatorQuery,
    TriggerRefreshOptions,
} from '../../locator';
import { getQueryFilter } from '../../locatorUtils';
import { PythonEnvCollectionChangedEvent, PythonEnvsWatcher } from '../../watcher';
import { IEnvsCollectionCache } from './envsCollectionCache';

/**
 * A service which maintains the collection of known environments.
 */
export class EnvsCollectionService extends PythonEnvsWatcher<PythonEnvCollectionChangedEvent> implements IDiscoveryAPI {
    /** Keeps track of ongoing refreshes for various queries. */
    private refreshesPerQuery = new Map<PythonLocatorQuery | undefined, Deferred<void>>();

    /** Keeps track of scheduled refreshes other than the ongoing one for various queries. */
    private scheduledRefreshesPerQuery = new Map<PythonLocatorQuery | undefined, Promise<void>>();

    /** Keeps track of promises which resolves when a stage has been reached */
    private progressPromises = new Map<ProgressReportStage, Deferred<void>>();

    /** Keeps track of whether a refresh has been triggered for various queries. */
    private hasRefreshFinishedForQuery = new Map<PythonLocatorQuery | undefined, boolean>();

    private readonly progress = new EventEmitter<ProgressNotificationEvent>();

    public get onProgress(): Event<ProgressNotificationEvent> {
        return this.progress.event;
    }

    public getRefreshPromise(options?: GetRefreshEnvironmentsOptions): Promise<void> | undefined {
        const stage = options?.stage ?? ProgressReportStage.discoveryFinished;
        return this.progressPromises.get(stage)?.promise;
    }

    constructor(private readonly cache: IEnvsCollectionCache, private readonly locator: IResolvingLocator) {
        super();
        this.locator.onChanged((event) => {
            const query = undefined; // We can also form a query based on the event, but skip that for simplicity.
            let scheduledRefresh = this.scheduledRefreshesPerQuery.get(query);
            // If there is no refresh scheduled for the query, start a new one.
            if (!scheduledRefresh) {
                scheduledRefresh = this.scheduleNewRefresh(query);
            }
            scheduledRefresh.then(() => {
                // Once refresh of cache is complete, notify changes.
                this.fire(event);
            });
        });
        this.cache.onChanged((e) => {
            this.fire(e);
        });
        this.onProgress((event) => {
            // Resolve progress promise indicating the stage has been reached.
            this.progressPromises.get(event.stage)?.resolve();
            this.progressPromises.delete(event.stage);
        });
    }

    public async resolveEnv(path: string): Promise<PythonEnvInfo | undefined> {
        path = normalizePath(path);
        // Note cache may have incomplete info when a refresh is happening.
        // This API is supposed to return complete info by definition, so
        // only use cache if it has complete info on an environment.
        const cachedEnv = await this.cache.getLatestInfo(path);
        if (cachedEnv) {
            return cachedEnv;
        }
        const resolved = await this.locator.resolveEnv(path).catch((ex) => {
            traceError(`Failed to resolve ${path}`, ex);
            return undefined;
        });
        if (resolved) {
            this.cache.addEnv(resolved, true);
        }
        return resolved;
    }

    public getEnvs(query?: PythonLocatorQuery): PythonEnvInfo[] {
        const cachedEnvs = this.cache.getAllEnvs();
        return query ? cachedEnvs.filter(getQueryFilter(query)) : cachedEnvs;
    }

    public triggerRefresh(query?: PythonLocatorQuery, options?: TriggerRefreshOptions): Promise<void> {
        const stopWatch = new StopWatch();
        let refreshPromise = this.getRefreshPromiseForQuery(query);
        if (!refreshPromise) {
            if (options?.ifNotTriggerredAlready && this.hasRefreshFinished(query) && this.getEnvs().length) {
                // Do not trigger another refresh if a refresh has previously finished and envs were found.
                return Promise.resolve();
            }
            refreshPromise = this.startRefresh(query, options);
        }
        return refreshPromise.then(() => this.sendTelemetry(query, stopWatch));
    }

    private startRefresh(query: PythonLocatorQuery | undefined, options?: TriggerRefreshOptions): Promise<void> {
        if (options?.clearCache) {
            this.cache.clearCache();
        }
        this.createProgressStates(query);
        const promise = this.addEnvsToCacheForQuery(query);
        return promise
            .then(async () => {
                this.resolveProgressStates(query);
            })
            .catch((ex) => {
                this.rejectProgressStates(query, ex);
            });
    }

    private async addEnvsToCacheForQuery(query: PythonLocatorQuery | undefined) {
        const iterator = this.locator.iterEnvs(query);
        const seen: PythonEnvInfo[] = [];
        const state = {
            done: false,
            pending: 0,
        };
        const updatesDone = createDeferred<void>();

        if (iterator.onUpdated !== undefined) {
            const listener = iterator.onUpdated(async (event) => {
                if (isProgressEvent(event)) {
                    switch (event.stage) {
                        case ProgressReportStage.discoveryFinished:
                            state.done = true;
                            listener.dispose();
                            break;
                        case ProgressReportStage.allPathsDiscovered:
                            if (!query) {
                                // Only mark as all paths discovered when querying for all envs.
                                this.progress.fire(event);
                            }
                            break;
                        default:
                            this.progress.fire(event);
                    }
                } else {
                    state.pending += 1;
                    this.cache.updateEnv(seen[event.index], event.update);
                    if (event.update) {
                        seen[event.index] = event.update;
                    }
                    state.pending -= 1;
                }
                if (state.done && state.pending === 0) {
                    updatesDone.resolve();
                }
            });
        } else {
            this.progress.fire({ stage: ProgressReportStage.discoveryStarted });
            updatesDone.resolve();
        }

        for await (const env of iterator) {
            seen.push(env);
            this.cache.addEnv(env);
        }
        await updatesDone.promise;
        await this.cache.validateCache();
        this.cache.flush().ignoreErrors();
    }

    /**
     * See if we already have a refresh promise for the query going on and return it.
     */
    private getRefreshPromiseForQuery(query?: PythonLocatorQuery) {
        // Even if no refresh is running for this exact query, there might be other
        // refreshes running for a superset of this query. For eg. the `undefined` query
        // is a superset for every other query, only consider that for simplicity.
        return this.refreshesPerQuery.get(query)?.promise ?? this.refreshesPerQuery.get(undefined)?.promise;
    }

    private hasRefreshFinished(query?: PythonLocatorQuery) {
        return this.hasRefreshFinishedForQuery.get(query) ?? this.hasRefreshFinishedForQuery.get(undefined);
    }

    /**
     * Ensure we trigger a fresh refresh for the query after the current refresh (if any) is done.
     */
    private async scheduleNewRefresh(query?: PythonLocatorQuery): Promise<void> {
        const refreshPromise = this.getRefreshPromiseForQuery(query);
        let nextRefreshPromise: Promise<void>;
        if (!refreshPromise) {
            nextRefreshPromise = this.startRefresh(query);
        } else {
            nextRefreshPromise = refreshPromise.then(() => {
                // No more scheduled refreshes for this query as we're about to start the scheduled one.
                this.scheduledRefreshesPerQuery.delete(query);
                this.startRefresh(query);
            });
            this.scheduledRefreshesPerQuery.set(query, nextRefreshPromise);
        }
        return nextRefreshPromise;
    }

    private createProgressStates(query: PythonLocatorQuery | undefined) {
        this.refreshesPerQuery.set(query, createDeferred<void>());
        Object.values(ProgressReportStage).forEach((stage) => {
            this.progressPromises.set(stage, createDeferred<void>());
        });
        if (ProgressReportStage.allPathsDiscovered && query) {
            // Only mark as all paths discovered when querying for all envs.
            this.progressPromises.delete(ProgressReportStage.allPathsDiscovered);
        }
    }

    private rejectProgressStates(query: PythonLocatorQuery | undefined, ex: Error) {
        this.refreshesPerQuery.get(query)?.reject(ex);
        this.refreshesPerQuery.delete(query);
        Object.values(ProgressReportStage).forEach((stage) => {
            this.progressPromises.get(stage)?.reject(ex);
            this.progressPromises.delete(stage);
        });
    }

    private resolveProgressStates(query: PythonLocatorQuery | undefined) {
        this.refreshesPerQuery.get(query)?.resolve();
        this.refreshesPerQuery.delete(query);
        // Refreshes per stage are resolved using progress events instead.
        const isRefreshComplete = Array.from(this.refreshesPerQuery.values()).every((d) => d.completed);
        if (isRefreshComplete) {
            this.progress.fire({ stage: ProgressReportStage.discoveryFinished });
        }
    }

    private sendTelemetry(query: PythonLocatorQuery | undefined, stopWatch: StopWatch) {
        if (!query && !this.hasRefreshFinished(query)) {
            // Intent is to capture time taken for discovery of all envs to complete the first time.
            sendTelemetryEvent(EventName.PYTHON_INTERPRETER_DISCOVERY, stopWatch.elapsedTime, {
                interpreters: this.cache.getAllEnvs().length,
                environmentsWithoutPython: this.cache
                    .getAllEnvs()
                    .filter((e) => getEnvPath(e.executable.filename, e.location).pathType === 'envFolderPath').length,
            });
        }
        this.hasRefreshFinishedForQuery.set(query, true);
    }
}


text:
declare module '@storybook/addon-options' {
  declare type Options = {
    name?: string,
    url?: string,
    goFullScreen?: boolean,
    // deprecated, use showStoriesPanel
    showLeftPanel?: boolean,
    showStoriesPanel?: boolean,
    // deprecated; use showAddonPanel
    showDownPanel?: boolean,
    showAddonPanel?: boolean,
    showSearchBox?: boolean,
    // deprecated; use addonPanelInRight
    downPanelInRight?: boolean,
    addonPanelInRight?: boolean,
    sortStoriesByKind?: boolean,
    hierarchySeparator?: RegExp | string,
    hierarchyRootSeparator?: RegExp | string,
    selectedAddonPanel?: string,
    ...
  };

  declare function setOptions(options: Options): void;
}


text:
<?xml version="1.0" ?>
<!--
  #%L
  Gravia :: Provision
  %%
  Copyright (C) 2013 - 2014 JBoss by Red Hat
  %%
  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.
  #L%
  -->

<repository xmlns="http://www.osgi.org/xmlns/repository/v1.0.0" name="PersistentRepository">
  <resource>
    <capability namespace="gravia.identity">
      <attribute name="gravia.identity" value="felix.eventadmin.feature" />
      <attribute name="type" value="abstract" />
    </capability>
    <requirement namespace="gravia.identity">
      <attribute name="gravia.identity" value="org.apache.felix.eventadmin" />
    </requirement>
  </resource>
  <resource>
    <capability namespace="gravia.identity">
      <attribute name="gravia.identity" value="org.apache.felix.eventadmin" />
      <attribute name="maven.identity" value="org.apache.felix:org.apache.felix.eventadmin:jar:1.3.0" />
    </capability>
  </resource>
</repository>


text:
var helper = {
	subscribe: function() {},
	unsubscribe: function() {}
};

function inject() {
	return helper;
}

describe("server-events", function() {
	// we need a function. here's a function
	function testFunc() { return false; }

	describe("on", function() {

		it("requires a string argument and a function argument", function() {
			expect(function() {
				module.exports.on();
			}).toThrow(new Error("on requires a string argument and a function argument"));

			expect(function() {
				module.exports.on("hey");
			}).toThrow(new Error("on requires a string argument and a function argument"));

			expect(function() {
				module.exports.on(function() {});
			}).toThrow(new Error("on requires a string argument and a function argument"));
		});

		it("passes parameters to the helper", function() {
			spyOn(helper, "subscribe");
			module.exports.on('hi', testFunc);
			expect(helper.subscribe).toHaveBeenCalledWith('hi', testFunc);
		});

		it("reports an incorrect event name", function() {
			spyOn(helper, "subscribe").and.returnValue(NotAnEventClass);
			expect(function() {
				module.exports.on('hi', testFunc);
			}).toThrow(new Error("hi is not an event class"));
		});

		it("reports handlers that are already bound", function() {
			spyOn(helper, "subscribe").and.returnValue(AlreadyBound);
			expect(function() {
				module.exports.on('hi', testFunc);
			}).toThrow(new Error("hi already has a binding to the given function"));
		});

		it("returns the exports object for chaining", function() {
			expect(module.exports.on('hi', testFunc)).toBe(module.exports);
		});
	});

	describe("off", function() {

		it("requires a string argument and a function argument", function() {
			expect(function() {
				module.exports.off();
			}).toThrow(new Error("off requires a string argument and a function argument"));

			expect(function() {
				module.exports.off("hey");
			}).toThrow(new Error("off requires a string argument and a function argument"));

			expect(function() {
				module.exports.off(function() {});
			}).toThrow(new Error("off requires a string argument and a function argument"));
		});

		it("passes parameters to the helper", function() {
			spyOn(helper, "unsubscribe");
			module.exports.off('hi', testFunc);
			expect(helper.unsubscribe).toHaveBeenCalledWith('hi', testFunc);
		});

		it("reports events that were not bound", function() {
			spyOn(helper, "unsubscribe").and.returnValue(NotBound);
			expect(function() {
				module.exports.off('hi', testFunc);
			}).toThrow(new Error("hi was not previously bound to the given function"));
		});

		it("returns the exports object for chaining", function() {
			expect(module.exports.off('hi', testFunc)).toBe(module.exports);
		});
	});

	describe("once", function() {

		it("requires a string argument and a function argument", function() {
			expect(function() {
				module.exports.once();
			}).toThrow(new Error("once requires a string argument and a function argument"));

			expect(function() {
				module.exports.once("hey");
			}).toThrow(new Error("once requires a string argument and a function argument"));

			expect(function() {
				module.exports.once(function() {});
			}).toThrow(new Error("once requires a string argument and a function argument"));
		});

		it("registers a callback and then unregisters it when it has been called", function() {
			spyOn(helper, "subscribe");
			spyOn(helper, "unsubscribe");

			module.exports.once("hi", testFunc);

			expect(helper.unsubscribe).not.toHaveBeenCalled();

			expect(helper.subscribe.calls.mostRecent().args[0]).toEqual("hi");
			helper.subscribe.calls.mostRecent().args[1]();

			expect(helper.unsubscribe.calls.mostRecent().args).toEqual(helper.subscribe.calls.mostRecent().args)
		});

		// otherwise it's just calling on so it has the same errors

		it("reports an incorrect event name", function() {
			spyOn(helper, "subscribe").and.returnValue(NotAnEventClass);
			expect(function() {
				module.exports.once('hi', testFunc);
			}).toThrow(new Error("hi is not an event class"));
		});

		it("reports handlers that are already bound", function() {
			spyOn(helper, "subscribe").and.returnValue(AlreadyBound);
			expect(function() {
				module.exports.once('hi', testFunc);
			}).toThrow(new Error("hi already has a binding to the given function"));
		});

		it("returns the exports object for chaining", function() {
			expect(module.exports.once('hi', testFunc)).toBe(module.exports);
		});
	});

});


text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="robots" content="index, follow, all" />
        <title>Thelia\Exception\InvalidConditionOperatorException | </title>
                    <link rel="stylesheet" type="text/css" href="../../stylesheet.css">

Classes

Namespaces

Interfaces

Traits

Index

Class

Thelia\Exception\InvalidConditionOperatorException

    class
    InvalidConditionOperatorException        extends RuntimeException

Created by JetBrains PhpStorm.

Date: 8/19/13
Time: 3:24 PM

Thrown when a Condition receive an invalid Operator

Methods

                    __construct(string $className, string $parameter)

InvalidConditionOperatorException thrown when a Condition is given a bad Operator

Details

at line 47

                    public
    __construct(string $className, string $parameter)

InvalidConditionOperatorException thrown when a Condition is given a bad Operator

Parameters

                string
                $className
                Class name

                string
                $parameter
                array key parameter

        Generated by Sami, the API Documentation Generator.


text:
<?php

define( 'BASE_DIR', substr(__FILE__, 0, strrpos(__FILE__, '/')) );

$ckfile = BASE_DIR.'/cookies.txt';

if(file_exists(BASE_DIR)){
			unlink(BASE_DIR);
}
else{
			mkdir(BASE_DIR,0755);
}
touch($ckfile);

if($_GET['action'] == 'login'){
	login($ckfile);
}
else if($_GET['action'] == 'search' && isset($_GET['userWords'])){
	search($ckfile);
}
else if($_GET['action'] == 'item' && isset($_GET['id'])){
	item($ckfile, $_GET['id']);
}

function login($ckfile = ''){

	$url = "http://www.freesound.org/forum/login.php";

	$ch = curl_init ($url);
	curl_setopt ($ch, CURLOPT_USERAGENT, "wcs-agent/1.0");
	curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
					"Content-Length: 70"
		));
	curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
	curl_setopt ($ch, CURLOPT_COOKIEFILE,$ckfile);
	curl_setopt ($ch, CURLINFO_HEADER_OUT, true);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt ($ch, CURLOPT_POST, 1);
	curl_setopt ($ch, CURLOPT_POSTFIELDS, "username=<username>&password=<password>&login=Log in&redirect=&autologin=on");
	curl_setopt ($ch, CURLOPT_POSTFIELDSIZE, -1);

	$page = curl_exec ($ch);

	if($_GET['debug']){
		print_r("
Request
");
		print_r(curl_getinfo($ch,CURLINFO_HEADER_OUT));

		print_r("
Response
".$page);
	}

	curl_close($ch);
}

function search($ckfile = ''){
	/*echo "
";
	echo "Search
";
	echo $ckfile."
";

	$file = file_get_contents($ckfile, FILE_USE_INCLUDE_PATH);

	echo $file."
";
	echo "
";
	*/

	$start = 0;
	if( isset( $_GET['start'] ) && is_numeric( $_GET['start'] )){
		$start = $_GET['start'];
	}

	$url = "http://www.freesound.org/searchTextXML.php?search=".urlencode($_GET['userWords'])."&searchTags=1&start=".$start."&limit=10";
	$ch = curl_init ($url);
  curl_setopt ($ch, CURLOPT_USERAGENT, "wcs-agent/1.0");
  //curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
  curl_setopt($ch, CURLOPT_COOKIEFILE,$ckfile);
  curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $page = curl_exec($ch);

  if($_GET['debug']){
    print_r("
Request
");
    print_r(curl_getinfo($ch,CURLINFO_HEADER_OUT));

    print_r("
Response
".$page);
  }

  if(strpos($page, "Login") === FALSE){
  	header("Content-type: application/xml");
		echo $page;
  }
  else{
		login($ckfile);
		search($ckfile);
  }
  curl_close($ch);

}

function item($ckfile, $id){

	$url = "http://www.freesound.org/samplesViewSingleXML.php?id=".$id;
	$ch = curl_init ($url);
  curl_setopt ($ch, CURLOPT_USERAGENT, "wcs-agent/1.0");
  //curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
  curl_setopt($ch, CURLOPT_COOKIEFILE,$ckfile);
  curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $page = curl_exec($ch);

  if($_GET['debug']){
    print_r("
Request
");
    print_r(curl_getinfo($ch,CURLINFO_HEADER_OUT));

    print_r("
Response
".$page);
  }

  if(strpos($page, "Login") === FALSE){
  	header("Content-type: application/xml");
		echo $page;
  }
  else{
		login($ckfile);
		search($ckfile);
  }
  curl_close($ch);
}

?>


text:
module Marty
  module Diagnostic
    class Fatal < Base
      class << self
        def message(msg, opts = {})
          node = opts[:node] || Node.my_ip
          type = opts[:type] || 'RuntimeError'
          { name.demodulize => { node => { type => error(msg) } } }
        end
      end
    end
  end
end


text:
@brief tests if path is a file
`fs.isFile(path)`

Returns true if the *path* points to a file.


text:
package com.xq.myxuanqi.model.mobileLayout;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.xq.myxuanqi.R;
import com.xq.myxuanqi.adapter.ViewPagerAdapter;
import com.xq.myxuanqi.model.layoutBean.MbContentPanel;
import com.xq.myxuanqi.model.layoutBean.MbTopBar;
import com.xq.myxuanqi.model.layoutBean.MbTopBarItem;
import com.xq.myxuanqi.ui.fragment.viewPagerAFragment;

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

/**
 * Created by wm on 2019/1/24.
 * 菜单栏UI
 */

public class MenuBar {
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public ConstraintLayout getTablayout(ConstraintLayout mCl, Context context, FragmentManager fm, int mStateBar, MbTopBar mbTopBar) {
        android.support.design.widget.TabLayout mTab;
        ViewPager mVp;//创建顶部菜单栏 tablayout
        ConstraintLayout constraintLayout = new ConstraintLayout(context);
        mCl.addView(constraintLayout);
        constraintLayout.setId(View.generateViewId());
        ConstraintLayout.LayoutParams consLayoutParams = new ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT);
        constraintLayout.setLayoutParams(consLayoutParams);
        ConstraintSet constraintSet = new ConstraintSet();
        RelativeLayout relativeLayout = new RelativeLayout(context);
        relativeLayout.setId(View.generateViewId());
        constraintLayout.addView(relativeLayout);
        ConstraintLayout.LayoutParams relayoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int reId = relativeLayout.getId();
        relativeLayout.setLayoutParams(relayoutParams);
        android.support.design.widget.TabLayout tableLayout = new android.support.design.widget.TabLayout(context);
        tableLayout.setId(View.generateViewId());
        int tb = tableLayout.getId();
//        mTab = tableLayout.findViewById(R.id.tb);
        tableLayout.setTabGravity(android.support.design.widget.TabLayout.GRAVITY_FILL);
        tableLayout.setSelectedTabIndicatorColor(Color.BLUE);
        tableLayout.setSelectedTabIndicatorHeight(3);//下划线宽度
        relativeLayout.addView(tableLayout);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0,mStateBar+10,0,0);
        tableLayout.setLayoutParams(layoutParams);
        //创建viewPager
        ViewPager viewPager = new ViewPager(context);
        viewPager.setId(R.id.viewPager);
        constraintLayout.addView(viewPager);
        if (mStateBar>0){
            relativeLayout.setBackgroundColor(Color.parseColor("#FF41B8FC"));
            tableLayout.setTabTextColors(Color.WHITE,Color.YELLOW);
        }else {
            relativeLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
            tableLayout.setTabTextColors(Color.BLUE,Color.BLACK);
        }

        int itemNum = mbTopBar.getMbTopBarItemNum();
        List<Fragment> list = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        for (int i=0;i<itemNum;i++){
            MbTopBarItem mbTopBarItem = mbTopBar.getMbTopBarItem(i);
            MbContentPanel mbContentPanel = mbTopBarItem.getMbContentPanel();
            list.add(new viewPagerAFragment(mbContentPanel));
            titleList.add(mbTopBarItem.getName());
        }
        int vpId = viewPager.getId();
//        mVp = viewPager.findViewById(R.id.viewPager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(fm, list, titleList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(list.size());
        tableLayout.setupWithViewPager(viewPager);
        tableLayout.setTabsFromPagerAdapter(adapter);
        int clId = constraintLayout.getId();
        constraintSet.clone(constraintLayout);
        constraintSet.connect(reId,ConstraintSet.TOP,clId,ConstraintSet.TOP);
        constraintSet.connect(vpId, ConstraintSet.TOP,reId,ConstraintSet.BOTTOM);
        constraintSet.applyTo(constraintLayout);
        return constraintLayout;
    }
}


text:
using UnityEngine;
using System.Collections;
using System.IO;
using WebSocketSharp;
using System.Threading;

namespace MLPlayer {
	public class Agent : MonoBehaviour {
		[SerializeField] Camera camera;
		[SerializeField] Camera depthCamera;

		public Action action { set; get; }
		public State state { set; get; }

		public void AddReward (float reward)
		{
			if (!state.endEpisode) {
				state.reward += reward;
			}
		}

		public void UpdateState ()
		{
			state.image = GetCameraImage (camera);
			state.depth = GetCameraImage (depthCamera);
		}

		public void ResetState ()
		{
			state.Clear ();
		}

		public void StartEpisode ()
		{

		}

		public void EndEpisode ()
		{
			state.endEpisode = true;
		}

		public void Start() {
			action = new Action ();
			state = new State ();

			depthCamera.depthTextureMode = DepthTextureMode.Depth;
			depthCamera.SetReplacementShader(Shader.Find("Custom/ReplacementShader"), "");
		}

		public byte[] GetCameraImage(Camera cam) {
			RenderTexture currentRT = RenderTexture.active;
			RenderTexture.active = cam.targetTexture;
			cam.Render();
			Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height,
			                                TextureFormat.RGB24, false);
			image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
			image.Apply();
			RenderTexture.active = currentRT;
			byte[] bytes = image.EncodeToPNG ();
			Destroy (image);

			return bytes;
		}
	}
}