text:
from __future__ import division
from __future__ import print_function
import sys
import argparse
import binascii
import random
import struct
import os
import array
import csv
import zlib
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

""" Class for standard NVS page structure """
class Page(object):
    PAGE_PARAMS = {
        "max_size": 4096,
        "max_old_blob_size": 1984,
        "max_new_blob_size": 4000,
        "max_entries": 126
    }

    # Item type codes
    U8   = 0x01
    I8   = 0x11
    U16  = 0x02
    I16  = 0x12
    U32  = 0x04
    I32  = 0x14
    SZ   = 0x21
    BLOB = 0x41
    BLOB_DATA = 0x42
    BLOB_IDX = 0x48

    # Few Page constants
    HEADER_SIZE = 32
    BITMAPARRAY_OFFSET = 32
    BITMAPARRAY_SIZE_IN_BYTES = 32
    FIRST_ENTRY_OFFSET = 64
    SINGLE_ENTRY_SIZE = 32
    CHUNK_ANY = 0xFF
    ACTIVE = 0xFFFFFFFE
    FULL = 0xFFFFFFFC
    VERSION1=0xFF
    VERSION2=0xFE

    def __init__(self, page_num, is_rsrv_page=False):
        self.entry_num = 0
        self.is_encrypt = False
        self.encr_key = None
        self.bitmap_array = array.array('B')
        self.version = Page.VERSION2
        self.page_buf = bytearray(b'\xff')*Page.PAGE_PARAMS["max_size"]
        if not is_rsrv_page:
            self.bitmap_array = self.create_bitmap_array()
            self.set_header(page_num)

    def set_header(self, page_num):
        global page_header

        # set page state to active
        page_header= bytearray(b'\xff')*32
        page_state_active_seq = Page.ACTIVE
        page_header[0:4] = struct.pack('<I', page_state_active_seq)
        # set page sequence number
        page_header[4:8] = struct.pack('<I', page_num)
        # set version
        if version == Page.VERSION2:
            page_header[8] = Page.VERSION2
        elif version == Page.VERSION1:
            page_header[8] = Page.VERSION1
        # set header's CRC
        crc_data = page_header[4:28]
        crc = zlib.crc32(buffer(crc_data), 0xFFFFFFFF)
        page_header[28:32] = struct.pack('<I', crc & 0xFFFFFFFF)
        self.page_buf[0:len(page_header)] = page_header

    def create_bitmap_array(self):
        bitarray = array.array('B')
        charsize = 32 # bitmaparray has 256 bits, hence 32 bytes
        fill = 255 # Fill all 8 bits with 1's
        bitarray.extend((fill,) * charsize)
        return bitarray

    def write_bitmaparray(self):
        bitnum = self.entry_num * 2
        byte_idx = bitnum // 8 # Find byte index in the array
        bit_offset = bitnum & 7 # Find bit offset in given byte index
        mask = ~(1 << bit_offset)
        self.bitmap_array[byte_idx] &= mask
        start_idx = Page.BITMAPARRAY_OFFSET
        end_idx = Page.BITMAPARRAY_OFFSET + Page.BITMAPARRAY_SIZE_IN_BYTES
        self.page_buf[start_idx:end_idx] = self.bitmap_array

    def encrypt_entry(self, data_arr, tweak_arr, encr_key):
        # Encrypt 32 bytes of data using AES-XTS encryption
        backend = default_backend()
        plain_text = data_arr.decode('hex')
        tweak = tweak_arr.decode('hex')
        cipher = Cipher(algorithms.AES(encr_key), modes.XTS(tweak), backend=backend)
        encryptor = cipher.encryptor()
        encrypted_data = encryptor.update(plain_text)

        return encrypted_data

    def reverse_hexbytes(self, addr_tmp):
        addr = []
        reversed_bytes = ""
        for i in range(0, len(addr_tmp), 2):
            addr.append(addr_tmp[i:i+2])
        reversed_bytes = "".join(reversed(addr))

        return reversed_bytes

    def encrypt_data(self, data_input, no_of_entries, nvs_obj):
        # Set values needed for encryption and encrypt data byte wise
        encr_data_to_write = ''
        data_len_needed = 64 #in hex
        tweak_len_needed = 32 #in hex
        init_tweak_val = '0'
        init_data_val = 'f'
        tweak_tmp = ''
        encr_key_input = None

        # Extract encryption key and tweak key from given key input
        encr_key_input = self.encr_key.decode('hex')

        rel_addr = nvs_obj.page_num * Page.PAGE_PARAMS["max_size"] + Page.FIRST_ENTRY_OFFSET

        if type(data_input) != bytearray:
            byte_arr = bytearray('\xff') * 32
            byte_arr[0:len(data_input)] = data_input
            data_input = byte_arr

        data_input = binascii.hexlify(bytearray(data_input))

        entry_no = self.entry_num
        start_idx = 0
        end_idx = start_idx + 64

        for _ in range(0, no_of_entries):
            # Set tweak value
            offset = entry_no * Page.SINGLE_ENTRY_SIZE
            addr = hex(rel_addr + offset)[2:]
            addr_len = len(addr)
            if addr_len > 2:
                if not addr_len % 2:
                    addr_tmp = addr
                    tweak_tmp = self.reverse_hexbytes(addr_tmp)
                    tweak_val = tweak_tmp + (init_tweak_val * (tweak_len_needed - (len(tweak_tmp))))
                else:
                    addr_tmp = init_tweak_val + addr
                    tweak_tmp = self.reverse_hexbytes(addr_tmp)
                    tweak_val = tweak_tmp + (init_tweak_val * (tweak_len_needed - (len(tweak_tmp))))
            else:
                tweak_val = addr + (init_tweak_val * (tweak_len_needed - len(addr)))

            # Encrypt data
            data_bytes = data_input[start_idx:end_idx]
            data_val = data_bytes + (init_data_val * (data_len_needed - len(data_bytes)))
            encr_data_ret = self.encrypt_entry(data_val, tweak_val, encr_key_input)
            encr_data_to_write = encr_data_to_write + encr_data_ret
            # Update values for encrypting next set of data bytes
            start_idx = end_idx
            end_idx = start_idx + 64
            entry_no += 1

        return encr_data_to_write

    def write_entry_to_buf(self, data, entrycount,nvs_obj):
        encr_data = bytearray()
        if self.is_encrypt:
            encr_data_ret = self.encrypt_data(data, entrycount,nvs_obj)
            encr_data[0:len(encr_data_ret)] = encr_data_ret
            data = encr_data

        data_offset = Page.FIRST_ENTRY_OFFSET + (Page.SINGLE_ENTRY_SIZE * self.entry_num)
        start_idx = data_offset
        end_idx = data_offset + len(data)
        self.page_buf[start_idx:end_idx]  = data

        # Set bitmap array for entries in current page
        for i in range(0, entrycount):
            self.write_bitmaparray()
            self.entry_num += 1

    def set_crc_header(self, entry_struct):
        crc_data = bytearray(28)
        crc_data[0:4] = entry_struct[0:4]
        crc_data[4:28] = entry_struct[8:32]
        crc = zlib.crc32(buffer(crc_data), 0xFFFFFFFF)
        entry_struct[4:8] = struct.pack('<I', crc & 0xFFFFFFFF)
        return entry_struct

    def write_varlen_binary_data(self, entry_struct, ns_index, key, data, data_size, total_entry_count,nvs_obj):
        chunk_start = 0
        chunk_count = 0
        chunk_index = Page.CHUNK_ANY
        offset = 0
        remaining_size = data_size
        tailroom = None

        while True:
            chunk_size = 0

            # Get the size available in current page
            tailroom = (Page.PAGE_PARAMS["max_entries"] - self.entry_num - 1) * Page.SINGLE_ENTRY_SIZE
            assert tailroom >=0, "Page overflow!!"

            # Split the binary data into two and store a chunk of available size onto curr page
            if tailroom < remaining_size:
                chunk_size = tailroom
            else:
                chunk_size = remaining_size

            remaining_size = remaining_size - chunk_size

            # Change type of data to BLOB_DATA
            entry_struct[1] = Page.BLOB_DATA

            # Calculate no. of entries data chunk will require
            datachunk_rounded_size = (chunk_size + 31) & ~31
            datachunk_entry_count = datachunk_rounded_size // 32
            datachunk_total_entry_count = datachunk_entry_count + 1 # +1 for the entry header

            # Set Span
            entry_struct[2] = datachunk_total_entry_count

            # Update the chunkIndex
            chunk_index = chunk_start + chunk_count
            entry_struct[3] = chunk_index

            # Set data chunk
            data_chunk =  data[offset:offset + chunk_size]

            # Compute CRC of data chunk
            entry_struct[24:26] = struct.pack('<H', chunk_size)
            crc = zlib.crc32(data_chunk, 0xFFFFFFFF)
            entry_struct[28:32] = struct.pack('<I', crc & 0xFFFFFFFF)

            # compute crc of entry header
            entry_struct = self.set_crc_header(entry_struct)

            # write entry header
            self.write_entry_to_buf(entry_struct, 1,nvs_obj)
            # write actual data
            self.write_entry_to_buf(data_chunk, datachunk_entry_count,nvs_obj)

            chunk_count = chunk_count + 1

            if remaining_size or (tailroom - chunk_size) < Page.SINGLE_ENTRY_SIZE:
                if page_header[0:4] != Page.FULL:
                    page_state_full_seq = Page.FULL
                    page_header[0:4] = struct.pack('<I', page_state_full_seq)
                nvs_obj.create_new_page()
                self = nvs_obj.cur_page

            offset = offset + chunk_size

            # All chunks are stored, now store the index
            if not remaining_size:
                # Initialise data field to 0xff
                data_array = bytearray('\xff')*8
                entry_struct[24:32] = data_array

                # change type of data to BLOB_IDX
                entry_struct[1] = Page.BLOB_IDX

                # Set Span
                entry_struct[2] = 1

                # Update the chunkIndex
                chunk_index = Page.CHUNK_ANY
                entry_struct[3] = chunk_index

                entry_struct[24:28] = struct.pack('<I', data_size)
                entry_struct[28] = chunk_count
                entry_struct[29] = chunk_start

                # compute crc of entry header
                entry_struct = self.set_crc_header(entry_struct)

                # write last entry
                self.write_entry_to_buf(entry_struct, 1,nvs_obj)
                break

        return entry_struct

    def write_single_page_entry(self, entry_struct, data, datalen, data_entry_count, nvs_obj):
        # compute CRC of data
        entry_struct[24:26] = struct.pack('<H', datalen)
        crc = zlib.crc32(data, 0xFFFFFFFF)
        entry_struct[28:32] = struct.pack('<I', crc & 0xFFFFFFFF)

        # compute crc of entry header
        entry_struct = self.set_crc_header(entry_struct)

        # write entry header
        self.write_entry_to_buf(entry_struct, 1, nvs_obj)
        # write actual data
        self.write_entry_to_buf(data, data_entry_count, nvs_obj)

    """
    Low-level function to write variable length data into page buffer. Data should be formatted
    according to encoding specified.
    """
    def write_varlen_data(self, key, data, encoding, ns_index,nvs_obj):
        # Set size of data
        datalen = len(data)

        if version == Page.VERSION1:
            if datalen > Page.PAGE_PARAMS["max_old_blob_size"]:
                raise InputError("%s: Size exceeds max allowed length." % key)

        if version == Page.VERSION2:
            if encoding == "string":
                if datalen > Page.PAGE_PARAMS["max_new_blob_size"]:
                    raise InputError("%s: Size exceeds max allowed length." % key)

        # Calculate no. of entries data will require
        rounded_size = (datalen + 31) & ~31
        data_entry_count = rounded_size // 32
        total_entry_count = data_entry_count + 1 # +1 for the entry header

        # Check if page is already full and new page is needed to be created right away
        if encoding == "string":
            if (self.entry_num + total_entry_count) >= Page.PAGE_PARAMS["max_entries"]:
                raise PageFullError()

        # Entry header
        entry_struct = bytearray('\xff')*32
        # Set Namespace Index
        entry_struct[0] = ns_index
        # Set Span
        if version == Page.VERSION2:
            if encoding == "string":
                entry_struct[2] = data_entry_count + 1
            # Set Chunk Index
            chunk_index = Page.CHUNK_ANY
            entry_struct[3] = chunk_index
        else:
            entry_struct[2] = data_entry_count + 1

        # set key
        key_array = bytearray('\x00')*16
        entry_struct[8:24] = key_array
        entry_struct[8:8 + len(key)] = key

        # set Type
        if encoding == "string":
            entry_struct[1] = Page.SZ
        elif encoding in ["hex2bin", "binary", "base64"]:
            entry_struct[1] = Page.BLOB

        if version == Page.VERSION2 and (encoding in ["hex2bin", "binary", "base64"]):
                entry_struct = self.write_varlen_binary_data(entry_struct,ns_index,key,data,\
                datalen,total_entry_count, nvs_obj)
        else:
            self.write_single_page_entry(entry_struct, data, datalen, data_entry_count, nvs_obj)

    """ Low-level function to write data of primitive type into page buffer. """
    def write_primitive_data(self, key, data, encoding, ns_index,nvs_obj):
        # Check if entry exceeds max number of entries allowed per page
        if self.entry_num >= Page.PAGE_PARAMS["max_entries"]:
            raise PageFullError()

        entry_struct = bytearray('\xff')*32
        entry_struct[0] = ns_index # namespace index
        entry_struct[2] = 0x01 # Span
        chunk_index = Page.CHUNK_ANY
        entry_struct[3] = chunk_index

        # write key
        key_array = bytearray('\x00')*16
        entry_struct[8:24] = key_array
        entry_struct[8:8 + len(key)] = key

        if encoding == "u8":
            entry_struct[1] = Page.U8
            entry_struct[24] = struct.pack('<B', data)
        elif encoding == "i8":
            entry_struct[1] = Page.I8
            entry_struct[24] = struct.pack('<b', data)
        elif encoding == "u16":
            entry_struct[1] = Page.U16
            entry_struct[24:26] = struct.pack('<H', data)
        elif encoding == "u32":
            entry_struct[1] = Page.U32
            entry_struct[24:28] = struct.pack('<I', data)
        elif encoding == "i32":
            entry_struct[1] = Page.I32
            entry_struct[24:28] = struct.pack('<i', data)

        # Compute CRC
        crc_data = bytearray(28)
        crc_data[0:4] = entry_struct[0:4]
        crc_data[4:28] = entry_struct[8:32]
        crc = zlib.crc32(buffer(crc_data), 0xFFFFFFFF)
        entry_struct[4:8] = struct.pack('<I', crc & 0xFFFFFFFF)

        # write to file
        self.write_entry_to_buf(entry_struct, 1,nvs_obj)

    """ Get page buffer data of a given page """
    def get_data(self):
        return self.page_buf

"""
NVS class encapsulates all NVS specific operations to create a binary with given key-value pairs. Binary can later be flashed onto device via a flashing utility.
"""
class NVS(object):
    def __init__(self, fout, input_size):
        self.size = input_size
        self.namespace_idx = 0
        self.page_num = -1
        self.pages = []
        self.cur_page = self.create_new_page()
        self.fout = fout

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type == None and exc_value == None:
            # Create pages for remaining available size
            while True:
                try:
                    new_page = self.create_new_page()
                except InsufficientSizeError:
                    self.size = None
                    # Creating the last reserved page
                    self.create_new_page(is_rsrv_page=True)
                    break

            result = self.get_binary_data()
            self.fout.write(result)

    def create_new_page(self, is_rsrv_page=False):
        # Update available size as each page is created
        if self.size == 0:
            raise InsufficientSizeError("Size parameter is is less than the size of data in csv.Please increase size.")
        if not is_rsrv_page:
            self.size = self.size - Page.PAGE_PARAMS["max_size"]
        self.page_num += 1
        new_page = Page(self.page_num, is_rsrv_page)
        new_page.version = version
        new_page.is_encrypt = is_encrypt_data
        new_page.encr_key = key_input
        self.pages.append(new_page)
        self.cur_page = new_page
        return new_page

    """
    Write namespace entry and subsequently increase namespace count so that all upcoming entries
    will be mapped to a new namespace.
    """
    def write_namespace(self, key):
        self.namespace_idx += 1
        try:
            self.cur_page.write_primitive_data(key, self.namespace_idx, "u8", 0,self)
        except PageFullError:
            new_page = self.create_new_page()
            new_page.write_primitive_data(key, self.namespace_idx, "u8", 0,self)
            pass

    """
    Write key-value pair. Function accepts value in the form of ascii character and converts
    it into appropriate format before calling Page class's functions to write entry into NVS format.
    Function handles PageFullError and creates a new page and re-invokes the function on a new page.
    We don't have to guard re-invocation with try-except since no entry can span multiple pages.
    """
    def write_entry(self, key, value, encoding):
        if encoding == "hex2bin":
            if len(value) % 2 != 0:
                raise InputError("%s: Invalid data length. Should be multiple of 2." % key)
            value = binascii.a2b_hex(value)

        if encoding == "base64":
            value = binascii.a2b_base64(value)

        if encoding == "string":
            value += '\0'

        encoding = encoding.lower()
        varlen_encodings = ["string", "binary", "hex2bin", "base64"]
        primitive_encodings = ["u8", "i8", "u16", "u32", "i32"]
        if encoding in varlen_encodings:
            try:
                self.cur_page.write_varlen_data(key, value, encoding, self.namespace_idx,self)
            except PageFullError:
                new_page = self.create_new_page()
                new_page.write_varlen_data(key, value, encoding, self.namespace_idx,self)
                pass
        elif encoding in primitive_encodings:
            try:
                self.cur_page.write_primitive_data(key, int(value), encoding, self.namespace_idx,self)
            except PageFullError:
                new_page = self.create_new_page()
                new_page.write_primitive_data(key, int(value), encoding, self.namespace_idx,self)
                sys.exc_clear()
                pass
        else:
            raise InputError("%s: Unsupported encoding" % encoding)

    """ Return accumulated data of all pages """
    def get_binary_data(self):
        data = bytearray()
        for page in self.pages:
            data += page.get_data()
        return data

class PageFullError(RuntimeError):
    """
    Represents error when current page doesn't have sufficient entries left
    to accommodate current request
    """
    def __init__(self):
       super(PageFullError, self).__init__()

class InputError(RuntimeError):
    """
    Represents error on the input
    """
    def __init__(self, e):
        super(InputError, self).__init__(e)

class InsufficientSizeError(RuntimeError):
    """
    Represents error when NVS Partition size given is insufficient
    to accomodate the data in the given csv file
    """
    def __init__(self, e):
       super(InsufficientSizeError, self).__init__(e)

def nvs_open(result_obj, input_size):
    """ Wrapper to create and NVS class object. This object can later be used to set key-value pairs

    :param result_obj: File/Stream object to dump resultant binary. If data is to be dumped into memory, one way is to use BytesIO object
    :param input_size: Size of Partition
    :return: NVS class instance
    """
    return NVS(result_obj, input_size)

def write_entry(nvs_instance, key, datatype, encoding, value):
    """ Wrapper to set key-value pair in NVS format

    :param nvs_instance: Instance of an NVS class returned by nvs_open()
    :param key: Key of the data
    :param datatype: Data type. Valid values are "file", "data" and "namespace"
    :param encoding: Data encoding. Valid values are "u8", "i8", "u16", "u32", "i32", "string", "binary", "hex2bin" and "base64"
    :param value: Data value in ascii encoded string format for "data" datatype and filepath for "file" datatype
    :return: None
    """

    if datatype == "file":
        abs_file_path = value
        if os.path.isabs(value) == False:
            script_dir = os.path.dirname(__file__)
            abs_file_path = os.path.join(script_dir, value)
        with open(abs_file_path, 'rb') as f:
            value = f.read()

    if datatype == "namespace":
        nvs_instance.write_namespace(key)
    else:
        nvs_instance.write_entry(key, value, encoding)

def nvs_close(nvs_instance):
    """ Wrapper to finish writing to NVS and write data to file/stream object provided to nvs_open method

    :param nvs_instance: Instance of NVS class returned by nvs_open()
    :return: None
    """
    nvs_instance.__exit__(None, None, None)

def nvs_part_gen(input_filename=None, output_filename=None, input_size=None, key_gen=None, encrypt_mode=None, key_file=None, version_no=None):
    """ Wrapper to generate nvs partition binary

    :param input_filename: Name of input file containing data
    :param output_filename: Name of output file to store generated binary
    :param input_size: Size of partition
    :param key_gen: Enable encryption key generation in encryption mode
    :param encryption_mode: Enable/Disable encryption mode
    :param key_file: Input file having encryption keys in encryption mode
    :return: None
    """
    global version, is_encrypt_data, key_input
    version = version_no
    key_input = None
    is_encrypt_data = encrypt_mode

    # Set size
    input_size = int(input_size.split('KB')[0]) * 1024

    if input_size % 4096 !=0:
        sys.exit("Size parameter should be a multiple of 4KB.")

    if version == 'v1':
        version = Page.VERSION1
    elif version == 'v2':
        version = Page.VERSION2

    # Update size as a page needs to be reserved of size 4KB
    input_size = input_size - Page.PAGE_PARAMS["max_size"]

    if input_size == 0:
        sys.exit("Size parameter is insufficient.")

    if is_encrypt_data == 'True':
        is_encrypt_data = True
    elif is_encrypt_data == 'False':
        is_encrypt_data = False

    if key_gen == 'True':
        key_gen = True
    elif key_gen == 'False':
        key_gen = False

    if is_encrypt_data and not key_gen and not key_file:
        sys.exit("Missing parameter. Enter --keyfile or --keygen.")

    if is_encrypt_data and key_gen and key_file:
        sys.exit("Only one input allowed. Enter --keyfile or --keygen.")

    if not is_encrypt_data and key_gen:
        sys.exit("Invalid. Cannot give --key_gen as --encrypt is set to False.")

    if not is_encrypt_data and key_file:
        sys.exit("Invalid. Cannot give --key_file as --encrypt is set to False.")

    if key_gen:
        key_input = ''.join(random.choice('0123456789abcdef') for _ in xrange(128))
    elif key_file:
        with open(key_file) as key_f:
            key_input = key_f.readline()
            key_input = key_input.strip()

    input_file = open(input_filename, 'rb')
    output_file = open(output_filename, 'wb')

    with nvs_open(output_file, input_size) as nvs_obj:
        reader = csv.DictReader(input_file, delimiter=',')
        for row in reader:
            try:
                write_entry(nvs_obj, row["key"], row["type"], row["encoding"], row["value"])
            except (InputError) as e:
                print(e)
                input_file.close()
                output_file.close()
                sys.exit(-2)

    input_file.close()
    output_file.close()

    if is_encrypt_data:
        output_keys_file = open("encryption_keys.bin",'wb')
        keys_page_buf = bytearray(b'\xff')*Page.PAGE_PARAMS["max_size"]
        key_bytes = key_input.decode('hex')
        key_len = len(key_bytes)
        keys_page_buf[0:key_len] = key_bytes
        crc_data = keys_page_buf[0:key_len]
        crc = zlib.crc32(buffer(crc_data), 0xFFFFFFFF)
        keys_page_buf[64:68] = struct.pack('<I', crc & 0xFFFFFFFF)
        output_keys_file.write(keys_page_buf)

def main():
    parser = argparse.ArgumentParser(description="ESP32 NVS partition generation utility")
    parser.add_argument(
            "input",
            help="Path to CSV file to parse. Will use stdin if omitted",
            default=sys.stdin)

    parser.add_argument(
            "output",
            help='Path to output converted binary file. Will use stdout if omitted',
            default=sys.stdout)

    parser.add_argument(
            "size",
            help='Size of NVS Partition in KB. Eg. 12KB')

    parser.add_argument(
            "--version",
            help='Set version. Default: v2',
            choices=['v1','v2'],
            default='v2')

    parser.add_argument(
            "--keygen",
            help='Generate keys for encryption. Default: False (Applicable only if encryption mode is true)',
            choices=['True','False'],
            default= 'False')

    parser.add_argument(
            "--encrypt",
            help='Set encryption mode. Default: False',
            choices=['True','False'],
            default='False')

    parser.add_argument(
            "--keyfile",
            help='File having key for encryption (Applicable only if encryption mode is true)',
            default = None)

    args = parser.parse_args()
    input_filename = args.input
    output_filename = args.output
    input_size = args.size
    version_no = args.version

    key_gen = args.keygen
    is_encrypt_data = args.encrypt
    key_file = args.keyfile

    nvs_part_gen(input_filename, output_filename, input_size, key_gen, is_encrypt_data, key_file, version_no)

if __name__ == "__main__":
    main()


text:
"use strict";
var merge = require('utils-merge');
var Emitter = require('../emitter');

var defaultPort = 3883;
var defaultSecurePort = 4883;

/**
 * http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.javascript.git/tree/src/mqttws31.js
 */

exports.initialize = function initialize(socket, utils) {
    var settings = socket.settings || {};

    var host = settings.options.host || settings.host || defaultHost;
    var port = Number(settings.options.port || settings.port || (settings.useSSL ? defaultSecurePort : defaultPort));
    var clientId = settings.options.clientId || settings.clientId || utils.makeId();

    var options = {};
    options.userName = settings.username || settings.key;
    options.password = settings.password || settings.secret;
    options.useSSL = !!settings.useSSL;

    merge(options, settings.options);
    merge(settings, options); // update settings

    delete options.host;
    delete options.port;
    delete options.clientId;

    Object.keys(options).forEach(function(key) {
        if (options[key] === null || options[key] === undefined) {
            delete options[key];
        }
    });

    if (options.userName && !options.password) delete options.userName;

    var client = socket.client = new Paho.MQTT.Client(host, port, clientId);
    socket.adapter = new PahoAdapter(client, options);
};

function PahoAdapter(client, options) {
    this.client = client;

    var adapter = this;
    client.onConnectionLost = function () {
        adapter.emit('close');
    };
    client.onMessageArrived = function (message) {
        adapter.emit('message', message.destinationName, message.payloadString);
    };

    options = options || {};
    options.onSuccess = function onConnected() {
        adapter.emit('connect');
    };
    options.onFailure = function (message) {
        adapter.emit(new Error(message.errorMessage));
    };

    client.connect(options);
}

Emitter.extend(PahoAdapter);

PahoAdapter.prototype.__defineGetter__('connected', function () {
    return this.client.connected;
});

PahoAdapter.prototype.subscribe = function (topic, opts, cb) {
    opts = opts || {qos: 1};
    cb = cb || function () {};
    opts.onSuccess = function (messsage) {
        cb(null, messsage.grantedQos);
    };
    opts.onFailure = function (messsage) {
        cb(messsage.errorCode);
    };
    return this.client.subscribe(topic, opts);
};

PahoAdapter.prototype.unsubscribe = function (topic, opts, cb) {
    opts = opts || {};
    cb = cb || function () {};
    opts.onSuccess = function (messsage) {
        cb();
    };
    return this.client.unsubscribe(topic, opts);
};

PahoAdapter.prototype.publish = function (topic, message) {
    var m = new Paho.MQTT.Message(message);
    m.destinationName = topic;
    return this.client.send(m);
};

PahoAdapter.prototype.close = function () {
    try {
        this.client.disconnect();
    } catch (e) {
        console.warn(e.message);
        this.emit('close');
    }
};

redpajama_set_name: RedPajamaGithub


text:
class User < ActiveRecord::Base
  has_many :suggestions
  has_many :seen_relics
  has_many :widgets

  has_many :user_relics
  has_many :relics, :through => :user_relics

  devise :database_authenticatable, :registerable, :omniauthable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauth_providers => [:facebook]

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :registration, :terms_of_service
  attr_accessible :email, :password, :password_confirmation, :role, :as => :admin
  attr_accessor :force_password_required, :current_password

  attr_accessible :avatar, :language, :current_password

  mount_uploader :avatar, AvatarUploader

  validates :role, :inclusion => { :in => ["admin", "user"] }
  validates :language, :inclusion => { :in => Settings.oz.locale.available.map(&:to_s) }
  validates :username, :email, :uniqueness => { :message => I18n.t('activemodel.errors.messages.already_taken') }

  def admin?
    role == 'admin'
  end

  # Set this to true to enable additional validations and password generation
  attr_accessor :registration
  def registration?; registration.present? end
  def registered?; email.present? end

  # We require e-mail only on registration as nil-user exist
  def email_required?
    registration?
  end

  # Other logic on user registration
  with_options :if => :registration? do |model|

    model.validates :username,
      :uniqueness => true, :presence => true, :format => /[\w\.]/,
      :length => { :maximum => 30, :minimum => 3 }

    model.validates_acceptance_of :terms_of_service, :accept => true
    model.validates :terms_of_service, presence: true

    model.before_save do
      self.password = self.password_confirmation = Devise.friendly_token[0,20]
      # Generate API key
      self.generate_api_key!
    end

  end

  # We don't require password because it is sent on e-mail
  def password_required?
    force_password_required
  end

  def mark_relic_as_seen(relic_id)
    sr = self.seen_relics.find_or_create_by_relic_id relic_id
    sr.touch
    if seen_relic_ids.first == relic_id
      self.seen_relic_order = (self.seen_relic_order == 'asc' ? 'desc' : 'asc')
      self.update_attribute(:seen_relic_order, self.seen_relic_order) if self.seen_relic_order_changed?
    end
  end

  def seen_relic_ids
    self.seen_relics.order("updated_at #{self.seen_relic_order}").pluck(:relic_id)
  end

  def earn_points
    return @earn_points if defined? @earn_points
    @earn_points = self.suggestions.not_skipped.count
  end

  def ability
    @ability ||= Ability.new(self)
  end

  def generate_api_key!
    self.api_key = Devise.friendly_token
  end

  def generate_api_secret!
    self.api_secret = Devise.friendly_token
  end

  def ensure_api_keys_generated!
    generate_api_key!     unless api_key?
    generate_api_secret!  unless api_secret?
    save!
  end

  def adopted?(id)
    relics.exists?(id)
  end

  # def to_param
  #   self.username
  # end

  class << self
    def reset_password_by_token(attributes={})
      recoverable = find_or_initialize_with_error_by(:reset_password_token, attributes[:reset_password_token])
      if recoverable.persisted?
        if recoverable.reset_password_period_valid?
          recoverable.force_password_required = true
          recoverable.reset_password!(attributes[:password], attributes[:password_confirmation])
        else
          recoverable.errors.add(:reset_password_token, :expired)
        end
      end
      recoverable
    end

    def find_for_facebook_oauth(auth, signed_in_resource=nil)
      User.where(["email = ? OR (provider = ? AND uid = ?)", auth.info.email, auth.provider, auth.uid]).first_or_create do |user|
        user.username  ||= auth.extra.raw_info.name
        user.password  ||= Devise.friendly_token[0,20]
        user.provider  = auth.provider
        user.uid       = auth.uid
        user.email     = auth.info.email
      end
    end
  end
end


text:
namespace RouteSystemUI
{
    using System;
    using System.Linq;
    using System.Windows.Forms;

    using RouteSystem.UI;

    public partial class RoutesSystemForm : Form
    {
        public RoutesSystemForm()
        {
            InitializeComponent();

            this.importDataTypeSelect.SelectedIndex = 0;
        }

        private void loadExcelButton_Click(object sender, EventArgs e)
        {
            this.loadExcelOpenFileDialog.ShowDialog();
            this.loadExcelTextBox.Text = this.loadExcelOpenFileDialog.FileName;
        }

        private void loadXMLButton_Click(object sender, EventArgs e)
        {
            this.loadXMLOpenFileDialog.ShowDialog();
            this.loadXMLTextbox.Text = this.loadXMLOpenFileDialog.FileName;
        }

        private void hideUnusedLoadData()
        {
            this.loadExcelLabel.Visible = false;
            this.loadExcelButton.Visible = false;
            this.loadExcelTextBox.Visible = false;

            this.loadMongoDBLabel.Visible = false;
            this.loadMongoDBTextBox.Visible = false;

            this.loadXMLLabel.Visible = false;
            this.loadXMLButton.Visible = false;
            this.loadXMLTextbox.Visible = false;

            this.loadMySQLLabel.Visible = false;
            this.loadMySQLTextBox.Visible = false;

            this.loadSQLiteLabel.Visible = false;
            this.loadSQLiteTextBox.Visible = false;
        }

        private void importDataTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.importDataTypeSelect.SelectedItem.ToString() == "MongoDB and Excel")
            {
                hideUnusedLoadData();

                this.loadExcelLabel.Visible = true;
                this.loadExcelButton.Visible = true;
                this.loadExcelTextBox.Visible = true;

                this.loadMongoDBLabel.Visible = true;
                this.loadMongoDBTextBox.Visible = true;
            }
            else if (this.importDataTypeSelect.SelectedItem.ToString() == "XML")
            {
                hideUnusedLoadData();

                this.loadXMLLabel.Visible = true;
                this.loadXMLButton.Visible = true;
                this.loadXMLTextbox.Visible = true;
                this.loadMongoDBLabel.Visible = true;
                this.loadMongoDBTextBox.Visible = true;
            }
        }

        private void importDataTypeButton_Click(object sender, EventArgs e)
        {
            if (this.importDataTypeSelect.SelectedItem.ToString() == "MongoDB and Excel")
            {
                if (this.loadExcelTextBox.Text == "" && this.loadMongoDBTextBox.Text == "")
                {
                    MessageBox.Show("Choose MongoDB connection string and Excel file first!");
                }
                else if (this.loadExcelTextBox.Text == "")
                {
                    MessageBox.Show("Choose Excel file first!");
                }
                else if (this.loadMongoDBTextBox.Text == "")
                {
                    MessageBox.Show("Choose MongoDB connection string first!");
                }
                else
                {
                    UIEngine.ImportExcelAndMongoData(this.loadMongoDBTextBox.Text, this.loadExcelTextBox.Text);
                }
            }
            else if (this.importDataTypeSelect.SelectedItem.ToString() == "XML")
            {
                if (this.loadXMLTextbox.Text == "")
                {
                    MessageBox.Show("Choose XML file first!");
                }
                else if (this.loadMongoDBTextBox.Text == "")
                {
                    MessageBox.Show("Choose MongoDB connection string first!");
                }
                else
                {
                    UIEngine.ImportXMLToMongoAndSQLServer(this.loadMongoDBTextBox.Text, this.loadXMLTextbox.Text);
                }
            }
        }

        private void generateReportButton_Click(object sender, EventArgs e)
        {
            this.SaveReportDialog.ShowDialog();
            var filePathInfo = this.SaveReportDialog.FileName;
            var checkedButton = tabReports.Controls
                .OfType<RadioButton>().FirstOrDefault(r => r.Checked);

            UIEngine.CreateReport(checkedButton, filePathInfo);
            MessageBox.Show("Report created!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void CheckBoxAggregateRouteReport_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void xmlReportRadio_CheckedChanged(object sender, EventArgs e)
        {
        }
    }
}


text:
* [
      soapyigu
      /
      LeetCode_Swift
](https://github.com/soapyigu/LeetCode_Swift):
      Solutions coded by Swift to LeetCode

* [
      linkedin
      /
      LayoutKit
](https://github.com/linkedin/LayoutKit):
      LayoutKit is a fast view layout library for iOS.

* [
      hyperoslo
      /
      BarcodeScanner
](https://github.com/hyperoslo/BarcodeScanner):

🔎 A simple and beautiful barcode scanner.

* [
      whitesmith
      /
      WSTagsField
](https://github.com/whitesmith/WSTagsField):
      An iOS text field that represents different Tags

* [
      kean
      /
      Preheat
](https://github.com/kean/Preheat):
      Automates prefetching of content in UITableView and UICollectionView

* [
      0x73
      /
      SwiftIconFont
](https://github.com/0x73/SwiftIconFont):
      Icons fonts for iOS (FontAwesome, Iconic, Ionicon, Octicon, Themify, MapIcon, MaterialIcon)

* [
      shadowsocks
      /
      Potatso
](https://github.com/shadowsocks/Potatso):
      Potatso is an iOS client that implements Shadowsocks proxy with the leverage of NetworkExtension framework in iOS 9.

* [
      teodorpatras
      /
      SideMenuController
](https://github.com/teodorpatras/SideMenuController):
      A side menu controller written in Swift

* [
      matteocrippa
      /
      awesome-swift
](https://github.com/matteocrippa/awesome-swift):
      A collaborative list of awesome swift resources. Feel free to contribute!

* [
      Codeido
      /
      PMAlertController
](https://github.com/Codeido/PMAlertController):
      PMAlertController is a great and customizable substitute to UIAlertController

* [
      vsouza
      /
      awesome-ios
](https://github.com/vsouza/awesome-ios):
      A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

* [
      dzenbot
      /
      Iconic
](https://github.com/dzenbot/Iconic):
      Auto-generated icon font library for iOS [beta]

* [
      danielgindi
      /
      Charts
](https://github.com/danielgindi/Charts):
      Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

* [
      Alamofire
      /
      Alamofire
](https://github.com/Alamofire/Alamofire):
      Elegant HTTP Networking in Swift

* [
      instant-solutions
      /
      ISTimeline
](https://github.com/instant-solutions/ISTimeline):
      Simple timeline view written in Swift 2.2

* [
      laszlokorte
      /
      reform-swift
](https://github.com/laszlokorte/reform-swift):
      Swift implementation of the reform dynamic drawing application inspired by Bret Victor's talk "Drawing Dynamic Visualizations"

* [
      raywenderlich
      /
      swift-algorithm-club
](https://github.com/raywenderlich/swift-algorithm-club):
      Algorithms and data structures in Swift, with explanations!

* [
      izotx
      /
      JMCBeaconManager
](https://github.com/izotx/JMCBeaconManager):
      iBeacon Manager

* [
      pkluz
      /
      PKHUD
](https://github.com/pkluz/PKHUD):
      A Swift based reimplementation of the Apple HUD (Volume, Ringer, Rotation,…) for iOS 8.

* [
      atljeremy
      /
      JFCardSelectionViewController
](https://github.com/atljeremy/JFCardSelectionViewController):
      A fancy collection style view controller

* [
      dkhamsing
      /
      open-source-ios-apps
](https://github.com/dkhamsing/open-source-ios-apps):

📱 Collaborative List of Open-Source iOS Apps

* [
      Urinx
      /
      iOSAppHook
](https://github.com/Urinx/iOSAppHook):
      专注于非越狱环境下iOS应用逆向研究,从dylib注入,应用重签名到App Hook

* [
      devxoul
      /
      RxTodo
](https://github.com/devxoul/RxTodo):
      iOS Todo Application with RxSwift + MVVM

* [
      ReactiveX
      /
      RxSwift
](https://github.com/ReactiveX/RxSwift):
      Reactive Programming in Swift

* [
      SwiftyJSON
      /
      SwiftyJSON
](https://github.com/SwiftyJSON/SwiftyJSON):
      The better way to deal with JSON data in Swift

#### objective-c
* [
      SunLiner
      /
      MiaowShow
](https://github.com/SunLiner/MiaowShow):
      iOS视频直播项目

* [
      GrayJIAXU
      /
      520Linkee
](https://github.com/GrayJIAXU/520Linkee):
      本项目实现了作为一个直播App的基本功能,比如本地视频流采集、播放、美颜、礼物、点赞出心等。

* [
      music4kid
      /
      PLeakSniffer
](https://github.com/music4kid/PLeakSniffer):
      Detect memory leaks for your iOS project automatically.

* [
      AFNetworking
      /
      AFNetworking
](https://github.com/AFNetworking/AFNetworking):
      A delightful networking framework for iOS, OS X, watchOS, and tvOS.

* [
      CoderJackyHuang
      /
      HYBHelperKit
](https://github.com/CoderJackyHuang/HYBHelperKit):
      日常开发必不可少的神器之一,UIBlockKit、UIMakerKit、UIKit、CommonKit、FoundationKit、Controllers、Constants等集于一身的神器!

* [
      coderyi
      /
      Eleven
](https://github.com/coderyi/Eleven):
      Eleven Player is a simple powerful video player.use ffmpeg.

* [
      Soulghost
      /
      SGUserGuide
](https://github.com/Soulghost/SGUserGuide):
      Make steps to help users do specific operations without breaking the structure of the project. 一个用于制作多步骤用户操作引导的框架,基于AOP,对原工程几乎无任何侵入。

* [
      ReactiveCocoa
      /
      ReactiveCocoa
](https://github.com/ReactiveCocoa/ReactiveCocoa):
      Streams of values over time

* [
      gsdios
      /
      SDAutoLayout
](https://github.com/gsdios/SDAutoLayout):
      One line of code to implement automatic layout. 一行代码搞定自动布局!支持Cell和Tableview高度自适应,Label和ScrollView内容自适应,致力于做最简单易用的AutoLayout库。The most easy way for autoLayout. Based Runtime.Auto Layout .

* [
      BradLarson
      /
      GPUImage
](https://github.com/BradLarson/GPUImage):
      An open source iOS framework for GPU-based image and video processing

* [
      SnapKit
      /
      Masonry
](https://github.com/SnapKit/Masonry):
      Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout

* [
      rs
      /
      SDWebImage
](https://github.com/rs/SDWebImage):
      Asynchronous image downloader with cache support as a UIImageView category

* [
      Zepo
      /
      GYDataCenter
](https://github.com/Zepo/GYDataCenter):
      An alternative to Core Data for people who like using SQLite directly.

* [
      forkingdog
      /
      FDFullscreenPopGesture
](https://github.com/forkingdog/FDFullscreenPopGesture):
      A UINavigationController's category to enable fullscreen pop gesture with iOS7+ system style.

* [
      marcshilling
      /
      react-native-image-picker
](https://github.com/marcshilling/react-native-image-picker):
      A React Native module that allows you to use native UI to select media from the device library or directly from the camera

* [
      LaiFengiOS
      /
      LFLiveKit
](https://github.com/LaiFengiOS/LFLiveKit):
      LaiFeng IOS Live Kit

* [
      CoderMJLee
      /
      MJRefresh
](https://github.com/CoderMJLee/MJRefresh):
      An easy way to use pull-to-refresh.

* [
      dzenbot
      /
      DZNEmptyDataSet
](https://github.com/dzenbot/DZNEmptyDataSet):
      A drop-in UITableView/UICollectionView superclass category for showing empty datasets whenever the view has no content to display.

* [
      gnachman
      /
      iTerm2
](https://github.com/gnachman/iTerm2):
      iTerm2 is a terminal emulator for Mac OS X that does amazing things.

* [
      jdg
      /
      MBProgressHUD
](https://github.com/jdg/MBProgressHUD):
      MBProgressHUD + Customizations

* [
      Zepo
      /
      MLeaksFinder
](https://github.com/Zepo/MLeaksFinder):
      Find memory leaks in your iOS app at develop time.

* [
      daniulive
      /
      SmarterStreaming
](https://github.com/daniulive/SmarterStreaming):
      SmarterStreaming, an excellent cross-platform Live Streaming publisher/playback SDK, covered Windows/android/iOS platform with millisecond latency and great scalability. 跨平台视频采集、直播SDK(支持私有协议和RTMP推流,如Windows推流/android推流/iOS推流/Windows播放/android播放/iOS播放),公网毫秒级延迟,也许是国内最靠谱的视频直播推流、播放SDK之一,助您轻松实现类似于花椒、映客、斗鱼手机直播推送与播放。

* [
      YouXianMing
      /
      Animations
](https://github.com/YouXianMing/Animations):
      The Animation Collection.

* [
      ParsePlatform
      /
      Parse-SDK-iOS-OSX
](https://github.com/ParsePlatform/Parse-SDK-iOS-OSX):
      Parse SDK for iOS/OS X/watchOS/tvOS

* [
      banchichen
      /
      TZImagePickerController
](https://github.com/banchichen/TZImagePickerController):
      一个支持多选、选原图和视频的图片选择器,同时有预览功能,适配了iOS6789系统。 A clone of UIImagePickerController, support picking multiple photos、original photo、video, also allow preview photo and video, fitting iOS6789 system.

#### go
* [
      amyhaber
      /
      cnki-downloader
](https://github.com/amyhaber/cnki-downloader):
      CNKI文献下载工具

* [
      getlantern
      /
      lantern
](https://github.com/getlantern/lantern):

⚡ Open Internet for everyone. Lantern is a free desktop application that delivers fast, reliable and secure access to the open Internet for users in censored regions. It uses a variety of techniques to stay unblocked, including P2P and domain fronting. Lantern relies on users in uncensored regions acting as access points to the open Internet.

* [
      docker
      /
      docker
](https://github.com/docker/docker):
      Docker - the open-source application container engine

* [
      golang
      /
      go
](https://github.com/golang/go):
      The Go programming language

* [
      kubernetes
      /
      kubernetes
](https://github.com/kubernetes/kubernetes):
      Production-Grade Container Scheduling and Management

* [
      tucnak
      /
      store
](https://github.com/tucnak/store):
      A dead simple configuration manager for Go applications

* [
      apex
      /
      apex
](https://github.com/apex/apex):
      Build, deploy, and manage AWS Lambda functions with ease (with Go support!).

* [
      avelino
      /
      awesome-go
](https://github.com/avelino/awesome-go):
      A curated list of awesome Go frameworks, libraries and software

* [
      kubernetes
      /
      minikube
](https://github.com/kubernetes/minikube):
      Run Kubernetes locally

* [
      kataras
      /
      iris
](https://github.com/kataras/iris):
      The fastest web framework for Go in (THIS) earth

* [
      google
      /
      godepq
](https://github.com/google/godepq):
* [
      hyperledger
      /
      fabric
](https://github.com/hyperledger/fabric):
      Fabric is a blockchain project in Incubation proposed to the community and documented at https://goo.gl/RYQZ5N. Information on what Incubation entails can be found in the Hyperledger Project Lifecycle document (https://goo.gl/4edNRc)

* [
      astaxie
      /
      build-web-application-with-golang
](https://github.com/astaxie/build-web-application-with-golang):
      A golang ebook intro how to build a web with golang

* [
      Code-Hex
      /
      pget
](https://github.com/Code-Hex/pget):
      Parallel file download client

* [
      caixw
      /
      apidoc
](https://github.com/caixw/apidoc):
      RESTful API 文档生成工具

* [
      containous
      /
      traefik
](https://github.com/containous/traefik):
      Træfɪk, a modern reverse proxy

* [
      fiatjaf
      /
      summadb
](https://github.com/fiatjaf/summadb):
      A hierarchical database that syncs with PouchDB

* [
      prometheus
      /
      prometheus
](https://github.com/prometheus/prometheus):
      The Prometheus monitoring system and time series database.

* [
      minio
      /
      blake2b-simd
](https://github.com/minio/blake2b-simd):
      Fast hashing using pure Go implementation of BLAKE2b with SIMD instructions

* [
      knq
      /
      xo
](https://github.com/knq/xo):
      Command line tool to generate idiomatic Go code for SQL databases supporting PostgreSQL, MySQL, SQLite, Oracle, and Microsoft SQL Server

* [
      uber-go
      /
      zap
](https://github.com/uber-go/zap):
      Fast, structured, leveled logging in Go

* [
      wcharczuk
      /
      go-chart
](https://github.com/wcharczuk/go-chart):
      go chart is a basic charting library in native golang.

* [
      Requilence
      /
      integram
](https://github.com/Requilence/integram):
      Integrate Telegram into your workflow – https://integram.org

* [
      grafana
      /
      grafana
](https://github.com/grafana/grafana):
      Gorgeous metric viz, dashboards & editors for Graphite, InfluxDB & OpenTSDB

* [
      spf13
      /
      hugo
](https://github.com/spf13/hugo):
      A Fast and Flexible Static Site Generator built with love in GoLang

#### javascript
* [
      mozilla
      /
      fathom
](https://github.com/mozilla/fathom):
* [
      zakattax
      /
      bitscript-temperate
](https://github.com/zakattax/bitscript-temperate):
      Temperate is a healthcare application that aims to make healthcare more accessible to everyone, everywhere. This application was submitted as an entry to HealthHacksPH 2016.

* [
      vvo
      /
      gifify
](https://github.com/vvo/gifify):

😻 Convert any video file to an optimized animated GIF.

* [
      lambci
      /
      lambci
](https://github.com/lambci/lambci):
      A continuous integration system built on AWS Lambda

* [
      andrew-worsfold
      /
      tailor
](https://github.com/andrew-worsfold/tailor):
      Build beautiful page layouts quickly and easily using your favourite WordPress theme.

* [
      Moeditor
      /
      Moeditor
](https://github.com/Moeditor/Moeditor):
      Your all-purpose markdown editor.

* [
      terwanerik
      /
      ScrollTrigger
](https://github.com/terwanerik/ScrollTrigger):
      Triggers classes on html elements based on the scroll position. Uses requestAnimationFrame so it doesn't jack the users scroll.

* [
      sindresorhus
      /
      np
](https://github.com/sindresorhus/np):
      A better `npm publish`

* [
      vuejs
      /
      vue
](https://github.com/vuejs/vue):
      Simple yet powerful library for building modern web interfaces.

* [
      juliangarnier
      /
      anime
](https://github.com/juliangarnier/anime):
      Javascript Animation Engine

* [
      henryboldi
      /
      felony
](https://github.com/henryboldi/felony):

🔑🔥📈 Next Level PGP

* [
      zingchart
      /
      zingtouch
](https://github.com/zingchart/zingtouch):
      A JavaScript gesture detection library for the modern web

* [
      getify
      /
      You-Dont-Know-JS
](https://github.com/getify/You-Dont-Know-JS):
      A book series on JavaScript. @YDKJS on twitter.

* [
      cht8687
      /
      You-Dont-Need-Lodash-Underscore
](https://github.com/cht8687/You-Dont-Need-Lodash-Underscore):
      Lists of Javascript methods which you can use natively

* [
      facebook
      /
      react
](https://github.com/facebook/react):
      A declarative, efficient, and flexible JavaScript library for building user interfaces.

* [
      impress
      /
      impress.js
](https://github.com/impress/impress.js):
      It's a presentation framework based on the power of CSS3 transforms and transitions in modern browsers and inspired by the idea behind prezi.com.

* [
      huluoyang
      /
      freecodecamp.cn
](https://github.com/huluoyang/freecodecamp.cn):
      干货都在Wiki中,千万不要错过。

* [
      d3
      /
      d3
](https://github.com/d3/d3):
      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

* [
      nodejs
      /
      node
](https://github.com/nodejs/node):
      Node.js JavaScript runtime ✨🐢🚀✨

* [
      zloirock
      /
      core-js
](https://github.com/zloirock/core-js):
      Standard Library

* [
      bocoup
      /
      chatter
](https://github.com/bocoup/chatter):
      A collection of useful primitives for creating interactive chat bots.

* [
      sindresorhus
      /
      alfy
](https://github.com/sindresorhus/alfy):
      Create Alfred workflows with ease

* [
      git-tips
      /
      tips
](https://github.com/git-tips/tips):
      Most commonly used git tips and tricks.

* [
      airbnb
      /
      javascript
](https://github.com/airbnb/javascript):
      JavaScript Style Guide

* [
      typicode
      /
      json-server
](https://github.com/typicode/json-server):
      Get a full fake REST API with zero coding in less than 30 seconds (seriously)

#### ruby
* [
      rpplusplus
      /
      PokemonHook
](https://github.com/rpplusplus/PokemonHook):
* [
      fastlane
      /
      fastlane
](https://github.com/fastlane/fastlane):
      The easiest way to automate building and releasing your iOS and Android apps

* [
      helpyio
      /
      helpy
](https://github.com/helpyio/helpy):
      Helpy is a modern, "mobile-first" helpdesk application built in Ruby. Features include multi-lingual knowledgebase, community discussions and private tickets integrated with email.

* [
      nickjj
      /
      orats
](https://github.com/nickjj/orats):
      Opinionated rails application templates.

* [
      jekyll
      /
      jekyll
](https://github.com/jekyll/jekyll):

🌐 Jekyll is a blog-aware, static site generator in Ruby

* [
      jondot
      /
      awesome-react-native
](https://github.com/jondot/awesome-react-native):
      An "awesome" type curated list of React Native components, news, tools, and learning material

* [
      Homebrew
      /
      brew
](https://github.com/Homebrew/brew):

🍺 The missing package manager for OS X

* [
      rails
      /
      rails
](https://github.com/rails/rails):
      Ruby on Rails

* [
      twbs
      /
      bootstrap-sass
](https://github.com/twbs/bootstrap-sass):
      Official Sass port of Bootstrap 2 and 3.

* [
      Shopify
      /
      semian
](https://github.com/Shopify/semian):

🐒 Resiliency toolkit for Ruby for failing fast

* [
      skwp
      /
      dotfiles
](https://github.com/skwp/dotfiles):
      YADR - The best vim,git,zsh plugins and the cleanest vimrc you've ever seen

* [
      ruby
      /
      ruby
](https://github.com/ruby/ruby):
      The Ruby Programming Language

* [
      amatsuda
      /
      jb
](https://github.com/amatsuda/jb):
      A simple and fast JSON API template engine for Ruby on Rails

* [
      Thibaut
      /
      devdocs
](https://github.com/Thibaut/devdocs):
      API Documentation Browser

* [
      mitchellh
      /
      vagrant
](https://github.com/mitchellh/vagrant):
      Vagrant is a tool for building and distributing development environments.

* [
      discourse
      /
      discourse
](https://github.com/discourse/discourse):
      A platform for community discussion. Free, open, simple.

* [
      stympy
      /
      faker
](https://github.com/stympy/faker):
      A library for generating fake data such as names, addresses, and phone numbers.

* [
      cerebris
      /
      jsonapi-resources
](https://github.com/cerebris/jsonapi-resources):
      A resource-focused Rails library for developing JSON API compliant servers.

* [
      Shopify
      /
      liquid
](https://github.com/Shopify/liquid):
      Liquid markup language. Safe, customer facing template language for flexible web apps.

* [
      bountysource
      /
      core
](https://github.com/bountysource/core):
      Bountysource is the funding platform for open-source software.

* [
      bkeepers
      /
      dotenv
](https://github.com/bkeepers/dotenv):
      Loads environment variables from `.env`.

* [
      deadlyvipers
      /
      dojo_rules
](https://github.com/deadlyvipers/dojo_rules):
* [
      intrigueio
      /
      intrigue-core
](https://github.com/intrigueio/intrigue-core):
      Discover your attack surface!

* [
      voxpupuli
      /
      puppet-collectd
](https://github.com/voxpupuli/puppet-collectd):
      Collectd module for Puppet

* [
      mongodb
      /
      mongoid
](https://github.com/mongodb/mongoid):
      Ruby ODM framework for MongoDB


text:
<!DOCTYPE html>

	{{> head}}

    {{> topBar}}

Género

                                    {{#genres}} {{name}} ({{resources.size}}) {{/genres}}

Resultados para {{searchName}}

							{{#search}} {{> listItems}} {{/search}}

						{{#isEmpty}}<button type="button" class="btn btn-lg btn-block btn-view-more">No hay resultados</button>{{/isEmpty}}
						{{^isEmpty}}<button id="moreSearch" type="button" class="btn btn-lg btn-block btn-view-more">Ver más</button>{{/isEmpty}}

    {{> footer}}


text:
package com.rationaleemotions.servlets;

import com.google.common.base.Preconditions;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.rationaleemotions.config.ConfigReader;
import java.io.BufferedReader;
import java.nio.charset.Charset;
import java.util.stream.Collectors;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.openqa.grid.common.exception.GridConfigurationException;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.GridRegistry;
import org.openqa.grid.web.servlet.RegistryBasedServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * Represents a simple servlet that needs to be invoked in order to wire in our ghost node
 * which will act as a proxy for all proxies.
 */
public class EnrollServlet extends RegistryBasedServlet {
    private static String hubHost;

    public EnrollServlet(GridRegistry registry) {
        super(registry);
    }

    public EnrollServlet() {
        this(null);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        addProxy();
    }

    private void addProxy() {
        //After the construction is finished, lets wrap up.
        int status;

        HttpClient client = HttpClientBuilder.create().build();

        try {
            final int port = getRegistry().getHub().getConfiguration().port;
            hubHost = getRegistry().getHub().getConfiguration().host;
            final URL registration = new URL(String.format("http://%s:%d/grid/register", hubHost, port));
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                registration.toExternalForm());
            request.setEntity(getJsonAsEntity(hubHost, port));
            HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
            HttpResponse response = client.execute(host, request);
            status = response.getStatusLine().getStatusCode();

        } catch (IOException | GridConfigurationException e) {
            throw new GridException(e.getMessage(), e);
        }
        Preconditions.checkState(status == HttpStatus.SC_OK, "There was a problem in hooking in the ghost node.");
    }

    private String convert(InputStream inputStream, Charset charset) throws IOException {

        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset))) {
            return br.lines().collect(Collectors.joining(System.lineSeparator()));
        }
    }

    private StringEntity getJsonAsEntity(String host, int port) {
        try {
            InputStream isr = Thread.currentThread().getContextClassLoader().getResourceAsStream("ondemand.json");
            String string = convert(isr, Charset.defaultCharset());
            JsonObject ondemand = new JsonParser().parse(string).getAsJsonObject();
            int maxSession =ConfigReader.getInstance().getMaxSession();
            JsonArray capsArray = ondemand.get("capabilities").getAsJsonArray();
            for (int i=0; i < capsArray.size(); i++) {
                capsArray.get(i).getAsJsonObject().addProperty("maxInstances", maxSession);
            }
            JsonObject configuration = ondemand.get("configuration").getAsJsonObject();
            configuration.addProperty("maxSession", maxSession);
            configuration.addProperty("hub", String.format("http://%s:%d", host, port));
            string = ondemand.toString();
            return new StringEntity(string);
        } catch (IOException e) {
            throw new GridException(e.getMessage(), e);
        }
    }

    public static String getHubHost() {
        return hubHost;
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Modelo.Facturacion.Factura;
import Modelo.Productos.Combo;
import Modelo.Productos.ObjetoVendible;
import Modelo.Productos.Producto;
import Modelo.Usuarios.Cajero;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JViewport;

/**
 *
 * @author will
 */
public class FacturacionGUI extends javax.swing.JFrame implements iStalker {

    private Cajero cajero;
    private LinkedList<Combo> combos;
    private LinkedList<Producto> productos;
    private LinkedList<ObjetoVendible> objectosSeleccionados;
    private LinkedList<ContenedorObjetoVendible> contenedoresSeleccionados;

    /**
     * Creates new form FacturacionGUI
     */
    public FacturacionGUI() {
        initComponents();
    }

    public FacturacionGUI(Cajero pCajero) {
        initComponents();
        cajero = pCajero;

        objectosSeleccionados = new LinkedList<>();
        contenedoresSeleccionados = new LinkedList<>();

        combos = cajero.getAllCombos();

        initProductosTab();
        initCombosTab();

    }

    private void refreshProductosTab()
    {
        JPanel view = ((JPanel)scp_Productos.getViewport().getView());
        Component[] contenedores = view.getComponents();
        for(Component componente : contenedores)
        {
            if(componente instanceof ContenedorObjetoVendible)
            {
                ContenedorObjetoVendible contenedor = (ContenedorObjetoVendible) componente;
                if(!objectosSeleccionados.contains(contenedor))
                {
                    contenedor.deseleccionar();

                }

            }

        }
    }

    private void refreshCombosTab()
    {
        JPanel view = ((JPanel)scp_Combos.getViewport().getView());
        Component[] contenedores = view.getComponents();
        for(Component componente : contenedores)
        {
            if(componente instanceof ContenedorObjetoVendible)
            {
                ContenedorObjetoVendible contenedor = (ContenedorObjetoVendible) componente;
                if(!objectosSeleccionados.contains(contenedor))
                {
                    contenedor.deseleccionar();

                }

            }

        }
    }

    private void initProductosTab()
    {
        productos = cajero.getAllProductos();

        GridBagLayout grid = new GridBagLayout();

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.ipadx = 10;
        constraints.ipady = 10;
        constraints.insets = new Insets(10,10,10,10);
        constraints.gridx = 0;
        constraints.gridy = 0;

        JPanel panel = new JPanel(grid);

        panel.setSize(this.getSize());

        scp_Productos.setViewportView(panel);
        JPanel view = ((JPanel)scp_Productos.getViewport().getView());

        int cuentaX = 1;
        int cuentaY = 0;

        for(Producto producto : productos)
        {
            ContenedorObjetoVendible contenedor =
                    new ContenedorObjetoVendible((ObjetoVendible)producto, (iStalker)this);

            view.add(contenedor, constraints);
            constraints.gridx = cuentaX;
            constraints.gridy = cuentaY;

            cuentaX++;
            if(cuentaX == 4)
            {
                cuentaX = 0;
                cuentaY++;
            }

        }
        this.pack();
    }

    private void initCombosTab()
    {
        combos = cajero.getAllCombos();

        GridBagLayout grid = new GridBagLayout();

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.ipadx = 10;
        constraints.ipady = 10;
        constraints.insets = new Insets(10,10,10,10);
        constraints.gridx = 0;
        constraints.gridy = 0;

        JPanel panel = new JPanel(grid);

        panel.setSize(this.getSize());

        scp_Combos.setViewportView(panel);
        JPanel view = ((JPanel)scp_Combos.getViewport().getView());

        int cuentaX = 1;
        int cuentaY = 0;
        for(Combo combo : combos)
        {
            ContenedorObjetoVendible contenedor =
                    new ContenedorObjetoVendible((ObjetoVendible)combo, (iStalker)this);

            view.add(contenedor, constraints);
            constraints.gridx = cuentaX;
            constraints.gridy = cuentaY;

            cuentaX++;
            if(cuentaX == 4)
            {
                cuentaX = 0;
                cuentaY++;
            }

        }
        this.pack();
    }

    private void initOrdenTab()
    {

        GridBagLayout grid = new GridBagLayout();

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.ipadx = 10;
        constraints.ipady = 10;
        constraints.insets = new Insets(10,10,10,10);
        constraints.gridx = 0;
        constraints.gridy = 0;

        JPanel panel = new JPanel(grid);

        panel.setSize(this.getSize());

        scp_Orden.setViewportView(panel);
        JPanel view = ((JPanel)scp_Orden.getViewport().getView());

        int cuentaX = 1;
        int cuentaY = 0;
        for(ObjetoVendible objetoVendible : objectosSeleccionados)
        {
            ContenedorObjetoVendibleSeleccionado contenedor =
                    new ContenedorObjetoVendibleSeleccionado(objetoVendible, (iStalker)this);

            view.add(contenedor, constraints);
            constraints.gridx = cuentaX;
            constraints.gridy = cuentaY;

            cuentaX++;
            if(cuentaX == 4)
            {
                cuentaX = 0;
                cuentaY++;
            }

        }
        this.pack();
    }

    public void pagar(){
        double totall=0;
        for(ObjetoVendible objetoVendible : objectosSeleccionados){
                totall+=objetoVendible.getPrecio();}
        int impuesto = (int) (totall*0.1);
        totall+=impuesto;
        MontoTempo.setText(Double.toString(totall));
    }

    @Override
    public void actualizar(iSujeto pSujeto, boolean pRemover)
    {

        ContenedorObjetoVendible contenedorObjetoVendible = (ContenedorObjetoVendible)pSujeto;
        if(pRemover)
        {
            objectosSeleccionados.remove(contenedorObjetoVendible.getObjetoVendible());
            contenedoresSeleccionados.remove(contenedorObjetoVendible);
            pagar();
            if(pSujeto instanceof ContenedorObjetoVendibleSeleccionado)
            {

                refreshProductosTab();
                refreshCombosTab();

            }
        }
        else
        {
            objectosSeleccionados.add(contenedorObjetoVendible.getObjetoVendible());
            contenedoresSeleccionados.add(contenedorObjetoVendible);
            pagar();
        }

        initOrdenTab();
        /*for(ObjetoVendible objetoVendible : objectosSeleccionados)
        {
            System.out.println(objetoVendible);
        }*/
    }

    private boolean esFormValido()
    {
        boolean res = true;

        res &= !objectosSeleccionados.isEmpty();

        return res;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        scp_Productos = new javax.swing.JScrollPane();
        scp_Combos = new javax.swing.JScrollPane();
        scp_Orden = new javax.swing.JScrollPane();
        btnFacturar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        Monto = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        MontoTempo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Facturación");

        scp_Productos.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scp_Productos.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jTabbedPane1.addTab("Productos", scp_Productos);

        scp_Combos.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scp_Combos.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jTabbedPane1.addTab("Combos", scp_Combos);

        scp_Orden.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scp_Orden.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jTabbedPane1.addTab("Orden", scp_Orden);

        btnFacturar.setText("Facturar");
        btnFacturar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFacturarActionPerformed(evt);
            }
        });

        jLabel1.setText("Efectivo Colones");

        jLabel2.setText("Total");

        MontoTempo.setText("0");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(MontoTempo)
                    .addComponent(Monto, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 365, Short.MAX_VALUE)
                .addComponent(btnFacturar, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 466, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnFacturar, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(Monto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(MontoTempo))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public boolean isDigit(){
        try{
            Double efectivo = Double.valueOf(Monto.getText());
            }
            catch(NumberFormatException e){
                JOptionPane.showMessageDialog(this, "Monto en Efectivo no es valido");
                Monto.setText("");
                return false;
            }
        return true;
    }
    private void btnFacturarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFacturarActionPerformed
        if(esFormValido())
        {
            if (isDigit()){

            Double efectivo = Double.valueOf(Monto.getText());
            LinkedList<ObjetoVendible> items = new LinkedList<>(objectosSeleccionados);
            Factura factura = new Factura(cajero, items);
            double total=0;
            for(ObjetoVendible objetoVendible : items){
                total+=objetoVendible.getPrecio();}
            if (efectivo-(total+(total*0.1))>=0){
            factura.setFacturaPagada();
            cajero.guardarFactura(factura);
            MontoTempo.setText("0");
            FacturaFinal facturaCreada = new FacturaFinal(factura,cajero.getNombre(),efectivo);
            facturaCreada.setVisible(true);

            objectosSeleccionados.clear();
            initProductosTab();
            initCombosTab();
            initOrdenTab();}else{
                JOptionPane.showMessageDialog(this, "Monto insuficiente");
            }}
        }
        else
        {
            JOptionPane.showMessageDialog(this, "No hay items en la orden");
            MontoTempo.setText("0");
        }
    }//GEN-LAST:event_btnFacturarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FacturacionGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FacturacionGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FacturacionGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FacturacionGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FacturacionGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Monto;
    private javax.swing.JLabel MontoTempo;
    private javax.swing.JButton btnFacturar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JScrollPane scp_Combos;
    private javax.swing.JScrollPane scp_Orden;
    private javax.swing.JScrollPane scp_Productos;
    // End of variables declaration//GEN-END:variables
}


text:
/**
 * gRPC channel management.
 */
package org.apache.beam.harness.channel;


text:
package com.intellij.util;

import com.intellij.ide.highlighter.ArchiveFileType;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.StandardFileSystems;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.FilteringIterator;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.*;

import static com.intellij.util.containers.ContainerUtil.*;

public class PathsList  {
  private final List<String>  myPath = new ArrayList<String>();
  private final List<String> myPathTail = new ArrayList<String>();
  private final Set<String> myPathSet = new HashSet<String>();

  private static final Function<String, VirtualFile> PATH_TO_LOCAL_VFILE = new NullableFunction<String, VirtualFile>() {
    @Override
    public VirtualFile fun(String path) {
      return StandardFileSystems.local().findFileByPath(path.replace(File.separatorChar, '/'));
    }
  };

  private static final Function<VirtualFile, String> LOCAL_PATH = new Function<VirtualFile, String>() {
    @Override
    public String fun(VirtualFile file) {
      return PathUtil.getLocalPath(file);
    }
  };

  private static final Function<String, VirtualFile> PATH_TO_DIR = new NullableFunction<String, VirtualFile>() {
    @Override
    public VirtualFile fun(String s) {
      final FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(s);
      final VirtualFile localFile = PATH_TO_LOCAL_VFILE.fun(s);
      if (localFile == null) return null;

      if (fileType instanceof ArchiveFileType && !localFile.isDirectory()) {
        return ((ArchiveFileType)fileType).getFileSystem().findByPathWithSeparator(localFile);
      }
      return localFile;
    }
  };

  public void add(@NonNls String path) {
    addAllLast(chooseFirstTimeItems(path), myPath);
  }

  public void remove(@NotNull String path) {
    myPath.remove(path);
    myPathTail.remove(path);
    myPathSet.remove(path);
  }

  public void add(VirtualFile file) {
    add(LOCAL_PATH.fun(file));
  }

  public void addFirst(@NonNls String path) {
    final Iterator<String> elements = chooseFirstTimeItems(path);
    int index = 0;
    while (elements.hasNext()) {
      final String element = elements.next();
      myPath.add(index, element);
      myPathSet.add(element);
      index++;
    }
  }

  public void addTail(String path) {
    addAllLast(chooseFirstTimeItems(path), myPathTail);
  }

  private Iterator<String> chooseFirstTimeItems(String path) {
    if (path == null) {
      return emptyIterator();
    }
    final StringTokenizer tokenizer = new StringTokenizer(path, File.pathSeparator);
    // in JDK 1.5 StringTokenizer implements Enumeration<Object> rather then Enumeration<String>, need to convert
    final Enumeration<String> en = new Enumeration<String>() {
      @Override
      public boolean hasMoreElements() {
        return tokenizer.hasMoreElements();
      }

      @Override
      public String nextElement() {
        return (String)tokenizer.nextElement();
      }
    };
    return FilteringIterator.create(iterate(en), new Condition<String>() {
      @Override
      public boolean value(String element) {
        element = element.trim();
        return !element.isEmpty() && !myPathSet.contains(element);
      }
    });
  }

  private void addAllLast(Iterator<String> elements, List<String> toArray) {
    while (elements.hasNext()) {
      final String element = elements.next();
      toArray.add(element);
      myPathSet.add(element);
    }
  }

  @NotNull
  public String getPathsString() {
    return StringUtil.join(getPathList(), File.pathSeparator);
  }

  public List<String> getPathList() {
    final List<String> result = new ArrayList<String>();
    result.addAll(myPath);
    result.addAll(myPathTail);
    return result;
  }

  /**
   * @return {@link VirtualFile}s on local file system (returns jars as files).
   */
  public List<VirtualFile> getVirtualFiles() {
    return skipNulls(map(getPathList(), PATH_TO_LOCAL_VFILE));
  }

  /**
   * @return The same as {@link #getVirtualFiles()} but returns jars as {@link JarFileSystem} roots.
   */
  public List<VirtualFile> getRootDirs() {
    return skipNulls(map(getPathList(), PATH_TO_DIR));
  }

  public void addAll(List<String> allClasspath) {
    for (String path : allClasspath) {
      add(path);
    }
  }

  public void addAllFiles(File[] classpathList) {
    addAllFiles(Arrays.asList(classpathList));
  }

  public void addAllFiles(List<File> classpathList) {
    for (File file : classpathList) {
      add(file);
    }
  }

  public void add(File file) {
    add(FileUtil.toCanonicalPath(file.getAbsolutePath()).replace('/', File.separatorChar));
  }

  public void addVirtualFiles(Collection<VirtualFile> files) {
    for (final VirtualFile file : files) {
      add(file);
    }
  }

  public void addVirtualFiles(VirtualFile[] files) {
    for (VirtualFile file : files) {
      add(file);
    }
  }
}


text:
PYTHONIC_NS_BEGIN

namespace numpy
{

#define NUMPY_NARY_FUNC_NAME multiply
#define NUMPY_NARY_FUNC_SYM pythonic::operator_::mul
#include "pythonic/types/numpy_nary_expr.hpp"
}
PYTHONIC_NS_END

#endif


text:
package gw.testharness;

import gw.testharness.DoNotRunTest;
import gw.testharness.IncludeInTestResults;

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Inherited
@DoNotRunTest
@IncludeInTestResults
public @interface   Disabled {
  String assignee();
  String reason();
}


text:
package demo.java.v2c08javabean.ChartBean.com.horstmann.corejava;

import java.awt.*;
import java.beans.*;
import javax.swing.*;

/**
 * The property editor for the inverse property of the ChartBean. The inverse property toggles
 * between colored graph bars and colored background.
 * @version 1.30 2007-10-03
 * @author Cay Horstmann
 */
public class InverseEditor extends PropertyEditorSupport
{
   public Component getCustomEditor()
   {
      return new InverseEditorPanel(this);
   }

   public boolean supportsCustomEditor()
   {
      return true;
   }

   public boolean isPaintable()
   {
      return true;
   }

   public String getAsText()
   {
      return null;
   }

   public String getJavaInitializationString()
   {
      return "" + getValue();
   }

   public void paintValue(Graphics g, Rectangle bounds)
   {
      ImageIcon icon = (Boolean) getValue() ? inverseIcon : normalIcon;
      int x = bounds.x + (bounds.width - icon.getIconWidth()) / 2;
      int y = bounds.y + (bounds.height - icon.getIconHeight()) / 2;
      g.drawImage(icon.getImage(), x, y, null);
   }

   private ImageIcon inverseIcon = new ImageIcon(getClass().getResource(
         "ChartBean_INVERSE_16x16.gif"));
   private ImageIcon normalIcon = new ImageIcon(getClass().getResource("ChartBean_MONO_16x16.gif"));
}


text:
package org.eclipse.rdf4j.federated.algebra;

/**
 * Interface representing nodes that can exclusively be evaluated at a single {@link StatementSource}.
 * <p>
 * Implementations are recommended to additionally implement {@link ExclusiveTupleExprRenderer}
 * </p>
 *
 * @author Andreas Schwarte
 * @see ExclusiveStatement
 */
public interface ExclusiveTupleExpr extends FedXTupleExpr {

	/**
	 *
	 * @return the owner for this expression
	 */
	StatementSource getOwner();

}


text:
inline int my_add(int x, int y) {
    return x + y;
}

struct multiplier {
    int operator()(int x) {
        return x * 10;
    }

    static int by_five(int x) {
        return x * 5;
    }
};

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base);

    // setting a function is simple
    lua.set_function("my_add", my_add);

    // you could even use a lambda
    lua.set_function("my_mul", [](double x, double y) { return x * y; });

    // member function pointers and functors as well
    lua.set_function("mult_by_ten", multiplier{});
    lua.set_function("mult_by_five", &multiplier::by_five);

    // assert that the functions work
    lua.script("assert(my_add(10, 11) == 21)");
    lua.script("assert(my_mul(4.5, 10) == 45)");
    lua.script("assert(mult_by_ten(50) == 500)");
    lua.script("assert(mult_by_five(10) == 50)");

    // using lambdas, functions could have state.
    int x = 0;
    lua.set_function("inc", [&x]() { x += 10; });

    // calling a stateful lambda modifies the value
    lua.script("inc()");
    assert(x == 10);

    // this can be done as many times as you want
    lua.script("inc()\ninc()\ninc()");
    assert(x == 40);

    // retrieval of a function is done similarly
    // to other variables, using sol::function
    sol::function add = lua["my_add"];
    assert(add.call<int>(10, 11) == 21);

    // multi-return functions are supported using
    // std::tuple as the interface.
    lua.set_function("multi", []{ return std::make_tuple(10, "goodbye"); });
    lua.script("x, y = multi()");
    lua.script("assert(x == 10 and y == 'goodbye')");

    auto multi = lua.get<sol::function>("multi");
    int first;
    std::string second;
    std::tie(first, second) = multi.call<int, std::string>();

    // assert the values
    assert(first == 10);
    assert(second == "goodbye");
}


text:
<?php

namespace Api\Model\Languageforge\Lexicon\Config;

class LexiconReviewTask extends LexiconTask {}


text:
import Check from "../Core/Check.js";
import defaultValue from "../Core/defaultValue.js";
import defined from "../Core/defined.js";
import PropertyTable from "./PropertyTable.js";
import PropertyTexture from "./PropertyTexture.js";
import PropertyAttribute from "./PropertyAttribute.js";
import StructuralMetadata from "./StructuralMetadata.js";
import MetadataTable from "./MetadataTable.js";

/**
 * Parse the EXT_structural_metadata glTF extension to create a
 * structural metadata object.
 *
 * @param {Object} options Object with the following properties:
 * @param {Object} options.extension The extension JSON object.
 * @param {MetadataSchema} options.schema The parsed schema.
 * @param {Object.<String, Uint8Array>} [options.bufferViews] An object mapping bufferView IDs to Uint8Array objects.
 * @param {Object.<String, Texture>} [options.textures] An object mapping texture IDs to {@link Texture} objects.
 * @return {StructuralMetadata} A structural metadata object
 * @private
 * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
 */
export default function parseStructuralMetadata(options) {
  options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  const extension = options.extension;

  // The calling code is responsible for loading the schema.
  // This keeps metadata parsing synchronous.
  const schema = options.schema;

  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options.extension", extension);
  Check.typeOf.object("options.schema", schema);
  //>>includeEnd('debug');

  const propertyTables = [];
  if (defined(extension.propertyTables)) {
    for (let i = 0; i < extension.propertyTables.length; i++) {
      const propertyTable = extension.propertyTables[i];
      const classDefinition = schema.classes[propertyTable.class];
      const metadataTable = new MetadataTable({
        count: propertyTable.count,
        properties: propertyTable.properties,
        class: classDefinition,
        bufferViews: options.bufferViews,
      });
      propertyTables.push(
        new PropertyTable({
          id: i,
          name: propertyTable.name,
          count: propertyTable.count,
          metadataTable: metadataTable,
          extras: propertyTable.extras,
          extensions: propertyTable.extensions,
        })
      );
    }
  }

  const propertyTextures = [];
  if (defined(extension.propertyTextures)) {
    for (let i = 0; i < extension.propertyTextures.length; i++) {
      const propertyTexture = extension.propertyTextures[i];
      propertyTextures.push(
        new PropertyTexture({
          id: i,
          name: propertyTexture.name,
          propertyTexture: propertyTexture,
          class: schema.classes[propertyTexture.class],
          textures: options.textures,
        })
      );
    }
  }

  const propertyAttributes = [];
  if (defined(extension.propertyAttributes)) {
    for (let i = 0; i < extension.propertyAttributes.length; i++) {
      const propertyAttribute = extension.propertyAttributes[i];
      propertyAttributes.push(
        new PropertyAttribute({
          id: i,
          name: propertyAttribute.name,
          class: schema.classes[propertyAttribute.class],
          propertyAttribute: propertyAttribute,
        })
      );
    }
  }

  return new StructuralMetadata({
    schema: schema,
    propertyTables: propertyTables,
    propertyTextures: propertyTextures,
    propertyAttributes: propertyAttributes,
    statistics: extension.statistics,
    extras: extension.extras,
    extensions: extension.extensions,
  });
}


text:
module.exports = function(name) {

  if (this.$root.$refs.hasOwnProperty(name))
    return this.$root.$refs[name];

  return getField(this, name);

}

function getField(parent, name){

     if(parent.name == name){
          return parent;
     } else if (parent.$children && parent.$children.length){
          var i;
          var result = null;
          for(i=0; result == null && i < parent.$children.length; i++){
               result = getField(parent.$children[i], name);
          }

          return result;
     }

     return null;
}


text:
from pprint import pprint as pp

class SubDict(dict):
    """
    SubLists class
    """

    def __init__(self, api, parentObjName,
                 parentPayloadObj, parentKey,
                 objType):
        """ Function load
        To be rewriten

        @param id: The Domain ID
        @return RETURN: DESCRIPTION
        """
        self.api = api
        self.parentObjName = parentObjName
        self.parentPayloadObj = parentPayloadObj
        self.parentKey = parentKey
        self.objType = objType
        self.objName = objType.objName
        self.payloadObj = objType.payloadObj
        self.index = objType.index
        self.objNameSet = objType.objNameSet
        dict.__init__(self, self.load())

    def load(self, limit=9999):
        """ Function list
        Get the list of all interfaces

        @param key: The targeted object
        @param limit: The limit of items to return
        @return RETURN: A ForemanItem list
        """
        subItemList = self.api.list('{}/{}/{}'.format(self.parentObjName,
                                                      self.parentKey,
                                                      self.objName,
                                                      ),
                                    limit=limit)
        if self.objName == 'puppetclass_ids':
            subItemList = list(map(lambda x: {'id': x}, subItemList))
        if self.objName == 'puppetclasses':
            sil_tmp = subItemList.values()
            subItemList = []
            for i in sil_tmp:
                subItemList.extend(i)
        return {x[self.index]: self.objType(self.api, x['id'],
                                            self.parentObjName,
                                            self.parentPayloadObj,
                                            self.parentKey,
                                            x)
                for x in subItemList}

    def __setitem__(self, key, attributes):
        """ Function __setitem__
        Set a parameter of a foreman object as a dict

        @param key: The key to modify
        @param attribute: The data
        @return RETURN: The API result
        """
        return self.api.set('{}/{}/{}'.format(self.parentName,
                                              self.parentKey,
                                              self.objNameSet),
                            key,
                            self.getPayloadStruct(attributes))

    def __delitem__(self, key):
        """ Function __delitem__
        Delete a parameter of a foreman object

        @param key: The key to modify
        @return RETURN: The API result
        """
        return self.api.delete('{}/{}/{}'.format(self.parentObjName,
                                                 self.parentKey,
                                                 self.objNameSet),
                               key)

    def append(self, payload):
        """ Function __iadd__

        @param payload: The payload corresponding to the object to add
        @return RETURN: A ForemanItem
        """
        if self.objType.setInParentPayload:
            print('Error, {} is not elibible to addition, but only set'
                  .format(self.objName))
            return False
        ret = self.api.create("{}/{}/{}".format(self.parentObjName,
                                                self.parentKey,
                                                self.objNameSet),
                              self.getPayloadStruct(payload))
        return ret

    def getPayloadStruct(self, payload):
        """ Function getPayloadStruct

        @param payload: The payload structure to the object to add
        @return RETURN: A dict
        """
        newSubItem = self.objType(self.api, 0, self.parentObjName,
                                  self.parentPayloadObj, self.parentKey, {})
        return newSubItem.getPayloadStruct(payload, self.parentPayloadObj)


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Core\Provider;

use Doctrine\Common\Collections\ArrayCollection;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Channel\Context\ChannelNotFoundException;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Provider\ChannelBasedLocaleProvider;
use Sylius\Component\Locale\Model\LocaleInterface;
use Sylius\Component\Locale\Provider\LocaleProviderInterface;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class ChannelBasedLocaleProviderSpec extends ObjectBehavior
{
    function let(ChannelContextInterface $channelContext)
    {
        $this->beConstructedWith($channelContext, 'pl_PL');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(ChannelBasedLocaleProvider::class);
    }

    function it_is_a_locale_provider()
    {
        $this->shouldImplement(LocaleProviderInterface::class);
    }

    function it_returns_all_channels_locales_as_available_ones(
        ChannelContextInterface $channelContext,
        ChannelInterface $channel,
        LocaleInterface $enabledLocale
    ) {
        $channelContext->getChannel()->willReturn($channel);

        $channel->getLocales()->willReturn(new ArrayCollection([
            $enabledLocale->getWrappedObject(),
        ]));

        $enabledLocale->getCode()->willReturn('en_US');

        $this->getAvailableLocalesCodes()->shouldReturn(['en_US']);
    }

    function it_returns_the_default_locale_as_the_available_one_if_channel_cannot_be_determined(
        ChannelContextInterface $channelContext
    ) {
        $channelContext->getChannel()->willThrow(ChannelNotFoundException::class);

        $this->getAvailableLocalesCodes()->shouldReturn(['pl_PL']);
    }

    function it_returns_channels_default_locale(
        ChannelContextInterface $channelContext,
        ChannelInterface $channel,
        LocaleInterface $locale
    ) {
        $channelContext->getChannel()->willReturn($channel);

        $channel->getDefaultLocale()->willReturn($locale);

        $locale->getCode()->willReturn('en_US');

        $this->getDefaultLocaleCode()->shouldReturn('en_US');
    }

    function it_returns_the_default_locale_if_channel_cannot_be_determined(
        ChannelContextInterface $channelContext
    ) {
        $channelContext->getChannel()->willThrow(ChannelNotFoundException::class);

        $this->getDefaultLocaleCode()->shouldReturn('pl_PL');
    }
}