Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.
485527
def get_input_channel(entity):
    """"""
    try:
        if entity.SUBCLASS_OF_ID == 0x40f202fd:  # crc32(b'InputChannel')
            return entity
    except AttributeError:
        _raise_cast_fail(entity, 'InputChannel')

    if isinstance(entity, (types.Channel, types.ChannelForbidden)):
        return types.InputChannel(entity.id, entity.access_hash or 0)

    if isinstance(entity, types.InputPeerChannel):
        return types.InputChannel(entity.channel_id, entity.access_hash)

    _raise_cast_fail(entity, 'InputChannel')
636771
def getPeer(self, url):
        
        peers = filter(lambda x: x.getUrl() == url, self.getPeers())
        if len(peers) == 0:
            raise exceptions.PeerNotFoundException(url)
        return peers[0]
1288432
def _getpwnam(name, root=None):
    '''
    
    '''
    root = '/' if not root else root
    passwd = os.path.join(root, 'etc/passwd')
    with salt.utils.files.fopen(passwd) as fp_:
        for line in fp_:
            line = salt.utils.stringutils.to_unicode(line)
            comps = line.strip().split(':')
            if comps[0] == name:
                # Generate a getpwnam compatible output
                comps[2], comps[3] = int(comps[2]), int(comps[3])
                return pwd.struct_passwd(comps)
    raise KeyError
1063686
def _get_inputs(self):
        
        # Convert file inputs to a dict, to make it easier to override
        # them with commandline inputs
        file_inputs = self._get_file_inputs()
        try:
            jsonschema.validate(file_inputs, file_input_schema)
        except jsonschema.ValidationError:
            raise SystemExit("ERROR! Input file was invalid")
        input_dict = {}
        for (channel, input_id) in file_inputs.iteritems():
            input_dict[channel] = input_id

        if self.args.inputs:
            for kv_pair in self.args.inputs:
                (channel, input_id) = kv_pair.split('=')
                input_dict[channel] = self._parse_string_to_nested_lists(
                    input_id)

        inputs = []
        for (channel, contents) in input_dict.iteritems():
            inputs.append({
                'channel': channel,
                'data': {
                    'contents': contents
                }
            })
        return inputs
747337
def input(self):
        """"""
        if self._input is None:
            input_file = self.environ['wsgi.input']
            content_length = self.content_length or 0
            self._input = WsgiInput(input_file, self.content_length)
        return self._input
452523
def srbt(peer, pkts, inter=0.1, *args, **kargs):
    """"""
    s = conf.BTsocket(peer=peer)
    a,b = sndrcv(s,pkts,inter=inter,*args,**kargs)
    s.close()
    return a,b
623718
def get_socket(addr, type=socket.SOCK_STREAM, proto=0):
    '''
    
    '''

    version = ipaddress.ip_address(addr).version
    if version == 4:
        family = socket.AF_INET
    elif version == 6:
        family = socket.AF_INET6
    return socket.socket(family, type, proto)
359739
def _get_inputs(self, old_inputs):
        
        # Convert inputs to dict to facilitate overriding by channel name
        # Also, drop DataNode ID and keep only contents.
        input_dict = {}
        for input in old_inputs:
            # Strip out DataNode UUID and URL
            input['data'] = {'contents': input['data']['contents']}
            input_dict[input['channel']] = input

        file_inputs = self._get_file_inputs()
        try:
            jsonschema.validate(file_inputs, file_input_schema)
        except jsonschema.ValidationError:
            raise SystemExit("ERROR! User inputs file is not valid")
        for (channel, input_id) in file_inputs.iteritems():
            input_dict[channel] = {
                'channel': channel,
                'data': {'contents': input_id}
            }
        # Override with cli user inputs if specified
        if self.args.inputs:
            for kv_pair in self.args.inputs:
                (channel, input_id) = kv_pair.split('=')
                input_dict[channel] = {
                    'channel': channel,
                    'data': {
                        'contents':
                        self._parse_string_to_nested_lists(input_id)}
                }
        return input_dict.values()
1171238
def p2pkh_input_and_witness(outpoint, sig, pubkey, sequence=0xFFFFFFFE):
    '''
    
    '''
    stack_script = '{sig} {pk}'.format(sig=sig, pk=pubkey)
    return tb.make_legacy_input_and_empty_witness(
        outpoint=outpoint,
        stack_script=script_ser.serialize(stack_script),
        redeem_script=b'',
        sequence=sequence)
26748
def _get_input_buffer(self):
        """"""
        input_buffer = ''
        if self.current_prompt_pos is not None:
            input_buffer = self.get_text(self.current_prompt_pos, 'eol')
            input_buffer = input_buffer.replace(os.linesep, '\n')
        return input_buffer
169910
def get_ntp_stats(self):
        """"""
        # NTP Peers does not have XML RPC defined
        # thus we need to retrieve raw text and parse...
        # :(

        ntp_stats = []

        REGEX = (
            r"^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)"
            r"\s+([a-zA-Z0-9\.]+)\s+([0-9]{1,2})"
            r"\s+(-|u)\s+([0-9h-]+)\s+([0-9]+)"
            r"\s+([0-9]+)\s+([0-9\.]+)\s+([0-9\.-]+)"
            r"\s+([0-9\.]+)\s?$"
        )

        ntp_assoc_output = self.device.cli("show ntp associations no-resolve")
        ntp_assoc_output_lines = ntp_assoc_output.splitlines()

        for ntp_assoc_output_line in ntp_assoc_output_lines[3:]:  # except last line
            line_search = re.search(REGEX, ntp_assoc_output_line, re.I)
            if not line_search:
                continue  # pattern not found
            line_groups = line_search.groups()
            try:
                ntp_stats.append(
                    {
                        "remote": napalm.base.helpers.ip(line_groups[1]),
                        "synchronized": (line_groups[0] == "*"),
                        "referenceid": py23_compat.text_type(line_groups[2]),
                        "stratum": int(line_groups[3]),
                        "type": py23_compat.text_type(line_groups[4]),
                        "when": py23_compat.text_type(line_groups[5]),
                        "hostpoll": int(line_groups[6]),
                        "reachability": int(line_groups[7]),
                        "delay": float(line_groups[8]),
                        "offset": float(line_groups[9]),
                        "jitter": float(line_groups[10]),
                    }
                )
            except Exception:
                continue  # jump to next line

        return ntp_stats
853649
def get_pmt(self, dom_id, channel_id):
        """"""
        du, floor, _ = self.doms[dom_id]
        pmt = self.pmts[self._pmt_index_by_omkey[(du, floor, channel_id)]]
        return pmt
183998
def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)
259409
def _get_channel(host, timeout):
    
    connection = create_blocking_connection(host)

    # register timeout
    if timeout >= 0:
        connection.add_timeout(
            timeout,
            lambda: sys.stderr.write("Timeouted!\n") or sys.exit(1)
        )

    return connection.channel()
500887
def from_input(cls, input, workdir=None, manager=None):
        
        return cls(input, workdir=workdir, manager=manager)
1134893
def GetInput(self):
    """"""
    client_list = GetAllClients(token=self.token)
    logging.debug("Got %d clients", len(client_list))
    for client_group in collection.Batch(client_list, self.client_chunksize):
      for fd in aff4.FACTORY.MultiOpen(
          client_group,
          mode="r",
          aff4_type=aff4_grr.VFSGRRClient,
          token=self.token):
        if isinstance(fd, aff4_grr.VFSGRRClient):
          # Skip if older than max_age
          oldest_time = (time.time() - self.max_age) * 1e6
        if fd.Get(aff4_grr.VFSGRRClient.SchemaCls.PING) >= oldest_time:
          yield fd
585872
def recv(self, buf=None, flags=0):
        """"""
        if buf is None:
            rtn, out_buf = wrapper.nn_recv(self.fd, flags)
        else:
            rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags)
        _nn_check_positive_rtn(rtn)
        return bytes(buffer(out_buf))[:rtn]