def disconnect_async(self, conn_id, callback):

        found_handle = None
        # Find the handle by connection id
        for handle, conn in self._connections.items():
            if conn['connection_id'] == conn_id:
                found_handle = handle

        if found_handle is None:
            callback(conn_id, self.id, False, 'Invalid connection_id')
            return

        self._command_task.async_command(['_disconnect', found_handle], self._on_disconnect,
                                         {'connection_id': conn_id, 'handle': found_handle,
                                          'callback': callback})

Asynchronously disconnect from a device that has previously been connected

Args:
        conn_id (int): a unique identifier for this connection on the DeviceManager
            that owns this adapter.
        callback (callable): A function called as callback(conn_id, adapter_id, success, failure_reason)
        when the disconnection finishes.  Disconnection can only either succeed or timeout.


def _CreateLineReader(self, file_object):

    # The Python 2 csv module reads bytes and the Python 3 csv module Unicode
    # reads strings.
    if py2to3.PY_3:
      line_reader = text_file.TextFile(
          file_object, encoding=self._encoding, end_of_line=self._end_of_line)

      # pylint: disable=protected-access
      maximum_read_buffer_size = line_reader._MAXIMUM_READ_BUFFER_SIZE

    else:
      line_reader = line_reader_file.BinaryLineReader(
          file_object, end_of_line=self._end_of_line)

      maximum_read_buffer_size = line_reader.MAXIMUM_READ_BUFFER_SIZE

    # Line length is one less than the maximum read buffer size so that we
    # tell if there's a line that doesn't end at the end before the end of
    # the file.
    if self._maximum_line_length > maximum_read_buffer_size:
      self._maximum_line_length = maximum_read_buffer_size - 1

    # If we specifically define a number of lines we should skip, do that here.
    for _ in range(0, self.NUMBER_OF_HEADER_LINES):
      line_reader.readline(self._maximum_line_length)
    return line_reader

Creates an object that reads lines from a text file.

    The line reader is advanced to the beginning of the DSV content, skipping
    any header lines.

Args:
        file_object (dfvfs.FileIO): file-like object.

Returns:
        TextFile|BinaryLineReader: an object that implements an iterator
        over lines in a text file.

Raises:
        UnicodeDecodeError: if the file cannot be read with the specified
        encoding.


def _sendline(self, line):

        logging.info('%s: sending line', self.port)
        # clear buffer
        self._lines = []
        try:
            self._read()
        except socket.error:
            logging.debug('%s: Nothing cleared', self.port)

        print 'sending [%s]' % line
        self._write(line + '\r\n')

        # wait for write to complete
        time.sleep(0.1)

Send exactly one line to the device

Args:
        line str: data send to device


def select_by_value(self, value):

        self._selected_key = None
        self._selected_item = None
        for k in self.children:
            item = self.children[k]
            item.attributes['selected'] = False
            if value == item.get_value():
                self._selected_key = k
                self._selected_item = item
                self._selected_item.attributes['selected'] = True

Selects an item by the text content of the child.

Args:
        value (str): Text content of the item that have to be selected.


def _internal_add(self, pattern: Pattern, label, renaming) -> int:

        pattern_index = len(self.patterns)
        renamed_constraints = [c.with_renamed_vars(renaming) for c in pattern.local_constraints]
        constraint_indices = [self._add_constraint(c, pattern_index) for c in renamed_constraints]
        self.patterns.append((pattern, label, constraint_indices))
        self.pattern_vars.append(renaming)
        pattern = rename_variables(pattern.expression, renaming)
        state = self.root
        patterns_stack = [deque([pattern])]

        self._process_pattern_stack(state, patterns_stack, renamed_constraints, pattern_index)

        return pattern_index

Add a new pattern to the matcher.

    Equivalent patterns are not added again. However, patterns that are structurally equivalent,
    but have different constraints or different variable names are distinguished by the matcher.

Args:
        pattern: The pattern to add.

Returns:
        The internal id for the pattern. This is mainly used by the :class:`CommutativeMatcher`.


def load(fin, dtype=np.float32, max_vocab=None):

    vocab = {}
    arr = None
    i = 0
    for line in fin:
        if max_vocab is not None and i >= max_vocab:
            break
        try:
            token, v = _parse_line(line, dtype)
        except (ValueError, IndexError):
            raise ParseError(b'Parsing error in line: ' + line)
        if token in vocab:
            parse_warn(b'Duplicated vocabulary ' + token)
            continue
        if arr is None:
            arr = np.array(v, dtype=dtype).reshape(1, -1)
        else:
            if arr.shape[1] != len(v):
                raise ParseError(b'Vector size did not match in line: ' + line)
            arr = np.append(arr, [v], axis=0)
        vocab[token] = i
        i += 1
    return arr, vocab

Load word embedding file.

Args:
        fin (File): File object to read. File should be open for reading ascii.
        dtype (numpy.dtype): Element data type to use for the array.
        max_vocab (int): Number of vocabulary to read.

Returns:
        numpy.ndarray: Word embedding representation vectors
        dict: Mapping from words to vector indices.


def process_tag(self, tag_proc_name, tag):

        tag_processor = self.tag_procs[tag_proc_name]

        db_entry = (tag_processor.get_name(tag),
                    tag_processor.get_entry_type(tag),
                    tag_processor.get_filename(tag))

        self.zeal_db.insert(*db_entry)

        self.entry_count += 1

Process a tag with a tag processor and insert a DB entry.

Args:
        tag_proc_name: A string key that maps to the TagProcessor to use.
        tag: A BeautifulSoup Tag to process.


def add_curves_from_las(self, fname, remap=None, funcs=None):

        try:  # To treat as a single file
            self.add_curves_from_lasio(lasio.read(fname),
                                       remap=remap,
                                       funcs=funcs
                                       )
        except:  # It's a list!
            for f in fname:
                self.add_curves_from_lasio(lasio.read(f),
                                           remap=remap,
                                           funcs=funcs
                                           )

        return None

Given a LAS file, add curves from it to the current well instance.
    Essentially just wraps ``add_curves_from_lasio()``.

Args:
        fname (str): The path of the LAS file to read curves from.
        remap (dict): Optional. A dict of 'old': 'new' LAS field names.
        funcs (dict): Optional. A dict of 'las field': function() for
            implementing a transform before loading. Can be a lambda.

Returns:
        None. Works in place.


def List(self, device_path):

        connection = self.protocol_handler.Open(self._handle, destination=b'sync:')
        listing = self.filesync_handler.List(connection, device_path)
        connection.Close()
        return listing

Return a directory listing of the given path.

Args:
        device_path: Directory to list.


def bind(self, devices_to_bind):

        if self.entity_api_key == "":
            return {'status': 'failure', 'response': 'No API key found in request'}
        url = self.base_url + "api/0.1.0/subscribe/bind"
        headers = {"apikey": self.entity_api_key}
        data = {
            "exchange": "amq.topic",
            "keys": devices_to_bind,
            "queue": self.entity_id
        }

        with self.no_ssl_verification():
            r = requests.post(url, json=data, headers=headers)
        response = dict()
        if "No API key" in str(r.content.decode("utf-8")):
            response["status"] = "failure"
            r = json.loads(r.content.decode("utf-8"))['message']
        elif 'bind queue ok' in str(r.content.decode("utf-8")):
            response["status"] = "success"
            r = r.content.decode("utf-8")
        else:
            response["status"] = "failure"
            r = r.content.decode("utf-8")
        response["response"] = str(r)
        return response

This function allows an entity to list the devices to subscribe for data. This function must be called
    at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here.

Args:
        devices_to_bind  (list): an array of devices to listen to.
                                Example bind(["test100","testDemo"])


def get_fieldset_index(fieldsets, index_or_name):

    if isinstance(index_or_name, six.integer_types):
        return index_or_name

    for key, value in enumerate(fieldsets):
        if value[0] == index_or_name:
            return key

    raise KeyError("Key not found: '{}'.".format(index_or_name))

Return the index of a fieldset in the ``fieldsets`` list.

Args:
        fieldsets (list): The original ``fieldsets`` list.
        index_or_name (int or str): The value of the reference element, or directly its numeric index.

Returns:
        (int) The index of the fieldset in the ``fieldsets`` list.


def export_to_tf_tensor(self, x, laid_out_x):

    return self.combine_slices(laid_out_x.all_slices, x.shape)

Turn a Tensor into a tf.Tensor.

Args:
        x: a Tensor
        laid_out_x: a LaidOutTensor

Returns:
        a tf.Tensor


def _UpdateSudoer(self, user, sudoer=False):

    if sudoer:
      self.logger.info('Adding user %s to the Google sudoers group.', user)
      command = self.gpasswd_add_cmd.format(
          user=user, group=self.google_sudoers_group)
    else:
      self.logger.info('Removing user %s from the Google sudoers group.', user)
      command = self.gpasswd_remove_cmd.format(
          user=user, group=self.google_sudoers_group)

    try:
      subprocess.check_call(command.split(' '))
    except subprocess.CalledProcessError as e:
      self.logger.warning('Could not update user %s. %s.', user, str(e))
      return False
    else:
      self.logger.debug('Removed user %s from the Google sudoers group.', user)
      return True

Update sudoer group membership for a Linux user account.

Args:
        user: string, the name of the Linux user account.
        sudoer: bool, True if the user should be a sudoer.

Returns:
        bool, True if user update succeeded.


def struct_member_error(err, sid, name, offset, size):

    exception, msg = STRUCT_ERROR_MAP[err]
    struct_name = idc.GetStrucName(sid)
    return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) '
                      'failed: {}').format(
        struct_name,
        name,
        offset,
        size,
        msg
    ))

Create and format a struct member exception.

Args:
        err: The error value returned from struct member creation
        sid: The struct id
        name: The member name
        offset: Memeber offset
        size: Member size

Returns:
        A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an
        informative message.


def _or_join(self, terms):

        if isinstance(terms, (tuple, list)):
            if len(terms) > 1:
                return '(' + ' OR '.join(terms) + ')'
            else:
                return terms[0]
        else:
            return terms

Joins terms using OR operator.

Args:
        terms (list): terms to join

Example:
        self._or_join(['term1', 'term2']) -> 'term1 OR term2'

Returns:
        str


def on_connection_state_change(self, event_type, callback):

        listeners = self._connection_state_listeners.get(event_type, [])
        listeners.append(callback)
        self._connection_state_listeners[event_type] = listeners

Register a callback for a specific connection state change.

    Register a callback to be triggered when the connection changes to
    the specified state, signified by a ConnectionEvent.

    The callback must be a coroutine.

Args:
        event_type (ConnectionEvent): the connection event to listen for
        callback (coroutine): a coroutine to call on the event occurrence


def setAccessPolicy(self, pid, accessPolicy, serialVersion, vendorSpecific=None):

        response = self.setAccessPolicyResponse(
            pid, accessPolicy, serialVersion, vendorSpecific
        )
        return self._read_boolean_response(response)

See Also: setAccessPolicyResponse()

Args:
        pid:
        accessPolicy:
        serialVersion:
        vendorSpecific:

    Returns:


def QA_util_make_hour_index(day, type_='1h'):

    if QA_util_if_trade(day) is True:
        return pd.date_range(
            str(day) + ' 09:30:00',
            str(day) + ' 11:30:00',
            freq=type_,
            closed='right'
        ).append(
            pd.date_range(
                str(day) + ' 13:00:00',
                str(day) + ' 15:00:00',
                freq=type_,
                closed='right'
            )
        )
    else:
        return pd.DataFrame(['No trade'])

创建股票的小时线的index

Args:
        day {[type]} -- [description]

Returns:
        [type] -- [description]


def add_file_to_tree(tree, file_path, file_contents, is_executable=False):

    record = {
        "path": file_path,
        "mode": "100755" if is_executable else "100644",
        "type": "blob",
        "content": file_contents,
        }
    tree.append(record)
    return tree

Add a file to a tree.

Args:
        tree
            A list of dicts containing info about each blob in a tree.

        file_path
            The path of the new file in the tree.

        file_contents
            The (UTF-8 encoded) contents of the new file.

        is_executable
            If ``True``, the new file will get executable permissions (0755).
            Otherwise, it will get 0644 permissions.

Returns:
        The provided tree, but with the new file added.


def GetSubkeyByIndex(self, index):

    subkeys = list(self._subkeys.values())

    if index < 0 or index >= len(subkeys):
      raise IndexError('Index out of bounds.')

    return subkeys[index]

Retrieves a subkey by index.

Args:
        index (int): index of the subkey.

Returns:
        WinRegistryKey: Windows Registry subkey or None if not found.

Raises:
        IndexError: if the index is out of bounds.


def create_tree(tree):

    # Create tree
    config.LOGGER.info("\nCreating tree on Kolibri Studio...")
    channel_id, channel_link = tree.upload_tree()
    # channel_id, channel_link = tree.upload_channel_structure()

    return channel_link, channel_id

create_tree: Upload tree to Kolibri Studio

Args:
        tree (ChannelManager): manager to handle communication to Kolibri Studio
    Returns: channel id of created channel and link to channel


def build_exon(exon_info, build='37'):

    try:
        chrom = exon_info['chrom']
    except KeyError:
        raise KeyError("Exons has to have a chromosome")

    try:
        start = int(exon_info['start'])
    except KeyError:
        raise KeyError("Exon has to have a start")
    except TypeError:
        raise TypeError("Exon start has to be integer")

    try:
        end = int(exon_info['end'])
    except KeyError:
        raise KeyError("Exon has to have a end")
    except TypeError:
        raise TypeError("Exon end has to be integer")

    try:
        rank = int(exon_info['rank'])
    except KeyError:
        raise KeyError("Exon has to have a rank")
    except TypeError:
        raise TypeError("Exon rank has to be integer")

    try:
        exon_id = exon_info['exon_id']
    except KeyError:
        raise KeyError("Exons has to have a id")

    try:
        transcript = exon_info['transcript']
    except KeyError:
        raise KeyError("Exons has to have a transcript")

    try:
        hgnc_id = int(exon_info['hgnc_id'])
    except KeyError:
        raise KeyError("Exons has to have a hgnc_id")
    except TypeError:
        raise TypeError("hgnc_id has to be integer")

    exon_obj = Exon(
        exon_id = exon_id,
        chrom = chrom,
        start = start,
        end = end,
        rank = rank,
        transcript = transcript,
        hgnc_id = hgnc_id,
        build = build,
    )

    return exon_obj

Build a Exon object object

Args:
        exon_info(dict): Exon information

Returns:
        exon_obj(Exon)

    "exon_id": str, # str(chrom-start-end)
    "chrom": str,
    "start": int,
    "end": int,
    "transcript": str, # ENST ID
    "hgnc_id": int,      # HGNC_id
    "rank": int, # Order of exon in transcript
    "build": str, # Genome build