code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
fields = []
if asm_format:
indexed_operand = set(['name', 'local', 'compare', 'free'])
# Column: Source code line number
if lineno_width:
if self.starts_line is not None:
if asm_format:
lineno_fmt = "%%%dd:\n" % lineno_width
fields.append(lineno_fmt % self.starts_line)
fields.append(' ' * (lineno_width))
if self.is_jump_target:
fields.append(' ' * (lineno_width-1))
else:
lineno_fmt = "%%%dd:" % lineno_width
fields.append(lineno_fmt % self.starts_line)
else:
fields.append(' ' * (lineno_width+1))
# Column: Current instruction indicator
if mark_as_current and not asm_format:
fields.append('-->')
else:
fields.append(' ')
# Column: Jump target marker
if self.is_jump_target:
if not asm_format:
fields.append('>>')
else:
fields = ["L%d:\n" % self.offset] + fields
if not self.starts_line:
fields.append(' ')
else:
fields.append(' ')
# Column: Instruction offset from start of code sequence
if not asm_format:
fields.append(repr(self.offset).rjust(4))
if show_bytes:
hex_bytecode = "|%02x" % self.opcode
if self.inst_size == 1:
# Not 3.6 or later
hex_bytecode += ' ' * (2*3)
if self.inst_size == 2:
# Must by Python 3.6 or later
if self.has_arg:
hex_bytecode += " %02x" % (self.arg % 256)
else :
hex_bytecode += ' 00'
elif self.inst_size == 3:
# Not 3.6 or later
hex_bytecode += " %02x %02x" % (
(self.arg >> 8, self.arg % 256))
fields.append(hex_bytecode + '|')
# Column: Opcode name
fields.append(self.opname.ljust(20))
# Column: Opcode argument
if self.arg is not None:
argrepr = self.argrepr
if asm_format:
if self.optype == 'jabs':
fields.append('L' + str(self.arg))
elif self.optype == 'jrel':
argval = self.offset + self.arg + self.inst_size
fields.append('L' + str(argval))
elif self.optype in indexed_operand:
fields.append('(%s)' % argrepr)
argrepr = None
elif (self.optype == 'const'
and not re.search('\s', argrepr)):
fields.append('(%s)' % argrepr)
argrepr = None
else:
fields.append(repr(self.arg))
elif not (show_bytes and argrepr):
fields.append(repr(self.arg).rjust(6))
# Column: Opcode argument details
if argrepr:
fields.append('(%s)' % argrepr)
pass
pass
return ' '.join(fields).rstrip() | def disassemble(self, lineno_width=3,
mark_as_current=False,
asm_format=False,
show_bytes=False) | Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*mark_as_current* inserts a '-->' marker arrow as part of the line | 3.015571 | 3.046255 | 0.989927 |
while tb.tb_next:
tb = tb.tb_next
return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) | def from_traceback(cls, tb) | Construct a Bytecode from the given traceback | 3.139473 | 2.981538 | 1.052971 |
co = self.codeobj
if self.current_offset is not None:
offset = self.current_offset
else:
offset = -1
output = StringIO()
self.disassemble_bytes(co.co_code, varnames=co.co_varnames,
names=co.co_names, constants=co.co_consts,
cells=self._cell_names,
linestarts=self._linestarts,
line_offset=self._line_offset,
file=output,
lasti=offset,
asm_format=asm_format,
show_bytes=show_bytes)
return output.getvalue() | def dis(self, asm_format=False, show_bytes=False) | Return a formatted view of the bytecode operations. | 2.95033 | 2.782181 | 1.060438 |
co = get_code_object(x)
cell_names = co.co_cellvars + co.co_freevars
linestarts = dict(self.opc.findlinestarts(co))
if first_line is not None:
line_offset = first_line - co.co_firstlineno
else:
line_offset = 0
return get_instructions_bytes(co.co_code, self.opc, co.co_varnames,
co.co_names, co.co_consts, cell_names, linestarts,
line_offset) | def get_instructions(self, x, first_line=None) | Iterator for the opcodes in methods, functions or code
Generates a series of Instruction named tuples giving the details of
each operations in the supplied code.
If *first_line* is not None, it indicates the line number that should
be reported for the first source line in the disassembled code.
Otherwise, the source line information (if any) is taken directly from
the disassembled code object. | 2.846259 | 3.225609 | 0.882394 |
if PYTHON3:
byte_increments = code.co_lnotab[0::2]
line_increments = code.co_lnotab[1::2]
else:
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]
line_increments = [ord(c) for c in code.co_lnotab[1::2]]
lastlineno = None
lineno = code.co_firstlineno
addr = 0
for byte_incr, line_incr in zip(byte_increments, line_increments):
if byte_incr:
if (lineno != lastlineno or
(not dup_lines and 0 < byte_incr < 255)):
yield (addr, lineno)
lastlineno = lineno
addr += byte_incr
if line_incr >= 0x80:
# line_increments is an array of 8-bit signed integers
line_incr -= 0x100
lineno += line_incr
if (lineno != lastlineno or
(not dup_lines and 0 < byte_incr < 255)):
yield (addr, lineno) | def findlinestarts(code, dup_lines=False) | Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c. | 2.114147 | 2.045027 | 1.033799 |
offsets = []
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if arg is not None:
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
else:
continue
if jump_offset not in offsets:
offsets.append(jump_offset)
return offsets | def get_jump_targets(code, opc) | Returns a list of instruction offsets in the supplied bytecode
which are the targets of some sort of jump instruction. | 3.718266 | 3.388372 | 1.09736 |
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
prev_offset = offset
if op in opc.NOFOLLOW:
prev_offset = -1
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev | def get_jump_target_maps(code, opc) | Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachible
instructions. The values of the dictionary may be useful in control-flow
analysis. | 2.579139 | 2.432834 | 1.060138 |
if isinstance(python_version, float):
major = int(python_version)
minor = int(((python_version - major) + 0.05) * 10)
python_version = (major, minor)
return _StdApi(python_version, variant) | def make_std_api(python_version=sys.version_info, variant=VARIANT) | Generate an object which can be used in the same way as the python
standard dis module. The difference is that the generated 'module' can be
used to disassemble byte / word code from a different python version than
the version of the interpreter under which we are running.
:param python_version: Generate a dis module for this version of python
(defaults to the currently running python version.)
:param variant: The string denoting the variant of the python version
being run, for example 'pypy' or 'alpha0', 'rc1' etc,
or None to auto detect based on the currently running
interpreter.
:return: object which can be used like the std dis module. | 3.044444 | 3.81734 | 0.79753 |
return _show_code(x, self.opc.version, file) | def show_code(self, x, file=None) | Print details of methods, functions, or code to *file*.
If *file* is not provided, the output is printed on stdout. | 18.631386 | 28.393917 | 0.656175 |
self._print(self.Bytecode(x).dis(), file) | def dis(self, x=None, file=None) | Disassemble classes, methods, functions, generators, or code.
With no argument, disassemble the last traceback. | 27.975307 | 20.413025 | 1.370464 |
if tb is None:
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError("no last traceback to disassemble")
while tb.tb_next: tb = tb.tb_next
self.disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file) | def distb(self, tb=None, file=None) | Disassemble a traceback (default: last traceback). | 2.591325 | 2.126756 | 1.21844 |
return self.disco(code, lasti, file) | def disassemble(self, code, lasti=-1, file=None) | Disassemble a code object. | 7.487426 | 6.502685 | 1.151436 |
return _disco(self.python_version, code, timestamp=0,
out=file, is_pypy=self.is_pypy, header=False) | def disco(self, code, lasti=-1, file=None) | Disassemble a code object. | 12.370123 | 11.205572 | 1.103926 |
return self.Bytecode(x).get_instructions(x, first_line) | def get_instructions(self, x, first_line=None) | Iterator for the opcodes in methods, functions or code
Generates a series of Instruction named tuples giving the details of
each operations in the supplied code.
If *first_line* is not None, it indicates the line number that should
be reported for the first source line in the disassembled code.
Otherwise, the source line information (if any) is taken directly from
the disassembled code object. | 9.844019 | 10.879174 | 0.90485 |
DELTA = 0x9e3779b9
n = len(v)
rounds = 6 + 52//n
sum = (rounds*DELTA)
y = v[0]
while sum != 0:
e = (sum >> 2) & 3
for p in range(n-1, -1, -1):
z = v[(n + p - 1) % n]
v[p] = (v[p] - MX(z, y, sum, key, p, e)) & 0xffffffff
y = v[p]
sum -= DELTA
return v | def tea_decipher(v, key) | Tiny Decryption Algorithm decription (TEA)
See https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm | 4.201798 | 4.215447 | 0.996762 |
a = self.load_int()
b = self.load_int()
key = get_keys(a, b)
padsize = (b + 15) & ~0xf
intsize = padsize/4
data = self.bufstr[self.bufpos:self.bufpos+padsize]
# print("%d: %d (%d=%d)" % (self.bufpos, b, padsize, len(data)))
data = list(struct.unpack('<%dL' % intsize, data))
tea_decipher(data, key)
self.bufpos += padsize
obj = xmarshal._FastUnmarshaller(struct.pack('<%dL' % intsize, *data))
code = obj.load_code()
co_code = patch(code.co_code)
if PYTHON3:
return Code2Compat(code.co_argcount, code.co_nlocals, code.co_stacksize,
code.co_flags,
co_code, code.co_consts, code.co_names, code.co_varnames,
code.co_filename, code.co_name, code.co_firstlineno,
code.co_lnotab, code.co_freevars, code.co_cellvars)
else:
return types.CodeType(code.co_argcount, code.co_nlocals, code.co_stacksize, code.co_flags,
co_code, code.co_consts, code.co_names, code.co_varnames,
code.co_filename, code.co_name, code.co_firstlineno,
code.co_lnotab, code.co_freevars, code.co_cellvars) | def load_code(self) | Returns a Python code object like xdis.unmarshal.load_code(),
but in we decrypt the data in self.bufstr.
That is:
* calculate the TEA key,
* decrypt self.bufstr
* create and return a Python code-object | 2.714541 | 2.534447 | 1.071058 |
um = xmarshal._FastUnmarshaller(s)
um.dispatch[xmarshal.TYPE_CODE] = load_code
return um.load() | def loads(s) | xdis.marshal.load() but with its dispatch load_code() function replaced
with our decoding version. | 19.212606 | 9.540247 | 2.013848 |
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls | def get_protocol_from_name(name) | Returns the protocol class for the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: The protocol class. | 3.742326 | 4.534064 | 0.82538 |
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls(**kwargs) | def create_protocol(name, **kwargs) | Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol. | 3.093619 | 3.88482 | 0.796335 |
host = to_host(host, default_protocol=default_protocol)
protocol = host.get_protocol()
conn = create_protocol(protocol, **kwargs)
if protocol == 'pseudo':
filename = host.get_address()
conn.device.add_commands_from_file(filename)
return conn | def prepare(host, default_protocol='telnet', **kwargs) | Creates an instance of the protocol by either parsing the given
URL-formatted hostname using :class:`Exscript.util.url`, or according to
the options of the given :class:`Exscript.Host`.
:type host: str or Host
:param host: A URL-formatted hostname or a :class:`Exscript.Host` instance.
:type default_protocol: str
:param default_protocol: Protocol that is used if the URL specifies none.
:type kwargs: dict
:param kwargs: Passed to the protocol constructor.
:rtype: Protocol
:return: An instance of the protocol. | 5.203897 | 7.21487 | 0.721274 |
host = to_host(host)
conn = prepare(host, default_protocol, **kwargs)
account = host.get_account()
conn.connect(host.get_address(), host.get_tcp_port())
if account is not None:
conn.login(account)
return conn | def connect(host, default_protocol='telnet', **kwargs) | Like :class:`prepare()`, but also connects to the host by calling
:class:`Protocol.connect()`. If the URL or host contain any login info, this
function also logs into the host using :class:`Protocol.login()`.
:type host: str or Host
:param host: A URL-formatted hostname or a :class:`Exscript.Host` object.
:type default_protocol: str
:param default_protocol: Protocol that is used if the URL specifies none.
:type kwargs: dict
:param kwargs: Passed to the protocol constructor.
:rtype: Protocol
:return: An instance of the protocol. | 4.044531 | 4.997929 | 0.809241 |
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h]))
return hashnum | def _long_from_raw(thehash) | Fold to a long, a digest supplied as a string. | 4.085284 | 4.167863 | 0.980187 |
if len(password) not in list(range(4, 64)):
raise ValueError('passphrase length')
if len(seed) not in list(range(1, 17)):
raise ValueError('seed length')
for x in seed:
if not x in _VALIDSEEDCHARACTERS:
raise ValueError('seed composition')
if sequence < 0:
raise ValueError('sequence')
# Pycryptodome only supports byte strings.
seed = seed.encode('utf-8')
password = password.encode('utf-8')
# Discard the first <sequence> keys
thehash = MD4.new(seed + password).digest()
thehash = _fold_md4_or_md5(thehash)
for i in range(0, sequence):
thehash = _fold_md4_or_md5(MD4.new(thehash).digest())
# Generate the result
return _sixword_from_raw(thehash) | def otp(password, seed, sequence) | Calculates a one-time password hash using the given password, seed, and
sequence number and returns it.
Uses the MD4/sixword algorithm as supported by TACACS+ servers.
:type password: str
:param password: A password.
:type seed: str
:param seed: A cryptographic seed.
:type sequence: int
:param sequence: A sequence number.
:rtype: string
:return: A hash. | 4.023088 | 3.883417 | 1.035966 |
if isinstance(string, Protocol):
string = string.response
return _first_match(string, re.compile(regex, flags)) | def first_match(string, regex, flags=re.M) | Matches the given string against the given regex.
- If no match is found and the regular expression has zero or one
groups, this function returns None.
- If no match is found and the regular expression has more than one
group, this function returns a tuple of None. The number of elements
in the tuple equals the number of groups in the regular expression.
- If a match is found and the regular expression has no groups,
the entire string is returned.
- If a match is found and the regular expression has one group,
the matching string from the group is returned.
- If a match is found and the regular expression has multiple groups,
a tuple containing the matching strings from the groups is returned.
This behavior ensures that the following assignments can never fail::
foo = 'my test'
match = first_match(foo, r'aaa') # Returns None
match = first_match(foo, r'\S+') # Returns 'my test'
match = first_match(foo, r'(aaa)') # Returns None
match = first_match(foo, r'(\S+)') # Returns 'my'
match = first_match(foo, r'(aaa) (\S+)') # Returns (None, None)
match = first_match(foo, r'(\S+) (\S+)') # Returns ('my', 'foo')
:type string: string|Exscript.protocols.Protocol
:param string: The string that is matched, or a Protocol object.
:type regex: string
:param regex: A regular expression.
:type flags: int
:param flags: The flags for compiling the regex; e.g. re.I
:rtype: string|tuple
:return: A match, or a tuple of matches. | 6.537038 | 5.879942 | 1.111752 |
if isinstance(string, Protocol):
string = string.response
compiled = re.compile(regex, flags)
results = []
if compiled.groups <= 1:
for line in string.split('\n'):
match = _first_match(line, compiled)
if match is None:
continue
results.append(match)
else:
for line in string.split('\n'):
match = _first_match(line, compiled)
if match[0] is None:
continue
results.append(match)
return results | def any_match(string, regex, flags=re.M) | Matches the given string against the given regex.
- If no match is found, this function returns an empty list.
- If a match is found and the regular expression has no groups,
a list of matching lines returned.
- If a match is found and the regular expression has one group,
a list of matching strings is returned.
- If a match is found and the regular expression has multiple groups,
a list containing tuples of matching strings is returned.
This behavior ensures that the following can never fail::
foo = '1 uno\\n2 due'
for m in any_match(foo, r'aaa'): # Returns []
print(m)
for m in any_match(foo, r'\S+'): # Returns ['1 uno', '2 due']
print(m)
for m in any_match(foo, r'(aaa)'): # Returns []
print(m)
for m in any_match(foo, r'(\S+)'): # Returns ['1', '2']
print(m)
for one, two in any_match(foo, r'(aaa) (\S+)'): # Returns []
print(m)
for one, two in any_match(foo, r'(\S+) (\S+)'): # Returns [('1', 'uno'), ('2', 'due')]
print(m)
:type string: string|Exscript.protocols.Protocol
:param string: The string that is matched, or a Protocol object.
:type regex: string
:param regex: A regular expression.
:type flags: int
:param flags: The flags for compiling the regex; e.g. re.I
:rtype: list[string|tuple]
:return: A list of strings, or a list of tuples. | 2.682902 | 2.47708 | 1.083091 |
sys.stdout.flush()
sys.stderr.flush()
# UNIX double-fork magic. We need to fork before any threads are
# created.
pid = os.fork()
if pid > 0:
# Exit first parent.
sys.exit(0)
# Decouple from parent environment.
os.chdir('/')
os.setsid()
os.umask(0)
# Now fork again.
pid = os.fork()
if pid > 0:
# Exit second parent.
sys.exit(0)
_redirect_output(os.devnull) | def daemonize() | Forks and daemonizes the current process. Does not automatically track
the process id; to do this, use :class:`Exscript.util.pidutil`. | 2.551119 | 2.836895 | 0.899264 |
self.exc_info = exc_info
self.did_end = True
self.write(format_exception(*self.exc_info)) | def aborted(self, exc_info) | Called by a logger to log an exception. | 5.91113 | 5.1662 | 1.144193 |
if keytype is None:
try:
key = RSAKey.from_private_key_file(filename)
keytype = 'rsa'
except SSHException as e:
try:
key = DSSKey.from_private_key_file(filename)
keytype = 'dss'
except SSHException as e:
msg = 'not a recognized private key: ' + repr(filename)
raise ValueError(msg)
key = PrivateKey(keytype)
key.filename = filename
key.password = password
return key | def from_file(filename, password='', keytype=None) | Returns a new PrivateKey instance with the given attributes.
If keytype is None, we attempt to automatically detect the type.
:type filename: string
:param filename: The key file name.
:type password: string
:param password: The key password.
:type keytype: string
:param keytype: The key type.
:rtype: PrivateKey
:return: The new key. | 2.32359 | 2.340901 | 0.992605 |
theip = ip
if theip.startswith('::'):
theip = '0' + theip
if theip.endswith('::'):
theip += '0'
segments = theip.split(':')
if len(segments) == 1:
raise ValueError('no colons in ipv6 address: ' + repr(ip))
fill = 8 - len(segments)
if fill < 0:
raise ValueError('ipv6 address has too many segments: ' + repr(ip))
result = []
for segment in segments:
if segment == '':
if fill == 0:
raise ValueError('unexpected double colon: ' + repr(ip))
for n in range(fill + 1):
result.append('0000')
fill = 0
else:
try:
int(segment, 16)
except ValueError:
raise ValueError('invalid hex value in ' + repr(ip))
result.append(segment.rjust(4, '0'))
return ':'.join(result).lower() | def normalize_ip(ip) | Transform the address into a standard, fixed-length form, such as:
1234:0:01:02:: -> 1234:0000:0001:0002:0000:0000:0000:0000
1234::A -> 1234:0000:0000:0000:0000:0000:0000:000a
:type ip: string
:param ip: An IP address.
:rtype: string
:return: The normalized IP. | 2.426972 | 2.489334 | 0.974948 |
theip = normalize_ip(ip)
segments = ['%x' % int(s, 16) for s in theip.split(':')]
# Find the longest consecutive sequence of zeroes.
seq = {0: 0}
start = None
count = 0
for n, segment in enumerate(segments):
if segment != '0':
start = None
count = 0
continue
if start is None:
start = n
count += 1
seq[count] = start
# Replace those zeroes by a double colon.
count = max(seq)
start = seq[count]
result = []
for n, segment in enumerate(segments):
if n == start and count > 1:
if n == 0:
result.append('')
result.append('')
if n == 7:
result.append('')
continue
elif start < n < start + count:
if n == 7:
result.append('')
continue
result.append(segment)
return ':'.join(result) | def clean_ip(ip) | Cleans the ip address up, useful for removing leading zeros, e.g.::
1234:0:01:02:: -> 1234:0:1:2::
1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a
1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1::
0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:0:0
:type ip: string
:param ip: An IP address.
:rtype: string
:return: The cleaned up IP. | 3.066605 | 3.013411 | 1.017652 |
if '/' in prefix:
network, pfxlen = prefix.split('/')
else:
network = prefix
pfxlen = default_length
return network, int(pfxlen) | def parse_prefix(prefix, default_length=128) | Splits the given IP prefix into a network address and a prefix length.
If the prefix does not have a length (i.e., it is a simple IP address),
it is presumed to have the given default length.
:type prefix: string
:param prefix: An IP mask.
:type default_length: long
:param default_length: The default ip prefix length.
:rtype: string, int
:return: A tuple containing the IP address and prefix length. | 2.997637 | 3.196667 | 0.937738 |
try:
uri = Url.from_string(uri, self.protocol)
except ValueError:
raise ValueError('Hostname parse error: ' + repr(uri))
hostname = uri.hostname or ''
name = uri.path and hostname + uri.path or hostname
self.set_protocol(uri.protocol)
self.set_tcp_port(uri.port)
self.set_name(name)
self.set_address(name)
if uri.username is not None \
or uri.password1 is not None \
or uri.password2:
account = Account(uri.username, uri.password1, uri.password2)
self.set_account(account)
for key, val in list(uri.vars.items()):
self.set(key, val) | def set_uri(self, uri) | Defines the protocol, hostname/address, TCP port number, username,
and password from the given URL. The hostname may be URL formatted,
so the following formats are all valid:
- myhostname
- myhostname.domain
- ssh:hostname
- ssh:hostname.domain
- ssh://hostname
- ssh://user@hostname
- ssh://user:password@hostname
- ssh://user:password@hostname:21
For a list of supported protocols please see set_protocol().
:type uri: string
:param uri: An URL formatted hostname. | 3.481796 | 3.574874 | 0.973963 |
url = Url()
url.protocol = self.get_protocol()
url.hostname = self.get_address()
url.port = self.get_tcp_port()
url.vars = dict((k, to_list(v))
for (k, v) in list(self.get_all().items())
if isinstance(v, str) or isinstance(v, list))
if self.account:
url.username = self.account.get_name()
url.password1 = self.account.get_password()
url.password2 = self.account.authorization_password
return str(url) | def get_uri(self) | Returns a URI formatted representation of the host, including all
of it's attributes except for the name. Uses the
address, not the name of the host to build the URI.
:rtype: str
:return: A URI. | 3.564108 | 3.751315 | 0.950096 |
return {'hostname': self.get_name(),
'address': self.get_address(),
'protocol': self.get_protocol(),
'port': self.get_tcp_port()} | def get_dict(self) | Returns a dict containing the host's attributes. The following
keys are contained:
- hostname
- address
- protocol
- port
:rtype: dict
:return: The resulting dictionary. | 4.341832 | 3.178512 | 1.365995 |
if is_ip(address):
self.address = clean_ip(address)
else:
self.address = address | def set_address(self, address) | Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param address: A hostname or IP name. | 4.549494 | 8.162968 | 0.557333 |
if name not in ('debug', 'verify_fingerprint', 'driver'):
raise TypeError('No such option: ' + repr(name))
if self.options is None:
self.options = {}
self.options[name] = value | def set_option(self, name, value) | Defines a (possibly protocol-specific) option for the host.
Possible options include:
verify_fingerprint: bool
:type name: str
:param name: The option name.
:type value: object
:param value: The option value. | 4.66095 | 4.727184 | 0.985989 |
if self.options is None:
return default
return self.options.get(name, default) | def get_option(self, name, default=None) | Returns the value of the given option if it is defined, returns
the given default value otherwise.
:type name: str
:param name: The option name.
:type default: object
:param default: A default value. | 3.071775 | 4.629937 | 0.663459 |
if tcp_port is None:
self.tcp_port = None
return
self.tcp_port = int(tcp_port) | def set_tcp_port(self, tcp_port) | Defines the TCP port number.
:type tcp_port: int
:param tcp_port: The TCP port number. | 2.484341 | 3.961488 | 0.627123 |
if self.vars is None:
self.vars = {}
self.vars[name] = value | def set(self, name, value) | Stores the given variable/value in the object for later retrieval.
:type name: string
:param name: The name of the variable.
:type value: object
:param value: The value of the variable. | 3.528001 | 4.749774 | 0.742772 |
if self.vars is None:
self.vars = {}
if name in self.vars:
self.vars[name].append(value)
else:
self.vars[name] = [value] | def append(self, name, value) | Appends the given value to the list variable with the given name.
:type name: string
:param name: The name of the variable.
:type value: object
:param value: The appended value. | 2.085771 | 2.271843 | 0.918096 |
if self.vars is None:
self.vars = {}
if name not in self.vars:
self.vars[name] = value | def set_default(self, name, value) | Like set(), but only sets the value if the variable is not already
defined.
:type name: string
:param name: The name of the variable.
:type value: object
:param value: The value of the variable. | 2.818553 | 3.196395 | 0.881791 |
if self.vars is None:
return default
return self.vars.get(name, default) | def get(self, name, default=None) | Returns the value of the given variable, or the given default
value if the variable is not defined.
:type name: string
:param name: The name of the variable.
:type default: object
:param default: The default value.
:rtype: object
:return: The value of the variable. | 3.789001 | 4.62639 | 0.818997 |
return [crypt.otp(password[0], seed[0], int(seq)) for seq in seqs] | def otp(scope, password, seed, seqs) | Calculates a one-time password hash using the given password, seed, and
sequence number and returns it.
Uses the md4/sixword algorithm as supported by TACACS+ servers.
:type password: string
:param password: A password.
:type seed: string
:param seed: A username.
:type seqs: int
:param seqs: A sequence number, or a list of sequence numbers.
:rtype: string
:return: A hash, or a list of hashes. | 7.030788 | 11.428149 | 0.615217 |
labels = obj.__dict__.setdefault('_labels', dict())
labels[name] = kwargs
return obj | def add_label(obj, name, **kwargs) | Labels an object such that it can later be checked with
:class:`get_label()`.
:type obj: object
:param obj: The object that is labeled.
:type name: str
:param name: A label.
:type kwargs: dict
:param kwargs: Optional values to store with the label.
:rtype: object
:return: The labeled function. | 4.909735 | 8.001673 | 0.613589 |
labels = obj.__dict__.get('_labels')
if labels is None:
return None
return labels.get(name) | def get_label(obj, name) | Checks whether an object has the given label attached (see
:class:`add_label()`) and returns the associated options.
:type obj: object
:param obj: The object to check for the label.
:type name: str
:param name: A label.
:rtype: dict or None
:return: The optional values if the label is attached, None otherwise. | 3.42223 | 5.463501 | 0.62638 |
labels = src.__dict__.get('_labels')
if labels is None:
return
dst.__dict__['_labels'] = labels.copy() | def copy_labels(src, dst) | Copies all labels of one object to another object.
:type src: object
:param src: The object to check read the labels from.
:type dst: object
:param dst: The object into which the labels are copied. | 3.442514 | 4.943199 | 0.696414 |
return thetype, ex, ''.join(traceback.format_exception(thetype, ex, tb)) | def serializeable_exc_info(thetype, ex, tb) | Since traceback objects can not be pickled, this function manipulates
exception info tuples before they are passed accross process
boundaries. | 3.056282 | 3.658335 | 0.83543 |
if isinstance(tb, str):
return tb
return ''.join(traceback.format_exception(thetype, ex, tb)) | def format_exception(thetype, ex, tb) | This function is a drop-in replacement for Python's
traceback.format_exception().
Since traceback objects can not be pickled, Exscript is forced to
manipulate them before they are passed accross process boundaries.
This leads to the fact the Python's traceback.format_exception()
no longer works for those objects.
This function works with any traceback object, regardless of whether
or not Exscript manipulated it. | 3.190575 | 3.574295 | 0.892645 |
def decorated(*args, **kwargs):
warnings.warn('Call to deprecated function %s.' % func.__name__,
category=DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
decorated.__name__ = func.__name__
decorated.__doc__ = func.__doc__
decorated.__dict__.update(func.__dict__)
return decorated | def deprecated(func) | A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used. | 1.429326 | 1.508909 | 0.947258 |
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
except AttributeError:
from multiprocessing import RLock
rlock = self.__dict__.setdefault('_sync_lock', RLock())
with rlock:
return func(self, *args, **kwargs)
return wrapped | def synchronized(func) | Decorator for synchronizing method access. | 2.429868 | 2.461241 | 0.987253 |
@wraps(func)
def wrapped(*args, **kwargs):
arg = repr(args) + ' ' + repr(kwargs)
sys.stdout.write('Entering ' + func.__name__ + arg + '\n')
try:
result = func(*args, **kwargs)
except:
sys.stdout.write('Traceback caught:\n')
sys.stdout.write(format_exception(*sys.exc_info()))
raise
arg = repr(result)
sys.stdout.write('Leaving ' + func.__name__ + '(): ' + arg + '\n')
return result
return wrapped | def debug(func) | Decorator that prints a message whenever a function is entered or left. | 2.205639 | 2.402356 | 0.918115 |
parser_args = {'strip_command': strip_command}
return _run(conn, None, string, parser_args, **kwargs) | def eval(conn, string, strip_command=True, **kwargs) | Compiles the given template and executes it on the given
connection.
Raises an exception if the compilation fails.
if strip_command is True, the first line of each response that is
received after any command sent by the template is stripped. For
example, consider the following template::
ls -1{extract /(\S+)/ as filenames}
{loop filenames as filename}
touch $filename
{end}
If strip_command is False, the response, (and hence, the `filenames'
variable) contains the following::
ls -1
myfile
myfile2
[...]
By setting strip_command to True, the first line is ommitted.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type string: string
:param string: The template to compile.
:type strip_command: bool
:param strip_command: Whether to strip the command echo from the response.
:type kwargs: dict
:param kwargs: Variables to define in the template.
:rtype: dict
:return: The variables that are defined after execution of the script. | 4.82034 | 7.570827 | 0.636699 |
parser_args = {'strip_command': strip_command}
with open(filename, 'r') as fp:
return _run(conn, filename, fp.read(), parser_args, **kwargs) | def eval_file(conn, filename, strip_command=True, **kwargs) | Convenience wrapper around eval() that reads the template from a file
instead.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type filename: string
:param filename: The name of the template file.
:type strip_command: bool
:param strip_command: Whether to strip the command echo from the response.
:type kwargs: dict
:param kwargs: Variables to define in the template. | 3.486811 | 5.143904 | 0.677853 |
with open(filename, 'r') as fp:
return _run(conn, None, fp.read(), {'no_prompt': True}, **kwargs) | def paste_file(conn, filename, **kwargs) | Convenience wrapper around paste() that reads the template from a file
instead.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type filename: string
:param filename: The name of the template file.
:type kwargs: dict
:param kwargs: Variables to define in the template. | 6.483876 | 7.695888 | 0.842512 |
result = string.split('%')
for i, item in enumerate(result[1:]):
i += 1
try:
result[i] = _HEXTOCHR[item[:2]] + item[2:]
except KeyError:
result[i] = '%' + item
except UnicodeDecodeError:
result[i] = chr(int(item[:2], 16)) + item[2:]
return ''.join(result) | def _unquote(string) | _unquote('abc%20def') -> 'abc def'. | 2.5848 | 2.678927 | 0.964864 |
# Extract the query part from the URL.
querystring = urlparse(url)[4]
# Split the query into name/value pairs.
pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')]
# Split the name/value pairs.
result = OrderedDefaultDict(list)
for name_value in pairs:
pair = name_value.split('=', 1)
if len(pair) != 2:
continue
if len(pair[1]) > 0:
name = _unquote(pair[0].replace('+', ' '))
value = _unquote(pair[1].replace('+', ' '))
result[name].append(value)
return result | def _urlparse_qs(url) | Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param url: URL with query string to be parsed | 2.397112 | 2.537404 | 0.94471 |
if url is None:
raise TypeError('Expected string but got' + type(url))
# Extract the protocol name from the URL.
result = Url()
match = re.match(r'(\w+)://', url)
if match:
result.protocol = match.group(1)
else:
result.protocol = default_protocol
# Now remove the query from the url.
query = ''
if '?' in url:
url, query = url.split('?', 1)
result.vars = _urlparse_qs('http://dummy/?' + query)
# Substitute the protocol name by 'http', because Python's urlsplit
# fails on our protocol names otherwise.
prefix = result.protocol + '://'
if url.startswith(prefix):
url = url[len(prefix):]
url = 'http://' + url
# Parse the remaining url.
parsed = urlsplit(url, 'http', False)
netloc = parsed[1]
# Parse username and password.
auth = ''
if '@' in netloc:
auth, netloc = netloc.split('@')
auth = auth.split(':')
try:
result.username = _unquote(auth[0])
result.password1 = _unquote(auth[1])
result.password2 = _unquote(auth[2])
except IndexError:
pass
# Parse hostname and port number.
result.hostname = netloc + parsed.path
result.port = _WELL_KNOWN_PORTS.get(result.protocol)
if ':' in netloc:
result.hostname, port = netloc.split(':')
result.port = int(port)
return result | def from_string(url, default_protocol='telnet') | Parses the given URL and returns an URL object. There are some
differences to Python's built-in URL parser:
- It is less strict, many more inputs are accepted. This is
necessary to allow for passing a simple hostname as a URL.
- You may specify a default protocol that is used when the http://
portion is missing.
- The port number defaults to the well-known port of the given
protocol.
- The query variables are parsed into a dictionary (Url.vars).
:type url: str
:param url: A URL.
:type default_protocol: string
:param default_protocol: A protocol name.
:rtype: Url
:return: The Url object contructed from the given URL. | 3.157187 | 3.082275 | 1.024304 |
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug | def set_debug(self, debug=1) | Set the debug level.
:type debug: int
:param debug: The debug level. | 7.391458 | 9.203486 | 0.803115 |
if max_threads is None:
raise TypeError('max_threads must not be None.')
self._check_if_ready()
self.collection.set_max_working(max_threads) | def set_max_threads(self, max_threads) | Set the maximum number of concurrent threads.
:type max_threads: int
:param max_threads: The number of threads. | 6.277554 | 8.442465 | 0.743569 |
self._check_if_ready()
return self.main_loop.enqueue(function, name, times, data) | def enqueue(self, function, name=None, times=1, data=None) | Appends a function to the queue for execution. The times argument
specifies the number of attempts if the function raises an exception.
If the name argument is None it defaults to whatever id(function)
returns.
:type function: callable
:param function: The function that is executed.
:type name: str
:param name: Stored in Job.name.
:type times: int
:param times: The maximum number of attempts.
:type data: object
:param data: Optional data to store in Job.data.
:rtype: int
:return: The id of the new job. | 5.412575 | 8.883924 | 0.609255 |
self._check_if_ready()
return self.main_loop.enqueue_or_ignore(function, name, times, data) | def enqueue_or_ignore(self, function, name=None, times=1, data=None) | Like enqueue(), but does nothing if a function with the same name
is already in the queue.
Returns a job id if a new job was added, returns None otherwise.
:type function: callable
:param function: The function that is executed.
:type name: str
:param name: Stored in Job.name.
:type times: int
:param times: The maximum number of attempts.
:type data: object
:param data: Optional data to store in Job.data.
:rtype: int or None
:return: The id of the new job. | 4.254085 | 6.443289 | 0.660235 |
self._check_if_ready()
return self.main_loop.priority_enqueue(function,
name,
force_start,
times,
data) | def priority_enqueue(self,
function,
name=None,
force_start=False,
times=1,
data=None) | Like :class:`enqueue()`, but adds the given function at the top of the
queue.
If force_start is True, the function is immediately started even when
the maximum number of concurrent threads is already reached.
:type function: callable
:param function: The function that is executed.
:type name: str
:param name: Stored in Job.name.
:type force_start: bool
:param force_start: Whether to start execution immediately.
:type times: int
:param times: The maximum number of attempts.
:type data: object
:param data: Optional data to store in Job.data.
:rtype: int
:return: The id of the new job. | 3.623824 | 6.435713 | 0.56308 |
self._check_if_ready()
self.collection.stop()
self.collection.wait()
self.main_loop.join()
self.main_loop = None
self.collection.clear()
if restart:
self.collection.start()
self._init() | def shutdown(self, restart=True) | Stop the execution of enqueued jobs, and wait for all running
jobs to complete. This method is synchronous and returns as soon
as all jobs are terminated (i.e. all threads are stopped).
If restart is True, the workqueue is restarted and paused,
so you may fill it with new jobs.
If restart is False, the WorkQueue can no longer be used after calling
this method.
:type restart: bool
:param restart: Whether to restart the queue after shutting down. | 4.690849 | 4.996322 | 0.93886 |
self._check_if_ready()
self.collection.stop()
self.main_loop.join()
self.main_loop = None
self.collection.clear() | def destroy(self) | Like shutdown(), but does not restart the queue and does not
wait for already started jobs to complete. | 7.514287 | 6.379337 | 1.17791 |
conn = scope.get('__connection__')
user = user[0]
if user is None:
conn.app_authenticate()
else:
account = Account(user, password[0])
conn.app_authenticate(account)
return True | def authenticate_user(scope, user=[None], password=[None]) | Like authenticate(), but logs in using the given user and password.
If a user and password are not given, the function uses the same
user and password that were used at the last login attempt; it is
an error if no such attempt was made before.
:type user: string
:param user: A username.
:type password: string
:param password: A password. | 4.814486 | 7.174276 | 0.671076 |
conn = scope.get('__connection__')
password = password[0]
if password is None:
conn.app_authorize()
else:
account = Account('', password)
conn.app_authorize(account)
return True | def authorize(scope, password=[None]) | Looks for a password prompt on the current connection
and enters the given password.
If a password is not given, the function uses the same
password that was used at the last login attempt; it is
an error if no such attempt was made before.
:type password: string
:param password: A password. | 6.725494 | 9.783983 | 0.687398 |
conn = scope.get('__connection__')
password = password[0]
if password is None:
conn.auto_app_authorize()
else:
account = Account('', password)
conn.auto_app_authorize(account)
return True | def auto_authorize(scope, password=[None]) | Executes a command on the remote host that causes an authorization
procedure to be started, then authorizes using the given password
in the same way in which authorize() works.
Depending on the detected operating system of the remote host the
following commands are started:
- on IOS, the "enable" command is executed.
- nothing on other operating systems yet.
:type password: string
:param password: A password. | 6.060185 | 9.670261 | 0.626683 |
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
return True | def close(scope) | Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed. | 15.264446 | 14.654441 | 1.041626 |
conn = scope.get('__connection__')
response = []
for line in data:
conn.send(line)
conn.expect_prompt()
response += conn.response.split('\n')[1:]
scope.define(__response__=response)
return True | def exec_(scope, data) | Sends the given data to the remote host and waits until the host
has responded with a prompt.
If the given data is a list of strings, each item is sent, and
after each item a prompt is expected.
This function also causes the response of the command to be stored
in the built-in __response__ variable.
:type data: string
:param data: The data that is sent. | 6.72926 | 5.907128 | 1.139176 |
conn = scope.get('__connection__')
response = []
for line in data:
conn.execute(line)
response += conn.response.split('\n')[1:]
scope.define(__response__=response)
return True | def execline(scope, data) | Like exec(), but appends a newline to the command in data before sending
it.
:type data: string
:param data: The data that is sent. | 6.998491 | 10.062191 | 0.695524 |
conn = scope.get('__connection__')
for line in data:
conn.send(line)
return True | def send(scope, data) | Like exec(), but does not wait for a response of the remote host after
sending the command.
:type data: string
:param data: The data that is sent. | 9.173071 | 11.868782 | 0.772874 |
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True | def wait_for(scope, prompt) | Waits until the response of the remote host contains the given pattern.
:type prompt: regex
:param prompt: The prompt pattern. | 13.780628 | 23.21549 | 0.593596 |
conn = scope.get('__connection__')
conn.set_prompt(prompt)
return True | def set_prompt(scope, prompt=None) | Defines the pattern that is recognized at any future time when Exscript
needs to wait for a prompt.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and continues as soon as the
pattern is found.
Exscript waits for a prompt whenever it sends a command (unless the send()
method was used). set_prompt() redefines as to what is recognized as a
prompt.
:type prompt: regex
:param prompt: The prompt pattern. | 6.75598 | 17.675442 | 0.382224 |
conn = scope.get('__connection__')
conn.set_error_prompt(error_re)
return True | def set_error(scope, error_re=None) | Defines a pattern that, whenever detected in the response of the remote
host, causes an error to be raised.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and raises an error if the
pattern is found.
:type error_re: regex
:param error_re: The error pattern. | 8.299741 | 15.088782 | 0.55006 |
conn = scope.get('__connection__')
conn.set_timeout(int(timeout[0]))
return True | def set_timeout(scope, timeout) | Defines the time after which Exscript fails if it does not receive a
prompt from the remote host.
:type timeout: int
:param timeout: The timeout in seconds. | 7.299356 | 13.971321 | 0.522453 |
if prompt:
thehandler = self._create_autoprompt_handler(handler)
else:
thehandler = handler
self.commands.add(command, thehandler) | def add_command(self, command, handler, prompt=True) | Registers a command.
The command may be either a string (which is then automatically
compiled into a regular expression), or a pre-compiled regular
expression object.
If the given response handler is a string, it is sent as the
response to any command that matches the given regular expression.
If the given response handler is a function, it is called
with the command passed as an argument.
:type command: str|regex
:param command: A string or a compiled regular expression.
:type handler: function|str
:param handler: A string, or a response handler.
:type prompt: bool
:param prompt: Whether to show a prompt after completing the command. | 5.056115 | 8.12862 | 0.622014 |
if autoprompt:
deco = self._create_autoprompt_handler
else:
deco = None
self.commands.add_from_file(filename, deco) | def add_commands_from_file(self, filename, autoprompt=True) | Wrapper around add_command_handler that reads the handlers from the
file with the given name. The file is a Python script containing
a list named 'commands' of tuples that map command names to
handlers.
:type filename: str
:param filename: The name of the file containing the tuples.
:type autoprompt: bool
:param autoprompt: Whether to append a prompt to each response. | 5.010313 | 7.255003 | 0.690601 |
self.logged_in = False
if self.login_type == self.LOGIN_TYPE_PASSWORDONLY:
self.prompt_stage = self.PROMPT_STAGE_PASSWORD
elif self.login_type == self.LOGIN_TYPE_NONE:
self.prompt_stage = self.PROMPT_STAGE_CUSTOM
else:
self.prompt_stage = self.PROMPT_STAGE_USERNAME
return self.banner + self._get_prompt() | def init(self) | Init or reset the virtual device.
:rtype: str
:return: The initial response of the virtual device. | 3.741465 | 3.964061 | 0.943847 |
echo = self.echo and command or ''
if not self.logged_in:
return echo + '\n' + self._get_prompt()
response = self.commands.eval(command)
if response is None:
return echo + '\n' + self._get_prompt()
return echo + response | def do(self, command) | "Executes" the given command on the virtual device, and returns
the response.
:type command: str
:param command: The command to be executed.
:rtype: str
:return: The response of the virtual device. | 4.779776 | 6.226686 | 0.767627 |
if history is None:
history = InputHistory()
if not doverh or default is None:
default = history.get(key, str(default))
while True:
if default is None:
value = input('%s: ' % message)
else:
value = input('%s [%s]: ' % (message, default)) or default
if strip and isinstance(value, str):
value = value.strip()
if not check:
break
errors = check(value)
if errors:
print('\n'.join(to_list(errors)))
else:
break
history.set(key, value)
return value | def prompt(key,
message,
default=None,
doverh=True,
strip=True,
check=None,
history=None) | Prompt the user for input. This function is similar to Python's built
in raw_input, with the following differences:
- You may specify a default value that is returned if the user
presses "enter" without entering anything.
- The user's input is recorded in a config file, and offered
as the default value the next time this function is used
(based on the key argument).
The config file is based around the :class:`InputHistory`. If a history object
is not passed in the history argument, a new one will be created.
The key argument specifies under which name the input is saved in the
config file.
The given default value is only used if a default was not found in the
history.
The strip argument specifies that the returned value should be stripped
of whitespace (default).
The check argument allows for validating the input; if the validation
fails, the user is prompted again before the value is stored in the
InputHistory. Example usage::
def validate(input):
if len(input) < 4:
return 'Please enter at least 4 characters!'
value = prompt('test', 'Enter a value', 'My Default', check = validate)
print('You entered:', value)
This leads to the following output::
Please enter a value [My Default]: abc
Please enter at least 4 characters!
Please enter a value [My Default]: Foobar
You entered: Foobar
The next time the same code is started, the input 'Foobar' is remembered::
Please enter a value [Foobar]: (enters nothing)
You entered: Foobar
:type key: str
:param key: The key under which to store the input in the :class:`InputHistory`.
:type message: str
:param message: The user prompt.
:type default: str|None
:param default: The offered default if none was found in the history.
:type doverh: bool
:param doverh: Whether to prefer default value over history value.
:type strip: bool
:param strip: Whether to remove whitespace from the input.
:type check: callable
:param check: A function that is called for validating the input.
:type history: :class:`InputHistory` or None
:param history: The history used for recording default values, or None. | 2.303517 | 2.701199 | 0.852776 |
def _validate(string):
if not os.path.isfile(string):
return 'File not found. Please enter a filename.'
return prompt(key, message, default, True, _validate, history) | def get_filename(key, message, default=None, history=None) | Like :meth:`prompt`, but only accepts the name of an existing file
as an input.
:type key: str
:param key: The key under which to store the input in the :class:`InputHistory`.
:type message: str
:param message: The user prompt.
:type default: str|None
:param default: The offered default if none was found in the history.
:type history: :class:`InputHistory` or None
:param history: The history used for recording default values, or None. | 5.984743 | 6.36265 | 0.940605 |
# Read username and password.
try:
env_user = getpass.getuser()
except KeyError:
env_user = ''
if prompt is None:
prompt = "Please enter your user name"
if env_user is None or env_user == '':
user = input('%s: ' % prompt)
else:
user = input('%s [%s]: ' % (prompt, env_user))
if user == '':
user = env_user
return user | def get_user(prompt=None) | Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default one if None.
:rtype: string
:return: A username. | 2.687161 | 2.923007 | 0.919314 |
if not self.parser:
return default
try:
return self.parser.get(self.section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default | def get(self, key, default=None) | Returns the input with the given key from the section that was
passed to the constructor. If either the section or the key
are not found, the default value is returned.
:type key: str
:param key: The key for which to return a value.
:type default: str|object
:param default: The default value that is returned.
:rtype: str|object
:return: The value from the config file, or the default. | 2.352576 | 2.755628 | 0.853735 |
if value is None:
return None
self.parser.set(self.section, key, value)
# Unfortunately ConfigParser attempts to write a string to the file
# object, and NamedTemporaryFile uses binary mode. So we nee to create
# the tempfile, and then re-open it.
with NamedTemporaryFile(delete=False) as tmpfile:
pass
with codecs.open(tmpfile.name, 'w', encoding='utf8') as fp:
self.parser.write(fp)
self.file.close()
shutil.move(tmpfile.name, self.file.name)
self.file = open(self.file.name)
return value | def set(self, key, value) | Saves the input with the given key in the section that was
passed to the constructor. If either the section or the key
are not found, they are created.
Does nothing if the given value is None.
:type key: str
:param key: The key for which to define a value.
:type value: str|None
:param value: The value that is defined, or None.
:rtype: str|None
:return: The given value. | 3.867229 | 3.892935 | 0.993397 |
if not self.needs_lock:
return
with self.synclock:
while not self.lock.acquire(False):
self.synclock.wait()
if signal:
self.acquired_event(self)
self.synclock.notify_all() | def acquire(self, signal=True) | Locks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the acquired_event signal. | 4.737247 | 3.930407 | 1.205282 |
if not self.needs_lock:
return
with self.synclock:
self.lock.release()
if signal:
self.released_event(self)
self.synclock.notify_all() | def release(self, signal=True) | Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal. | 6.043377 | 4.448798 | 1.358429 |
self.name = name
self.changed_event.emit(self) | def set_name(self, name) | Changes the name of the account.
:type name: string
:param name: The account name. | 7.219174 | 21.932402 | 0.329156 |
self.password = password
self.changed_event.emit(self) | def set_password(self, password) | Changes the password of the account.
:type password: string
:param password: The account password. | 9.222653 | 21.698845 | 0.42503 |
self.authorization_password = password
self.changed_event.emit(self) | def set_authorization_password(self, password) | Changes the authorization password of the account.
:type password: string
:param password: The new authorization password. | 8.791244 | 27.070679 | 0.324752 |
account = AccountProxy(parent)
account.host = host
if account.acquire():
return account
return None | def for_host(parent, host) | Returns a new AccountProxy that has an account acquired. The
account is chosen based on what the connected AccountManager
selects for the given host. | 10.688583 | 5.526274 | 1.934139 |
account = AccountProxy(parent)
account.account_hash = account_hash
if account.acquire():
return account
return None | def for_account_hash(parent, account_hash) | Returns a new AccountProxy that acquires the account with the
given hash, if such an account is known to the account manager.
It is an error if the account manager does not have such an
account. | 7.022598 | 4.5391 | 1.547134 |
if self.host:
self.parent.send(('acquire-account-for-host', self.host))
elif self.account_hash:
self.parent.send(('acquire-account-from-hash', self.account_hash))
else:
self.parent.send(('acquire-account'))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response is None:
return False
self.account_hash, \
self.user, \
self.password, \
self.authorization_password, \
self.key = response
return True | def acquire(self) | Locks the account. Returns True on success, False if the account
is thread-local and must not be locked. | 3.525294 | 3.271873 | 1.077454 |
self.parent.send(('release-account', self.account_hash))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response != 'ok':
raise ValueError('unexpected response: ' + repr(response)) | def release(self) | Unlocks the account. | 5.532064 | 4.702555 | 1.176396 |
for account in self.accounts:
if account.__hash__() == account_hash:
return account
return None | def get_account_from_hash(self, account_hash) | Returns the account with the given hash, or None if no such
account is included in the account pool. | 3.44392 | 3.047923 | 1.129924 |
with self.unlock_cond:
for account in to_list(accounts):
account.acquired_event.listen(self._on_account_acquired)
account.released_event.listen(self._on_account_released)
self.accounts.add(account)
self.unlocked_accounts.append(account)
self.unlock_cond.notify_all() | def add_account(self, accounts) | Adds one or more account instances to the pool.
:type accounts: Account|list[Account]
:param accounts: The account to be added. | 3.654446 | 3.90702 | 0.935354 |
for account in to_list(accounts):
if account not in self.accounts:
msg = 'attempt to remove unknown account %s' % account
raise Exception(msg)
if account not in self.unlocked_accounts:
raise Exception('account %s should be unlocked' % account)
account.acquired_event.disconnect(self._on_account_acquired)
account.released_event.disconnect(self._on_account_released)
self.accounts.remove(account)
self.unlocked_accounts.remove(account) | def _remove_account(self, accounts) | :type accounts: Account|list[Account]
:param accounts: The accounts to be removed. | 2.880281 | 2.958169 | 0.97367 |
with self.unlock_cond:
for owner in self.owner2account:
self.release_accounts(owner)
self._remove_account(self.accounts.copy())
self.unlock_cond.notify_all() | def reset(self) | Removes all accounts. | 9.188091 | 7.855379 | 1.169656 |
for account in self.accounts:
if account.get_name() == name:
return account
return None | def get_account_from_name(self, name) | Returns the account with the given name.
:type name: string
:param name: The name of the account. | 2.841901 | 5.343966 | 0.531796 |
with self.unlock_cond:
if len(self.accounts) == 0:
raise ValueError('account pool is empty')
if account:
# Specific account requested.
while account not in self.unlocked_accounts:
self.unlock_cond.wait()
self.unlocked_accounts.remove(account)
else:
# Else take the next available one.
while len(self.unlocked_accounts) == 0:
self.unlock_cond.wait()
account = self.unlocked_accounts.popleft()
if owner is not None:
self.owner2account[owner].append(account)
self.account2owner[account] = owner
account.acquire(False)
self.unlock_cond.notify_all()
return account | def acquire_account(self, account=None, owner=None) | Waits until an account becomes available, then locks and returns it.
If an account is not passed, the next available account is returned.
:type account: Account
:param account: The account to be acquired, or None.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired. | 3.040798 | 2.959404 | 1.027504 |
with self.unlock_cond:
for account in self.owner2account[owner]:
self.account2owner.pop(account)
account.release(False)
self.unlocked_accounts.append(account)
self.owner2account.pop(owner)
self.unlock_cond.notify_all() | def release_accounts(self, owner) | Releases all accounts that were acquired by the given owner.
:type owner: object
:param owner: The owner descriptor as passed to acquire_account(). | 3.650701 | 4.505167 | 0.810336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.