code
stringlengths 75
104k
| code_sememe
stringlengths 47
309k
| token_type
stringlengths 215
214k
| code_dependency
stringlengths 75
155k
|
|---|---|---|---|
def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if you only have ten items, you'll have two groups of three and
two of two.
>>> partition_items(10, 3)
[3, 3, 2, 2]
"""
num_bins = int(math.ceil(count / float(bin_size)))
bins = [0] * num_bins
for i in range(count):
bins[i % num_bins] += 1
return bins
|
def function[partition_items, parameter[count, bin_size]]:
constant[
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if you only have ten items, you'll have two groups of three and
two of two.
>>> partition_items(10, 3)
[3, 3, 2, 2]
]
variable[num_bins] assign[=] call[name[int], parameter[call[name[math].ceil, parameter[binary_operation[name[count] / call[name[float], parameter[name[bin_size]]]]]]]]
variable[bins] assign[=] binary_operation[list[[<ast.Constant object at 0x7da1b03bac50>]] * name[num_bins]]
for taget[name[i]] in starred[call[name[range], parameter[name[count]]]] begin[:]
<ast.AugAssign object at 0x7da1b03ba050>
return[name[bins]]
|
keyword[def] identifier[partition_items] ( identifier[count] , identifier[bin_size] ):
literal[string]
identifier[num_bins] = identifier[int] ( identifier[math] . identifier[ceil] ( identifier[count] / identifier[float] ( identifier[bin_size] )))
identifier[bins] =[ literal[int] ]* identifier[num_bins]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[count] ):
identifier[bins] [ identifier[i] % identifier[num_bins] ]+= literal[int]
keyword[return] identifier[bins]
|
def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if you only have ten items, you'll have two groups of three and
two of two.
>>> partition_items(10, 3)
[3, 3, 2, 2]
"""
num_bins = int(math.ceil(count / float(bin_size)))
bins = [0] * num_bins
for i in range(count):
bins[i % num_bins] += 1 # depends on [control=['for'], data=['i']]
return bins
|
def pickupSearch(self):
"""Pick up the latest search from a saved jobID and monitor it to completion
Parameters:
----------------------------------------------------------------------
retval: nothing
"""
self.__searchJob = self.loadSavedHyperSearchJob(
permWorkDir=self._options["permWorkDir"],
outputLabel=self._options["outputLabel"])
self.monitorSearchJob()
|
def function[pickupSearch, parameter[self]]:
constant[Pick up the latest search from a saved jobID and monitor it to completion
Parameters:
----------------------------------------------------------------------
retval: nothing
]
name[self].__searchJob assign[=] call[name[self].loadSavedHyperSearchJob, parameter[]]
call[name[self].monitorSearchJob, parameter[]]
|
keyword[def] identifier[pickupSearch] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__searchJob] = identifier[self] . identifier[loadSavedHyperSearchJob] (
identifier[permWorkDir] = identifier[self] . identifier[_options] [ literal[string] ],
identifier[outputLabel] = identifier[self] . identifier[_options] [ literal[string] ])
identifier[self] . identifier[monitorSearchJob] ()
|
def pickupSearch(self):
"""Pick up the latest search from a saved jobID and monitor it to completion
Parameters:
----------------------------------------------------------------------
retval: nothing
"""
self.__searchJob = self.loadSavedHyperSearchJob(permWorkDir=self._options['permWorkDir'], outputLabel=self._options['outputLabel'])
self.monitorSearchJob()
|
def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1
|
def function[_initialize, parameter[self, no_components, no_item_features, no_user_features]]:
constant[
Initialise internal latent representations.
]
name[self].item_embeddings assign[=] call[binary_operation[binary_operation[call[name[self].random_state.rand, parameter[name[no_item_features], name[no_components]]] - constant[0.5]] / name[no_components]].astype, parameter[name[np].float32]]
name[self].item_embedding_gradients assign[=] call[name[np].zeros_like, parameter[name[self].item_embeddings]]
name[self].item_embedding_momentum assign[=] call[name[np].zeros_like, parameter[name[self].item_embeddings]]
name[self].item_biases assign[=] call[name[np].zeros, parameter[name[no_item_features]]]
name[self].item_bias_gradients assign[=] call[name[np].zeros_like, parameter[name[self].item_biases]]
name[self].item_bias_momentum assign[=] call[name[np].zeros_like, parameter[name[self].item_biases]]
name[self].user_embeddings assign[=] call[binary_operation[binary_operation[call[name[self].random_state.rand, parameter[name[no_user_features], name[no_components]]] - constant[0.5]] / name[no_components]].astype, parameter[name[np].float32]]
name[self].user_embedding_gradients assign[=] call[name[np].zeros_like, parameter[name[self].user_embeddings]]
name[self].user_embedding_momentum assign[=] call[name[np].zeros_like, parameter[name[self].user_embeddings]]
name[self].user_biases assign[=] call[name[np].zeros, parameter[name[no_user_features]]]
name[self].user_bias_gradients assign[=] call[name[np].zeros_like, parameter[name[self].user_biases]]
name[self].user_bias_momentum assign[=] call[name[np].zeros_like, parameter[name[self].user_biases]]
if compare[name[self].learning_schedule equal[==] constant[adagrad]] begin[:]
<ast.AugAssign object at 0x7da1b1734730>
<ast.AugAssign object at 0x7da1b1735f60>
<ast.AugAssign object at 0x7da1b1737af0>
<ast.AugAssign object at 0x7da1b17366b0>
|
keyword[def] identifier[_initialize] ( identifier[self] , identifier[no_components] , identifier[no_item_features] , identifier[no_user_features] ):
literal[string]
identifier[self] . identifier[item_embeddings] =(
( identifier[self] . identifier[random_state] . identifier[rand] ( identifier[no_item_features] , identifier[no_components] )- literal[int] )
/ identifier[no_components]
). identifier[astype] ( identifier[np] . identifier[float32] )
identifier[self] . identifier[item_embedding_gradients] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[item_embeddings] )
identifier[self] . identifier[item_embedding_momentum] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[item_embeddings] )
identifier[self] . identifier[item_biases] = identifier[np] . identifier[zeros] ( identifier[no_item_features] , identifier[dtype] = identifier[np] . identifier[float32] )
identifier[self] . identifier[item_bias_gradients] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[item_biases] )
identifier[self] . identifier[item_bias_momentum] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[item_biases] )
identifier[self] . identifier[user_embeddings] =(
( identifier[self] . identifier[random_state] . identifier[rand] ( identifier[no_user_features] , identifier[no_components] )- literal[int] )
/ identifier[no_components]
). identifier[astype] ( identifier[np] . identifier[float32] )
identifier[self] . identifier[user_embedding_gradients] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[user_embeddings] )
identifier[self] . identifier[user_embedding_momentum] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[user_embeddings] )
identifier[self] . identifier[user_biases] = identifier[np] . identifier[zeros] ( identifier[no_user_features] , identifier[dtype] = identifier[np] . identifier[float32] )
identifier[self] . identifier[user_bias_gradients] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[user_biases] )
identifier[self] . identifier[user_bias_momentum] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[user_biases] )
keyword[if] identifier[self] . identifier[learning_schedule] == literal[string] :
identifier[self] . identifier[item_embedding_gradients] += literal[int]
identifier[self] . identifier[item_bias_gradients] += literal[int]
identifier[self] . identifier[user_embedding_gradients] += literal[int]
identifier[self] . identifier[user_bias_gradients] += literal[int]
|
def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = ((self.random_state.rand(no_item_features, no_components) - 0.5) / no_components).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = ((self.random_state.rand(no_user_features, no_components) - 0.5) / no_components).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == 'adagrad':
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 # depends on [control=['if'], data=[]]
|
def srv_rec(rdatas):
'''
Validate and parse DNS record data for SRV record(s)
:param rdata: DNS record data
:return: dict w/fields
'''
rschema = OrderedDict((
('prio', int),
('weight', int),
('port', _to_port),
('name', str),
))
return _data2rec_group(rschema, rdatas, 'prio')
|
def function[srv_rec, parameter[rdatas]]:
constant[
Validate and parse DNS record data for SRV record(s)
:param rdata: DNS record data
:return: dict w/fields
]
variable[rschema] assign[=] call[name[OrderedDict], parameter[tuple[[<ast.Tuple object at 0x7da1b1fa2950>, <ast.Tuple object at 0x7da1b1f9a980>, <ast.Tuple object at 0x7da1b1f9bbb0>, <ast.Tuple object at 0x7da1b1f9b880>]]]]
return[call[name[_data2rec_group], parameter[name[rschema], name[rdatas], constant[prio]]]]
|
keyword[def] identifier[srv_rec] ( identifier[rdatas] ):
literal[string]
identifier[rschema] = identifier[OrderedDict] ((
( literal[string] , identifier[int] ),
( literal[string] , identifier[int] ),
( literal[string] , identifier[_to_port] ),
( literal[string] , identifier[str] ),
))
keyword[return] identifier[_data2rec_group] ( identifier[rschema] , identifier[rdatas] , literal[string] )
|
def srv_rec(rdatas):
"""
Validate and parse DNS record data for SRV record(s)
:param rdata: DNS record data
:return: dict w/fields
"""
rschema = OrderedDict((('prio', int), ('weight', int), ('port', _to_port), ('name', str)))
return _data2rec_group(rschema, rdatas, 'prio')
|
def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None):
'''
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the \'pcs cluster setup\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster
'''
cmd = ['pcs', 'cluster', 'setup']
cmd += ['--name', pcsclustername]
cmd += nodes
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
|
def function[cluster_setup, parameter[nodes, pcsclustername, extra_args]]:
constant[
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the 'pcs cluster setup' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da207f01de0>, <ast.Constant object at 0x7da207f02560>, <ast.Constant object at 0x7da207f00310>]]
<ast.AugAssign object at 0x7da207f03610>
<ast.AugAssign object at 0x7da207f01ff0>
if call[name[isinstance], parameter[name[extra_args], tuple[[<ast.Name object at 0x7da207f01b40>, <ast.Name object at 0x7da207f00160>]]]] begin[:]
<ast.AugAssign object at 0x7da207f02740>
return[call[call[name[__salt__]][constant[cmd.run_all]], parameter[name[cmd]]]]
|
keyword[def] identifier[cluster_setup] ( identifier[nodes] , identifier[pcsclustername] = literal[string] , identifier[extra_args] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] ]
identifier[cmd] +=[ literal[string] , identifier[pcsclustername] ]
identifier[cmd] += identifier[nodes]
keyword[if] identifier[isinstance] ( identifier[extra_args] ,( identifier[list] , identifier[tuple] )):
identifier[cmd] += identifier[extra_args]
keyword[return] identifier[__salt__] [ literal[string] ]( identifier[cmd] , identifier[output_loglevel] = literal[string] , identifier[python_shell] = keyword[False] )
|
def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None):
"""
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the 'pcs cluster setup' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster
"""
cmd = ['pcs', 'cluster', 'setup']
cmd += ['--name', pcsclustername]
cmd += nodes
if isinstance(extra_args, (list, tuple)):
cmd += extra_args # depends on [control=['if'], data=[]]
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
|
def parse_status_file(status_file,nas_addr):
''' parse openvpn status log
'''
session_users = {}
flag1 = False
flag2 = False
with open(status_file) as stlines:
for line in stlines:
if line.startswith("Common Name"):
flag1 = True
continue
if line.startswith("ROUTING TABLE"):
flag1 = False
continue
if line.startswith("Virtual Address"):
flag2 = True
continue
if line.startswith("GLOBAL STATS"):
flag2 = False
continue
if flag1:
try:
username,realaddr,inbytes,outbytes,_ = line.split(',')
realip,realport = realaddr.split(':')
session_id = md5(nas_addr + realip + realport).hexdigest()
session_users.setdefault(session_id, {}).update(dict(
session_id=session_id,
username=username,
realip=realip,
realport=realport,
inbytes=inbytes,
outbytes=outbytes
))
except:
traceback.print_exc()
if flag2:
try:
userip,username,realaddr,_ = line.split(',')
realip,realport = realaddr.split(':')
session_id = md5(nas_addr + realip + realport).hexdigest()
session_users.setdefault(session_id, {}).update(dict(
session_id=session_id,
username=username,
realip=realip,
realport=realport,
userip=userip,
))
except:
traceback.print_exc()
return session_users
|
def function[parse_status_file, parameter[status_file, nas_addr]]:
constant[ parse openvpn status log
]
variable[session_users] assign[=] dictionary[[], []]
variable[flag1] assign[=] constant[False]
variable[flag2] assign[=] constant[False]
with call[name[open], parameter[name[status_file]]] begin[:]
for taget[name[line]] in starred[name[stlines]] begin[:]
if call[name[line].startswith, parameter[constant[Common Name]]] begin[:]
variable[flag1] assign[=] constant[True]
continue
if call[name[line].startswith, parameter[constant[ROUTING TABLE]]] begin[:]
variable[flag1] assign[=] constant[False]
continue
if call[name[line].startswith, parameter[constant[Virtual Address]]] begin[:]
variable[flag2] assign[=] constant[True]
continue
if call[name[line].startswith, parameter[constant[GLOBAL STATS]]] begin[:]
variable[flag2] assign[=] constant[False]
continue
if name[flag1] begin[:]
<ast.Try object at 0x7da1b24e2740>
if name[flag2] begin[:]
<ast.Try object at 0x7da1b24e1f60>
return[name[session_users]]
|
keyword[def] identifier[parse_status_file] ( identifier[status_file] , identifier[nas_addr] ):
literal[string]
identifier[session_users] ={}
identifier[flag1] = keyword[False]
identifier[flag2] = keyword[False]
keyword[with] identifier[open] ( identifier[status_file] ) keyword[as] identifier[stlines] :
keyword[for] identifier[line] keyword[in] identifier[stlines] :
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[flag1] = keyword[True]
keyword[continue]
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[flag1] = keyword[False]
keyword[continue]
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[flag2] = keyword[True]
keyword[continue]
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[flag2] = keyword[False]
keyword[continue]
keyword[if] identifier[flag1] :
keyword[try] :
identifier[username] , identifier[realaddr] , identifier[inbytes] , identifier[outbytes] , identifier[_] = identifier[line] . identifier[split] ( literal[string] )
identifier[realip] , identifier[realport] = identifier[realaddr] . identifier[split] ( literal[string] )
identifier[session_id] = identifier[md5] ( identifier[nas_addr] + identifier[realip] + identifier[realport] ). identifier[hexdigest] ()
identifier[session_users] . identifier[setdefault] ( identifier[session_id] ,{}). identifier[update] ( identifier[dict] (
identifier[session_id] = identifier[session_id] ,
identifier[username] = identifier[username] ,
identifier[realip] = identifier[realip] ,
identifier[realport] = identifier[realport] ,
identifier[inbytes] = identifier[inbytes] ,
identifier[outbytes] = identifier[outbytes]
))
keyword[except] :
identifier[traceback] . identifier[print_exc] ()
keyword[if] identifier[flag2] :
keyword[try] :
identifier[userip] , identifier[username] , identifier[realaddr] , identifier[_] = identifier[line] . identifier[split] ( literal[string] )
identifier[realip] , identifier[realport] = identifier[realaddr] . identifier[split] ( literal[string] )
identifier[session_id] = identifier[md5] ( identifier[nas_addr] + identifier[realip] + identifier[realport] ). identifier[hexdigest] ()
identifier[session_users] . identifier[setdefault] ( identifier[session_id] ,{}). identifier[update] ( identifier[dict] (
identifier[session_id] = identifier[session_id] ,
identifier[username] = identifier[username] ,
identifier[realip] = identifier[realip] ,
identifier[realport] = identifier[realport] ,
identifier[userip] = identifier[userip] ,
))
keyword[except] :
identifier[traceback] . identifier[print_exc] ()
keyword[return] identifier[session_users]
|
def parse_status_file(status_file, nas_addr):
""" parse openvpn status log
"""
session_users = {}
flag1 = False
flag2 = False
with open(status_file) as stlines:
for line in stlines:
if line.startswith('Common Name'):
flag1 = True
continue # depends on [control=['if'], data=[]]
if line.startswith('ROUTING TABLE'):
flag1 = False
continue # depends on [control=['if'], data=[]]
if line.startswith('Virtual Address'):
flag2 = True
continue # depends on [control=['if'], data=[]]
if line.startswith('GLOBAL STATS'):
flag2 = False
continue # depends on [control=['if'], data=[]]
if flag1:
try:
(username, realaddr, inbytes, outbytes, _) = line.split(',')
(realip, realport) = realaddr.split(':')
session_id = md5(nas_addr + realip + realport).hexdigest()
session_users.setdefault(session_id, {}).update(dict(session_id=session_id, username=username, realip=realip, realport=realport, inbytes=inbytes, outbytes=outbytes)) # depends on [control=['try'], data=[]]
except:
traceback.print_exc() # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]]
if flag2:
try:
(userip, username, realaddr, _) = line.split(',')
(realip, realport) = realaddr.split(':')
session_id = md5(nas_addr + realip + realport).hexdigest()
session_users.setdefault(session_id, {}).update(dict(session_id=session_id, username=username, realip=realip, realport=realport, userip=userip)) # depends on [control=['try'], data=[]]
except:
traceback.print_exc() # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] # depends on [control=['with'], data=['stlines']]
return session_users
|
def tune_pair(self, pair):
"""Tune a pair of images."""
self._save_bm_state()
self.pair = pair
self.update_disparity_map()
|
def function[tune_pair, parameter[self, pair]]:
constant[Tune a pair of images.]
call[name[self]._save_bm_state, parameter[]]
name[self].pair assign[=] name[pair]
call[name[self].update_disparity_map, parameter[]]
|
keyword[def] identifier[tune_pair] ( identifier[self] , identifier[pair] ):
literal[string]
identifier[self] . identifier[_save_bm_state] ()
identifier[self] . identifier[pair] = identifier[pair]
identifier[self] . identifier[update_disparity_map] ()
|
def tune_pair(self, pair):
"""Tune a pair of images."""
self._save_bm_state()
self.pair = pair
self.update_disparity_map()
|
def Verify(self, completely=False):
"""
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
"""
res = super(Block, self).Verify()
if not res:
return False
from neo.Blockchain import GetBlockchain, GetConsensusAddress
# first TX has to be a miner transaction. other tx after that cant be miner tx
if self.Transactions[0].Type != TransactionType.MinerTransaction:
return False
for tx in self.Transactions[1:]:
if tx.Type == TransactionType.MinerTransaction:
return False
if completely:
bc = GetBlockchain()
if self.NextConsensus != GetConsensusAddress(bc.GetValidators(self.Transactions).ToArray()):
return False
for tx in self.Transactions:
if not tx.Verify():
pass
logger.error("Blocks cannot be fully validated at this moment. please pass completely=False")
raise NotImplementedError()
# do this below!
# foreach(Transaction tx in Transactions)
# if (!tx.Verify(Transactions.Where(p = > !p.Hash.Equals(tx.Hash)))) return false;
# Transaction tx_gen = Transactions.FirstOrDefault(p= > p.Type == TransactionType.MinerTransaction);
# if (tx_gen?.Outputs.Sum(p = > p.Value) != CalculateNetFee(Transactions)) return false;
return True
|
def function[Verify, parameter[self, completely]]:
constant[
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
]
variable[res] assign[=] call[call[name[super], parameter[name[Block], name[self]]].Verify, parameter[]]
if <ast.UnaryOp object at 0x7da204623310> begin[:]
return[constant[False]]
from relative_module[neo.Blockchain] import module[GetBlockchain], module[GetConsensusAddress]
if compare[call[name[self].Transactions][constant[0]].Type not_equal[!=] name[TransactionType].MinerTransaction] begin[:]
return[constant[False]]
for taget[name[tx]] in starred[call[name[self].Transactions][<ast.Slice object at 0x7da2046221d0>]] begin[:]
if compare[name[tx].Type equal[==] name[TransactionType].MinerTransaction] begin[:]
return[constant[False]]
if name[completely] begin[:]
variable[bc] assign[=] call[name[GetBlockchain], parameter[]]
if compare[name[self].NextConsensus not_equal[!=] call[name[GetConsensusAddress], parameter[call[call[name[bc].GetValidators, parameter[name[self].Transactions]].ToArray, parameter[]]]]] begin[:]
return[constant[False]]
for taget[name[tx]] in starred[name[self].Transactions] begin[:]
if <ast.UnaryOp object at 0x7da18bc73a90> begin[:]
pass
call[name[logger].error, parameter[constant[Blocks cannot be fully validated at this moment. please pass completely=False]]]
<ast.Raise object at 0x7da18bc73790>
return[constant[True]]
|
keyword[def] identifier[Verify] ( identifier[self] , identifier[completely] = keyword[False] ):
literal[string]
identifier[res] = identifier[super] ( identifier[Block] , identifier[self] ). identifier[Verify] ()
keyword[if] keyword[not] identifier[res] :
keyword[return] keyword[False]
keyword[from] identifier[neo] . identifier[Blockchain] keyword[import] identifier[GetBlockchain] , identifier[GetConsensusAddress]
keyword[if] identifier[self] . identifier[Transactions] [ literal[int] ]. identifier[Type] != identifier[TransactionType] . identifier[MinerTransaction] :
keyword[return] keyword[False]
keyword[for] identifier[tx] keyword[in] identifier[self] . identifier[Transactions] [ literal[int] :]:
keyword[if] identifier[tx] . identifier[Type] == identifier[TransactionType] . identifier[MinerTransaction] :
keyword[return] keyword[False]
keyword[if] identifier[completely] :
identifier[bc] = identifier[GetBlockchain] ()
keyword[if] identifier[self] . identifier[NextConsensus] != identifier[GetConsensusAddress] ( identifier[bc] . identifier[GetValidators] ( identifier[self] . identifier[Transactions] ). identifier[ToArray] ()):
keyword[return] keyword[False]
keyword[for] identifier[tx] keyword[in] identifier[self] . identifier[Transactions] :
keyword[if] keyword[not] identifier[tx] . identifier[Verify] ():
keyword[pass]
identifier[logger] . identifier[error] ( literal[string] )
keyword[raise] identifier[NotImplementedError] ()
keyword[return] keyword[True]
|
def Verify(self, completely=False):
"""
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
"""
res = super(Block, self).Verify()
if not res:
return False # depends on [control=['if'], data=[]]
from neo.Blockchain import GetBlockchain, GetConsensusAddress
# first TX has to be a miner transaction. other tx after that cant be miner tx
if self.Transactions[0].Type != TransactionType.MinerTransaction:
return False # depends on [control=['if'], data=[]]
for tx in self.Transactions[1:]:
if tx.Type == TransactionType.MinerTransaction:
return False # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['tx']]
if completely:
bc = GetBlockchain()
if self.NextConsensus != GetConsensusAddress(bc.GetValidators(self.Transactions).ToArray()):
return False # depends on [control=['if'], data=[]]
for tx in self.Transactions:
if not tx.Verify():
pass # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['tx']]
logger.error('Blocks cannot be fully validated at this moment. please pass completely=False')
raise NotImplementedError() # depends on [control=['if'], data=[]]
# do this below!
# foreach(Transaction tx in Transactions)
# if (!tx.Verify(Transactions.Where(p = > !p.Hash.Equals(tx.Hash)))) return false;
# Transaction tx_gen = Transactions.FirstOrDefault(p= > p.Type == TransactionType.MinerTransaction);
# if (tx_gen?.Outputs.Sum(p = > p.Value) != CalculateNetFee(Transactions)) return false;
return True
|
def open_data(self, url, data=None):
"""Use "data" URL."""
if not isinstance(url, str):
raise URLError('data error: proxy support for data protocol currently not implemented')
# ignore POSTed data
#
# syntax of data URLs:
# dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
# mediatype := [ type "/" subtype ] *( ";" parameter )
# data := *urlchar
# parameter := attribute "=" value
try:
[type, data] = url.split(',', 1)
except ValueError:
raise IOError('data error', 'bad data URL')
if not type:
type = 'text/plain;charset=US-ASCII'
semi = type.rfind(';')
if semi >= 0 and '=' not in type[semi:]:
encoding = type[semi+1:]
type = type[:semi]
else:
encoding = ''
msg = []
msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(time.time())))
msg.append('Content-type: %s' % type)
if encoding == 'base64':
# XXX is this encoding/decoding ok?
data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
else:
data = unquote(data)
msg.append('Content-Length: %d' % len(data))
msg.append('')
msg.append(data)
msg = '\n'.join(msg)
headers = email.message_from_string(msg)
f = io.StringIO(msg)
#f.fileno = None # needed for addinfourl
return addinfourl(f, headers, url)
|
def function[open_data, parameter[self, url, data]]:
constant[Use "data" URL.]
if <ast.UnaryOp object at 0x7da20c6abe50> begin[:]
<ast.Raise object at 0x7da20c6aa3e0>
<ast.Try object at 0x7da20c6a9f60>
if <ast.UnaryOp object at 0x7da20c6a9ff0> begin[:]
variable[type] assign[=] constant[text/plain;charset=US-ASCII]
variable[semi] assign[=] call[name[type].rfind, parameter[constant[;]]]
if <ast.BoolOp object at 0x7da20c6aaef0> begin[:]
variable[encoding] assign[=] call[name[type]][<ast.Slice object at 0x7da18f58fcd0>]
variable[type] assign[=] call[name[type]][<ast.Slice object at 0x7da18f58f640>]
variable[msg] assign[=] list[[]]
call[name[msg].append, parameter[binary_operation[constant[Date: %s] <ast.Mod object at 0x7da2590d6920> call[name[time].strftime, parameter[constant[%a, %d %b %Y %H:%M:%S GMT], call[name[time].gmtime, parameter[call[name[time].time, parameter[]]]]]]]]]
call[name[msg].append, parameter[binary_operation[constant[Content-type: %s] <ast.Mod object at 0x7da2590d6920> name[type]]]]
if compare[name[encoding] equal[==] constant[base64]] begin[:]
variable[data] assign[=] call[call[name[base64].decodebytes, parameter[call[name[data].encode, parameter[constant[ascii]]]]].decode, parameter[constant[latin-1]]]
call[name[msg].append, parameter[binary_operation[constant[Content-Length: %d] <ast.Mod object at 0x7da2590d6920> call[name[len], parameter[name[data]]]]]]
call[name[msg].append, parameter[constant[]]]
call[name[msg].append, parameter[name[data]]]
variable[msg] assign[=] call[constant[
].join, parameter[name[msg]]]
variable[headers] assign[=] call[name[email].message_from_string, parameter[name[msg]]]
variable[f] assign[=] call[name[io].StringIO, parameter[name[msg]]]
return[call[name[addinfourl], parameter[name[f], name[headers], name[url]]]]
|
keyword[def] identifier[open_data] ( identifier[self] , identifier[url] , identifier[data] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[url] , identifier[str] ):
keyword[raise] identifier[URLError] ( literal[string] )
keyword[try] :
[ identifier[type] , identifier[data] ]= identifier[url] . identifier[split] ( literal[string] , literal[int] )
keyword[except] identifier[ValueError] :
keyword[raise] identifier[IOError] ( literal[string] , literal[string] )
keyword[if] keyword[not] identifier[type] :
identifier[type] = literal[string]
identifier[semi] = identifier[type] . identifier[rfind] ( literal[string] )
keyword[if] identifier[semi] >= literal[int] keyword[and] literal[string] keyword[not] keyword[in] identifier[type] [ identifier[semi] :]:
identifier[encoding] = identifier[type] [ identifier[semi] + literal[int] :]
identifier[type] = identifier[type] [: identifier[semi] ]
keyword[else] :
identifier[encoding] = literal[string]
identifier[msg] =[]
identifier[msg] . identifier[append] ( literal[string] % identifier[time] . identifier[strftime] ( literal[string] ,
identifier[time] . identifier[gmtime] ( identifier[time] . identifier[time] ())))
identifier[msg] . identifier[append] ( literal[string] % identifier[type] )
keyword[if] identifier[encoding] == literal[string] :
identifier[data] = identifier[base64] . identifier[decodebytes] ( identifier[data] . identifier[encode] ( literal[string] )). identifier[decode] ( literal[string] )
keyword[else] :
identifier[data] = identifier[unquote] ( identifier[data] )
identifier[msg] . identifier[append] ( literal[string] % identifier[len] ( identifier[data] ))
identifier[msg] . identifier[append] ( literal[string] )
identifier[msg] . identifier[append] ( identifier[data] )
identifier[msg] = literal[string] . identifier[join] ( identifier[msg] )
identifier[headers] = identifier[email] . identifier[message_from_string] ( identifier[msg] )
identifier[f] = identifier[io] . identifier[StringIO] ( identifier[msg] )
keyword[return] identifier[addinfourl] ( identifier[f] , identifier[headers] , identifier[url] )
|
def open_data(self, url, data=None):
"""Use "data" URL."""
if not isinstance(url, str):
raise URLError('data error: proxy support for data protocol currently not implemented') # depends on [control=['if'], data=[]]
# ignore POSTed data
#
# syntax of data URLs:
# dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
# mediatype := [ type "/" subtype ] *( ";" parameter )
# data := *urlchar
# parameter := attribute "=" value
try:
[type, data] = url.split(',', 1) # depends on [control=['try'], data=[]]
except ValueError:
raise IOError('data error', 'bad data URL') # depends on [control=['except'], data=[]]
if not type:
type = 'text/plain;charset=US-ASCII' # depends on [control=['if'], data=[]]
semi = type.rfind(';')
if semi >= 0 and '=' not in type[semi:]:
encoding = type[semi + 1:]
type = type[:semi] # depends on [control=['if'], data=[]]
else:
encoding = ''
msg = []
msg.append('Date: %s' % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time())))
msg.append('Content-type: %s' % type)
if encoding == 'base64':
# XXX is this encoding/decoding ok?
data = base64.decodebytes(data.encode('ascii')).decode('latin-1') # depends on [control=['if'], data=[]]
else:
data = unquote(data)
msg.append('Content-Length: %d' % len(data))
msg.append('')
msg.append(data)
msg = '\n'.join(msg)
headers = email.message_from_string(msg)
f = io.StringIO(msg)
#f.fileno = None # needed for addinfourl
return addinfourl(f, headers, url)
|
def rpcexec(self, payload):
""" Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
log.debug(json.dumps(payload))
self.ws.send(json.dumps(payload, ensure_ascii=False).encode("utf8"))
|
def function[rpcexec, parameter[self, payload]]:
constant[ Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
]
call[name[log].debug, parameter[call[name[json].dumps, parameter[name[payload]]]]]
call[name[self].ws.send, parameter[call[call[name[json].dumps, parameter[name[payload]]].encode, parameter[constant[utf8]]]]]
|
keyword[def] identifier[rpcexec] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[log] . identifier[debug] ( identifier[json] . identifier[dumps] ( identifier[payload] ))
identifier[self] . identifier[ws] . identifier[send] ( identifier[json] . identifier[dumps] ( identifier[payload] , identifier[ensure_ascii] = keyword[False] ). identifier[encode] ( literal[string] ))
|
def rpcexec(self, payload):
""" Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
log.debug(json.dumps(payload))
self.ws.send(json.dumps(payload, ensure_ascii=False).encode('utf8'))
|
def _parse_bbox_list(bbox_list):
""" Helper method for parsing a list of bounding boxes
"""
if isinstance(bbox_list, BBoxCollection):
return bbox_list.bbox_list, bbox_list.crs
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueError('Expected non-empty list of BBox objects')
for bbox in bbox_list:
if not isinstance(bbox, BBox):
raise ValueError('Elements in the list should be of type {}, got {}'.format(BBox.__name__, type(bbox)))
crs = bbox_list[0].crs
for bbox in bbox_list:
if bbox.crs is not crs:
raise ValueError('All bounding boxes should have the same CRS')
return bbox_list, crs
|
def function[_parse_bbox_list, parameter[bbox_list]]:
constant[ Helper method for parsing a list of bounding boxes
]
if call[name[isinstance], parameter[name[bbox_list], name[BBoxCollection]]] begin[:]
return[tuple[[<ast.Attribute object at 0x7da1b180d1e0>, <ast.Attribute object at 0x7da1b180cbe0>]]]
if <ast.BoolOp object at 0x7da1b180c2b0> begin[:]
<ast.Raise object at 0x7da1b180cfa0>
for taget[name[bbox]] in starred[name[bbox_list]] begin[:]
if <ast.UnaryOp object at 0x7da1b180da50> begin[:]
<ast.Raise object at 0x7da1b180d090>
variable[crs] assign[=] call[name[bbox_list]][constant[0]].crs
for taget[name[bbox]] in starred[name[bbox_list]] begin[:]
if compare[name[bbox].crs is_not name[crs]] begin[:]
<ast.Raise object at 0x7da1b18b46d0>
return[tuple[[<ast.Name object at 0x7da1b18b64a0>, <ast.Name object at 0x7da1b18b6a70>]]]
|
keyword[def] identifier[_parse_bbox_list] ( identifier[bbox_list] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[bbox_list] , identifier[BBoxCollection] ):
keyword[return] identifier[bbox_list] . identifier[bbox_list] , identifier[bbox_list] . identifier[crs]
keyword[if] keyword[not] identifier[isinstance] ( identifier[bbox_list] , identifier[list] ) keyword[or] keyword[not] identifier[bbox_list] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[for] identifier[bbox] keyword[in] identifier[bbox_list] :
keyword[if] keyword[not] identifier[isinstance] ( identifier[bbox] , identifier[BBox] ):
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[BBox] . identifier[__name__] , identifier[type] ( identifier[bbox] )))
identifier[crs] = identifier[bbox_list] [ literal[int] ]. identifier[crs]
keyword[for] identifier[bbox] keyword[in] identifier[bbox_list] :
keyword[if] identifier[bbox] . identifier[crs] keyword[is] keyword[not] identifier[crs] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[bbox_list] , identifier[crs]
|
def _parse_bbox_list(bbox_list):
""" Helper method for parsing a list of bounding boxes
"""
if isinstance(bbox_list, BBoxCollection):
return (bbox_list.bbox_list, bbox_list.crs) # depends on [control=['if'], data=[]]
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueError('Expected non-empty list of BBox objects') # depends on [control=['if'], data=[]]
for bbox in bbox_list:
if not isinstance(bbox, BBox):
raise ValueError('Elements in the list should be of type {}, got {}'.format(BBox.__name__, type(bbox))) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['bbox']]
crs = bbox_list[0].crs
for bbox in bbox_list:
if bbox.crs is not crs:
raise ValueError('All bounding boxes should have the same CRS') # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['bbox']]
return (bbox_list, crs)
|
def quit(self):
"""
Send LMTP QUIT command, read the server response and disconnect.
"""
self._send('QUIT\r\n')
resp = self._read()
if not resp.startswith('221'):
logger.warning('Unexpected server response at QUIT: ' + resp)
self._socket.close()
self._socket = None
self._recipients = []
self.results = {}
|
def function[quit, parameter[self]]:
constant[
Send LMTP QUIT command, read the server response and disconnect.
]
call[name[self]._send, parameter[constant[QUIT
]]]
variable[resp] assign[=] call[name[self]._read, parameter[]]
if <ast.UnaryOp object at 0x7da1b0adbf40> begin[:]
call[name[logger].warning, parameter[binary_operation[constant[Unexpected server response at QUIT: ] + name[resp]]]]
call[name[self]._socket.close, parameter[]]
name[self]._socket assign[=] constant[None]
name[self]._recipients assign[=] list[[]]
name[self].results assign[=] dictionary[[], []]
|
keyword[def] identifier[quit] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_send] ( literal[string] )
identifier[resp] = identifier[self] . identifier[_read] ()
keyword[if] keyword[not] identifier[resp] . identifier[startswith] ( literal[string] ):
identifier[logger] . identifier[warning] ( literal[string] + identifier[resp] )
identifier[self] . identifier[_socket] . identifier[close] ()
identifier[self] . identifier[_socket] = keyword[None]
identifier[self] . identifier[_recipients] =[]
identifier[self] . identifier[results] ={}
|
def quit(self):
"""
Send LMTP QUIT command, read the server response and disconnect.
"""
self._send('QUIT\r\n')
resp = self._read()
if not resp.startswith('221'):
logger.warning('Unexpected server response at QUIT: ' + resp) # depends on [control=['if'], data=[]]
self._socket.close()
self._socket = None
self._recipients = []
self.results = {}
|
def installed(name, password, keychain="/Library/Keychains/System.keychain", **kwargs):
'''
Install a p12 certificate file into the macOS keychain
name
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
allow_any
Allow any application to access the imported certificate without warning
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
if 'http' in name or 'salt' in name:
name = __salt__['cp.cache_file'](name)
certs = __salt__['keychain.list_certs'](keychain)
friendly_name = __salt__['keychain.get_friendly_name'](name, password)
if friendly_name in certs:
file_hash = __salt__['keychain.get_hash'](name, password)
keychain_hash = __salt__['keychain.get_hash'](friendly_name)
if file_hash != keychain_hash:
out = __salt__['keychain.uninstall'](friendly_name, keychain,
keychain_password=kwargs.get('keychain_password'))
if "unable" not in out:
ret['comment'] += "Found a certificate with the same name but different hash, removing it.\n"
ret['changes']['uninstalled'] = friendly_name
# Reset the certs found
certs = __salt__['keychain.list_certs'](keychain)
else:
ret['result'] = False
ret['comment'] += "Found an incorrect cert but was unable to uninstall it: {0}".format(friendly_name)
return ret
if friendly_name not in certs:
out = __salt__['keychain.install'](name, password, keychain, **kwargs)
if "imported" in out:
ret['changes']['installed'] = friendly_name
else:
ret['result'] = False
ret['comment'] += "Failed to install {0}".format(friendly_name)
else:
ret['comment'] += "{0} already installed.".format(friendly_name)
return ret
|
def function[installed, parameter[name, password, keychain]]:
constant[
Install a p12 certificate file into the macOS keychain
name
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
allow_any
Allow any application to access the imported certificate without warning
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da18f58d030>, <ast.Constant object at 0x7da18f58edd0>, <ast.Constant object at 0x7da18f58d7e0>, <ast.Constant object at 0x7da18f58c700>], [<ast.Name object at 0x7da18f58d6f0>, <ast.Constant object at 0x7da18f58cd00>, <ast.Constant object at 0x7da18f58c880>, <ast.Dict object at 0x7da18f58f910>]]
if <ast.BoolOp object at 0x7da18f58e5f0> begin[:]
variable[name] assign[=] call[call[name[__salt__]][constant[cp.cache_file]], parameter[name[name]]]
variable[certs] assign[=] call[call[name[__salt__]][constant[keychain.list_certs]], parameter[name[keychain]]]
variable[friendly_name] assign[=] call[call[name[__salt__]][constant[keychain.get_friendly_name]], parameter[name[name], name[password]]]
if compare[name[friendly_name] in name[certs]] begin[:]
variable[file_hash] assign[=] call[call[name[__salt__]][constant[keychain.get_hash]], parameter[name[name], name[password]]]
variable[keychain_hash] assign[=] call[call[name[__salt__]][constant[keychain.get_hash]], parameter[name[friendly_name]]]
if compare[name[file_hash] not_equal[!=] name[keychain_hash]] begin[:]
variable[out] assign[=] call[call[name[__salt__]][constant[keychain.uninstall]], parameter[name[friendly_name], name[keychain]]]
if compare[constant[unable] <ast.NotIn object at 0x7da2590d7190> name[out]] begin[:]
<ast.AugAssign object at 0x7da2044c2770>
call[call[name[ret]][constant[changes]]][constant[uninstalled]] assign[=] name[friendly_name]
variable[certs] assign[=] call[call[name[__salt__]][constant[keychain.list_certs]], parameter[name[keychain]]]
if compare[name[friendly_name] <ast.NotIn object at 0x7da2590d7190> name[certs]] begin[:]
variable[out] assign[=] call[call[name[__salt__]][constant[keychain.install]], parameter[name[name], name[password], name[keychain]]]
if compare[constant[imported] in name[out]] begin[:]
call[call[name[ret]][constant[changes]]][constant[installed]] assign[=] name[friendly_name]
return[name[ret]]
|
keyword[def] identifier[installed] ( identifier[name] , identifier[password] , identifier[keychain] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] : keyword[True] ,
literal[string] : literal[string] ,
literal[string] :{}}
keyword[if] literal[string] keyword[in] identifier[name] keyword[or] literal[string] keyword[in] identifier[name] :
identifier[name] = identifier[__salt__] [ literal[string] ]( identifier[name] )
identifier[certs] = identifier[__salt__] [ literal[string] ]( identifier[keychain] )
identifier[friendly_name] = identifier[__salt__] [ literal[string] ]( identifier[name] , identifier[password] )
keyword[if] identifier[friendly_name] keyword[in] identifier[certs] :
identifier[file_hash] = identifier[__salt__] [ literal[string] ]( identifier[name] , identifier[password] )
identifier[keychain_hash] = identifier[__salt__] [ literal[string] ]( identifier[friendly_name] )
keyword[if] identifier[file_hash] != identifier[keychain_hash] :
identifier[out] = identifier[__salt__] [ literal[string] ]( identifier[friendly_name] , identifier[keychain] ,
identifier[keychain_password] = identifier[kwargs] . identifier[get] ( literal[string] ))
keyword[if] literal[string] keyword[not] keyword[in] identifier[out] :
identifier[ret] [ literal[string] ]+= literal[string]
identifier[ret] [ literal[string] ][ literal[string] ]= identifier[friendly_name]
identifier[certs] = identifier[__salt__] [ literal[string] ]( identifier[keychain] )
keyword[else] :
identifier[ret] [ literal[string] ]= keyword[False]
identifier[ret] [ literal[string] ]+= literal[string] . identifier[format] ( identifier[friendly_name] )
keyword[return] identifier[ret]
keyword[if] identifier[friendly_name] keyword[not] keyword[in] identifier[certs] :
identifier[out] = identifier[__salt__] [ literal[string] ]( identifier[name] , identifier[password] , identifier[keychain] ,** identifier[kwargs] )
keyword[if] literal[string] keyword[in] identifier[out] :
identifier[ret] [ literal[string] ][ literal[string] ]= identifier[friendly_name]
keyword[else] :
identifier[ret] [ literal[string] ]= keyword[False]
identifier[ret] [ literal[string] ]+= literal[string] . identifier[format] ( identifier[friendly_name] )
keyword[else] :
identifier[ret] [ literal[string] ]+= literal[string] . identifier[format] ( identifier[friendly_name] )
keyword[return] identifier[ret]
|
def installed(name, password, keychain='/Library/Keychains/System.keychain', **kwargs):
"""
Install a p12 certificate file into the macOS keychain
name
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
allow_any
Allow any application to access the imported certificate without warning
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
"""
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'http' in name or 'salt' in name:
name = __salt__['cp.cache_file'](name) # depends on [control=['if'], data=[]]
certs = __salt__['keychain.list_certs'](keychain)
friendly_name = __salt__['keychain.get_friendly_name'](name, password)
if friendly_name in certs:
file_hash = __salt__['keychain.get_hash'](name, password)
keychain_hash = __salt__['keychain.get_hash'](friendly_name)
if file_hash != keychain_hash:
out = __salt__['keychain.uninstall'](friendly_name, keychain, keychain_password=kwargs.get('keychain_password'))
if 'unable' not in out:
ret['comment'] += 'Found a certificate with the same name but different hash, removing it.\n'
ret['changes']['uninstalled'] = friendly_name
# Reset the certs found
certs = __salt__['keychain.list_certs'](keychain) # depends on [control=['if'], data=[]]
else:
ret['result'] = False
ret['comment'] += 'Found an incorrect cert but was unable to uninstall it: {0}'.format(friendly_name)
return ret # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['friendly_name', 'certs']]
if friendly_name not in certs:
out = __salt__['keychain.install'](name, password, keychain, **kwargs)
if 'imported' in out:
ret['changes']['installed'] = friendly_name # depends on [control=['if'], data=[]]
else:
ret['result'] = False
ret['comment'] += 'Failed to install {0}'.format(friendly_name) # depends on [control=['if'], data=['friendly_name']]
else:
ret['comment'] += '{0} already installed.'.format(friendly_name)
return ret
|
def _parse_timestamp(timestamp):
"""
Parse a given timestamp value, raising ValueError if None or Flasey
"""
if timestamp:
try:
return aniso8601.parse_datetime(timestamp)
except AttributeError:
# raised by aniso8601 if raw_timestamp is not valid string
# in ISO8601 format
try:
return datetime.utcfromtimestamp(timestamp)
except:
# relax the timestamp a bit in case it was sent in millis
return datetime.utcfromtimestamp(timestamp/1000)
raise ValueError('Invalid timestamp value! Cannot parse from either ISO8601 string or UTC timestamp.')
|
def function[_parse_timestamp, parameter[timestamp]]:
constant[
Parse a given timestamp value, raising ValueError if None or Flasey
]
if name[timestamp] begin[:]
<ast.Try object at 0x7da18c4cd090>
<ast.Raise object at 0x7da18c4cf1f0>
|
keyword[def] identifier[_parse_timestamp] ( identifier[timestamp] ):
literal[string]
keyword[if] identifier[timestamp] :
keyword[try] :
keyword[return] identifier[aniso8601] . identifier[parse_datetime] ( identifier[timestamp] )
keyword[except] identifier[AttributeError] :
keyword[try] :
keyword[return] identifier[datetime] . identifier[utcfromtimestamp] ( identifier[timestamp] )
keyword[except] :
keyword[return] identifier[datetime] . identifier[utcfromtimestamp] ( identifier[timestamp] / literal[int] )
keyword[raise] identifier[ValueError] ( literal[string] )
|
def _parse_timestamp(timestamp):
"""
Parse a given timestamp value, raising ValueError if None or Flasey
"""
if timestamp:
try:
return aniso8601.parse_datetime(timestamp) # depends on [control=['try'], data=[]]
except AttributeError:
# raised by aniso8601 if raw_timestamp is not valid string
# in ISO8601 format
try:
return datetime.utcfromtimestamp(timestamp) # depends on [control=['try'], data=[]]
except:
# relax the timestamp a bit in case it was sent in millis
return datetime.utcfromtimestamp(timestamp / 1000) # depends on [control=['except'], data=[]] # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]]
raise ValueError('Invalid timestamp value! Cannot parse from either ISO8601 string or UTC timestamp.')
|
def sed_or_dryrun(*args, **kwargs):
"""
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option.
http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
"""
dryrun = get_dryrun(kwargs.get('dryrun'))
if 'dryrun' in kwargs:
del kwargs['dryrun']
use_sudo = kwargs.get('use_sudo', False)
if dryrun:
context = dict(
filename=args[0] if len(args) >= 1 else kwargs['filename'],
before=args[1] if len(args) >= 2 else kwargs['before'],
after=args[2] if len(args) >= 3 else kwargs['after'],
backup=args[3] if len(args) >= 4 else kwargs.get('backup', '.bak'),
limit=kwargs.get('limit', ''),
)
cmd = 'sed -i{backup} -r -e "/{limit}/ s/{before}/{after}/g {filename}"'.format(**context)
cmd_run = 'sudo' if use_sudo else 'run'
if BURLAP_COMMAND_PREFIX:
print('%s %s: %s' % (render_command_prefix(), cmd_run, cmd))
else:
print(cmd)
else:
from fabric.contrib.files import sed
sed(*args, **kwargs)
|
def function[sed_or_dryrun, parameter[]]:
constant[
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option.
http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
]
variable[dryrun] assign[=] call[name[get_dryrun], parameter[call[name[kwargs].get, parameter[constant[dryrun]]]]]
if compare[constant[dryrun] in name[kwargs]] begin[:]
<ast.Delete object at 0x7da1b00b9d20>
variable[use_sudo] assign[=] call[name[kwargs].get, parameter[constant[use_sudo], constant[False]]]
if name[dryrun] begin[:]
variable[context] assign[=] call[name[dict], parameter[]]
variable[cmd] assign[=] call[constant[sed -i{backup} -r -e "/{limit}/ s/{before}/{after}/g {filename}"].format, parameter[]]
variable[cmd_run] assign[=] <ast.IfExp object at 0x7da1b00ba050>
if name[BURLAP_COMMAND_PREFIX] begin[:]
call[name[print], parameter[binary_operation[constant[%s %s: %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b00b8d00>, <ast.Name object at 0x7da1b00ba200>, <ast.Name object at 0x7da1b00ba2c0>]]]]]
|
keyword[def] identifier[sed_or_dryrun] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[dryrun] = identifier[get_dryrun] ( identifier[kwargs] . identifier[get] ( literal[string] ))
keyword[if] literal[string] keyword[in] identifier[kwargs] :
keyword[del] identifier[kwargs] [ literal[string] ]
identifier[use_sudo] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] )
keyword[if] identifier[dryrun] :
identifier[context] = identifier[dict] (
identifier[filename] = identifier[args] [ literal[int] ] keyword[if] identifier[len] ( identifier[args] )>= literal[int] keyword[else] identifier[kwargs] [ literal[string] ],
identifier[before] = identifier[args] [ literal[int] ] keyword[if] identifier[len] ( identifier[args] )>= literal[int] keyword[else] identifier[kwargs] [ literal[string] ],
identifier[after] = identifier[args] [ literal[int] ] keyword[if] identifier[len] ( identifier[args] )>= literal[int] keyword[else] identifier[kwargs] [ literal[string] ],
identifier[backup] = identifier[args] [ literal[int] ] keyword[if] identifier[len] ( identifier[args] )>= literal[int] keyword[else] identifier[kwargs] . identifier[get] ( literal[string] , literal[string] ),
identifier[limit] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] ),
)
identifier[cmd] = literal[string] . identifier[format] (** identifier[context] )
identifier[cmd_run] = literal[string] keyword[if] identifier[use_sudo] keyword[else] literal[string]
keyword[if] identifier[BURLAP_COMMAND_PREFIX] :
identifier[print] ( literal[string] %( identifier[render_command_prefix] (), identifier[cmd_run] , identifier[cmd] ))
keyword[else] :
identifier[print] ( identifier[cmd] )
keyword[else] :
keyword[from] identifier[fabric] . identifier[contrib] . identifier[files] keyword[import] identifier[sed]
identifier[sed] (* identifier[args] ,** identifier[kwargs] )
|
def sed_or_dryrun(*args, **kwargs):
"""
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option.
http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
"""
dryrun = get_dryrun(kwargs.get('dryrun'))
if 'dryrun' in kwargs:
del kwargs['dryrun'] # depends on [control=['if'], data=['kwargs']]
use_sudo = kwargs.get('use_sudo', False)
if dryrun:
context = dict(filename=args[0] if len(args) >= 1 else kwargs['filename'], before=args[1] if len(args) >= 2 else kwargs['before'], after=args[2] if len(args) >= 3 else kwargs['after'], backup=args[3] if len(args) >= 4 else kwargs.get('backup', '.bak'), limit=kwargs.get('limit', ''))
cmd = 'sed -i{backup} -r -e "/{limit}/ s/{before}/{after}/g {filename}"'.format(**context)
cmd_run = 'sudo' if use_sudo else 'run'
if BURLAP_COMMAND_PREFIX:
print('%s %s: %s' % (render_command_prefix(), cmd_run, cmd)) # depends on [control=['if'], data=[]]
else:
print(cmd) # depends on [control=['if'], data=[]]
else:
from fabric.contrib.files import sed
sed(*args, **kwargs)
|
def blob(self, nodeid, tag, start=0, end=0xFFFFFFFF):
"""
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
"""
startkey = self.makekey(nodeid, tag, start)
endkey = self.makekey(nodeid, tag, end)
cur = self.btree.find('ge', startkey)
data = b''
while cur.getkey() <= endkey:
data += cur.getval()
cur.next()
return data
|
def function[blob, parameter[self, nodeid, tag, start, end]]:
constant[
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
]
variable[startkey] assign[=] call[name[self].makekey, parameter[name[nodeid], name[tag], name[start]]]
variable[endkey] assign[=] call[name[self].makekey, parameter[name[nodeid], name[tag], name[end]]]
variable[cur] assign[=] call[name[self].btree.find, parameter[constant[ge], name[startkey]]]
variable[data] assign[=] constant[b'']
while compare[call[name[cur].getkey, parameter[]] less_or_equal[<=] name[endkey]] begin[:]
<ast.AugAssign object at 0x7da2045663b0>
call[name[cur].next, parameter[]]
return[name[data]]
|
keyword[def] identifier[blob] ( identifier[self] , identifier[nodeid] , identifier[tag] , identifier[start] = literal[int] , identifier[end] = literal[int] ):
literal[string]
identifier[startkey] = identifier[self] . identifier[makekey] ( identifier[nodeid] , identifier[tag] , identifier[start] )
identifier[endkey] = identifier[self] . identifier[makekey] ( identifier[nodeid] , identifier[tag] , identifier[end] )
identifier[cur] = identifier[self] . identifier[btree] . identifier[find] ( literal[string] , identifier[startkey] )
identifier[data] = literal[string]
keyword[while] identifier[cur] . identifier[getkey] ()<= identifier[endkey] :
identifier[data] += identifier[cur] . identifier[getval] ()
identifier[cur] . identifier[next] ()
keyword[return] identifier[data]
|
def blob(self, nodeid, tag, start=0, end=4294967295):
"""
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
"""
startkey = self.makekey(nodeid, tag, start)
endkey = self.makekey(nodeid, tag, end)
cur = self.btree.find('ge', startkey)
data = b''
while cur.getkey() <= endkey:
data += cur.getval()
cur.next() # depends on [control=['while'], data=[]]
return data
|
def _get_identical_contigs(self, hits_dict):
'''Input is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns a list of sets of contigs that are equivalent'''
equivalent_contigs = []
for qry_name, containing in hits_dict.items():
equivalent = set()
for containing_name in containing:
if containing_name in hits_dict and qry_name in hits_dict[containing_name]:
equivalent.add(containing_name)
equivalent.add(qry_name)
if len(equivalent):
equivalent_contigs.append(equivalent)
equivalent_contigs = self._collapse_list_of_sets(equivalent_contigs)
return equivalent_contigs
|
def function[_get_identical_contigs, parameter[self, hits_dict]]:
constant[Input is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns a list of sets of contigs that are equivalent]
variable[equivalent_contigs] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da20c6a9ea0>, <ast.Name object at 0x7da20c6a96c0>]]] in starred[call[name[hits_dict].items, parameter[]]] begin[:]
variable[equivalent] assign[=] call[name[set], parameter[]]
for taget[name[containing_name]] in starred[name[containing]] begin[:]
if <ast.BoolOp object at 0x7da204347f70> begin[:]
call[name[equivalent].add, parameter[name[containing_name]]]
call[name[equivalent].add, parameter[name[qry_name]]]
if call[name[len], parameter[name[equivalent]]] begin[:]
call[name[equivalent_contigs].append, parameter[name[equivalent]]]
variable[equivalent_contigs] assign[=] call[name[self]._collapse_list_of_sets, parameter[name[equivalent_contigs]]]
return[name[equivalent_contigs]]
|
keyword[def] identifier[_get_identical_contigs] ( identifier[self] , identifier[hits_dict] ):
literal[string]
identifier[equivalent_contigs] =[]
keyword[for] identifier[qry_name] , identifier[containing] keyword[in] identifier[hits_dict] . identifier[items] ():
identifier[equivalent] = identifier[set] ()
keyword[for] identifier[containing_name] keyword[in] identifier[containing] :
keyword[if] identifier[containing_name] keyword[in] identifier[hits_dict] keyword[and] identifier[qry_name] keyword[in] identifier[hits_dict] [ identifier[containing_name] ]:
identifier[equivalent] . identifier[add] ( identifier[containing_name] )
identifier[equivalent] . identifier[add] ( identifier[qry_name] )
keyword[if] identifier[len] ( identifier[equivalent] ):
identifier[equivalent_contigs] . identifier[append] ( identifier[equivalent] )
identifier[equivalent_contigs] = identifier[self] . identifier[_collapse_list_of_sets] ( identifier[equivalent_contigs] )
keyword[return] identifier[equivalent_contigs]
|
def _get_identical_contigs(self, hits_dict):
"""Input is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns a list of sets of contigs that are equivalent"""
equivalent_contigs = []
for (qry_name, containing) in hits_dict.items():
equivalent = set()
for containing_name in containing:
if containing_name in hits_dict and qry_name in hits_dict[containing_name]:
equivalent.add(containing_name)
equivalent.add(qry_name) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['containing_name']]
if len(equivalent):
equivalent_contigs.append(equivalent)
equivalent_contigs = self._collapse_list_of_sets(equivalent_contigs) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
return equivalent_contigs
|
def ux_actions(parser, args):
"""Handle some human triggers actions"""
# cryptorito uses native logging (as aomi should tbh)
normal_fmt = '%(message)s'
if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2:
logging.basicConfig(level=logging.DEBUG)
elif hasattr(args, 'verbose') and args.verbose >= 1:
logging.basicConfig(level=logging.INFO, format=normal_fmt)
else:
logging.basicConfig(level=logging.WARN, format=normal_fmt)
if args.operation == 'help':
help_me(parser, args)
|
def function[ux_actions, parameter[parser, args]]:
constant[Handle some human triggers actions]
variable[normal_fmt] assign[=] constant[%(message)s]
if <ast.BoolOp object at 0x7da1b1bee830> begin[:]
call[name[logging].basicConfig, parameter[]]
if compare[name[args].operation equal[==] constant[help]] begin[:]
call[name[help_me], parameter[name[parser], name[args]]]
|
keyword[def] identifier[ux_actions] ( identifier[parser] , identifier[args] ):
literal[string]
identifier[normal_fmt] = literal[string]
keyword[if] identifier[hasattr] ( identifier[args] , literal[string] ) keyword[and] identifier[args] . identifier[verbose] keyword[and] identifier[args] . identifier[verbose] >= literal[int] :
identifier[logging] . identifier[basicConfig] ( identifier[level] = identifier[logging] . identifier[DEBUG] )
keyword[elif] identifier[hasattr] ( identifier[args] , literal[string] ) keyword[and] identifier[args] . identifier[verbose] >= literal[int] :
identifier[logging] . identifier[basicConfig] ( identifier[level] = identifier[logging] . identifier[INFO] , identifier[format] = identifier[normal_fmt] )
keyword[else] :
identifier[logging] . identifier[basicConfig] ( identifier[level] = identifier[logging] . identifier[WARN] , identifier[format] = identifier[normal_fmt] )
keyword[if] identifier[args] . identifier[operation] == literal[string] :
identifier[help_me] ( identifier[parser] , identifier[args] )
|
def ux_actions(parser, args):
"""Handle some human triggers actions"""
# cryptorito uses native logging (as aomi should tbh)
normal_fmt = '%(message)s'
if hasattr(args, 'verbose') and args.verbose and (args.verbose >= 2):
logging.basicConfig(level=logging.DEBUG) # depends on [control=['if'], data=[]]
elif hasattr(args, 'verbose') and args.verbose >= 1:
logging.basicConfig(level=logging.INFO, format=normal_fmt) # depends on [control=['if'], data=[]]
else:
logging.basicConfig(level=logging.WARN, format=normal_fmt)
if args.operation == 'help':
help_me(parser, args) # depends on [control=['if'], data=[]]
|
def run(self):
"Run each middleware function on files"
# load files from source directory
files = self.get_files()
# loop through each middleware
for func in self.middleware:
# call each one, ignoring return value
func(files, self)
# store and return the result
self.files.update(files)
return files
|
def function[run, parameter[self]]:
constant[Run each middleware function on files]
variable[files] assign[=] call[name[self].get_files, parameter[]]
for taget[name[func]] in starred[name[self].middleware] begin[:]
call[name[func], parameter[name[files], name[self]]]
call[name[self].files.update, parameter[name[files]]]
return[name[files]]
|
keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[files] = identifier[self] . identifier[get_files] ()
keyword[for] identifier[func] keyword[in] identifier[self] . identifier[middleware] :
identifier[func] ( identifier[files] , identifier[self] )
identifier[self] . identifier[files] . identifier[update] ( identifier[files] )
keyword[return] identifier[files]
|
def run(self):
"""Run each middleware function on files"""
# load files from source directory
files = self.get_files()
# loop through each middleware
for func in self.middleware:
# call each one, ignoring return value
func(files, self) # depends on [control=['for'], data=['func']]
# store and return the result
self.files.update(files)
return files
|
def get_usrgos_g_hdrgos(self, hdrgos):
"""Return usrgos under provided hdrgos."""
usrgos_all = set()
if isinstance(hdrgos, str):
hdrgos = [hdrgos]
for hdrgo in hdrgos:
usrgos_cur = self.hdrgo2usrgos.get(hdrgo, None)
if usrgos_cur is not None:
usrgos_all |= usrgos_cur
if hdrgo in self.hdrgo_is_usrgo:
usrgos_all.add(hdrgo)
return usrgos_all
|
def function[get_usrgos_g_hdrgos, parameter[self, hdrgos]]:
constant[Return usrgos under provided hdrgos.]
variable[usrgos_all] assign[=] call[name[set], parameter[]]
if call[name[isinstance], parameter[name[hdrgos], name[str]]] begin[:]
variable[hdrgos] assign[=] list[[<ast.Name object at 0x7da18bcca890>]]
for taget[name[hdrgo]] in starred[name[hdrgos]] begin[:]
variable[usrgos_cur] assign[=] call[name[self].hdrgo2usrgos.get, parameter[name[hdrgo], constant[None]]]
if compare[name[usrgos_cur] is_not constant[None]] begin[:]
<ast.AugAssign object at 0x7da18bcc8040>
if compare[name[hdrgo] in name[self].hdrgo_is_usrgo] begin[:]
call[name[usrgos_all].add, parameter[name[hdrgo]]]
return[name[usrgos_all]]
|
keyword[def] identifier[get_usrgos_g_hdrgos] ( identifier[self] , identifier[hdrgos] ):
literal[string]
identifier[usrgos_all] = identifier[set] ()
keyword[if] identifier[isinstance] ( identifier[hdrgos] , identifier[str] ):
identifier[hdrgos] =[ identifier[hdrgos] ]
keyword[for] identifier[hdrgo] keyword[in] identifier[hdrgos] :
identifier[usrgos_cur] = identifier[self] . identifier[hdrgo2usrgos] . identifier[get] ( identifier[hdrgo] , keyword[None] )
keyword[if] identifier[usrgos_cur] keyword[is] keyword[not] keyword[None] :
identifier[usrgos_all] |= identifier[usrgos_cur]
keyword[if] identifier[hdrgo] keyword[in] identifier[self] . identifier[hdrgo_is_usrgo] :
identifier[usrgos_all] . identifier[add] ( identifier[hdrgo] )
keyword[return] identifier[usrgos_all]
|
def get_usrgos_g_hdrgos(self, hdrgos):
"""Return usrgos under provided hdrgos."""
usrgos_all = set()
if isinstance(hdrgos, str):
hdrgos = [hdrgos] # depends on [control=['if'], data=[]]
for hdrgo in hdrgos:
usrgos_cur = self.hdrgo2usrgos.get(hdrgo, None)
if usrgos_cur is not None:
usrgos_all |= usrgos_cur # depends on [control=['if'], data=['usrgos_cur']]
if hdrgo in self.hdrgo_is_usrgo:
usrgos_all.add(hdrgo) # depends on [control=['if'], data=['hdrgo']] # depends on [control=['for'], data=['hdrgo']]
return usrgos_all
|
def call_senders(self, routing, clients_list, *args, **kwargs):
"""
Calls senders callbacks
"""
for func, routings, routings_re in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings_re is None):
call_callback = True
# Message is not published globally
else:
# Message is catched by a string routing key
if routings and routing in routings:
call_callback = True
# Message is catched by a regex routing key
if routings_re and any(r.match(routing) for r in routings_re):
call_callback = True
if call_callback:
func(routing, clients_list, *args, **kwargs)
|
def function[call_senders, parameter[self, routing, clients_list]]:
constant[
Calls senders callbacks
]
for taget[tuple[[<ast.Name object at 0x7da2041daef0>, <ast.Name object at 0x7da2041d8b50>, <ast.Name object at 0x7da2041da560>]]] in starred[name[self].senders] begin[:]
variable[call_callback] assign[=] constant[False]
if <ast.BoolOp object at 0x7da2041d9e10> begin[:]
variable[call_callback] assign[=] constant[True]
if name[call_callback] begin[:]
call[name[func], parameter[name[routing], name[clients_list], <ast.Starred object at 0x7da204621180>]]
|
keyword[def] identifier[call_senders] ( identifier[self] , identifier[routing] , identifier[clients_list] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[func] , identifier[routings] , identifier[routings_re] keyword[in] identifier[self] . identifier[senders] :
identifier[call_callback] = keyword[False]
keyword[if] identifier[routing] keyword[is] keyword[None] keyword[or] ( identifier[routings] keyword[is] keyword[None] keyword[and] identifier[routings_re] keyword[is] keyword[None] ):
identifier[call_callback] = keyword[True]
keyword[else] :
keyword[if] identifier[routings] keyword[and] identifier[routing] keyword[in] identifier[routings] :
identifier[call_callback] = keyword[True]
keyword[if] identifier[routings_re] keyword[and] identifier[any] ( identifier[r] . identifier[match] ( identifier[routing] ) keyword[for] identifier[r] keyword[in] identifier[routings_re] ):
identifier[call_callback] = keyword[True]
keyword[if] identifier[call_callback] :
identifier[func] ( identifier[routing] , identifier[clients_list] ,* identifier[args] ,** identifier[kwargs] )
|
def call_senders(self, routing, clients_list, *args, **kwargs):
"""
Calls senders callbacks
"""
for (func, routings, routings_re) in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings_re is None):
call_callback = True # depends on [control=['if'], data=[]]
else:
# Message is not published globally
# Message is catched by a string routing key
if routings and routing in routings:
call_callback = True # depends on [control=['if'], data=[]]
# Message is catched by a regex routing key
if routings_re and any((r.match(routing) for r in routings_re)):
call_callback = True # depends on [control=['if'], data=[]]
if call_callback:
func(routing, clients_list, *args, **kwargs) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
|
def _get_all_ns_packages(self):
"""Return sorted list of all package namespaces"""
nsp = set()
for pkg in self.distribution.namespace_packages or []:
pkg = pkg.split('.')
while pkg:
nsp.add('.'.join(pkg))
pkg.pop()
return sorted(nsp)
|
def function[_get_all_ns_packages, parameter[self]]:
constant[Return sorted list of all package namespaces]
variable[nsp] assign[=] call[name[set], parameter[]]
for taget[name[pkg]] in starred[<ast.BoolOp object at 0x7da18f811ba0>] begin[:]
variable[pkg] assign[=] call[name[pkg].split, parameter[constant[.]]]
while name[pkg] begin[:]
call[name[nsp].add, parameter[call[constant[.].join, parameter[name[pkg]]]]]
call[name[pkg].pop, parameter[]]
return[call[name[sorted], parameter[name[nsp]]]]
|
keyword[def] identifier[_get_all_ns_packages] ( identifier[self] ):
literal[string]
identifier[nsp] = identifier[set] ()
keyword[for] identifier[pkg] keyword[in] identifier[self] . identifier[distribution] . identifier[namespace_packages] keyword[or] []:
identifier[pkg] = identifier[pkg] . identifier[split] ( literal[string] )
keyword[while] identifier[pkg] :
identifier[nsp] . identifier[add] ( literal[string] . identifier[join] ( identifier[pkg] ))
identifier[pkg] . identifier[pop] ()
keyword[return] identifier[sorted] ( identifier[nsp] )
|
def _get_all_ns_packages(self):
"""Return sorted list of all package namespaces"""
nsp = set()
for pkg in self.distribution.namespace_packages or []:
pkg = pkg.split('.')
while pkg:
nsp.add('.'.join(pkg))
pkg.pop() # depends on [control=['while'], data=[]] # depends on [control=['for'], data=['pkg']]
return sorted(nsp)
|
def part(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
"""Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found
"""
_parts = self.parts(*args, **kwargs)
if len(_parts) == 0:
raise NotFoundError("No part fits criteria")
if len(_parts) != 1:
raise MultipleFoundError("Multiple parts fit criteria")
return _parts[0]
|
def function[part, parameter[self]]:
constant[Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found
]
variable[_parts] assign[=] call[name[self].parts, parameter[<ast.Starred object at 0x7da1b246a830>]]
if compare[call[name[len], parameter[name[_parts]]] equal[==] constant[0]] begin[:]
<ast.Raise object at 0x7da1b25d1840>
if compare[call[name[len], parameter[name[_parts]]] not_equal[!=] constant[1]] begin[:]
<ast.Raise object at 0x7da1b25d1bd0>
return[call[name[_parts]][constant[0]]]
|
keyword[def] identifier[part] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[_parts] = identifier[self] . identifier[parts] (* identifier[args] ,** identifier[kwargs] )
keyword[if] identifier[len] ( identifier[_parts] )== literal[int] :
keyword[raise] identifier[NotFoundError] ( literal[string] )
keyword[if] identifier[len] ( identifier[_parts] )!= literal[int] :
keyword[raise] identifier[MultipleFoundError] ( literal[string] )
keyword[return] identifier[_parts] [ literal[int] ]
|
def part(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
'Retrieve single KE-chain part.\n\n Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`\n instance.\n\n If additional `keyword=value` arguments are provided, these are added to the request parameters. Please\n refer to the documentation of the KE-chain API for additional query parameters.\n\n :return: a single :class:`models.Part`\n :raises NotFoundError: When no `Part` is found\n :raises MultipleFoundError: When more than a single `Part` is found\n '
_parts = self.parts(*args, **kwargs)
if len(_parts) == 0:
raise NotFoundError('No part fits criteria') # depends on [control=['if'], data=[]]
if len(_parts) != 1:
raise MultipleFoundError('Multiple parts fit criteria') # depends on [control=['if'], data=[]]
return _parts[0]
|
def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number
except ImportError:
from operator import isNumberType
return isNumberType(obj)
else:
return isinstance(obj, Number)
|
def function[is_number, parameter[obj]]:
constant[
Helper function to determine numbers
across Python 2.x and 3.x
]
<ast.Try object at 0x7da18bc71630>
|
keyword[def] identifier[is_number] ( identifier[obj] ):
literal[string]
keyword[try] :
keyword[from] identifier[numbers] keyword[import] identifier[Number]
keyword[except] identifier[ImportError] :
keyword[from] identifier[operator] keyword[import] identifier[isNumberType]
keyword[return] identifier[isNumberType] ( identifier[obj] )
keyword[else] :
keyword[return] identifier[isinstance] ( identifier[obj] , identifier[Number] )
|
def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number # depends on [control=['try'], data=[]]
except ImportError:
from operator import isNumberType
return isNumberType(obj) # depends on [control=['except'], data=[]]
else:
return isinstance(obj, Number)
|
def encode(self, value):
"""
Return a bytestring representation of the value
"""
if isinstance(value, Token):
return b(value.value)
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = b(str(value))
elif isinstance(value, float):
value = repr(value)
elif not isinstance(value, basestring):
value = str(value)
if isinstance(value, unicode):
value = value.encode(self.encoding, self.encoding_errors)
return value
|
def function[encode, parameter[self, value]]:
constant[
Return a bytestring representation of the value
]
if call[name[isinstance], parameter[name[value], name[Token]]] begin[:]
return[call[name[b], parameter[name[value].value]]]
if call[name[isinstance], parameter[name[value], name[bytes]]] begin[:]
return[name[value]]
if call[name[isinstance], parameter[name[value], name[unicode]]] begin[:]
variable[value] assign[=] call[name[value].encode, parameter[name[self].encoding, name[self].encoding_errors]]
return[name[value]]
|
keyword[def] identifier[encode] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[Token] ):
keyword[return] identifier[b] ( identifier[value] . identifier[value] )
keyword[if] identifier[isinstance] ( identifier[value] , identifier[bytes] ):
keyword[return] identifier[value]
keyword[elif] identifier[isinstance] ( identifier[value] ,( identifier[int] , identifier[long] )):
identifier[value] = identifier[b] ( identifier[str] ( identifier[value] ))
keyword[elif] identifier[isinstance] ( identifier[value] , identifier[float] ):
identifier[value] = identifier[repr] ( identifier[value] )
keyword[elif] keyword[not] identifier[isinstance] ( identifier[value] , identifier[basestring] ):
identifier[value] = identifier[str] ( identifier[value] )
keyword[if] identifier[isinstance] ( identifier[value] , identifier[unicode] ):
identifier[value] = identifier[value] . identifier[encode] ( identifier[self] . identifier[encoding] , identifier[self] . identifier[encoding_errors] )
keyword[return] identifier[value]
|
def encode(self, value):
"""
Return a bytestring representation of the value
"""
if isinstance(value, Token):
return b(value.value) # depends on [control=['if'], data=[]]
if isinstance(value, bytes):
return value # depends on [control=['if'], data=[]]
elif isinstance(value, (int, long)):
value = b(str(value)) # depends on [control=['if'], data=[]]
elif isinstance(value, float):
value = repr(value) # depends on [control=['if'], data=[]]
elif not isinstance(value, basestring):
value = str(value) # depends on [control=['if'], data=[]]
if isinstance(value, unicode):
value = value.encode(self.encoding, self.encoding_errors) # depends on [control=['if'], data=[]]
return value
|
def validateDtdFinal(self, ctxt):
"""Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one of the defined entities. - check that NOTATION type
attributes default or possible values matches one of the
defined notations. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.xmlValidateDtdFinal(ctxt__o, self._o)
return ret
|
def function[validateDtdFinal, parameter[self, ctxt]]:
constant[Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one of the defined entities. - check that NOTATION type
attributes default or possible values matches one of the
defined notations. ]
if compare[name[ctxt] is constant[None]] begin[:]
variable[ctxt__o] assign[=] constant[None]
variable[ret] assign[=] call[name[libxml2mod].xmlValidateDtdFinal, parameter[name[ctxt__o], name[self]._o]]
return[name[ret]]
|
keyword[def] identifier[validateDtdFinal] ( identifier[self] , identifier[ctxt] ):
literal[string]
keyword[if] identifier[ctxt] keyword[is] keyword[None] : identifier[ctxt__o] = keyword[None]
keyword[else] : identifier[ctxt__o] = identifier[ctxt] . identifier[_o]
identifier[ret] = identifier[libxml2mod] . identifier[xmlValidateDtdFinal] ( identifier[ctxt__o] , identifier[self] . identifier[_o] )
keyword[return] identifier[ret]
|
def validateDtdFinal(self, ctxt):
"""Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one of the defined entities. - check that NOTATION type
attributes default or possible values matches one of the
defined notations. """
if ctxt is None:
ctxt__o = None # depends on [control=['if'], data=[]]
else:
ctxt__o = ctxt._o
ret = libxml2mod.xmlValidateDtdFinal(ctxt__o, self._o)
return ret
|
def call_closers(self, client, clients_list):
"""
Calls closers callbacks
"""
for func in self.closers:
func(client, clients_list)
|
def function[call_closers, parameter[self, client, clients_list]]:
constant[
Calls closers callbacks
]
for taget[name[func]] in starred[name[self].closers] begin[:]
call[name[func], parameter[name[client], name[clients_list]]]
|
keyword[def] identifier[call_closers] ( identifier[self] , identifier[client] , identifier[clients_list] ):
literal[string]
keyword[for] identifier[func] keyword[in] identifier[self] . identifier[closers] :
identifier[func] ( identifier[client] , identifier[clients_list] )
|
def call_closers(self, client, clients_list):
"""
Calls closers callbacks
"""
for func in self.closers:
func(client, clients_list) # depends on [control=['for'], data=['func']]
|
def paraminfo(param="", short=False):
""" Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
"""
## If the short flag is set return the short description, otherwise
## return the long.
if short:
desc = 1
else:
desc = 0
try:
description = pinfo[str(param)][desc]
except (KeyError, ValueError) as err:
## TODO: paramsinfo get description by param string not working.
## It would be cool to have an assembly object bcz then you could
## just do this:
##
## print(pinfo[data.paramsinfo.keys().index(param)])
print("\tKey name/number not recognized - ".format(param), err)
raise
return description
|
def function[paraminfo, parameter[param, short]]:
constant[ Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
]
if name[short] begin[:]
variable[desc] assign[=] constant[1]
<ast.Try object at 0x7da1b01413c0>
return[name[description]]
|
keyword[def] identifier[paraminfo] ( identifier[param] = literal[string] , identifier[short] = keyword[False] ):
literal[string]
keyword[if] identifier[short] :
identifier[desc] = literal[int]
keyword[else] :
identifier[desc] = literal[int]
keyword[try] :
identifier[description] = identifier[pinfo] [ identifier[str] ( identifier[param] )][ identifier[desc] ]
keyword[except] ( identifier[KeyError] , identifier[ValueError] ) keyword[as] identifier[err] :
identifier[print] ( literal[string] . identifier[format] ( identifier[param] ), identifier[err] )
keyword[raise]
keyword[return] identifier[description]
|
def paraminfo(param='', short=False):
""" Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
"""
## If the short flag is set return the short description, otherwise
## return the long.
if short:
desc = 1 # depends on [control=['if'], data=[]]
else:
desc = 0
try:
description = pinfo[str(param)][desc] # depends on [control=['try'], data=[]]
except (KeyError, ValueError) as err:
## TODO: paramsinfo get description by param string not working.
## It would be cool to have an assembly object bcz then you could
## just do this:
##
## print(pinfo[data.paramsinfo.keys().index(param)])
print('\tKey name/number not recognized - '.format(param), err)
raise # depends on [control=['except'], data=['err']]
return description
|
def show(self):
"""
Prints the content of this method to stdout.
This will print the method signature and the decompiled code.
"""
args, ret = self.method.get_descriptor()[1:].split(")")
if self.code:
# We patch the descriptor here and add the registers, if code is available
args = args.split(" ")
reg_len = self.code.get_registers_size()
nb_args = len(args)
start_reg = reg_len - nb_args
args = ["{} v{}".format(a, start_reg + i) for i, a in enumerate(args)]
print("METHOD {} {} {} ({}){}".format(
self.method.get_class_name(),
self.method.get_access_flags_string(),
self.method.get_name(),
", ".join(args), ret))
bytecode.PrettyShow(self, self.basic_blocks.gets(), self.method.notes)
|
def function[show, parameter[self]]:
constant[
Prints the content of this method to stdout.
This will print the method signature and the decompiled code.
]
<ast.Tuple object at 0x7da2041da3b0> assign[=] call[call[call[name[self].method.get_descriptor, parameter[]]][<ast.Slice object at 0x7da2041d8d60>].split, parameter[constant[)]]]
if name[self].code begin[:]
variable[args] assign[=] call[name[args].split, parameter[constant[ ]]]
variable[reg_len] assign[=] call[name[self].code.get_registers_size, parameter[]]
variable[nb_args] assign[=] call[name[len], parameter[name[args]]]
variable[start_reg] assign[=] binary_operation[name[reg_len] - name[nb_args]]
variable[args] assign[=] <ast.ListComp object at 0x7da20c7c91b0>
call[name[print], parameter[call[constant[METHOD {} {} {} ({}){}].format, parameter[call[name[self].method.get_class_name, parameter[]], call[name[self].method.get_access_flags_string, parameter[]], call[name[self].method.get_name, parameter[]], call[constant[, ].join, parameter[name[args]]], name[ret]]]]]
call[name[bytecode].PrettyShow, parameter[name[self], call[name[self].basic_blocks.gets, parameter[]], name[self].method.notes]]
|
keyword[def] identifier[show] ( identifier[self] ):
literal[string]
identifier[args] , identifier[ret] = identifier[self] . identifier[method] . identifier[get_descriptor] ()[ literal[int] :]. identifier[split] ( literal[string] )
keyword[if] identifier[self] . identifier[code] :
identifier[args] = identifier[args] . identifier[split] ( literal[string] )
identifier[reg_len] = identifier[self] . identifier[code] . identifier[get_registers_size] ()
identifier[nb_args] = identifier[len] ( identifier[args] )
identifier[start_reg] = identifier[reg_len] - identifier[nb_args]
identifier[args] =[ literal[string] . identifier[format] ( identifier[a] , identifier[start_reg] + identifier[i] ) keyword[for] identifier[i] , identifier[a] keyword[in] identifier[enumerate] ( identifier[args] )]
identifier[print] ( literal[string] . identifier[format] (
identifier[self] . identifier[method] . identifier[get_class_name] (),
identifier[self] . identifier[method] . identifier[get_access_flags_string] (),
identifier[self] . identifier[method] . identifier[get_name] (),
literal[string] . identifier[join] ( identifier[args] ), identifier[ret] ))
identifier[bytecode] . identifier[PrettyShow] ( identifier[self] , identifier[self] . identifier[basic_blocks] . identifier[gets] (), identifier[self] . identifier[method] . identifier[notes] )
|
def show(self):
"""
Prints the content of this method to stdout.
This will print the method signature and the decompiled code.
"""
(args, ret) = self.method.get_descriptor()[1:].split(')')
if self.code:
# We patch the descriptor here and add the registers, if code is available
args = args.split(' ')
reg_len = self.code.get_registers_size()
nb_args = len(args)
start_reg = reg_len - nb_args
args = ['{} v{}'.format(a, start_reg + i) for (i, a) in enumerate(args)] # depends on [control=['if'], data=[]]
print('METHOD {} {} {} ({}){}'.format(self.method.get_class_name(), self.method.get_access_flags_string(), self.method.get_name(), ', '.join(args), ret))
bytecode.PrettyShow(self, self.basic_blocks.gets(), self.method.notes)
|
def check_folders(name):
"""Only checks and asks questions. Nothing is written to disk."""
if os.getcwd().endswith('analyses'):
correct = input('You are in an analyses folder. This will create '
'another analyses folder inside this one. Do '
'you want to continue? (y/N)')
if correct != 'y':
return False
if not os.path.exists(os.path.join(os.getcwd(), 'analyses')):
correct = input('This is the first analysis here. Do '
'you want to continue? (y/N)')
if correct != 'y':
return False
if os.path.exists(os.path.join(os.getcwd(), 'analyses', name)):
correct = input('An analysis with this name exists already. Do '
'you want to continue? (y/N)')
if correct != 'y':
return False
return True
|
def function[check_folders, parameter[name]]:
constant[Only checks and asks questions. Nothing is written to disk.]
if call[call[name[os].getcwd, parameter[]].endswith, parameter[constant[analyses]]] begin[:]
variable[correct] assign[=] call[name[input], parameter[constant[You are in an analyses folder. This will create another analyses folder inside this one. Do you want to continue? (y/N)]]]
if compare[name[correct] not_equal[!=] constant[y]] begin[:]
return[constant[False]]
if <ast.UnaryOp object at 0x7da18f09ef80> begin[:]
variable[correct] assign[=] call[name[input], parameter[constant[This is the first analysis here. Do you want to continue? (y/N)]]]
if compare[name[correct] not_equal[!=] constant[y]] begin[:]
return[constant[False]]
if call[name[os].path.exists, parameter[call[name[os].path.join, parameter[call[name[os].getcwd, parameter[]], constant[analyses], name[name]]]]] begin[:]
variable[correct] assign[=] call[name[input], parameter[constant[An analysis with this name exists already. Do you want to continue? (y/N)]]]
if compare[name[correct] not_equal[!=] constant[y]] begin[:]
return[constant[False]]
return[constant[True]]
|
keyword[def] identifier[check_folders] ( identifier[name] ):
literal[string]
keyword[if] identifier[os] . identifier[getcwd] (). identifier[endswith] ( literal[string] ):
identifier[correct] = identifier[input] ( literal[string]
literal[string]
literal[string] )
keyword[if] identifier[correct] != literal[string] :
keyword[return] keyword[False]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[getcwd] (), literal[string] )):
identifier[correct] = identifier[input] ( literal[string]
literal[string] )
keyword[if] identifier[correct] != literal[string] :
keyword[return] keyword[False]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[getcwd] (), literal[string] , identifier[name] )):
identifier[correct] = identifier[input] ( literal[string]
literal[string] )
keyword[if] identifier[correct] != literal[string] :
keyword[return] keyword[False]
keyword[return] keyword[True]
|
def check_folders(name):
"""Only checks and asks questions. Nothing is written to disk."""
if os.getcwd().endswith('analyses'):
correct = input('You are in an analyses folder. This will create another analyses folder inside this one. Do you want to continue? (y/N)')
if correct != 'y':
return False # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
if not os.path.exists(os.path.join(os.getcwd(), 'analyses')):
correct = input('This is the first analysis here. Do you want to continue? (y/N)')
if correct != 'y':
return False # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
if os.path.exists(os.path.join(os.getcwd(), 'analyses', name)):
correct = input('An analysis with this name exists already. Do you want to continue? (y/N)')
if correct != 'y':
return False # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
return True
|
def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501
"""Download dataset file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_download(owner_slug, dataset_slug, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_slug: Dataset owner (required)
:param str dataset_slug: Dataset name (required)
:param str dataset_version_number: Dataset version number
:return: Result
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501
else:
(data) = self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501
return data
|
def function[datasets_download, parameter[self, owner_slug, dataset_slug]]:
constant[Download dataset file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_download(owner_slug, dataset_slug, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_slug: Dataset owner (required)
:param str dataset_slug: Dataset name (required)
:param str dataset_version_number: Dataset version number
:return: Result
If the method is called asynchronously,
returns the request thread.
]
call[name[kwargs]][constant[_return_http_data_only]] assign[=] constant[True]
if call[name[kwargs].get, parameter[constant[async_req]]] begin[:]
return[call[name[self].datasets_download_with_http_info, parameter[name[owner_slug], name[dataset_slug]]]]
|
keyword[def] identifier[datasets_download] ( identifier[self] , identifier[owner_slug] , identifier[dataset_slug] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifier[datasets_download_with_http_info] ( identifier[owner_slug] , identifier[dataset_slug] ,** identifier[kwargs] )
keyword[else] :
( identifier[data] )= identifier[self] . identifier[datasets_download_with_http_info] ( identifier[owner_slug] , identifier[dataset_slug] ,** identifier[kwargs] )
keyword[return] identifier[data]
|
def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501
'Download dataset file # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.datasets_download(owner_slug, dataset_slug, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str owner_slug: Dataset owner (required)\n :param str dataset_slug: Dataset name (required)\n :param str dataset_version_number: Dataset version number\n :return: Result\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 # depends on [control=['if'], data=[]]
else:
data = self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501
return data
|
def _split_source_page(self, path):
"""Split the source file texts by triple-dashed lines.
shit code
"""
with codecs.open(path, "rb", "utf-8") as fd:
textlist = fd.readlines()
metadata_notation = "---\n"
if textlist[0] != metadata_notation:
logging.error(
"{} first line must be triple-dashed!".format(path)
)
sys.exit(1)
metadata_textlist = []
metadata_end_flag = False
idx = 1
max_idx = len(textlist)
# TODO(crow): BE PYTHONIC!!!
while not metadata_end_flag:
metadata_textlist.append(textlist[idx])
idx += 1
if idx >= max_idx:
logging.error(
"{} doesn't have end triple-dashed!".format(path)
)
sys.exit(1)
if textlist[idx] == metadata_notation:
metadata_end_flag = True
content = textlist[idx + 1:]
return metadata_textlist, content
|
def function[_split_source_page, parameter[self, path]]:
constant[Split the source file texts by triple-dashed lines.
shit code
]
with call[name[codecs].open, parameter[name[path], constant[rb], constant[utf-8]]] begin[:]
variable[textlist] assign[=] call[name[fd].readlines, parameter[]]
variable[metadata_notation] assign[=] constant[---
]
if compare[call[name[textlist]][constant[0]] not_equal[!=] name[metadata_notation]] begin[:]
call[name[logging].error, parameter[call[constant[{} first line must be triple-dashed!].format, parameter[name[path]]]]]
call[name[sys].exit, parameter[constant[1]]]
variable[metadata_textlist] assign[=] list[[]]
variable[metadata_end_flag] assign[=] constant[False]
variable[idx] assign[=] constant[1]
variable[max_idx] assign[=] call[name[len], parameter[name[textlist]]]
while <ast.UnaryOp object at 0x7da18f722d10> begin[:]
call[name[metadata_textlist].append, parameter[call[name[textlist]][name[idx]]]]
<ast.AugAssign object at 0x7da18f721090>
if compare[name[idx] greater_or_equal[>=] name[max_idx]] begin[:]
call[name[logging].error, parameter[call[constant[{} doesn't have end triple-dashed!].format, parameter[name[path]]]]]
call[name[sys].exit, parameter[constant[1]]]
if compare[call[name[textlist]][name[idx]] equal[==] name[metadata_notation]] begin[:]
variable[metadata_end_flag] assign[=] constant[True]
variable[content] assign[=] call[name[textlist]][<ast.Slice object at 0x7da18f721c00>]
return[tuple[[<ast.Name object at 0x7da18f722920>, <ast.Name object at 0x7da18f7211e0>]]]
|
keyword[def] identifier[_split_source_page] ( identifier[self] , identifier[path] ):
literal[string]
keyword[with] identifier[codecs] . identifier[open] ( identifier[path] , literal[string] , literal[string] ) keyword[as] identifier[fd] :
identifier[textlist] = identifier[fd] . identifier[readlines] ()
identifier[metadata_notation] = literal[string]
keyword[if] identifier[textlist] [ literal[int] ]!= identifier[metadata_notation] :
identifier[logging] . identifier[error] (
literal[string] . identifier[format] ( identifier[path] )
)
identifier[sys] . identifier[exit] ( literal[int] )
identifier[metadata_textlist] =[]
identifier[metadata_end_flag] = keyword[False]
identifier[idx] = literal[int]
identifier[max_idx] = identifier[len] ( identifier[textlist] )
keyword[while] keyword[not] identifier[metadata_end_flag] :
identifier[metadata_textlist] . identifier[append] ( identifier[textlist] [ identifier[idx] ])
identifier[idx] += literal[int]
keyword[if] identifier[idx] >= identifier[max_idx] :
identifier[logging] . identifier[error] (
literal[string] . identifier[format] ( identifier[path] )
)
identifier[sys] . identifier[exit] ( literal[int] )
keyword[if] identifier[textlist] [ identifier[idx] ]== identifier[metadata_notation] :
identifier[metadata_end_flag] = keyword[True]
identifier[content] = identifier[textlist] [ identifier[idx] + literal[int] :]
keyword[return] identifier[metadata_textlist] , identifier[content]
|
def _split_source_page(self, path):
"""Split the source file texts by triple-dashed lines.
shit code
"""
with codecs.open(path, 'rb', 'utf-8') as fd:
textlist = fd.readlines() # depends on [control=['with'], data=['fd']]
metadata_notation = '---\n'
if textlist[0] != metadata_notation:
logging.error('{} first line must be triple-dashed!'.format(path))
sys.exit(1) # depends on [control=['if'], data=[]]
metadata_textlist = []
metadata_end_flag = False
idx = 1
max_idx = len(textlist)
# TODO(crow): BE PYTHONIC!!!
while not metadata_end_flag:
metadata_textlist.append(textlist[idx])
idx += 1
if idx >= max_idx:
logging.error("{} doesn't have end triple-dashed!".format(path))
sys.exit(1) # depends on [control=['if'], data=[]]
if textlist[idx] == metadata_notation:
metadata_end_flag = True # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]]
content = textlist[idx + 1:]
return (metadata_textlist, content)
|
def read_file(path, encoding='utf-8', *args, **kwargs):
''' Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
'''
if 'mode' in kwargs and kwargs['mode'] == 'rb':
return process_file(path, processor=lambda x: x.read(),
encoding=encoding, *args, **kwargs)
else:
return process_file(path, processor=lambda x: to_string(x.read(), encoding),
encoding=encoding, *args, **kwargs)
|
def function[read_file, parameter[path, encoding]]:
constant[ Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
]
if <ast.BoolOp object at 0x7da1b1132470> begin[:]
return[call[name[process_file], parameter[name[path], <ast.Starred object at 0x7da1b1130190>]]]
|
keyword[def] identifier[read_file] ( identifier[path] , identifier[encoding] = literal[string] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[and] identifier[kwargs] [ literal[string] ]== literal[string] :
keyword[return] identifier[process_file] ( identifier[path] , identifier[processor] = keyword[lambda] identifier[x] : identifier[x] . identifier[read] (),
identifier[encoding] = identifier[encoding] ,* identifier[args] ,** identifier[kwargs] )
keyword[else] :
keyword[return] identifier[process_file] ( identifier[path] , identifier[processor] = keyword[lambda] identifier[x] : identifier[to_string] ( identifier[x] . identifier[read] (), identifier[encoding] ),
identifier[encoding] = identifier[encoding] ,* identifier[args] ,** identifier[kwargs] )
|
def read_file(path, encoding='utf-8', *args, **kwargs):
""" Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
"""
if 'mode' in kwargs and kwargs['mode'] == 'rb':
return process_file(path, *args, processor=lambda x: x.read(), encoding=encoding, **kwargs) # depends on [control=['if'], data=[]]
else:
return process_file(path, *args, processor=lambda x: to_string(x.read(), encoding), encoding=encoding, **kwargs)
|
def _get_energy(self, x):
"""
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy.
"""
return self.pd.get_hull_energy(self.comp1 * x + self.comp2 * (1-x)) - \
self.e1 * x - self.e2 * (1-x)
|
def function[_get_energy, parameter[self, x]]:
constant[
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy.
]
return[binary_operation[binary_operation[call[name[self].pd.get_hull_energy, parameter[binary_operation[binary_operation[name[self].comp1 * name[x]] + binary_operation[name[self].comp2 * binary_operation[constant[1] - name[x]]]]]] - binary_operation[name[self].e1 * name[x]]] - binary_operation[name[self].e2 * binary_operation[constant[1] - name[x]]]]]
|
keyword[def] identifier[_get_energy] ( identifier[self] , identifier[x] ):
literal[string]
keyword[return] identifier[self] . identifier[pd] . identifier[get_hull_energy] ( identifier[self] . identifier[comp1] * identifier[x] + identifier[self] . identifier[comp2] *( literal[int] - identifier[x] ))- identifier[self] . identifier[e1] * identifier[x] - identifier[self] . identifier[e2] *( literal[int] - identifier[x] )
|
def _get_energy(self, x):
"""
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy.
"""
return self.pd.get_hull_energy(self.comp1 * x + self.comp2 * (1 - x)) - self.e1 * x - self.e2 * (1 - x)
|
def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
'''
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
to the server as well as any health checks. This is the equivalent of the
"disable server" command. Setting the mode to "drain" only removes the server
from load balancing but still allows it to be checked and to accept new
persistent connections. Changes are propagated to tracking servers if any.
name
Server name
backend
haproxy backend
state
A string of the state to set. Must be 'ready', 'drain', or 'maint'
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.set_state my_proxy_server my_backend ready
'''
# Pulling this in from the latest 0.5 release which is not yet in PyPi.
# https://github.com/neurogeek/haproxyctl
class setServerState(haproxy.cmds.Cmd):
"""Set server state command."""
cmdTxt = "set server %(backend)s/%(server)s state %(value)s\r\n"
p_args = ['backend', 'server', 'value']
helpTxt = "Force a server's administrative state to a new state."
ha_conn = _get_conn(socket)
ha_cmd = setServerState(server=name, backend=backend, value=state)
return ha_conn.sendCmd(ha_cmd)
|
def function[set_state, parameter[name, backend, state, socket]]:
constant[
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
to the server as well as any health checks. This is the equivalent of the
"disable server" command. Setting the mode to "drain" only removes the server
from load balancing but still allows it to be checked and to accept new
persistent connections. Changes are propagated to tracking servers if any.
name
Server name
backend
haproxy backend
state
A string of the state to set. Must be 'ready', 'drain', or 'maint'
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.set_state my_proxy_server my_backend ready
]
class class[setServerState, parameter[]] begin[:]
constant[Set server state command.]
variable[cmdTxt] assign[=] constant[set server %(backend)s/%(server)s state %(value)s
]
variable[p_args] assign[=] list[[<ast.Constant object at 0x7da1b21f1b40>, <ast.Constant object at 0x7da1b21f0fd0>, <ast.Constant object at 0x7da1b21f2b90>]]
variable[helpTxt] assign[=] constant[Force a server's administrative state to a new state.]
variable[ha_conn] assign[=] call[name[_get_conn], parameter[name[socket]]]
variable[ha_cmd] assign[=] call[name[setServerState], parameter[]]
return[call[name[ha_conn].sendCmd, parameter[name[ha_cmd]]]]
|
keyword[def] identifier[set_state] ( identifier[name] , identifier[backend] , identifier[state] , identifier[socket] = identifier[DEFAULT_SOCKET_URL] ):
literal[string]
keyword[class] identifier[setServerState] ( identifier[haproxy] . identifier[cmds] . identifier[Cmd] ):
literal[string]
identifier[cmdTxt] = literal[string]
identifier[p_args] =[ literal[string] , literal[string] , literal[string] ]
identifier[helpTxt] = literal[string]
identifier[ha_conn] = identifier[_get_conn] ( identifier[socket] )
identifier[ha_cmd] = identifier[setServerState] ( identifier[server] = identifier[name] , identifier[backend] = identifier[backend] , identifier[value] = identifier[state] )
keyword[return] identifier[ha_conn] . identifier[sendCmd] ( identifier[ha_cmd] )
|
def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
"""
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
to the server as well as any health checks. This is the equivalent of the
"disable server" command. Setting the mode to "drain" only removes the server
from load balancing but still allows it to be checked and to accept new
persistent connections. Changes are propagated to tracking servers if any.
name
Server name
backend
haproxy backend
state
A string of the state to set. Must be 'ready', 'drain', or 'maint'
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.set_state my_proxy_server my_backend ready
"""
# Pulling this in from the latest 0.5 release which is not yet in PyPi.
# https://github.com/neurogeek/haproxyctl
class setServerState(haproxy.cmds.Cmd):
"""Set server state command."""
cmdTxt = 'set server %(backend)s/%(server)s state %(value)s\r\n'
p_args = ['backend', 'server', 'value']
helpTxt = "Force a server's administrative state to a new state."
ha_conn = _get_conn(socket)
ha_cmd = setServerState(server=name, backend=backend, value=state)
return ha_conn.sendCmd(ha_cmd)
|
def _cast_message(self, message=None):
'''Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
'''
if message is None:
message = {}
if isinstance(message, Mapping):
message = Message.load_message(message)
return message.load_from(self.message, verify=True)
|
def function[_cast_message, parameter[self, message]]:
constant[Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
]
if compare[name[message] is constant[None]] begin[:]
variable[message] assign[=] dictionary[[], []]
if call[name[isinstance], parameter[name[message], name[Mapping]]] begin[:]
variable[message] assign[=] call[name[Message].load_message, parameter[name[message]]]
return[call[name[message].load_from, parameter[name[self].message]]]
|
keyword[def] identifier[_cast_message] ( identifier[self] , identifier[message] = keyword[None] ):
literal[string]
keyword[if] identifier[message] keyword[is] keyword[None] :
identifier[message] ={}
keyword[if] identifier[isinstance] ( identifier[message] , identifier[Mapping] ):
identifier[message] = identifier[Message] . identifier[load_message] ( identifier[message] )
keyword[return] identifier[message] . identifier[load_from] ( identifier[self] . identifier[message] , identifier[verify] = keyword[True] )
|
def _cast_message(self, message=None):
"""Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
"""
if message is None:
message = {} # depends on [control=['if'], data=['message']]
if isinstance(message, Mapping):
message = Message.load_message(message) # depends on [control=['if'], data=[]]
return message.load_from(self.message, verify=True)
|
async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Executes statements in the system shell.
This uses the bash shell. Execution can be cancelled by closing the paginator.
"""
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
paginator = WrappedPaginator(prefix="```sh", max_size=1985)
paginator.add_line(f"$ {argument.content}\n")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
self.bot.loop.create_task(interface.send_to(ctx))
with ShellReader(argument.content) as reader:
async for line in reader:
if interface.closed:
return
await interface.add_line(line)
await interface.add_line(f"\n[status] Return code {reader.close_code}")
|
<ast.AsyncFunctionDef object at 0x7da1b1e65f30>
|
keyword[async] keyword[def] identifier[jsk_shell] ( identifier[self] , identifier[ctx] : identifier[commands] . identifier[Context] ,*, identifier[argument] : identifier[CodeblockConverter] ):
literal[string]
keyword[async] keyword[with] identifier[ReplResponseReactor] ( identifier[ctx] . identifier[message] ):
keyword[with] identifier[self] . identifier[submit] ( identifier[ctx] ):
identifier[paginator] = identifier[WrappedPaginator] ( identifier[prefix] = literal[string] , identifier[max_size] = literal[int] )
identifier[paginator] . identifier[add_line] ( literal[string] )
identifier[interface] = identifier[PaginatorInterface] ( identifier[ctx] . identifier[bot] , identifier[paginator] , identifier[owner] = identifier[ctx] . identifier[author] )
identifier[self] . identifier[bot] . identifier[loop] . identifier[create_task] ( identifier[interface] . identifier[send_to] ( identifier[ctx] ))
keyword[with] identifier[ShellReader] ( identifier[argument] . identifier[content] ) keyword[as] identifier[reader] :
keyword[async] keyword[for] identifier[line] keyword[in] identifier[reader] :
keyword[if] identifier[interface] . identifier[closed] :
keyword[return]
keyword[await] identifier[interface] . identifier[add_line] ( identifier[line] )
keyword[await] identifier[interface] . identifier[add_line] ( literal[string] )
|
async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Executes statements in the system shell.
This uses the bash shell. Execution can be cancelled by closing the paginator.
"""
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
paginator = WrappedPaginator(prefix='```sh', max_size=1985)
paginator.add_line(f'$ {argument.content}\n')
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
self.bot.loop.create_task(interface.send_to(ctx))
with ShellReader(argument.content) as reader:
async for line in reader:
if interface.closed:
return # depends on [control=['if'], data=[]]
await interface.add_line(line) # depends on [control=['with'], data=['reader']]
await interface.add_line(f'\n[status] Return code {reader.close_code}') # depends on [control=['with'], data=[]]
|
def _to_string(inp: str) -> str:
""" Convert a URL or file name to a string """
if '://' in inp:
req = requests.get(inp)
if not req.ok:
raise ValueError(f"Unable to read {inp}")
return req.text
else:
with open(inp) as infile:
return infile.read()
|
def function[_to_string, parameter[inp]]:
constant[ Convert a URL or file name to a string ]
if compare[constant[://] in name[inp]] begin[:]
variable[req] assign[=] call[name[requests].get, parameter[name[inp]]]
if <ast.UnaryOp object at 0x7da1b2491900> begin[:]
<ast.Raise object at 0x7da1b24919c0>
return[name[req].text]
|
keyword[def] identifier[_to_string] ( identifier[inp] : identifier[str] )-> identifier[str] :
literal[string]
keyword[if] literal[string] keyword[in] identifier[inp] :
identifier[req] = identifier[requests] . identifier[get] ( identifier[inp] )
keyword[if] keyword[not] identifier[req] . identifier[ok] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[req] . identifier[text]
keyword[else] :
keyword[with] identifier[open] ( identifier[inp] ) keyword[as] identifier[infile] :
keyword[return] identifier[infile] . identifier[read] ()
|
def _to_string(inp: str) -> str:
""" Convert a URL or file name to a string """
if '://' in inp:
req = requests.get(inp)
if not req.ok:
raise ValueError(f'Unable to read {inp}') # depends on [control=['if'], data=[]]
return req.text # depends on [control=['if'], data=['inp']]
else:
with open(inp) as infile:
return infile.read() # depends on [control=['with'], data=['infile']]
|
def et2lst(et, body, lon, typein, timlen=_default_len_out, ampmlen=_default_len_out):
"""
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch in seconds past J2000 epoch.
:type et: float
:param body: ID-code of the body of interest.
:type body: int
:param lon: Longitude of surface point (RADIANS).
:type lon: float
:param typein: Type of longitude "PLANETOCENTRIC", etc.
:type typein: str
:param timlen: Available room in output time string.
:type timlen: int
:param ampmlen: Available room in output ampm string.
:type ampmlen: int
:return:
Local hour on a "24 hour" clock,
Minutes past the hour,
Seconds past the minute,
String giving local time on 24 hour clock,
String giving time on A.M. / P.M. scale.
:rtype: tuple
"""
et = ctypes.c_double(et)
body = ctypes.c_int(body)
lon = ctypes.c_double(lon)
typein = stypes.stringToCharP(typein)
timlen = ctypes.c_int(timlen)
ampmlen = ctypes.c_int(ampmlen)
hr = ctypes.c_int()
mn = ctypes.c_int()
sc = ctypes.c_int()
time = stypes.stringToCharP(timlen)
ampm = stypes.stringToCharP(ampmlen)
libspice.et2lst_c(et, body, lon, typein, timlen, ampmlen,
ctypes.byref(hr), ctypes.byref(mn), ctypes.byref(sc),
time, ampm)
return hr.value, mn.value, sc.value, stypes.toPythonString(
time), stypes.toPythonString(ampm)
|
def function[et2lst, parameter[et, body, lon, typein, timlen, ampmlen]]:
constant[
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch in seconds past J2000 epoch.
:type et: float
:param body: ID-code of the body of interest.
:type body: int
:param lon: Longitude of surface point (RADIANS).
:type lon: float
:param typein: Type of longitude "PLANETOCENTRIC", etc.
:type typein: str
:param timlen: Available room in output time string.
:type timlen: int
:param ampmlen: Available room in output ampm string.
:type ampmlen: int
:return:
Local hour on a "24 hour" clock,
Minutes past the hour,
Seconds past the minute,
String giving local time on 24 hour clock,
String giving time on A.M. / P.M. scale.
:rtype: tuple
]
variable[et] assign[=] call[name[ctypes].c_double, parameter[name[et]]]
variable[body] assign[=] call[name[ctypes].c_int, parameter[name[body]]]
variable[lon] assign[=] call[name[ctypes].c_double, parameter[name[lon]]]
variable[typein] assign[=] call[name[stypes].stringToCharP, parameter[name[typein]]]
variable[timlen] assign[=] call[name[ctypes].c_int, parameter[name[timlen]]]
variable[ampmlen] assign[=] call[name[ctypes].c_int, parameter[name[ampmlen]]]
variable[hr] assign[=] call[name[ctypes].c_int, parameter[]]
variable[mn] assign[=] call[name[ctypes].c_int, parameter[]]
variable[sc] assign[=] call[name[ctypes].c_int, parameter[]]
variable[time] assign[=] call[name[stypes].stringToCharP, parameter[name[timlen]]]
variable[ampm] assign[=] call[name[stypes].stringToCharP, parameter[name[ampmlen]]]
call[name[libspice].et2lst_c, parameter[name[et], name[body], name[lon], name[typein], name[timlen], name[ampmlen], call[name[ctypes].byref, parameter[name[hr]]], call[name[ctypes].byref, parameter[name[mn]]], call[name[ctypes].byref, parameter[name[sc]]], name[time], name[ampm]]]
return[tuple[[<ast.Attribute object at 0x7da204565f60>, <ast.Attribute object at 0x7da204567d30>, <ast.Attribute object at 0x7da204564ac0>, <ast.Call object at 0x7da204564130>, <ast.Call object at 0x7da204567dc0>]]]
|
keyword[def] identifier[et2lst] ( identifier[et] , identifier[body] , identifier[lon] , identifier[typein] , identifier[timlen] = identifier[_default_len_out] , identifier[ampmlen] = identifier[_default_len_out] ):
literal[string]
identifier[et] = identifier[ctypes] . identifier[c_double] ( identifier[et] )
identifier[body] = identifier[ctypes] . identifier[c_int] ( identifier[body] )
identifier[lon] = identifier[ctypes] . identifier[c_double] ( identifier[lon] )
identifier[typein] = identifier[stypes] . identifier[stringToCharP] ( identifier[typein] )
identifier[timlen] = identifier[ctypes] . identifier[c_int] ( identifier[timlen] )
identifier[ampmlen] = identifier[ctypes] . identifier[c_int] ( identifier[ampmlen] )
identifier[hr] = identifier[ctypes] . identifier[c_int] ()
identifier[mn] = identifier[ctypes] . identifier[c_int] ()
identifier[sc] = identifier[ctypes] . identifier[c_int] ()
identifier[time] = identifier[stypes] . identifier[stringToCharP] ( identifier[timlen] )
identifier[ampm] = identifier[stypes] . identifier[stringToCharP] ( identifier[ampmlen] )
identifier[libspice] . identifier[et2lst_c] ( identifier[et] , identifier[body] , identifier[lon] , identifier[typein] , identifier[timlen] , identifier[ampmlen] ,
identifier[ctypes] . identifier[byref] ( identifier[hr] ), identifier[ctypes] . identifier[byref] ( identifier[mn] ), identifier[ctypes] . identifier[byref] ( identifier[sc] ),
identifier[time] , identifier[ampm] )
keyword[return] identifier[hr] . identifier[value] , identifier[mn] . identifier[value] , identifier[sc] . identifier[value] , identifier[stypes] . identifier[toPythonString] (
identifier[time] ), identifier[stypes] . identifier[toPythonString] ( identifier[ampm] )
|
def et2lst(et, body, lon, typein, timlen=_default_len_out, ampmlen=_default_len_out):
"""
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch in seconds past J2000 epoch.
:type et: float
:param body: ID-code of the body of interest.
:type body: int
:param lon: Longitude of surface point (RADIANS).
:type lon: float
:param typein: Type of longitude "PLANETOCENTRIC", etc.
:type typein: str
:param timlen: Available room in output time string.
:type timlen: int
:param ampmlen: Available room in output ampm string.
:type ampmlen: int
:return:
Local hour on a "24 hour" clock,
Minutes past the hour,
Seconds past the minute,
String giving local time on 24 hour clock,
String giving time on A.M. / P.M. scale.
:rtype: tuple
"""
et = ctypes.c_double(et)
body = ctypes.c_int(body)
lon = ctypes.c_double(lon)
typein = stypes.stringToCharP(typein)
timlen = ctypes.c_int(timlen)
ampmlen = ctypes.c_int(ampmlen)
hr = ctypes.c_int()
mn = ctypes.c_int()
sc = ctypes.c_int()
time = stypes.stringToCharP(timlen)
ampm = stypes.stringToCharP(ampmlen)
libspice.et2lst_c(et, body, lon, typein, timlen, ampmlen, ctypes.byref(hr), ctypes.byref(mn), ctypes.byref(sc), time, ampm)
return (hr.value, mn.value, sc.value, stypes.toPythonString(time), stypes.toPythonString(ampm))
|
def query_yes_no(question, default=None): # pragma: no cover
"""
Ask a yes/no question via `raw_input()` and return their answer.
:param question: A string that is presented to the user.
:param default: The presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
Code borrowed from cookiecutter
https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py
"""
valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
if default is None:
prompt = ' [y/n] '
elif default == 'yes':
prompt = ' [Y/n] '
elif default == 'no':
prompt = ' [y/N] '
else:
raise ValueError('invalid default answer: "{0}"'.format(default))
while True:
sys.stdout.write(question + prompt)
choice = compat.input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write('Please answer with "yes" or "no" (or "y" or "n").\n')
|
def function[query_yes_no, parameter[question, default]]:
constant[
Ask a yes/no question via `raw_input()` and return their answer.
:param question: A string that is presented to the user.
:param default: The presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
Code borrowed from cookiecutter
https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py
]
variable[valid] assign[=] dictionary[[<ast.Constant object at 0x7da1b01e5b40>, <ast.Constant object at 0x7da1b01e61d0>, <ast.Constant object at 0x7da1b01e52d0>, <ast.Constant object at 0x7da1b01e5660>, <ast.Constant object at 0x7da1b01e7e50>], [<ast.Constant object at 0x7da1b01e5900>, <ast.Constant object at 0x7da1b01e5810>, <ast.Constant object at 0x7da1b01e5a50>, <ast.Constant object at 0x7da1b01e7580>, <ast.Constant object at 0x7da1b01e6d10>]]
if compare[name[default] is constant[None]] begin[:]
variable[prompt] assign[=] constant[ [y/n] ]
while constant[True] begin[:]
call[name[sys].stdout.write, parameter[binary_operation[name[question] + name[prompt]]]]
variable[choice] assign[=] call[call[name[compat].input, parameter[]].lower, parameter[]]
if <ast.BoolOp object at 0x7da1b01e7e80> begin[:]
return[call[name[valid]][name[default]]]
|
keyword[def] identifier[query_yes_no] ( identifier[question] , identifier[default] = keyword[None] ):
literal[string]
identifier[valid] ={ literal[string] : keyword[True] , literal[string] : keyword[True] , literal[string] : keyword[True] , literal[string] : keyword[False] , literal[string] : keyword[False] }
keyword[if] identifier[default] keyword[is] keyword[None] :
identifier[prompt] = literal[string]
keyword[elif] identifier[default] == literal[string] :
identifier[prompt] = literal[string]
keyword[elif] identifier[default] == literal[string] :
identifier[prompt] = literal[string]
keyword[else] :
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[default] ))
keyword[while] keyword[True] :
identifier[sys] . identifier[stdout] . identifier[write] ( identifier[question] + identifier[prompt] )
identifier[choice] = identifier[compat] . identifier[input] (). identifier[lower] ()
keyword[if] identifier[default] keyword[is] keyword[not] keyword[None] keyword[and] identifier[choice] == literal[string] :
keyword[return] identifier[valid] [ identifier[default] ]
keyword[elif] identifier[choice] keyword[in] identifier[valid] :
keyword[return] identifier[valid] [ identifier[choice] ]
keyword[else] :
identifier[sys] . identifier[stdout] . identifier[write] ( literal[string] )
|
def query_yes_no(question, default=None): # pragma: no cover
'\n Ask a yes/no question via `raw_input()` and return their answer.\n\n :param question: A string that is presented to the user.\n :param default: The presumed answer if the user just hits <Enter>.\n It must be "yes" (the default), "no" or None (meaning\n an answer is required of the user).\n\n The "answer" return value is one of "yes" or "no".\n\n Code borrowed from cookiecutter\n https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py\n '
valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
if default is None:
prompt = ' [y/n] ' # depends on [control=['if'], data=[]]
elif default == 'yes':
prompt = ' [Y/n] ' # depends on [control=['if'], data=[]]
elif default == 'no':
prompt = ' [y/N] ' # depends on [control=['if'], data=[]]
else:
raise ValueError('invalid default answer: "{0}"'.format(default))
while True:
sys.stdout.write(question + prompt)
choice = compat.input().lower()
if default is not None and choice == '':
return valid[default] # depends on [control=['if'], data=[]]
elif choice in valid:
return valid[choice] # depends on [control=['if'], data=['choice', 'valid']]
else:
sys.stdout.write('Please answer with "yes" or "no" (or "y" or "n").\n') # depends on [control=['while'], data=[]]
|
def initialise_modified_data(self):
"""
Initialise the modified_data if necessary
"""
if self.__modified_data__ is None:
if self.__original_data__:
self.__modified_data__ = list(self.__original_data__)
else:
self.__modified_data__ = []
|
def function[initialise_modified_data, parameter[self]]:
constant[
Initialise the modified_data if necessary
]
if compare[name[self].__modified_data__ is constant[None]] begin[:]
if name[self].__original_data__ begin[:]
name[self].__modified_data__ assign[=] call[name[list], parameter[name[self].__original_data__]]
|
keyword[def] identifier[initialise_modified_data] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__modified_data__] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[__original_data__] :
identifier[self] . identifier[__modified_data__] = identifier[list] ( identifier[self] . identifier[__original_data__] )
keyword[else] :
identifier[self] . identifier[__modified_data__] =[]
|
def initialise_modified_data(self):
"""
Initialise the modified_data if necessary
"""
if self.__modified_data__ is None:
if self.__original_data__:
self.__modified_data__ = list(self.__original_data__) # depends on [control=['if'], data=[]]
else:
self.__modified_data__ = [] # depends on [control=['if'], data=[]]
|
def apply (self, img):
yup,uup,vup = self.getUpLimit()
ydwn,udwn,vdwn = self.getDownLimit()
''' We convert RGB as BGR because OpenCV
with RGB pass to YVU instead of YUV'''
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
minValues = np.array([ydwn,udwn,vdwn],dtype=np.uint8)
maxValues = np.array([yup,uup,vup], dtype=np.uint8)
mask = cv2.inRange(yuv, minValues, maxValues)
res = cv2.bitwise_and(img,img, mask= mask)
return res
|
def function[apply, parameter[self, img]]:
<ast.Tuple object at 0x7da1b26aff10> assign[=] call[name[self].getUpLimit, parameter[]]
<ast.Tuple object at 0x7da1b26ae050> assign[=] call[name[self].getDownLimit, parameter[]]
constant[ We convert RGB as BGR because OpenCV
with RGB pass to YVU instead of YUV]
variable[yuv] assign[=] call[name[cv2].cvtColor, parameter[name[img], name[cv2].COLOR_BGR2YUV]]
variable[minValues] assign[=] call[name[np].array, parameter[list[[<ast.Name object at 0x7da1b26af7c0>, <ast.Name object at 0x7da1b26aed70>, <ast.Name object at 0x7da1b26adf60>]]]]
variable[maxValues] assign[=] call[name[np].array, parameter[list[[<ast.Name object at 0x7da1b26af940>, <ast.Name object at 0x7da1b26af2e0>, <ast.Name object at 0x7da1b26adc90>]]]]
variable[mask] assign[=] call[name[cv2].inRange, parameter[name[yuv], name[minValues], name[maxValues]]]
variable[res] assign[=] call[name[cv2].bitwise_and, parameter[name[img], name[img]]]
return[name[res]]
|
keyword[def] identifier[apply] ( identifier[self] , identifier[img] ):
identifier[yup] , identifier[uup] , identifier[vup] = identifier[self] . identifier[getUpLimit] ()
identifier[ydwn] , identifier[udwn] , identifier[vdwn] = identifier[self] . identifier[getDownLimit] ()
literal[string]
identifier[yuv] = identifier[cv2] . identifier[cvtColor] ( identifier[img] , identifier[cv2] . identifier[COLOR_BGR2YUV] )
identifier[minValues] = identifier[np] . identifier[array] ([ identifier[ydwn] , identifier[udwn] , identifier[vdwn] ], identifier[dtype] = identifier[np] . identifier[uint8] )
identifier[maxValues] = identifier[np] . identifier[array] ([ identifier[yup] , identifier[uup] , identifier[vup] ], identifier[dtype] = identifier[np] . identifier[uint8] )
identifier[mask] = identifier[cv2] . identifier[inRange] ( identifier[yuv] , identifier[minValues] , identifier[maxValues] )
identifier[res] = identifier[cv2] . identifier[bitwise_and] ( identifier[img] , identifier[img] , identifier[mask] = identifier[mask] )
keyword[return] identifier[res]
|
def apply(self, img):
(yup, uup, vup) = self.getUpLimit()
(ydwn, udwn, vdwn) = self.getDownLimit()
' We convert RGB as BGR because OpenCV \n with RGB pass to YVU instead of YUV'
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
minValues = np.array([ydwn, udwn, vdwn], dtype=np.uint8)
maxValues = np.array([yup, uup, vup], dtype=np.uint8)
mask = cv2.inRange(yuv, minValues, maxValues)
res = cv2.bitwise_and(img, img, mask=mask)
return res
|
def get_nonlocal_ip(host, subnet=None):
"""
Search result of getaddrinfo() for a non-localhost-net address
"""
try:
ailist = socket.getaddrinfo(host, None)
except socket.gaierror:
raise exc.UnableToResolveError(host)
for ai in ailist:
# an ai is a 5-tuple; the last element is (ip, port)
ip = ai[4][0]
if subnet and ip_in_subnet(ip, subnet):
LOG.info('found ip (%s) for host (%s) to be in cluster subnet (%s)' % (
ip,
host,
subnet,)
)
return ip
if not ip.startswith('127.'):
if subnet:
LOG.warning('could not match ip (%s) for host (%s) for cluster subnet (%s)' % (
ip,
host,
subnet,)
)
return ip
raise exc.UnableToResolveError(host)
|
def function[get_nonlocal_ip, parameter[host, subnet]]:
constant[
Search result of getaddrinfo() for a non-localhost-net address
]
<ast.Try object at 0x7da1b1634130>
for taget[name[ai]] in starred[name[ailist]] begin[:]
variable[ip] assign[=] call[call[name[ai]][constant[4]]][constant[0]]
if <ast.BoolOp object at 0x7da1b1635150> begin[:]
call[name[LOG].info, parameter[binary_operation[constant[found ip (%s) for host (%s) to be in cluster subnet (%s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b16346a0>, <ast.Name object at 0x7da1b16346d0>, <ast.Name object at 0x7da1b1634d00>]]]]]
return[name[ip]]
if <ast.UnaryOp object at 0x7da1b1635000> begin[:]
if name[subnet] begin[:]
call[name[LOG].warning, parameter[binary_operation[constant[could not match ip (%s) for host (%s) for cluster subnet (%s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b16352d0>, <ast.Name object at 0x7da1b1634220>, <ast.Name object at 0x7da1b1635240>]]]]]
return[name[ip]]
<ast.Raise object at 0x7da1b16342e0>
|
keyword[def] identifier[get_nonlocal_ip] ( identifier[host] , identifier[subnet] = keyword[None] ):
literal[string]
keyword[try] :
identifier[ailist] = identifier[socket] . identifier[getaddrinfo] ( identifier[host] , keyword[None] )
keyword[except] identifier[socket] . identifier[gaierror] :
keyword[raise] identifier[exc] . identifier[UnableToResolveError] ( identifier[host] )
keyword[for] identifier[ai] keyword[in] identifier[ailist] :
identifier[ip] = identifier[ai] [ literal[int] ][ literal[int] ]
keyword[if] identifier[subnet] keyword[and] identifier[ip_in_subnet] ( identifier[ip] , identifier[subnet] ):
identifier[LOG] . identifier[info] ( literal[string] %(
identifier[ip] ,
identifier[host] ,
identifier[subnet] ,)
)
keyword[return] identifier[ip]
keyword[if] keyword[not] identifier[ip] . identifier[startswith] ( literal[string] ):
keyword[if] identifier[subnet] :
identifier[LOG] . identifier[warning] ( literal[string] %(
identifier[ip] ,
identifier[host] ,
identifier[subnet] ,)
)
keyword[return] identifier[ip]
keyword[raise] identifier[exc] . identifier[UnableToResolveError] ( identifier[host] )
|
def get_nonlocal_ip(host, subnet=None):
"""
Search result of getaddrinfo() for a non-localhost-net address
"""
try:
ailist = socket.getaddrinfo(host, None) # depends on [control=['try'], data=[]]
except socket.gaierror:
raise exc.UnableToResolveError(host) # depends on [control=['except'], data=[]]
for ai in ailist:
# an ai is a 5-tuple; the last element is (ip, port)
ip = ai[4][0]
if subnet and ip_in_subnet(ip, subnet):
LOG.info('found ip (%s) for host (%s) to be in cluster subnet (%s)' % (ip, host, subnet))
return ip # depends on [control=['if'], data=[]]
if not ip.startswith('127.'):
if subnet:
LOG.warning('could not match ip (%s) for host (%s) for cluster subnet (%s)' % (ip, host, subnet)) # depends on [control=['if'], data=[]]
return ip # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['ai']]
raise exc.UnableToResolveError(host)
|
def newton_iterate(evaluate_fn, s, t):
r"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used below:
* :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before
"giving up". This is based on the assumption that we are already starting
near a root, so quadratic convergence should terminate quickly.
* :math:`\tau = \frac{1}{4}` is used as the boundary between linear
and superlinear convergence. So if the current error
:math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times
the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence
is considered to be linear at that point.
* :math:`\frac{2}{3}` of all iterations must be converging linearly
for convergence to be stopped (and moved to the next regime). This
will only be checked after 4 or more updates have occurred.
* :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to
determine that an update is sufficiently small to stop iterating. So if
the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times
size of the term being updated :math:`\|p_n\|`, then we
exit with the "correct" answer.
It is assumed that ``evaluate_fn`` will use a Jacobian return value of
:data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We
**assume** that if the function evaluates to exactly ``0.0``, then we are
at a solution. It is possible however, that badly parameterized curves
can evaluate to exactly ``0.0`` for inputs that are relatively far away
from a solution (see issue #21).
Args:
evaluate_fn (Callable[Tuple[float, float], tuple]): A callable
which takes :math:`s` and :math:`t` and produces an evaluated
function value and the Jacobian matrix.
s (float): The (first) parameter where the iteration will start.
t (float): The (second) parameter where the iteration will start.
Returns:
Tuple[bool, float, float]: The triple of
* Flag indicating if the iteration converged.
* The current :math:`s` value when the iteration stopped.
* The current :math:`t` value when the iteration stopped.
"""
# Several quantities will be tracked throughout the iteration:
# * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}||
# * norm_update : ||p{n+1} - p{n} || = ||dp{n} ||
# * linear_updates : This is a count on the number of times that
# ``dp{n}`` "looks like" ``dp{n-1}`` (i.e.
# is within a constant factor of it).
norm_update_prev = None
norm_update = None
linear_updates = 0 # Track the number of "linear" updates.
current_s = s
current_t = t
for index in six.moves.xrange(MAX_NEWTON_ITERATIONS):
jacobian, func_val = evaluate_fn(current_s, current_t)
if jacobian is None:
return True, current_s, current_t
singular, delta_s, delta_t = _helpers.solve2x2(
jacobian, func_val[:, 0]
)
if singular:
break
norm_update_prev = norm_update
norm_update = np.linalg.norm([delta_s, delta_t], ord=2)
# If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means
# our convergence is acting linear at the current step.
if index > 0 and norm_update > 0.25 * norm_update_prev:
linear_updates += 1
# If ``>=2/3`` of the updates have been linear, we are near a
# non-simple root. (Make sure at least 5 updates have occurred.)
if index >= 4 and 3 * linear_updates >= 2 * index:
break
# Determine the norm of the "old" solution before updating.
norm_soln = np.linalg.norm([current_s, current_t], ord=2)
current_s -= delta_s
current_t -= delta_t
if norm_update < NEWTON_ERROR_RATIO * norm_soln:
return True, current_s, current_t
return False, current_s, current_t
|
def function[newton_iterate, parameter[evaluate_fn, s, t]]:
constant[Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used below:
* :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before
"giving up". This is based on the assumption that we are already starting
near a root, so quadratic convergence should terminate quickly.
* :math:`\tau = \frac{1}{4}` is used as the boundary between linear
and superlinear convergence. So if the current error
:math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times
the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence
is considered to be linear at that point.
* :math:`\frac{2}{3}` of all iterations must be converging linearly
for convergence to be stopped (and moved to the next regime). This
will only be checked after 4 or more updates have occurred.
* :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to
determine that an update is sufficiently small to stop iterating. So if
the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times
size of the term being updated :math:`\|p_n\|`, then we
exit with the "correct" answer.
It is assumed that ``evaluate_fn`` will use a Jacobian return value of
:data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We
**assume** that if the function evaluates to exactly ``0.0``, then we are
at a solution. It is possible however, that badly parameterized curves
can evaluate to exactly ``0.0`` for inputs that are relatively far away
from a solution (see issue #21).
Args:
evaluate_fn (Callable[Tuple[float, float], tuple]): A callable
which takes :math:`s` and :math:`t` and produces an evaluated
function value and the Jacobian matrix.
s (float): The (first) parameter where the iteration will start.
t (float): The (second) parameter where the iteration will start.
Returns:
Tuple[bool, float, float]: The triple of
* Flag indicating if the iteration converged.
* The current :math:`s` value when the iteration stopped.
* The current :math:`t` value when the iteration stopped.
]
variable[norm_update_prev] assign[=] constant[None]
variable[norm_update] assign[=] constant[None]
variable[linear_updates] assign[=] constant[0]
variable[current_s] assign[=] name[s]
variable[current_t] assign[=] name[t]
for taget[name[index]] in starred[call[name[six].moves.xrange, parameter[name[MAX_NEWTON_ITERATIONS]]]] begin[:]
<ast.Tuple object at 0x7da204621e10> assign[=] call[name[evaluate_fn], parameter[name[current_s], name[current_t]]]
if compare[name[jacobian] is constant[None]] begin[:]
return[tuple[[<ast.Constant object at 0x7da204620ca0>, <ast.Name object at 0x7da204623160>, <ast.Name object at 0x7da2046204f0>]]]
<ast.Tuple object at 0x7da204623e50> assign[=] call[name[_helpers].solve2x2, parameter[name[jacobian], call[name[func_val]][tuple[[<ast.Slice object at 0x7da2046236d0>, <ast.Constant object at 0x7da204620280>]]]]]
if name[singular] begin[:]
break
variable[norm_update_prev] assign[=] name[norm_update]
variable[norm_update] assign[=] call[name[np].linalg.norm, parameter[list[[<ast.Name object at 0x7da1b18484c0>, <ast.Name object at 0x7da1b1849420>]]]]
if <ast.BoolOp object at 0x7da1b184b0d0> begin[:]
<ast.AugAssign object at 0x7da1b18497e0>
if <ast.BoolOp object at 0x7da1b184a770> begin[:]
break
variable[norm_soln] assign[=] call[name[np].linalg.norm, parameter[list[[<ast.Name object at 0x7da1b184a710>, <ast.Name object at 0x7da1b1848430>]]]]
<ast.AugAssign object at 0x7da1b1848e20>
<ast.AugAssign object at 0x7da1b1849d20>
if compare[name[norm_update] less[<] binary_operation[name[NEWTON_ERROR_RATIO] * name[norm_soln]]] begin[:]
return[tuple[[<ast.Constant object at 0x7da1b184add0>, <ast.Name object at 0x7da1b18499c0>, <ast.Name object at 0x7da1b1848850>]]]
return[tuple[[<ast.Constant object at 0x7da1b184ad70>, <ast.Name object at 0x7da1b1848b20>, <ast.Name object at 0x7da1b1849510>]]]
|
keyword[def] identifier[newton_iterate] ( identifier[evaluate_fn] , identifier[s] , identifier[t] ):
literal[string]
identifier[norm_update_prev] = keyword[None]
identifier[norm_update] = keyword[None]
identifier[linear_updates] = literal[int]
identifier[current_s] = identifier[s]
identifier[current_t] = identifier[t]
keyword[for] identifier[index] keyword[in] identifier[six] . identifier[moves] . identifier[xrange] ( identifier[MAX_NEWTON_ITERATIONS] ):
identifier[jacobian] , identifier[func_val] = identifier[evaluate_fn] ( identifier[current_s] , identifier[current_t] )
keyword[if] identifier[jacobian] keyword[is] keyword[None] :
keyword[return] keyword[True] , identifier[current_s] , identifier[current_t]
identifier[singular] , identifier[delta_s] , identifier[delta_t] = identifier[_helpers] . identifier[solve2x2] (
identifier[jacobian] , identifier[func_val] [:, literal[int] ]
)
keyword[if] identifier[singular] :
keyword[break]
identifier[norm_update_prev] = identifier[norm_update]
identifier[norm_update] = identifier[np] . identifier[linalg] . identifier[norm] ([ identifier[delta_s] , identifier[delta_t] ], identifier[ord] = literal[int] )
keyword[if] identifier[index] > literal[int] keyword[and] identifier[norm_update] > literal[int] * identifier[norm_update_prev] :
identifier[linear_updates] += literal[int]
keyword[if] identifier[index] >= literal[int] keyword[and] literal[int] * identifier[linear_updates] >= literal[int] * identifier[index] :
keyword[break]
identifier[norm_soln] = identifier[np] . identifier[linalg] . identifier[norm] ([ identifier[current_s] , identifier[current_t] ], identifier[ord] = literal[int] )
identifier[current_s] -= identifier[delta_s]
identifier[current_t] -= identifier[delta_t]
keyword[if] identifier[norm_update] < identifier[NEWTON_ERROR_RATIO] * identifier[norm_soln] :
keyword[return] keyword[True] , identifier[current_s] , identifier[current_t]
keyword[return] keyword[False] , identifier[current_s] , identifier[current_t]
|
def newton_iterate(evaluate_fn, s, t):
"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used below:
* :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before
"giving up". This is based on the assumption that we are already starting
near a root, so quadratic convergence should terminate quickly.
* :math:`\\tau = \\frac{1}{4}` is used as the boundary between linear
and superlinear convergence. So if the current error
:math:`\\|p_{n + 1} - p_n\\|` is not smaller than :math:`\\tau` times
the previous error :math:`\\|p_n - p_{n - 1}\\|`, then convergence
is considered to be linear at that point.
* :math:`\\frac{2}{3}` of all iterations must be converging linearly
for convergence to be stopped (and moved to the next regime). This
will only be checked after 4 or more updates have occurred.
* :math:`\\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to
determine that an update is sufficiently small to stop iterating. So if
the error :math:`\\|p_{n + 1} - p_n\\|` smaller than :math:`\\tau` times
size of the term being updated :math:`\\|p_n\\|`, then we
exit with the "correct" answer.
It is assumed that ``evaluate_fn`` will use a Jacobian return value of
:data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We
**assume** that if the function evaluates to exactly ``0.0``, then we are
at a solution. It is possible however, that badly parameterized curves
can evaluate to exactly ``0.0`` for inputs that are relatively far away
from a solution (see issue #21).
Args:
evaluate_fn (Callable[Tuple[float, float], tuple]): A callable
which takes :math:`s` and :math:`t` and produces an evaluated
function value and the Jacobian matrix.
s (float): The (first) parameter where the iteration will start.
t (float): The (second) parameter where the iteration will start.
Returns:
Tuple[bool, float, float]: The triple of
* Flag indicating if the iteration converged.
* The current :math:`s` value when the iteration stopped.
* The current :math:`t` value when the iteration stopped.
"""
# Several quantities will be tracked throughout the iteration:
# * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}||
# * norm_update : ||p{n+1} - p{n} || = ||dp{n} ||
# * linear_updates : This is a count on the number of times that
# ``dp{n}`` "looks like" ``dp{n-1}`` (i.e.
# is within a constant factor of it).
norm_update_prev = None
norm_update = None
linear_updates = 0 # Track the number of "linear" updates.
current_s = s
current_t = t
for index in six.moves.xrange(MAX_NEWTON_ITERATIONS):
(jacobian, func_val) = evaluate_fn(current_s, current_t)
if jacobian is None:
return (True, current_s, current_t) # depends on [control=['if'], data=[]]
(singular, delta_s, delta_t) = _helpers.solve2x2(jacobian, func_val[:, 0])
if singular:
break # depends on [control=['if'], data=[]]
norm_update_prev = norm_update
norm_update = np.linalg.norm([delta_s, delta_t], ord=2)
# If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means
# our convergence is acting linear at the current step.
if index > 0 and norm_update > 0.25 * norm_update_prev:
linear_updates += 1 # depends on [control=['if'], data=[]]
# If ``>=2/3`` of the updates have been linear, we are near a
# non-simple root. (Make sure at least 5 updates have occurred.)
if index >= 4 and 3 * linear_updates >= 2 * index:
break # depends on [control=['if'], data=[]]
# Determine the norm of the "old" solution before updating.
norm_soln = np.linalg.norm([current_s, current_t], ord=2)
current_s -= delta_s
current_t -= delta_t
if norm_update < NEWTON_ERROR_RATIO * norm_soln:
return (True, current_s, current_t) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['index']]
return (False, current_s, current_t)
|
def ssh_known_hosts_lines(application_name, user=None):
"""Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
known_hosts_list = []
with open(known_hosts(application_name, user)) as hosts:
for hosts_line in hosts:
if hosts_line.rstrip():
known_hosts_list.append(hosts_line.rstrip())
return(known_hosts_list)
|
def function[ssh_known_hosts_lines, parameter[application_name, user]]:
constant[Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
]
variable[known_hosts_list] assign[=] list[[]]
with call[name[open], parameter[call[name[known_hosts], parameter[name[application_name], name[user]]]]] begin[:]
for taget[name[hosts_line]] in starred[name[hosts]] begin[:]
if call[name[hosts_line].rstrip, parameter[]] begin[:]
call[name[known_hosts_list].append, parameter[call[name[hosts_line].rstrip, parameter[]]]]
return[name[known_hosts_list]]
|
keyword[def] identifier[ssh_known_hosts_lines] ( identifier[application_name] , identifier[user] = keyword[None] ):
literal[string]
identifier[known_hosts_list] =[]
keyword[with] identifier[open] ( identifier[known_hosts] ( identifier[application_name] , identifier[user] )) keyword[as] identifier[hosts] :
keyword[for] identifier[hosts_line] keyword[in] identifier[hosts] :
keyword[if] identifier[hosts_line] . identifier[rstrip] ():
identifier[known_hosts_list] . identifier[append] ( identifier[hosts_line] . identifier[rstrip] ())
keyword[return] ( identifier[known_hosts_list] )
|
def ssh_known_hosts_lines(application_name, user=None):
"""Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
known_hosts_list = []
with open(known_hosts(application_name, user)) as hosts:
for hosts_line in hosts:
if hosts_line.rstrip():
known_hosts_list.append(hosts_line.rstrip()) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['hosts_line']] # depends on [control=['with'], data=['hosts']]
return known_hosts_list
|
def _construct_message(self):
"""Build the message params."""
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += self.body
self._add_attachments()
|
def function[_construct_message, parameter[self]]:
constant[Build the message params.]
call[name[self].message][constant[text]] assign[=] constant[]
if name[self].from_ begin[:]
<ast.AugAssign object at 0x7da1b26ad360>
if name[self].subject begin[:]
<ast.AugAssign object at 0x7da1b26ad7b0>
<ast.AugAssign object at 0x7da20e9542e0>
call[name[self]._add_attachments, parameter[]]
|
keyword[def] identifier[_construct_message] ( identifier[self] ):
literal[string]
identifier[self] . identifier[message] [ literal[string] ]= literal[string]
keyword[if] identifier[self] . identifier[from_] :
identifier[self] . identifier[message] [ literal[string] ]+= literal[string] + identifier[self] . identifier[from_] + literal[string]
keyword[if] identifier[self] . identifier[subject] :
identifier[self] . identifier[message] [ literal[string] ]+= literal[string] + identifier[self] . identifier[subject] + literal[string]
identifier[self] . identifier[message] [ literal[string] ]+= identifier[self] . identifier[body]
identifier[self] . identifier[_add_attachments] ()
|
def _construct_message(self):
"""Build the message params."""
self.message['text'] = ''
if self.from_:
self.message['text'] += 'From: ' + self.from_ + '\n' # depends on [control=['if'], data=[]]
if self.subject:
self.message['text'] += 'Subject: ' + self.subject + '\n' # depends on [control=['if'], data=[]]
self.message['text'] += self.body
self._add_attachments()
|
def run(self, *args):
"""Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
"""
params = self.parser.parse_args(args)
config_file = os.path.expanduser('~/.sortinghat')
if params.action == 'get':
code = self.get(params.parameter, config_file)
elif params.action == 'set':
code = self.set(params.parameter, params.value, config_file)
else:
raise RuntimeError("Not get or set action given")
return code
|
def function[run, parameter[self]]:
constant[Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
]
variable[params] assign[=] call[name[self].parser.parse_args, parameter[name[args]]]
variable[config_file] assign[=] call[name[os].path.expanduser, parameter[constant[~/.sortinghat]]]
if compare[name[params].action equal[==] constant[get]] begin[:]
variable[code] assign[=] call[name[self].get, parameter[name[params].parameter, name[config_file]]]
return[name[code]]
|
keyword[def] identifier[run] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[params] = identifier[self] . identifier[parser] . identifier[parse_args] ( identifier[args] )
identifier[config_file] = identifier[os] . identifier[path] . identifier[expanduser] ( literal[string] )
keyword[if] identifier[params] . identifier[action] == literal[string] :
identifier[code] = identifier[self] . identifier[get] ( identifier[params] . identifier[parameter] , identifier[config_file] )
keyword[elif] identifier[params] . identifier[action] == literal[string] :
identifier[code] = identifier[self] . identifier[set] ( identifier[params] . identifier[parameter] , identifier[params] . identifier[value] , identifier[config_file] )
keyword[else] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
keyword[return] identifier[code]
|
def run(self, *args):
"""Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
"""
params = self.parser.parse_args(args)
config_file = os.path.expanduser('~/.sortinghat')
if params.action == 'get':
code = self.get(params.parameter, config_file) # depends on [control=['if'], data=[]]
elif params.action == 'set':
code = self.set(params.parameter, params.value, config_file) # depends on [control=['if'], data=[]]
else:
raise RuntimeError('Not get or set action given')
return code
|
def compile_matchers(formatcode):
"""
Tests newick string against format types? and makes a re.compile
"""
matchers = {}
for node_type in ["leaf", "single", "internal"]:
if node_type == "leaf" or node_type == "single":
container1 = NW_FORMAT[formatcode][0][0]
container2 = NW_FORMAT[formatcode][1][0]
converterFn1 = NW_FORMAT[formatcode][0][1]
converterFn2 = NW_FORMAT[formatcode][1][1]
flexible1 = NW_FORMAT[formatcode][0][2]
flexible2 = NW_FORMAT[formatcode][1][2]
else:
container1 = NW_FORMAT[formatcode][2][0]
container2 = NW_FORMAT[formatcode][3][0]
converterFn1 = NW_FORMAT[formatcode][2][1]
converterFn2 = NW_FORMAT[formatcode][3][1]
flexible1 = NW_FORMAT[formatcode][2][2]
flexible2 = NW_FORMAT[formatcode][3][2]
if converterFn1 == str:
FIRST_MATCH = "("+_NAME_RE+")"
elif converterFn1 == float:
FIRST_MATCH = "("+_FLOAT_RE+")"
elif converterFn1 is None:
FIRST_MATCH = '()'
if converterFn2 == str:
SECOND_MATCH = "(:"+_NAME_RE+")"
elif converterFn2 == float:
SECOND_MATCH = "(:"+_FLOAT_RE+")"
elif converterFn2 is None:
SECOND_MATCH = '()'
if flexible1 and node_type != 'leaf':
FIRST_MATCH += "?"
if flexible2:
SECOND_MATCH += "?"
matcher_str= '^\s*%s\s*%s\s*(%s)?\s*$' % (FIRST_MATCH, SECOND_MATCH, _NHX_RE)
compiled_matcher = re.compile(matcher_str)
matchers[node_type] = [container1, container2, converterFn1, converterFn2, compiled_matcher]
return matchers
|
def function[compile_matchers, parameter[formatcode]]:
constant[
Tests newick string against format types? and makes a re.compile
]
variable[matchers] assign[=] dictionary[[], []]
for taget[name[node_type]] in starred[list[[<ast.Constant object at 0x7da18ede7fd0>, <ast.Constant object at 0x7da18ede55d0>, <ast.Constant object at 0x7da18ede7d00>]]] begin[:]
if <ast.BoolOp object at 0x7da18ede5450> begin[:]
variable[container1] assign[=] call[call[call[name[NW_FORMAT]][name[formatcode]]][constant[0]]][constant[0]]
variable[container2] assign[=] call[call[call[name[NW_FORMAT]][name[formatcode]]][constant[1]]][constant[0]]
variable[converterFn1] assign[=] call[call[call[name[NW_FORMAT]][name[formatcode]]][constant[0]]][constant[1]]
variable[converterFn2] assign[=] call[call[call[name[NW_FORMAT]][name[formatcode]]][constant[1]]][constant[1]]
variable[flexible1] assign[=] call[call[call[name[NW_FORMAT]][name[formatcode]]][constant[0]]][constant[2]]
variable[flexible2] assign[=] call[call[call[name[NW_FORMAT]][name[formatcode]]][constant[1]]][constant[2]]
if compare[name[converterFn1] equal[==] name[str]] begin[:]
variable[FIRST_MATCH] assign[=] binary_operation[binary_operation[constant[(] + name[_NAME_RE]] + constant[)]]
if compare[name[converterFn2] equal[==] name[str]] begin[:]
variable[SECOND_MATCH] assign[=] binary_operation[binary_operation[constant[(:] + name[_NAME_RE]] + constant[)]]
if <ast.BoolOp object at 0x7da18ede4100> begin[:]
<ast.AugAssign object at 0x7da18ede5540>
if name[flexible2] begin[:]
<ast.AugAssign object at 0x7da18ede4cd0>
variable[matcher_str] assign[=] binary_operation[constant[^\s*%s\s*%s\s*(%s)?\s*$] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18ede7b20>, <ast.Name object at 0x7da18ede6080>, <ast.Name object at 0x7da18ede73a0>]]]
variable[compiled_matcher] assign[=] call[name[re].compile, parameter[name[matcher_str]]]
call[name[matchers]][name[node_type]] assign[=] list[[<ast.Name object at 0x7da18ede58d0>, <ast.Name object at 0x7da18ede6aa0>, <ast.Name object at 0x7da18ede5240>, <ast.Name object at 0x7da18ede5120>, <ast.Name object at 0x7da18ede7850>]]
return[name[matchers]]
|
keyword[def] identifier[compile_matchers] ( identifier[formatcode] ):
literal[string]
identifier[matchers] ={}
keyword[for] identifier[node_type] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
keyword[if] identifier[node_type] == literal[string] keyword[or] identifier[node_type] == literal[string] :
identifier[container1] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[container2] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[converterFn1] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[converterFn2] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[flexible1] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[flexible2] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
keyword[else] :
identifier[container1] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[container2] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[converterFn1] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[converterFn2] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[flexible1] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
identifier[flexible2] = identifier[NW_FORMAT] [ identifier[formatcode] ][ literal[int] ][ literal[int] ]
keyword[if] identifier[converterFn1] == identifier[str] :
identifier[FIRST_MATCH] = literal[string] + identifier[_NAME_RE] + literal[string]
keyword[elif] identifier[converterFn1] == identifier[float] :
identifier[FIRST_MATCH] = literal[string] + identifier[_FLOAT_RE] + literal[string]
keyword[elif] identifier[converterFn1] keyword[is] keyword[None] :
identifier[FIRST_MATCH] = literal[string]
keyword[if] identifier[converterFn2] == identifier[str] :
identifier[SECOND_MATCH] = literal[string] + identifier[_NAME_RE] + literal[string]
keyword[elif] identifier[converterFn2] == identifier[float] :
identifier[SECOND_MATCH] = literal[string] + identifier[_FLOAT_RE] + literal[string]
keyword[elif] identifier[converterFn2] keyword[is] keyword[None] :
identifier[SECOND_MATCH] = literal[string]
keyword[if] identifier[flexible1] keyword[and] identifier[node_type] != literal[string] :
identifier[FIRST_MATCH] += literal[string]
keyword[if] identifier[flexible2] :
identifier[SECOND_MATCH] += literal[string]
identifier[matcher_str] = literal[string] %( identifier[FIRST_MATCH] , identifier[SECOND_MATCH] , identifier[_NHX_RE] )
identifier[compiled_matcher] = identifier[re] . identifier[compile] ( identifier[matcher_str] )
identifier[matchers] [ identifier[node_type] ]=[ identifier[container1] , identifier[container2] , identifier[converterFn1] , identifier[converterFn2] , identifier[compiled_matcher] ]
keyword[return] identifier[matchers]
|
def compile_matchers(formatcode):
"""
Tests newick string against format types? and makes a re.compile
"""
matchers = {}
for node_type in ['leaf', 'single', 'internal']:
if node_type == 'leaf' or node_type == 'single':
container1 = NW_FORMAT[formatcode][0][0]
container2 = NW_FORMAT[formatcode][1][0]
converterFn1 = NW_FORMAT[formatcode][0][1]
converterFn2 = NW_FORMAT[formatcode][1][1]
flexible1 = NW_FORMAT[formatcode][0][2]
flexible2 = NW_FORMAT[formatcode][1][2] # depends on [control=['if'], data=[]]
else:
container1 = NW_FORMAT[formatcode][2][0]
container2 = NW_FORMAT[formatcode][3][0]
converterFn1 = NW_FORMAT[formatcode][2][1]
converterFn2 = NW_FORMAT[formatcode][3][1]
flexible1 = NW_FORMAT[formatcode][2][2]
flexible2 = NW_FORMAT[formatcode][3][2]
if converterFn1 == str:
FIRST_MATCH = '(' + _NAME_RE + ')' # depends on [control=['if'], data=[]]
elif converterFn1 == float:
FIRST_MATCH = '(' + _FLOAT_RE + ')' # depends on [control=['if'], data=[]]
elif converterFn1 is None:
FIRST_MATCH = '()' # depends on [control=['if'], data=[]]
if converterFn2 == str:
SECOND_MATCH = '(:' + _NAME_RE + ')' # depends on [control=['if'], data=[]]
elif converterFn2 == float:
SECOND_MATCH = '(:' + _FLOAT_RE + ')' # depends on [control=['if'], data=[]]
elif converterFn2 is None:
SECOND_MATCH = '()' # depends on [control=['if'], data=[]]
if flexible1 and node_type != 'leaf':
FIRST_MATCH += '?' # depends on [control=['if'], data=[]]
if flexible2:
SECOND_MATCH += '?' # depends on [control=['if'], data=[]]
matcher_str = '^\\s*%s\\s*%s\\s*(%s)?\\s*$' % (FIRST_MATCH, SECOND_MATCH, _NHX_RE)
compiled_matcher = re.compile(matcher_str)
matchers[node_type] = [container1, container2, converterFn1, converterFn2, compiled_matcher] # depends on [control=['for'], data=['node_type']]
return matchers
|
def run(args):
"""Runs the acorn setup/configuration commands.
"""
if args is None:
return
cmd = args["commands"][0]
if cmd == "configure":
if len(args["commands"]) < 2:# pragma: no cover
msg.err("'configure' command requires a second, sub-command "
"parameter. E.g., `acorn.py configure packages`.")
exit(0)
subcmd = args["commands"][1]
_run_configure(subcmd, args)
|
def function[run, parameter[args]]:
constant[Runs the acorn setup/configuration commands.
]
if compare[name[args] is constant[None]] begin[:]
return[None]
variable[cmd] assign[=] call[call[name[args]][constant[commands]]][constant[0]]
if compare[name[cmd] equal[==] constant[configure]] begin[:]
if compare[call[name[len], parameter[call[name[args]][constant[commands]]]] less[<] constant[2]] begin[:]
call[name[msg].err, parameter[constant['configure' command requires a second, sub-command parameter. E.g., `acorn.py configure packages`.]]]
call[name[exit], parameter[constant[0]]]
variable[subcmd] assign[=] call[call[name[args]][constant[commands]]][constant[1]]
call[name[_run_configure], parameter[name[subcmd], name[args]]]
|
keyword[def] identifier[run] ( identifier[args] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
keyword[return]
identifier[cmd] = identifier[args] [ literal[string] ][ literal[int] ]
keyword[if] identifier[cmd] == literal[string] :
keyword[if] identifier[len] ( identifier[args] [ literal[string] ])< literal[int] :
identifier[msg] . identifier[err] ( literal[string]
literal[string] )
identifier[exit] ( literal[int] )
identifier[subcmd] = identifier[args] [ literal[string] ][ literal[int] ]
identifier[_run_configure] ( identifier[subcmd] , identifier[args] )
|
def run(args):
"""Runs the acorn setup/configuration commands.
"""
if args is None:
return # depends on [control=['if'], data=[]]
cmd = args['commands'][0]
if cmd == 'configure':
if len(args['commands']) < 2: # pragma: no cover
msg.err("'configure' command requires a second, sub-command parameter. E.g., `acorn.py configure packages`.")
exit(0) # depends on [control=['if'], data=[]]
subcmd = args['commands'][1]
_run_configure(subcmd, args) # depends on [control=['if'], data=[]]
|
def _sizes(self, package):
"""Package size summary
"""
data = Utils().read_file(self.meta.pkg_path + package)
for line in data.splitlines():
if line.startswith("UNCOMPRESSED PACKAGE SIZE:"):
digit = float((''.join(re.findall(
"[-+]?\d+[\.]?\d*[eE]?[-+]?\d*", line[26:]))))
self.file_size = line[26:].strip()
if "M" in line[26:]:
self.size += digit * 1024
else:
self.size += digit
break
|
def function[_sizes, parameter[self, package]]:
constant[Package size summary
]
variable[data] assign[=] call[call[name[Utils], parameter[]].read_file, parameter[binary_operation[name[self].meta.pkg_path + name[package]]]]
for taget[name[line]] in starred[call[name[data].splitlines, parameter[]]] begin[:]
if call[name[line].startswith, parameter[constant[UNCOMPRESSED PACKAGE SIZE:]]] begin[:]
variable[digit] assign[=] call[name[float], parameter[call[constant[].join, parameter[call[name[re].findall, parameter[constant[[-+]?\d+[\.]?\d*[eE]?[-+]?\d*], call[name[line]][<ast.Slice object at 0x7da1b282ae30>]]]]]]]
name[self].file_size assign[=] call[call[name[line]][<ast.Slice object at 0x7da1b282a950>].strip, parameter[]]
if compare[constant[M] in call[name[line]][<ast.Slice object at 0x7da1b282b310>]] begin[:]
<ast.AugAssign object at 0x7da1b282be50>
|
keyword[def] identifier[_sizes] ( identifier[self] , identifier[package] ):
literal[string]
identifier[data] = identifier[Utils] (). identifier[read_file] ( identifier[self] . identifier[meta] . identifier[pkg_path] + identifier[package] )
keyword[for] identifier[line] keyword[in] identifier[data] . identifier[splitlines] ():
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[digit] = identifier[float] (( literal[string] . identifier[join] ( identifier[re] . identifier[findall] (
literal[string] , identifier[line] [ literal[int] :]))))
identifier[self] . identifier[file_size] = identifier[line] [ literal[int] :]. identifier[strip] ()
keyword[if] literal[string] keyword[in] identifier[line] [ literal[int] :]:
identifier[self] . identifier[size] += identifier[digit] * literal[int]
keyword[else] :
identifier[self] . identifier[size] += identifier[digit]
keyword[break]
|
def _sizes(self, package):
"""Package size summary
"""
data = Utils().read_file(self.meta.pkg_path + package)
for line in data.splitlines():
if line.startswith('UNCOMPRESSED PACKAGE SIZE:'):
digit = float(''.join(re.findall('[-+]?\\d+[\\.]?\\d*[eE]?[-+]?\\d*', line[26:])))
self.file_size = line[26:].strip()
if 'M' in line[26:]:
self.size += digit * 1024 # depends on [control=['if'], data=[]]
else:
self.size += digit
break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']]
|
def add_functions(self, names, functions):
"""Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions.
functions : (list of) function(s)
The function(s) to call.
"""
if isinstance(names, string_types):
names = [names]
functions = [functions]
if len(functions) != len(names):
raise ValueError("number of provided names must be same as number "
"of functions")
self._functionlib.update(dict(zip(names, functions)))
|
def function[add_functions, parameter[self, names, functions]]:
constant[Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions.
functions : (list of) function(s)
The function(s) to call.
]
if call[name[isinstance], parameter[name[names], name[string_types]]] begin[:]
variable[names] assign[=] list[[<ast.Name object at 0x7da18bcc8310>]]
variable[functions] assign[=] list[[<ast.Name object at 0x7da18bccaa40>]]
if compare[call[name[len], parameter[name[functions]]] not_equal[!=] call[name[len], parameter[name[names]]]] begin[:]
<ast.Raise object at 0x7da18bcc89a0>
call[name[self]._functionlib.update, parameter[call[name[dict], parameter[call[name[zip], parameter[name[names], name[functions]]]]]]]
|
keyword[def] identifier[add_functions] ( identifier[self] , identifier[names] , identifier[functions] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[names] , identifier[string_types] ):
identifier[names] =[ identifier[names] ]
identifier[functions] =[ identifier[functions] ]
keyword[if] identifier[len] ( identifier[functions] )!= identifier[len] ( identifier[names] ):
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
identifier[self] . identifier[_functionlib] . identifier[update] ( identifier[dict] ( identifier[zip] ( identifier[names] , identifier[functions] )))
|
def add_functions(self, names, functions):
"""Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions.
functions : (list of) function(s)
The function(s) to call.
"""
if isinstance(names, string_types):
names = [names]
functions = [functions] # depends on [control=['if'], data=[]]
if len(functions) != len(names):
raise ValueError('number of provided names must be same as number of functions') # depends on [control=['if'], data=[]]
self._functionlib.update(dict(zip(names, functions)))
|
def indices_for_body(self, name, step=3):
'''Get a list of the indices for a specific body.
Parameters
----------
name : str
The name of the body to look up.
step : int, optional
The number of numbers for each body. Defaults to 3, should be set
to 4 for body rotation (since quaternions have 4 values).
Returns
-------
list of int :
A list of the index values for quantities related to the named body.
'''
for j, body in enumerate(self.bodies):
if body.name == name:
return list(range(j * step, (j + 1) * step))
return []
|
def function[indices_for_body, parameter[self, name, step]]:
constant[Get a list of the indices for a specific body.
Parameters
----------
name : str
The name of the body to look up.
step : int, optional
The number of numbers for each body. Defaults to 3, should be set
to 4 for body rotation (since quaternions have 4 values).
Returns
-------
list of int :
A list of the index values for quantities related to the named body.
]
for taget[tuple[[<ast.Name object at 0x7da1afef8a30>, <ast.Name object at 0x7da1afef8610>]]] in starred[call[name[enumerate], parameter[name[self].bodies]]] begin[:]
if compare[name[body].name equal[==] name[name]] begin[:]
return[call[name[list], parameter[call[name[range], parameter[binary_operation[name[j] * name[step]], binary_operation[binary_operation[name[j] + constant[1]] * name[step]]]]]]]
return[list[[]]]
|
keyword[def] identifier[indices_for_body] ( identifier[self] , identifier[name] , identifier[step] = literal[int] ):
literal[string]
keyword[for] identifier[j] , identifier[body] keyword[in] identifier[enumerate] ( identifier[self] . identifier[bodies] ):
keyword[if] identifier[body] . identifier[name] == identifier[name] :
keyword[return] identifier[list] ( identifier[range] ( identifier[j] * identifier[step] ,( identifier[j] + literal[int] )* identifier[step] ))
keyword[return] []
|
def indices_for_body(self, name, step=3):
"""Get a list of the indices for a specific body.
Parameters
----------
name : str
The name of the body to look up.
step : int, optional
The number of numbers for each body. Defaults to 3, should be set
to 4 for body rotation (since quaternions have 4 values).
Returns
-------
list of int :
A list of the index values for quantities related to the named body.
"""
for (j, body) in enumerate(self.bodies):
if body.name == name:
return list(range(j * step, (j + 1) * step)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
return []
|
def _parse_datetime_value(value):
"""Deserialize a DateTime object from its proper ISO-8601 representation."""
if value.endswith('Z'):
# Arrow doesn't support the "Z" literal to denote UTC time.
# Strip the "Z" and add an explicit time zone instead.
value = value[:-1] + '+00:00'
return arrow.get(value, 'YYYY-MM-DDTHH:mm:ssZ').datetime
|
def function[_parse_datetime_value, parameter[value]]:
constant[Deserialize a DateTime object from its proper ISO-8601 representation.]
if call[name[value].endswith, parameter[constant[Z]]] begin[:]
variable[value] assign[=] binary_operation[call[name[value]][<ast.Slice object at 0x7da1b17ed1e0>] + constant[+00:00]]
return[call[name[arrow].get, parameter[name[value], constant[YYYY-MM-DDTHH:mm:ssZ]]].datetime]
|
keyword[def] identifier[_parse_datetime_value] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] . identifier[endswith] ( literal[string] ):
identifier[value] = identifier[value] [:- literal[int] ]+ literal[string]
keyword[return] identifier[arrow] . identifier[get] ( identifier[value] , literal[string] ). identifier[datetime]
|
def _parse_datetime_value(value):
"""Deserialize a DateTime object from its proper ISO-8601 representation."""
if value.endswith('Z'):
# Arrow doesn't support the "Z" literal to denote UTC time.
# Strip the "Z" and add an explicit time zone instead.
value = value[:-1] + '+00:00' # depends on [control=['if'], data=[]]
return arrow.get(value, 'YYYY-MM-DDTHH:mm:ssZ').datetime
|
def start_time(self):
"""Retrieves the start time of the incident/incidents from the output
response
Returns:
start_time(namedtuple): List of named tuples of start time of the
incident/incidents
"""
resource_list = self.traffic_incident()
start_time = namedtuple('start_time', 'start_time')
if len(resource_list) == 1 and resource_list[0] is None:
return None
else:
try:
return [start_time(resource['start'])
for resource in resource_list]
except (KeyError, TypeError):
return [start_time(resource['StartTimeUTC'])
for resource in resource_list]
|
def function[start_time, parameter[self]]:
constant[Retrieves the start time of the incident/incidents from the output
response
Returns:
start_time(namedtuple): List of named tuples of start time of the
incident/incidents
]
variable[resource_list] assign[=] call[name[self].traffic_incident, parameter[]]
variable[start_time] assign[=] call[name[namedtuple], parameter[constant[start_time], constant[start_time]]]
if <ast.BoolOp object at 0x7da20c9934f0> begin[:]
return[constant[None]]
|
keyword[def] identifier[start_time] ( identifier[self] ):
literal[string]
identifier[resource_list] = identifier[self] . identifier[traffic_incident] ()
identifier[start_time] = identifier[namedtuple] ( literal[string] , literal[string] )
keyword[if] identifier[len] ( identifier[resource_list] )== literal[int] keyword[and] identifier[resource_list] [ literal[int] ] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[else] :
keyword[try] :
keyword[return] [ identifier[start_time] ( identifier[resource] [ literal[string] ])
keyword[for] identifier[resource] keyword[in] identifier[resource_list] ]
keyword[except] ( identifier[KeyError] , identifier[TypeError] ):
keyword[return] [ identifier[start_time] ( identifier[resource] [ literal[string] ])
keyword[for] identifier[resource] keyword[in] identifier[resource_list] ]
|
def start_time(self):
"""Retrieves the start time of the incident/incidents from the output
response
Returns:
start_time(namedtuple): List of named tuples of start time of the
incident/incidents
"""
resource_list = self.traffic_incident()
start_time = namedtuple('start_time', 'start_time')
if len(resource_list) == 1 and resource_list[0] is None:
return None # depends on [control=['if'], data=[]]
else:
try:
return [start_time(resource['start']) for resource in resource_list] # depends on [control=['try'], data=[]]
except (KeyError, TypeError):
return [start_time(resource['StartTimeUTC']) for resource in resource_list] # depends on [control=['except'], data=[]]
|
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period):
"""Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param status: status of the host or service
:type status:
:param creation_time: time the notification was created
:type creation_time:
:param interval: time interval length
:type interval: int
:return: timestamp for next notification or None
:rtype: int | None
"""
short_states = {u'WARNING': 'w', u'UNKNOWN': 'u', u'CRITICAL': 'c',
u'RECOVERY': 'r', u'FLAPPING': 'f', u'DOWNTIME': 's',
u'DOWN': 'd', u'UNREACHABLE': 'u', u'OK': 'o', u'UP': 'o'}
# If we are not time based, we bail out!
if not self.time_based:
return None
# Check if we are valid
if status in short_states and short_states[status] not in self.escalation_options:
return None
# Look for the min of our future validity
start = self.first_notification_time * interval + creation_time
# If we are after the classic next time, we are not asking for a smaller interval
if start > t_wished:
return None
# Maybe the time we found is not a valid one....
if escal_period is not None and not escal_period.is_time_valid(start):
return None
# Ok so I ask for my start as a possibility for the next notification time
return start
|
def function[get_next_notif_time, parameter[self, t_wished, status, creation_time, interval, escal_period]]:
constant[Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param status: status of the host or service
:type status:
:param creation_time: time the notification was created
:type creation_time:
:param interval: time interval length
:type interval: int
:return: timestamp for next notification or None
:rtype: int | None
]
variable[short_states] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c69b0>, <ast.Constant object at 0x7da20c6c7790>, <ast.Constant object at 0x7da20c6c69e0>, <ast.Constant object at 0x7da20c6c6140>, <ast.Constant object at 0x7da20c6c71c0>, <ast.Constant object at 0x7da20c6c5c60>, <ast.Constant object at 0x7da20c6c6170>, <ast.Constant object at 0x7da20c6c5330>, <ast.Constant object at 0x7da20c6c6fb0>, <ast.Constant object at 0x7da20c6c5f90>], [<ast.Constant object at 0x7da20c6c7d30>, <ast.Constant object at 0x7da20c6c4c40>, <ast.Constant object at 0x7da20c6c6c20>, <ast.Constant object at 0x7da20c6c4100>, <ast.Constant object at 0x7da20c6c51b0>, <ast.Constant object at 0x7da20c6c4b20>, <ast.Constant object at 0x7da20c6c4850>, <ast.Constant object at 0x7da20c6c4310>, <ast.Constant object at 0x7da20c6c60b0>, <ast.Constant object at 0x7da20c6c41f0>]]
if <ast.UnaryOp object at 0x7da20c6c52a0> begin[:]
return[constant[None]]
if <ast.BoolOp object at 0x7da20c6c4760> begin[:]
return[constant[None]]
variable[start] assign[=] binary_operation[binary_operation[name[self].first_notification_time * name[interval]] + name[creation_time]]
if compare[name[start] greater[>] name[t_wished]] begin[:]
return[constant[None]]
if <ast.BoolOp object at 0x7da20c6c4af0> begin[:]
return[constant[None]]
return[name[start]]
|
keyword[def] identifier[get_next_notif_time] ( identifier[self] , identifier[t_wished] , identifier[status] , identifier[creation_time] , identifier[interval] , identifier[escal_period] ):
literal[string]
identifier[short_states] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] ,
literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] ,
literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] }
keyword[if] keyword[not] identifier[self] . identifier[time_based] :
keyword[return] keyword[None]
keyword[if] identifier[status] keyword[in] identifier[short_states] keyword[and] identifier[short_states] [ identifier[status] ] keyword[not] keyword[in] identifier[self] . identifier[escalation_options] :
keyword[return] keyword[None]
identifier[start] = identifier[self] . identifier[first_notification_time] * identifier[interval] + identifier[creation_time]
keyword[if] identifier[start] > identifier[t_wished] :
keyword[return] keyword[None]
keyword[if] identifier[escal_period] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[escal_period] . identifier[is_time_valid] ( identifier[start] ):
keyword[return] keyword[None]
keyword[return] identifier[start]
|
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period):
"""Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param status: status of the host or service
:type status:
:param creation_time: time the notification was created
:type creation_time:
:param interval: time interval length
:type interval: int
:return: timestamp for next notification or None
:rtype: int | None
"""
short_states = {u'WARNING': 'w', u'UNKNOWN': 'u', u'CRITICAL': 'c', u'RECOVERY': 'r', u'FLAPPING': 'f', u'DOWNTIME': 's', u'DOWN': 'd', u'UNREACHABLE': 'u', u'OK': 'o', u'UP': 'o'}
# If we are not time based, we bail out!
if not self.time_based:
return None # depends on [control=['if'], data=[]]
# Check if we are valid
if status in short_states and short_states[status] not in self.escalation_options:
return None # depends on [control=['if'], data=[]]
# Look for the min of our future validity
start = self.first_notification_time * interval + creation_time
# If we are after the classic next time, we are not asking for a smaller interval
if start > t_wished:
return None # depends on [control=['if'], data=[]]
# Maybe the time we found is not a valid one....
if escal_period is not None and (not escal_period.is_time_valid(start)):
return None # depends on [control=['if'], data=[]]
# Ok so I ask for my start as a possibility for the next notification time
return start
|
def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop('bridge_members'))
# put bridge members in ifname attribute
if bridge_members:
interface['ifname'] = bridge_members
# if no members, this is an empty bridge
else:
interface['bridge_empty'] = True
del interface['ifname']
# bridge has already been defined
# but we need to add more references to it
elif interface['type'] == 'bridge' and i >= 2:
# openwrt adds "br-" prefix to bridge interfaces
# we need to take this into account when referring
# to these physical names
if 'br-' not in interface['ifname']:
interface['ifname'] = 'br-{ifname}'.format(**interface)
# do not repeat bridge attributes (they have already been processed)
for attr in ['type', 'bridge_members', 'stp', 'gateway']:
if attr in interface:
del interface[attr]
elif interface['type'] != 'bridge':
del interface['type']
return interface
|
def function[__intermediate_bridge, parameter[self, interface, i]]:
constant[
converts NetJSON bridge to
UCI intermediate data structure
]
if <ast.BoolOp object at 0x7da1b01418a0> begin[:]
variable[bridge_members] assign[=] call[constant[ ].join, parameter[call[name[interface].pop, parameter[constant[bridge_members]]]]]
if name[bridge_members] begin[:]
call[name[interface]][constant[ifname]] assign[=] name[bridge_members]
return[name[interface]]
|
keyword[def] identifier[__intermediate_bridge] ( identifier[self] , identifier[interface] , identifier[i] ):
literal[string]
keyword[if] identifier[interface] [ literal[string] ]== literal[string] keyword[and] identifier[i] < literal[int] :
identifier[bridge_members] = literal[string] . identifier[join] ( identifier[interface] . identifier[pop] ( literal[string] ))
keyword[if] identifier[bridge_members] :
identifier[interface] [ literal[string] ]= identifier[bridge_members]
keyword[else] :
identifier[interface] [ literal[string] ]= keyword[True]
keyword[del] identifier[interface] [ literal[string] ]
keyword[elif] identifier[interface] [ literal[string] ]== literal[string] keyword[and] identifier[i] >= literal[int] :
keyword[if] literal[string] keyword[not] keyword[in] identifier[interface] [ literal[string] ]:
identifier[interface] [ literal[string] ]= literal[string] . identifier[format] (** identifier[interface] )
keyword[for] identifier[attr] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] ]:
keyword[if] identifier[attr] keyword[in] identifier[interface] :
keyword[del] identifier[interface] [ identifier[attr] ]
keyword[elif] identifier[interface] [ literal[string] ]!= literal[string] :
keyword[del] identifier[interface] [ literal[string] ]
keyword[return] identifier[interface]
|
def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop('bridge_members'))
# put bridge members in ifname attribute
if bridge_members:
interface['ifname'] = bridge_members # depends on [control=['if'], data=[]]
else:
# if no members, this is an empty bridge
interface['bridge_empty'] = True
del interface['ifname'] # depends on [control=['if'], data=[]]
# bridge has already been defined
# but we need to add more references to it
elif interface['type'] == 'bridge' and i >= 2:
# openwrt adds "br-" prefix to bridge interfaces
# we need to take this into account when referring
# to these physical names
if 'br-' not in interface['ifname']:
interface['ifname'] = 'br-{ifname}'.format(**interface) # depends on [control=['if'], data=[]]
# do not repeat bridge attributes (they have already been processed)
for attr in ['type', 'bridge_members', 'stp', 'gateway']:
if attr in interface:
del interface[attr] # depends on [control=['if'], data=['attr', 'interface']] # depends on [control=['for'], data=['attr']] # depends on [control=['if'], data=[]]
elif interface['type'] != 'bridge':
del interface['type'] # depends on [control=['if'], data=[]]
return interface
|
def is_available(self):
"""
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
"""
if self.is_always_available:
return True
for viewname in self.__views__:
if getattr(self, viewname).is_available():
return True
return False
|
def function[is_available, parameter[self]]:
constant[
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
]
if name[self].is_always_available begin[:]
return[constant[True]]
for taget[name[viewname]] in starred[name[self].__views__] begin[:]
if call[call[name[getattr], parameter[name[self], name[viewname]]].is_available, parameter[]] begin[:]
return[constant[True]]
return[constant[False]]
|
keyword[def] identifier[is_available] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_always_available] :
keyword[return] keyword[True]
keyword[for] identifier[viewname] keyword[in] identifier[self] . identifier[__views__] :
keyword[if] identifier[getattr] ( identifier[self] , identifier[viewname] ). identifier[is_available] ():
keyword[return] keyword[True]
keyword[return] keyword[False]
|
def is_available(self):
"""
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
"""
if self.is_always_available:
return True # depends on [control=['if'], data=[]]
for viewname in self.__views__:
if getattr(self, viewname).is_available():
return True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['viewname']]
return False
|
def mcp_als(X, rank, mask, random_state=None, init='randn', **options):
"""Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
mask : (I_1, ..., I_N) array_like
A binary tensor with the same shape as ``X``. All entries equal to zero
correspond to held out or missing data in ``X``. All entries equal to
one correspond to observed entries in ``X`` and the decomposition is
fit to these datapoints.
random_state : integer, ``RandomState``, or ``None``, optional (default ``None``)
If integer, sets the seed of the random number generator;
If RandomState instance, random_state is the random number generator;
If None, use the RandomState instance used by ``numpy.random``.
init : str, or KTensor, optional (default ``'randn'``).
Specifies initial guess for KTensor factor matrices.
If ``'randn'``, Gaussian random numbers are used to initialize.
If ``'rand'``, uniform random numbers are used to initialize.
If KTensor instance, a copy is made to initialize the optimization.
options : dict, specifying fitting options.
tol : float, optional (default ``tol=1E-5``)
Stopping tolerance for reconstruction error.
max_iter : integer, optional (default ``max_iter = 500``)
Maximum number of iterations to perform before exiting.
min_iter : integer, optional (default ``min_iter = 1``)
Minimum number of iterations to perform before exiting.
max_time : integer, optional (default ``max_time = np.inf``)
Maximum computational time before exiting.
verbose : bool ``{'True', 'False'}``, optional (default ``verbose=True``)
Display progress.
Returns
-------
result : FitResult instance
Object which holds the fitted results. It provides the factor matrices
in form of a KTensor, ``result.factors``.
Notes
-----
Fitting CP decompositions with missing data can be exploited to perform
cross-validation.
References
----------
Williams, A. H.
"Solving Least-Squares Regression with Missing Data."
http://alexhwilliams.info/itsneuronalblog/2018/02/26/censored-lstsq/
"""
# Check inputs.
optim_utils._check_cpd_inputs(X, rank)
# Initialize problem.
U, _ = optim_utils._get_initial_ktensor(init, X, rank, random_state, scale_norm=False)
result = FitResult(U, 'MCP_ALS', **options)
normX = np.linalg.norm((X * mask))
# Main optimization loop.
while result.still_optimizing:
# Iterate over each tensor mode.
for n in range(X.ndim):
# i) Normalize factors to prevent singularities.
U.rebalance()
# ii) Unfold data and mask along the nth mode.
unf = unfold(X, n) # i_n x N
m = unfold(mask, n) # i_n x N
# iii) Form Khatri-Rao product of factors matrices.
components = [U[j] for j in range(X.ndim) if j != n]
krt = khatri_rao(components).T # N x r
# iv) Broadcasted solve of linear systems.
# Left hand side of equations, R x R x X.shape[n]
# Right hand side of equations, X.shape[n] x R x 1
lhs_stack = np.matmul(m[:, None, :] * krt[None, :, :], krt.T[None, :, :])
rhs_stack = np.dot(unf * m, krt.T)[:, :, None]
# vi) Update factor.
U[n] = np.linalg.solve(lhs_stack, rhs_stack).reshape(X.shape[n], rank)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Update the optimization result, checks for convergence.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Compute objective function
# grams *= U[-1].T.dot(U[-1])
# obj = np.sqrt(np.sum(grams) - 2*sci.sum(p*U[-1]) + normX**2) / normX
obj = linalg.norm(mask * (U.full() - X)) / normX
# Update result
result.update(obj)
# Finalize and return the optimization result.
return result.finalize()
|
def function[mcp_als, parameter[X, rank, mask, random_state, init]]:
constant[Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
mask : (I_1, ..., I_N) array_like
A binary tensor with the same shape as ``X``. All entries equal to zero
correspond to held out or missing data in ``X``. All entries equal to
one correspond to observed entries in ``X`` and the decomposition is
fit to these datapoints.
random_state : integer, ``RandomState``, or ``None``, optional (default ``None``)
If integer, sets the seed of the random number generator;
If RandomState instance, random_state is the random number generator;
If None, use the RandomState instance used by ``numpy.random``.
init : str, or KTensor, optional (default ``'randn'``).
Specifies initial guess for KTensor factor matrices.
If ``'randn'``, Gaussian random numbers are used to initialize.
If ``'rand'``, uniform random numbers are used to initialize.
If KTensor instance, a copy is made to initialize the optimization.
options : dict, specifying fitting options.
tol : float, optional (default ``tol=1E-5``)
Stopping tolerance for reconstruction error.
max_iter : integer, optional (default ``max_iter = 500``)
Maximum number of iterations to perform before exiting.
min_iter : integer, optional (default ``min_iter = 1``)
Minimum number of iterations to perform before exiting.
max_time : integer, optional (default ``max_time = np.inf``)
Maximum computational time before exiting.
verbose : bool ``{'True', 'False'}``, optional (default ``verbose=True``)
Display progress.
Returns
-------
result : FitResult instance
Object which holds the fitted results. It provides the factor matrices
in form of a KTensor, ``result.factors``.
Notes
-----
Fitting CP decompositions with missing data can be exploited to perform
cross-validation.
References
----------
Williams, A. H.
"Solving Least-Squares Regression with Missing Data."
http://alexhwilliams.info/itsneuronalblog/2018/02/26/censored-lstsq/
]
call[name[optim_utils]._check_cpd_inputs, parameter[name[X], name[rank]]]
<ast.Tuple object at 0x7da18dc9a650> assign[=] call[name[optim_utils]._get_initial_ktensor, parameter[name[init], name[X], name[rank], name[random_state]]]
variable[result] assign[=] call[name[FitResult], parameter[name[U], constant[MCP_ALS]]]
variable[normX] assign[=] call[name[np].linalg.norm, parameter[binary_operation[name[X] * name[mask]]]]
while name[result].still_optimizing begin[:]
for taget[name[n]] in starred[call[name[range], parameter[name[X].ndim]]] begin[:]
call[name[U].rebalance, parameter[]]
variable[unf] assign[=] call[name[unfold], parameter[name[X], name[n]]]
variable[m] assign[=] call[name[unfold], parameter[name[mask], name[n]]]
variable[components] assign[=] <ast.ListComp object at 0x7da18dc9a4d0>
variable[krt] assign[=] call[name[khatri_rao], parameter[name[components]]].T
variable[lhs_stack] assign[=] call[name[np].matmul, parameter[binary_operation[call[name[m]][tuple[[<ast.Slice object at 0x7da18dc9a0b0>, <ast.Constant object at 0x7da18dc99480>, <ast.Slice object at 0x7da18dc99360>]]] * call[name[krt]][tuple[[<ast.Constant object at 0x7da18dc9aa40>, <ast.Slice object at 0x7da18dc98e50>, <ast.Slice object at 0x7da18dc9bdc0>]]]], call[name[krt].T][tuple[[<ast.Constant object at 0x7da18dc9afb0>, <ast.Slice object at 0x7da18dc99b10>, <ast.Slice object at 0x7da18dc984c0>]]]]]
variable[rhs_stack] assign[=] call[call[name[np].dot, parameter[binary_operation[name[unf] * name[m]], name[krt].T]]][tuple[[<ast.Slice object at 0x7da18dc9b070>, <ast.Slice object at 0x7da18dc99510>, <ast.Constant object at 0x7da18dc9b9a0>]]]
call[name[U]][name[n]] assign[=] call[call[name[np].linalg.solve, parameter[name[lhs_stack], name[rhs_stack]]].reshape, parameter[call[name[X].shape][name[n]], name[rank]]]
variable[obj] assign[=] binary_operation[call[name[linalg].norm, parameter[binary_operation[name[mask] * binary_operation[call[name[U].full, parameter[]] - name[X]]]]] / name[normX]]
call[name[result].update, parameter[name[obj]]]
return[call[name[result].finalize, parameter[]]]
|
keyword[def] identifier[mcp_als] ( identifier[X] , identifier[rank] , identifier[mask] , identifier[random_state] = keyword[None] , identifier[init] = literal[string] ,** identifier[options] ):
literal[string]
identifier[optim_utils] . identifier[_check_cpd_inputs] ( identifier[X] , identifier[rank] )
identifier[U] , identifier[_] = identifier[optim_utils] . identifier[_get_initial_ktensor] ( identifier[init] , identifier[X] , identifier[rank] , identifier[random_state] , identifier[scale_norm] = keyword[False] )
identifier[result] = identifier[FitResult] ( identifier[U] , literal[string] ,** identifier[options] )
identifier[normX] = identifier[np] . identifier[linalg] . identifier[norm] (( identifier[X] * identifier[mask] ))
keyword[while] identifier[result] . identifier[still_optimizing] :
keyword[for] identifier[n] keyword[in] identifier[range] ( identifier[X] . identifier[ndim] ):
identifier[U] . identifier[rebalance] ()
identifier[unf] = identifier[unfold] ( identifier[X] , identifier[n] )
identifier[m] = identifier[unfold] ( identifier[mask] , identifier[n] )
identifier[components] =[ identifier[U] [ identifier[j] ] keyword[for] identifier[j] keyword[in] identifier[range] ( identifier[X] . identifier[ndim] ) keyword[if] identifier[j] != identifier[n] ]
identifier[krt] = identifier[khatri_rao] ( identifier[components] ). identifier[T]
identifier[lhs_stack] = identifier[np] . identifier[matmul] ( identifier[m] [:, keyword[None] ,:]* identifier[krt] [ keyword[None] ,:,:], identifier[krt] . identifier[T] [ keyword[None] ,:,:])
identifier[rhs_stack] = identifier[np] . identifier[dot] ( identifier[unf] * identifier[m] , identifier[krt] . identifier[T] )[:,:, keyword[None] ]
identifier[U] [ identifier[n] ]= identifier[np] . identifier[linalg] . identifier[solve] ( identifier[lhs_stack] , identifier[rhs_stack] ). identifier[reshape] ( identifier[X] . identifier[shape] [ identifier[n] ], identifier[rank] )
identifier[obj] = identifier[linalg] . identifier[norm] ( identifier[mask] *( identifier[U] . identifier[full] ()- identifier[X] ))/ identifier[normX]
identifier[result] . identifier[update] ( identifier[obj] )
keyword[return] identifier[result] . identifier[finalize] ()
|
def mcp_als(X, rank, mask, random_state=None, init='randn', **options):
"""Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
mask : (I_1, ..., I_N) array_like
A binary tensor with the same shape as ``X``. All entries equal to zero
correspond to held out or missing data in ``X``. All entries equal to
one correspond to observed entries in ``X`` and the decomposition is
fit to these datapoints.
random_state : integer, ``RandomState``, or ``None``, optional (default ``None``)
If integer, sets the seed of the random number generator;
If RandomState instance, random_state is the random number generator;
If None, use the RandomState instance used by ``numpy.random``.
init : str, or KTensor, optional (default ``'randn'``).
Specifies initial guess for KTensor factor matrices.
If ``'randn'``, Gaussian random numbers are used to initialize.
If ``'rand'``, uniform random numbers are used to initialize.
If KTensor instance, a copy is made to initialize the optimization.
options : dict, specifying fitting options.
tol : float, optional (default ``tol=1E-5``)
Stopping tolerance for reconstruction error.
max_iter : integer, optional (default ``max_iter = 500``)
Maximum number of iterations to perform before exiting.
min_iter : integer, optional (default ``min_iter = 1``)
Minimum number of iterations to perform before exiting.
max_time : integer, optional (default ``max_time = np.inf``)
Maximum computational time before exiting.
verbose : bool ``{'True', 'False'}``, optional (default ``verbose=True``)
Display progress.
Returns
-------
result : FitResult instance
Object which holds the fitted results. It provides the factor matrices
in form of a KTensor, ``result.factors``.
Notes
-----
Fitting CP decompositions with missing data can be exploited to perform
cross-validation.
References
----------
Williams, A. H.
"Solving Least-Squares Regression with Missing Data."
http://alexhwilliams.info/itsneuronalblog/2018/02/26/censored-lstsq/
"""
# Check inputs.
optim_utils._check_cpd_inputs(X, rank)
# Initialize problem.
(U, _) = optim_utils._get_initial_ktensor(init, X, rank, random_state, scale_norm=False)
result = FitResult(U, 'MCP_ALS', **options)
normX = np.linalg.norm(X * mask)
# Main optimization loop.
while result.still_optimizing:
# Iterate over each tensor mode.
for n in range(X.ndim):
# i) Normalize factors to prevent singularities.
U.rebalance()
# ii) Unfold data and mask along the nth mode.
unf = unfold(X, n) # i_n x N
m = unfold(mask, n) # i_n x N
# iii) Form Khatri-Rao product of factors matrices.
components = [U[j] for j in range(X.ndim) if j != n]
krt = khatri_rao(components).T # N x r
# iv) Broadcasted solve of linear systems.
# Left hand side of equations, R x R x X.shape[n]
# Right hand side of equations, X.shape[n] x R x 1
lhs_stack = np.matmul(m[:, None, :] * krt[None, :, :], krt.T[None, :, :])
rhs_stack = np.dot(unf * m, krt.T)[:, :, None]
# vi) Update factor.
U[n] = np.linalg.solve(lhs_stack, rhs_stack).reshape(X.shape[n], rank) # depends on [control=['for'], data=['n']]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Update the optimization result, checks for convergence.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Compute objective function
# grams *= U[-1].T.dot(U[-1])
# obj = np.sqrt(np.sum(grams) - 2*sci.sum(p*U[-1]) + normX**2) / normX
obj = linalg.norm(mask * (U.full() - X)) / normX
# Update result
result.update(obj) # depends on [control=['while'], data=[]]
# Finalize and return the optimization result.
return result.finalize()
|
def metric_ids(self):
""" Return the Metrics on this shelf in the order in which
they were used. """
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Metric)
])
|
def function[metric_ids, parameter[self]]:
constant[ Return the Metrics on this shelf in the order in which
they were used. ]
return[call[name[self]._sorted_ingredients, parameter[<ast.ListComp object at 0x7da20c992b90>]]]
|
keyword[def] identifier[metric_ids] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_sorted_ingredients] ([
identifier[d] . identifier[id] keyword[for] identifier[d] keyword[in] identifier[self] . identifier[values] () keyword[if] identifier[isinstance] ( identifier[d] , identifier[Metric] )
])
|
def metric_ids(self):
""" Return the Metrics on this shelf in the order in which
they were used. """
return self._sorted_ingredients([d.id for d in self.values() if isinstance(d, Metric)])
|
def channel(self, match):
""" Return Channel object for a given Slack ID or name """
if len(match) == 9 and match[0] in ('C','G','D'):
return self._lookup(Channel, 'id', match)
return self._lookup(Channel, 'name', match)
|
def function[channel, parameter[self, match]]:
constant[ Return Channel object for a given Slack ID or name ]
if <ast.BoolOp object at 0x7da20c6a85e0> begin[:]
return[call[name[self]._lookup, parameter[name[Channel], constant[id], name[match]]]]
return[call[name[self]._lookup, parameter[name[Channel], constant[name], name[match]]]]
|
keyword[def] identifier[channel] ( identifier[self] , identifier[match] ):
literal[string]
keyword[if] identifier[len] ( identifier[match] )== literal[int] keyword[and] identifier[match] [ literal[int] ] keyword[in] ( literal[string] , literal[string] , literal[string] ):
keyword[return] identifier[self] . identifier[_lookup] ( identifier[Channel] , literal[string] , identifier[match] )
keyword[return] identifier[self] . identifier[_lookup] ( identifier[Channel] , literal[string] , identifier[match] )
|
def channel(self, match):
""" Return Channel object for a given Slack ID or name """
if len(match) == 9 and match[0] in ('C', 'G', 'D'):
return self._lookup(Channel, 'id', match) # depends on [control=['if'], data=[]]
return self._lookup(Channel, 'name', match)
|
def _check_overlap(self, fragment):
"""
Check that the interval of the given fragment does not overlap
any existing interval in the list (except at its boundaries).
Raises an error if not OK.
"""
#
# NOTE bisect does not work if there is a configuration like:
#
# *********** <- existing interval
# *** <- query interval
#
# TODO one should probably check this by doing bisect
# over the begin and end lists separately
#
for existing_fragment in self.fragments:
if existing_fragment.interval.relative_position_of(fragment.interval) not in self.ALLOWED_POSITIONS:
self.log_exc(u"interval overlaps another already present interval", None, True, ValueError)
|
def function[_check_overlap, parameter[self, fragment]]:
constant[
Check that the interval of the given fragment does not overlap
any existing interval in the list (except at its boundaries).
Raises an error if not OK.
]
for taget[name[existing_fragment]] in starred[name[self].fragments] begin[:]
if compare[call[name[existing_fragment].interval.relative_position_of, parameter[name[fragment].interval]] <ast.NotIn object at 0x7da2590d7190> name[self].ALLOWED_POSITIONS] begin[:]
call[name[self].log_exc, parameter[constant[interval overlaps another already present interval], constant[None], constant[True], name[ValueError]]]
|
keyword[def] identifier[_check_overlap] ( identifier[self] , identifier[fragment] ):
literal[string]
keyword[for] identifier[existing_fragment] keyword[in] identifier[self] . identifier[fragments] :
keyword[if] identifier[existing_fragment] . identifier[interval] . identifier[relative_position_of] ( identifier[fragment] . identifier[interval] ) keyword[not] keyword[in] identifier[self] . identifier[ALLOWED_POSITIONS] :
identifier[self] . identifier[log_exc] ( literal[string] , keyword[None] , keyword[True] , identifier[ValueError] )
|
def _check_overlap(self, fragment):
"""
Check that the interval of the given fragment does not overlap
any existing interval in the list (except at its boundaries).
Raises an error if not OK.
"""
#
# NOTE bisect does not work if there is a configuration like:
#
# *********** <- existing interval
# *** <- query interval
#
# TODO one should probably check this by doing bisect
# over the begin and end lists separately
#
for existing_fragment in self.fragments:
if existing_fragment.interval.relative_position_of(fragment.interval) not in self.ALLOWED_POSITIONS:
self.log_exc(u'interval overlaps another already present interval', None, True, ValueError) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['existing_fragment']]
|
def confirm(self, msg, _timeout=-1):
''' Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
should be displayed to the user before a timeout occurs.
Defaults to -1 which indicates there is no timeout limit.
'''
return self.msgBox('confirm', _timeout=_timeout, msg=msg)
|
def function[confirm, parameter[self, msg, _timeout]]:
constant[ Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
should be displayed to the user before a timeout occurs.
Defaults to -1 which indicates there is no timeout limit.
]
return[call[name[self].msgBox, parameter[constant[confirm]]]]
|
keyword[def] identifier[confirm] ( identifier[self] , identifier[msg] , identifier[_timeout] =- literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[msgBox] ( literal[string] , identifier[_timeout] = identifier[_timeout] , identifier[msg] = identifier[msg] )
|
def confirm(self, msg, _timeout=-1):
""" Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
should be displayed to the user before a timeout occurs.
Defaults to -1 which indicates there is no timeout limit.
"""
return self.msgBox('confirm', _timeout=_timeout, msg=msg)
|
def _calc_a(self, y_C, y_H, y_O, y_N, y_S):
"""
Calculate the mean atomic weight for the specified element mass
fractions.
:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:param y_N: Nitrogen mass fraction
:param y_S: Sulphur mass fraction
:returns: [kg/kmol] mean atomic weight
See equation at bottom of page 538 of Merrick1983a.
"""
return 1 / (y_C/mm("C") + y_H/mm("H") + y_O/mm("O") + y_N/mm("N") +
y_S/mm("S"))
|
def function[_calc_a, parameter[self, y_C, y_H, y_O, y_N, y_S]]:
constant[
Calculate the mean atomic weight for the specified element mass
fractions.
:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:param y_N: Nitrogen mass fraction
:param y_S: Sulphur mass fraction
:returns: [kg/kmol] mean atomic weight
See equation at bottom of page 538 of Merrick1983a.
]
return[binary_operation[constant[1] / binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[name[y_C] / call[name[mm], parameter[constant[C]]]] + binary_operation[name[y_H] / call[name[mm], parameter[constant[H]]]]] + binary_operation[name[y_O] / call[name[mm], parameter[constant[O]]]]] + binary_operation[name[y_N] / call[name[mm], parameter[constant[N]]]]] + binary_operation[name[y_S] / call[name[mm], parameter[constant[S]]]]]]]
|
keyword[def] identifier[_calc_a] ( identifier[self] , identifier[y_C] , identifier[y_H] , identifier[y_O] , identifier[y_N] , identifier[y_S] ):
literal[string]
keyword[return] literal[int] /( identifier[y_C] / identifier[mm] ( literal[string] )+ identifier[y_H] / identifier[mm] ( literal[string] )+ identifier[y_O] / identifier[mm] ( literal[string] )+ identifier[y_N] / identifier[mm] ( literal[string] )+
identifier[y_S] / identifier[mm] ( literal[string] ))
|
def _calc_a(self, y_C, y_H, y_O, y_N, y_S):
"""
Calculate the mean atomic weight for the specified element mass
fractions.
:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:param y_N: Nitrogen mass fraction
:param y_S: Sulphur mass fraction
:returns: [kg/kmol] mean atomic weight
See equation at bottom of page 538 of Merrick1983a.
"""
return 1 / (y_C / mm('C') + y_H / mm('H') + y_O / mm('O') + y_N / mm('N') + y_S / mm('S'))
|
def put(self,
body: Body,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY,
ttr: int = DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param delay: The number of seconds to delay the job for.
:param ttr: The maximum number of seconds the job can be reserved for
before timing out.
"""
if isinstance(body, str):
if self.encoding is None:
raise TypeError("Unable to encode string with no encoding set")
body = body.encode(self.encoding)
cmd = b'put %d %d %d %d\r\n%b' % (priority, delay, ttr, len(body), body)
return self._int_cmd(cmd, b'INSERTED')
|
def function[put, parameter[self, body, priority, delay, ttr]]:
constant[Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param delay: The number of seconds to delay the job for.
:param ttr: The maximum number of seconds the job can be reserved for
before timing out.
]
if call[name[isinstance], parameter[name[body], name[str]]] begin[:]
if compare[name[self].encoding is constant[None]] begin[:]
<ast.Raise object at 0x7da1b05daa10>
variable[body] assign[=] call[name[body].encode, parameter[name[self].encoding]]
variable[cmd] assign[=] binary_operation[constant[b'put %d %d %d %d\r\n%b'] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b05db160>, <ast.Name object at 0x7da1b05d9ea0>, <ast.Name object at 0x7da1b05da290>, <ast.Call object at 0x7da1b05d8ca0>, <ast.Name object at 0x7da1b05d9540>]]]
return[call[name[self]._int_cmd, parameter[name[cmd], constant[b'INSERTED']]]]
|
keyword[def] identifier[put] ( identifier[self] ,
identifier[body] : identifier[Body] ,
identifier[priority] : identifier[int] = identifier[DEFAULT_PRIORITY] ,
identifier[delay] : identifier[int] = identifier[DEFAULT_DELAY] ,
identifier[ttr] : identifier[int] = identifier[DEFAULT_TTR] )-> identifier[int] :
literal[string]
keyword[if] identifier[isinstance] ( identifier[body] , identifier[str] ):
keyword[if] identifier[self] . identifier[encoding] keyword[is] keyword[None] :
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[body] = identifier[body] . identifier[encode] ( identifier[self] . identifier[encoding] )
identifier[cmd] = literal[string] %( identifier[priority] , identifier[delay] , identifier[ttr] , identifier[len] ( identifier[body] ), identifier[body] )
keyword[return] identifier[self] . identifier[_int_cmd] ( identifier[cmd] , literal[string] )
|
def put(self, body: Body, priority: int=DEFAULT_PRIORITY, delay: int=DEFAULT_DELAY, ttr: int=DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param delay: The number of seconds to delay the job for.
:param ttr: The maximum number of seconds the job can be reserved for
before timing out.
"""
if isinstance(body, str):
if self.encoding is None:
raise TypeError('Unable to encode string with no encoding set') # depends on [control=['if'], data=[]]
body = body.encode(self.encoding) # depends on [control=['if'], data=[]]
cmd = b'put %d %d %d %d\r\n%b' % (priority, delay, ttr, len(body), body)
return self._int_cmd(cmd, b'INSERTED')
|
def _getStringStream(self, filename, prefer='unicode'):
"""Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer/ specifies which will be
returned.
"""
if isinstance(filename, list):
# Join with slashes to make it easier to append the type
filename = "/".join(filename)
asciiVersion = self._getStream(filename + '001E')
unicodeVersion = windowsUnicode(self._getStream(filename + '001F'))
if asciiVersion is None:
return unicodeVersion
elif unicodeVersion is None:
return asciiVersion.decode('ascii', 'ignore')
else:
if prefer == 'unicode':
return unicodeVersion
else:
return asciiVersion.decode('ascii', 'ignore')
|
def function[_getStringStream, parameter[self, filename, prefer]]:
constant[Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer/ specifies which will be
returned.
]
if call[name[isinstance], parameter[name[filename], name[list]]] begin[:]
variable[filename] assign[=] call[constant[/].join, parameter[name[filename]]]
variable[asciiVersion] assign[=] call[name[self]._getStream, parameter[binary_operation[name[filename] + constant[001E]]]]
variable[unicodeVersion] assign[=] call[name[windowsUnicode], parameter[call[name[self]._getStream, parameter[binary_operation[name[filename] + constant[001F]]]]]]
if compare[name[asciiVersion] is constant[None]] begin[:]
return[name[unicodeVersion]]
|
keyword[def] identifier[_getStringStream] ( identifier[self] , identifier[filename] , identifier[prefer] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[filename] , identifier[list] ):
identifier[filename] = literal[string] . identifier[join] ( identifier[filename] )
identifier[asciiVersion] = identifier[self] . identifier[_getStream] ( identifier[filename] + literal[string] )
identifier[unicodeVersion] = identifier[windowsUnicode] ( identifier[self] . identifier[_getStream] ( identifier[filename] + literal[string] ))
keyword[if] identifier[asciiVersion] keyword[is] keyword[None] :
keyword[return] identifier[unicodeVersion]
keyword[elif] identifier[unicodeVersion] keyword[is] keyword[None] :
keyword[return] identifier[asciiVersion] . identifier[decode] ( literal[string] , literal[string] )
keyword[else] :
keyword[if] identifier[prefer] == literal[string] :
keyword[return] identifier[unicodeVersion]
keyword[else] :
keyword[return] identifier[asciiVersion] . identifier[decode] ( literal[string] , literal[string] )
|
def _getStringStream(self, filename, prefer='unicode'):
"""Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer/ specifies which will be
returned.
"""
if isinstance(filename, list):
# Join with slashes to make it easier to append the type
filename = '/'.join(filename) # depends on [control=['if'], data=[]]
asciiVersion = self._getStream(filename + '001E')
unicodeVersion = windowsUnicode(self._getStream(filename + '001F'))
if asciiVersion is None:
return unicodeVersion # depends on [control=['if'], data=[]]
elif unicodeVersion is None:
return asciiVersion.decode('ascii', 'ignore') # depends on [control=['if'], data=[]]
elif prefer == 'unicode':
return unicodeVersion # depends on [control=['if'], data=[]]
else:
return asciiVersion.decode('ascii', 'ignore')
|
def _newPage(self, pno=-1, width=595, height=842):
"""_newPage(self, pno=-1, width=595, height=842) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
val = _fitz.Document__newPage(self, pno, width, height)
self._reset_page_refs()
return val
|
def function[_newPage, parameter[self, pno, width, height]]:
constant[_newPage(self, pno=-1, width=595, height=842) -> PyObject *]
if <ast.BoolOp object at 0x7da18f811450> begin[:]
<ast.Raise object at 0x7da18f810940>
variable[val] assign[=] call[name[_fitz].Document__newPage, parameter[name[self], name[pno], name[width], name[height]]]
call[name[self]._reset_page_refs, parameter[]]
return[name[val]]
|
keyword[def] identifier[_newPage] ( identifier[self] , identifier[pno] =- literal[int] , identifier[width] = literal[int] , identifier[height] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[isClosed] keyword[or] identifier[self] . identifier[isEncrypted] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[val] = identifier[_fitz] . identifier[Document__newPage] ( identifier[self] , identifier[pno] , identifier[width] , identifier[height] )
identifier[self] . identifier[_reset_page_refs] ()
keyword[return] identifier[val]
|
def _newPage(self, pno=-1, width=595, height=842):
"""_newPage(self, pno=-1, width=595, height=842) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError('operation illegal for closed / encrypted doc') # depends on [control=['if'], data=[]]
val = _fitz.Document__newPage(self, pno, width, height)
self._reset_page_refs()
return val
|
def positionlesscrop(self,x,y,sheet_coord_system):
"""
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
"""
slice_inds = self.findinputslice(
sheet_coord_system.sheet2matrixidx(x,y),
self.shape_on_sheet(), sheet_coord_system.shape)
self.set(slice_inds)
|
def function[positionlesscrop, parameter[self, x, y, sheet_coord_system]]:
constant[
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
]
variable[slice_inds] assign[=] call[name[self].findinputslice, parameter[call[name[sheet_coord_system].sheet2matrixidx, parameter[name[x], name[y]]], call[name[self].shape_on_sheet, parameter[]], name[sheet_coord_system].shape]]
call[name[self].set, parameter[name[slice_inds]]]
|
keyword[def] identifier[positionlesscrop] ( identifier[self] , identifier[x] , identifier[y] , identifier[sheet_coord_system] ):
literal[string]
identifier[slice_inds] = identifier[self] . identifier[findinputslice] (
identifier[sheet_coord_system] . identifier[sheet2matrixidx] ( identifier[x] , identifier[y] ),
identifier[self] . identifier[shape_on_sheet] (), identifier[sheet_coord_system] . identifier[shape] )
identifier[self] . identifier[set] ( identifier[slice_inds] )
|
def positionlesscrop(self, x, y, sheet_coord_system):
"""
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
"""
slice_inds = self.findinputslice(sheet_coord_system.sheet2matrixidx(x, y), self.shape_on_sheet(), sheet_coord_system.shape)
self.set(slice_inds)
|
def runSearchExpressionLevels(self, request):
"""
Returns a SearchExpressionLevelResponse for the specified
SearchExpressionLevelRequest object.
"""
return self.runSearchRequest(
request, protocol.SearchExpressionLevelsRequest,
protocol.SearchExpressionLevelsResponse,
self.expressionLevelsGenerator)
|
def function[runSearchExpressionLevels, parameter[self, request]]:
constant[
Returns a SearchExpressionLevelResponse for the specified
SearchExpressionLevelRequest object.
]
return[call[name[self].runSearchRequest, parameter[name[request], name[protocol].SearchExpressionLevelsRequest, name[protocol].SearchExpressionLevelsResponse, name[self].expressionLevelsGenerator]]]
|
keyword[def] identifier[runSearchExpressionLevels] ( identifier[self] , identifier[request] ):
literal[string]
keyword[return] identifier[self] . identifier[runSearchRequest] (
identifier[request] , identifier[protocol] . identifier[SearchExpressionLevelsRequest] ,
identifier[protocol] . identifier[SearchExpressionLevelsResponse] ,
identifier[self] . identifier[expressionLevelsGenerator] )
|
def runSearchExpressionLevels(self, request):
"""
Returns a SearchExpressionLevelResponse for the specified
SearchExpressionLevelRequest object.
"""
return self.runSearchRequest(request, protocol.SearchExpressionLevelsRequest, protocol.SearchExpressionLevelsResponse, self.expressionLevelsGenerator)
|
def value_opt_step(i,
opt_state,
opt_update,
value_net_apply,
padded_observations,
padded_rewards,
reward_mask,
gamma=0.99):
"""Value optimizer step."""
value_params = trax_opt.get_params(opt_state)
# Note this partial application here and argnums above in ppo_opt_step.
g = grad(functools.partial(value_loss, value_net_apply))(
value_params,
padded_observations,
padded_rewards,
reward_mask,
gamma=gamma)
return opt_update(i, g, opt_state)
|
def function[value_opt_step, parameter[i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma]]:
constant[Value optimizer step.]
variable[value_params] assign[=] call[name[trax_opt].get_params, parameter[name[opt_state]]]
variable[g] assign[=] call[call[name[grad], parameter[call[name[functools].partial, parameter[name[value_loss], name[value_net_apply]]]]], parameter[name[value_params], name[padded_observations], name[padded_rewards], name[reward_mask]]]
return[call[name[opt_update], parameter[name[i], name[g], name[opt_state]]]]
|
keyword[def] identifier[value_opt_step] ( identifier[i] ,
identifier[opt_state] ,
identifier[opt_update] ,
identifier[value_net_apply] ,
identifier[padded_observations] ,
identifier[padded_rewards] ,
identifier[reward_mask] ,
identifier[gamma] = literal[int] ):
literal[string]
identifier[value_params] = identifier[trax_opt] . identifier[get_params] ( identifier[opt_state] )
identifier[g] = identifier[grad] ( identifier[functools] . identifier[partial] ( identifier[value_loss] , identifier[value_net_apply] ))(
identifier[value_params] ,
identifier[padded_observations] ,
identifier[padded_rewards] ,
identifier[reward_mask] ,
identifier[gamma] = identifier[gamma] )
keyword[return] identifier[opt_update] ( identifier[i] , identifier[g] , identifier[opt_state] )
|
def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99):
"""Value optimizer step."""
value_params = trax_opt.get_params(opt_state)
# Note this partial application here and argnums above in ppo_opt_step.
g = grad(functools.partial(value_loss, value_net_apply))(value_params, padded_observations, padded_rewards, reward_mask, gamma=gamma)
return opt_update(i, g, opt_state)
|
def create_subnet(self, snet):
"""Create subnet."""
snet_id = snet.get('id')
# This checks if the source of the subnet creation is FW,
# If yes, this event is ignored.
if self.fw_api.is_subnet_source_fw(snet.get('tenant_id'),
snet.get('cidr')):
LOG.info("Service subnet %s, returning", snet.get('cidr'))
return
if snet_id not in self.subnet:
self.subnet[snet_id] = {}
self.subnet[snet_id].update(snet)
net = self.network.get(self.subnet[snet_id].get('network_id'))
if not net:
LOG.error('Network %(network_id)s does not exist.',
{'network_id': self.subnet[snet_id].get('network_id')})
return
# Check if the network is created by DCNM.
query_net = self.get_network(net.get('id'))
if query_net.result != constants.SUBNET_PENDING:
LOG.info("Subnet exists, returning")
return
if query_net and query_net.source.lower() == 'dcnm':
# The network is created by DCNM.
# No need to process this event.
LOG.info('create_subnet: network %(name)s '
'was created by DCNM. Ignoring processing the '
'event.', {'name': query_net.name})
return
tenant_name = self.get_project_name(snet['tenant_id'])
subnet = utils.Dict2Obj(snet)
dcnm_net = utils.Dict2Obj(net)
if not tenant_name:
LOG.error('Project %(tenant_id)s does not exist.',
{'tenant_id': subnet.tenant_id})
self.update_network_db(dcnm_net.id, constants.CREATE_FAIL)
return
try:
self.dcnm_client.create_network(tenant_name, dcnm_net, subnet,
self.dcnm_dhcp)
self.update_network_db(net.get('id'), constants.RESULT_SUCCESS)
except dexc.DfaClientRequestFailed:
LOG.exception('Failed to create network %(net)s.',
{'net': dcnm_net.name})
# Update network database with failure result.
self.update_network_db(dcnm_net.id, constants.CREATE_FAIL)
self.network_sub_create_notif(snet.get('tenant_id'), tenant_name,
snet.get('cidr'))
|
def function[create_subnet, parameter[self, snet]]:
constant[Create subnet.]
variable[snet_id] assign[=] call[name[snet].get, parameter[constant[id]]]
if call[name[self].fw_api.is_subnet_source_fw, parameter[call[name[snet].get, parameter[constant[tenant_id]]], call[name[snet].get, parameter[constant[cidr]]]]] begin[:]
call[name[LOG].info, parameter[constant[Service subnet %s, returning], call[name[snet].get, parameter[constant[cidr]]]]]
return[None]
if compare[name[snet_id] <ast.NotIn object at 0x7da2590d7190> name[self].subnet] begin[:]
call[name[self].subnet][name[snet_id]] assign[=] dictionary[[], []]
call[call[name[self].subnet][name[snet_id]].update, parameter[name[snet]]]
variable[net] assign[=] call[name[self].network.get, parameter[call[call[name[self].subnet][name[snet_id]].get, parameter[constant[network_id]]]]]
if <ast.UnaryOp object at 0x7da1b1ba9d20> begin[:]
call[name[LOG].error, parameter[constant[Network %(network_id)s does not exist.], dictionary[[<ast.Constant object at 0x7da1b1baac80>], [<ast.Call object at 0x7da1b1bab2e0>]]]]
return[None]
variable[query_net] assign[=] call[name[self].get_network, parameter[call[name[net].get, parameter[constant[id]]]]]
if compare[name[query_net].result not_equal[!=] name[constants].SUBNET_PENDING] begin[:]
call[name[LOG].info, parameter[constant[Subnet exists, returning]]]
return[None]
if <ast.BoolOp object at 0x7da1b1babe20> begin[:]
call[name[LOG].info, parameter[constant[create_subnet: network %(name)s was created by DCNM. Ignoring processing the event.], dictionary[[<ast.Constant object at 0x7da1b1bab370>], [<ast.Attribute object at 0x7da1b1baa7d0>]]]]
return[None]
variable[tenant_name] assign[=] call[name[self].get_project_name, parameter[call[name[snet]][constant[tenant_id]]]]
variable[subnet] assign[=] call[name[utils].Dict2Obj, parameter[name[snet]]]
variable[dcnm_net] assign[=] call[name[utils].Dict2Obj, parameter[name[net]]]
if <ast.UnaryOp object at 0x7da1b1bab490> begin[:]
call[name[LOG].error, parameter[constant[Project %(tenant_id)s does not exist.], dictionary[[<ast.Constant object at 0x7da1b1babeb0>], [<ast.Attribute object at 0x7da1b1ba9930>]]]]
call[name[self].update_network_db, parameter[name[dcnm_net].id, name[constants].CREATE_FAIL]]
return[None]
<ast.Try object at 0x7da1b1ba8820>
call[name[self].network_sub_create_notif, parameter[call[name[snet].get, parameter[constant[tenant_id]]], name[tenant_name], call[name[snet].get, parameter[constant[cidr]]]]]
|
keyword[def] identifier[create_subnet] ( identifier[self] , identifier[snet] ):
literal[string]
identifier[snet_id] = identifier[snet] . identifier[get] ( literal[string] )
keyword[if] identifier[self] . identifier[fw_api] . identifier[is_subnet_source_fw] ( identifier[snet] . identifier[get] ( literal[string] ),
identifier[snet] . identifier[get] ( literal[string] )):
identifier[LOG] . identifier[info] ( literal[string] , identifier[snet] . identifier[get] ( literal[string] ))
keyword[return]
keyword[if] identifier[snet_id] keyword[not] keyword[in] identifier[self] . identifier[subnet] :
identifier[self] . identifier[subnet] [ identifier[snet_id] ]={}
identifier[self] . identifier[subnet] [ identifier[snet_id] ]. identifier[update] ( identifier[snet] )
identifier[net] = identifier[self] . identifier[network] . identifier[get] ( identifier[self] . identifier[subnet] [ identifier[snet_id] ]. identifier[get] ( literal[string] ))
keyword[if] keyword[not] identifier[net] :
identifier[LOG] . identifier[error] ( literal[string] ,
{ literal[string] : identifier[self] . identifier[subnet] [ identifier[snet_id] ]. identifier[get] ( literal[string] )})
keyword[return]
identifier[query_net] = identifier[self] . identifier[get_network] ( identifier[net] . identifier[get] ( literal[string] ))
keyword[if] identifier[query_net] . identifier[result] != identifier[constants] . identifier[SUBNET_PENDING] :
identifier[LOG] . identifier[info] ( literal[string] )
keyword[return]
keyword[if] identifier[query_net] keyword[and] identifier[query_net] . identifier[source] . identifier[lower] ()== literal[string] :
identifier[LOG] . identifier[info] ( literal[string]
literal[string]
literal[string] ,{ literal[string] : identifier[query_net] . identifier[name] })
keyword[return]
identifier[tenant_name] = identifier[self] . identifier[get_project_name] ( identifier[snet] [ literal[string] ])
identifier[subnet] = identifier[utils] . identifier[Dict2Obj] ( identifier[snet] )
identifier[dcnm_net] = identifier[utils] . identifier[Dict2Obj] ( identifier[net] )
keyword[if] keyword[not] identifier[tenant_name] :
identifier[LOG] . identifier[error] ( literal[string] ,
{ literal[string] : identifier[subnet] . identifier[tenant_id] })
identifier[self] . identifier[update_network_db] ( identifier[dcnm_net] . identifier[id] , identifier[constants] . identifier[CREATE_FAIL] )
keyword[return]
keyword[try] :
identifier[self] . identifier[dcnm_client] . identifier[create_network] ( identifier[tenant_name] , identifier[dcnm_net] , identifier[subnet] ,
identifier[self] . identifier[dcnm_dhcp] )
identifier[self] . identifier[update_network_db] ( identifier[net] . identifier[get] ( literal[string] ), identifier[constants] . identifier[RESULT_SUCCESS] )
keyword[except] identifier[dexc] . identifier[DfaClientRequestFailed] :
identifier[LOG] . identifier[exception] ( literal[string] ,
{ literal[string] : identifier[dcnm_net] . identifier[name] })
identifier[self] . identifier[update_network_db] ( identifier[dcnm_net] . identifier[id] , identifier[constants] . identifier[CREATE_FAIL] )
identifier[self] . identifier[network_sub_create_notif] ( identifier[snet] . identifier[get] ( literal[string] ), identifier[tenant_name] ,
identifier[snet] . identifier[get] ( literal[string] ))
|
def create_subnet(self, snet):
"""Create subnet."""
snet_id = snet.get('id')
# This checks if the source of the subnet creation is FW,
# If yes, this event is ignored.
if self.fw_api.is_subnet_source_fw(snet.get('tenant_id'), snet.get('cidr')):
LOG.info('Service subnet %s, returning', snet.get('cidr'))
return # depends on [control=['if'], data=[]]
if snet_id not in self.subnet:
self.subnet[snet_id] = {}
self.subnet[snet_id].update(snet) # depends on [control=['if'], data=['snet_id']]
net = self.network.get(self.subnet[snet_id].get('network_id'))
if not net:
LOG.error('Network %(network_id)s does not exist.', {'network_id': self.subnet[snet_id].get('network_id')})
return # depends on [control=['if'], data=[]]
# Check if the network is created by DCNM.
query_net = self.get_network(net.get('id'))
if query_net.result != constants.SUBNET_PENDING:
LOG.info('Subnet exists, returning')
return # depends on [control=['if'], data=[]]
if query_net and query_net.source.lower() == 'dcnm':
# The network is created by DCNM.
# No need to process this event.
LOG.info('create_subnet: network %(name)s was created by DCNM. Ignoring processing the event.', {'name': query_net.name})
return # depends on [control=['if'], data=[]]
tenant_name = self.get_project_name(snet['tenant_id'])
subnet = utils.Dict2Obj(snet)
dcnm_net = utils.Dict2Obj(net)
if not tenant_name:
LOG.error('Project %(tenant_id)s does not exist.', {'tenant_id': subnet.tenant_id})
self.update_network_db(dcnm_net.id, constants.CREATE_FAIL)
return # depends on [control=['if'], data=[]]
try:
self.dcnm_client.create_network(tenant_name, dcnm_net, subnet, self.dcnm_dhcp)
self.update_network_db(net.get('id'), constants.RESULT_SUCCESS) # depends on [control=['try'], data=[]]
except dexc.DfaClientRequestFailed:
LOG.exception('Failed to create network %(net)s.', {'net': dcnm_net.name})
# Update network database with failure result.
self.update_network_db(dcnm_net.id, constants.CREATE_FAIL) # depends on [control=['except'], data=[]]
self.network_sub_create_notif(snet.get('tenant_id'), tenant_name, snet.get('cidr'))
|
def _comparator_presence(_, tested_value):
"""
Tests a filter which simply a joker, i.e. a value presence test
"""
# The filter value is a joker : simple presence test
if tested_value is None:
return False
elif hasattr(tested_value, "__len__"):
# Refuse empty values
# pylint: disable=C1801
return len(tested_value) != 0
# Presence validated
return True
|
def function[_comparator_presence, parameter[_, tested_value]]:
constant[
Tests a filter which simply a joker, i.e. a value presence test
]
if compare[name[tested_value] is constant[None]] begin[:]
return[constant[False]]
return[constant[True]]
|
keyword[def] identifier[_comparator_presence] ( identifier[_] , identifier[tested_value] ):
literal[string]
keyword[if] identifier[tested_value] keyword[is] keyword[None] :
keyword[return] keyword[False]
keyword[elif] identifier[hasattr] ( identifier[tested_value] , literal[string] ):
keyword[return] identifier[len] ( identifier[tested_value] )!= literal[int]
keyword[return] keyword[True]
|
def _comparator_presence(_, tested_value):
"""
Tests a filter which simply a joker, i.e. a value presence test
"""
# The filter value is a joker : simple presence test
if tested_value is None:
return False # depends on [control=['if'], data=[]]
elif hasattr(tested_value, '__len__'):
# Refuse empty values
# pylint: disable=C1801
return len(tested_value) != 0 # depends on [control=['if'], data=[]]
# Presence validated
return True
|
def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError("Unable to download file")
with open(filename, "wb") as f:
f.write(r.content)
|
def function[download_file, parameter[url, filename]]:
constant[Downloads file from url to a path with filename]
variable[r] assign[=] call[call[name[_get_requests_session], parameter[]].get, parameter[name[url]]]
if <ast.UnaryOp object at 0x7da18ede5840> begin[:]
<ast.Raise object at 0x7da18ede5660>
with call[name[open], parameter[name[filename], constant[wb]]] begin[:]
call[name[f].write, parameter[name[r].content]]
|
keyword[def] identifier[download_file] ( identifier[url] , identifier[filename] ):
literal[string]
identifier[r] = identifier[_get_requests_session] (). identifier[get] ( identifier[url] , identifier[stream] = keyword[True] )
keyword[if] keyword[not] identifier[r] . identifier[ok] :
keyword[raise] identifier[IOError] ( literal[string] )
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[f] :
identifier[f] . identifier[write] ( identifier[r] . identifier[content] )
|
def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError('Unable to download file') # depends on [control=['if'], data=[]]
with open(filename, 'wb') as f:
f.write(r.content) # depends on [control=['with'], data=['f']]
|
def format_dict_to_str(dict, format):
"""
Format a dictionary to the string, param format is a specified format rule
such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-'
so result is 'name-Sylvanas, gender-Boy'.
>>> dict = {'name': 'Sylvanas', 'gender': 'Boy'}
>>> format_dict_to_str(dict, format='-')
'name-Sylvanas, gender-Boy'
"""
result = ''
for k, v in dict.items():
result = result + str(k) + format + str(v) + ', '
return result[:-2]
|
def function[format_dict_to_str, parameter[dict, format]]:
constant[
Format a dictionary to the string, param format is a specified format rule
such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-'
so result is 'name-Sylvanas, gender-Boy'.
>>> dict = {'name': 'Sylvanas', 'gender': 'Boy'}
>>> format_dict_to_str(dict, format='-')
'name-Sylvanas, gender-Boy'
]
variable[result] assign[=] constant[]
for taget[tuple[[<ast.Name object at 0x7da204346f20>, <ast.Name object at 0x7da18f09d150>]]] in starred[call[name[dict].items, parameter[]]] begin[:]
variable[result] assign[=] binary_operation[binary_operation[binary_operation[binary_operation[name[result] + call[name[str], parameter[name[k]]]] + name[format]] + call[name[str], parameter[name[v]]]] + constant[, ]]
return[call[name[result]][<ast.Slice object at 0x7da18f09f700>]]
|
keyword[def] identifier[format_dict_to_str] ( identifier[dict] , identifier[format] ):
literal[string]
identifier[result] = literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[dict] . identifier[items] ():
identifier[result] = identifier[result] + identifier[str] ( identifier[k] )+ identifier[format] + identifier[str] ( identifier[v] )+ literal[string]
keyword[return] identifier[result] [:- literal[int] ]
|
def format_dict_to_str(dict, format):
"""
Format a dictionary to the string, param format is a specified format rule
such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-'
so result is 'name-Sylvanas, gender-Boy'.
>>> dict = {'name': 'Sylvanas', 'gender': 'Boy'}
>>> format_dict_to_str(dict, format='-')
'name-Sylvanas, gender-Boy'
"""
result = ''
for (k, v) in dict.items():
result = result + str(k) + format + str(v) + ', ' # depends on [control=['for'], data=[]]
return result[:-2]
|
def make_index_unique(index: pd.Index, join: str = '-'):
"""Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.AnnData(np.ones((3, 2)), {'obs_names': ['a', 'b', 'c']})
>>> adata2 = sc.AnnData(np.zeros((3, 2)), {'obs_names': ['d', 'b', 'b']})
>>> adata = adata1.concatenate(adata2)
>>> adata.obs_names
Index(['a', 'b', 'c', 'd', 'b', 'b'], dtype='object')
>>> adata.obs_names_make_unique()
>>> adata.obs_names
Index(['a', 'b', 'c', 'd', 'b-1', 'b-2'], dtype='object')
"""
if index.is_unique:
return index
from collections import defaultdict
values = index.values
indices_dup = index.duplicated(keep='first')
values_dup = values[indices_dup]
counter = defaultdict(lambda: 0)
for i, v in enumerate(values_dup):
counter[v] += 1
values_dup[i] += join + str(counter[v])
values[indices_dup] = values_dup
index = pd.Index(values)
return index
|
def function[make_index_unique, parameter[index, join]]:
constant[Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.AnnData(np.ones((3, 2)), {'obs_names': ['a', 'b', 'c']})
>>> adata2 = sc.AnnData(np.zeros((3, 2)), {'obs_names': ['d', 'b', 'b']})
>>> adata = adata1.concatenate(adata2)
>>> adata.obs_names
Index(['a', 'b', 'c', 'd', 'b', 'b'], dtype='object')
>>> adata.obs_names_make_unique()
>>> adata.obs_names
Index(['a', 'b', 'c', 'd', 'b-1', 'b-2'], dtype='object')
]
if name[index].is_unique begin[:]
return[name[index]]
from relative_module[collections] import module[defaultdict]
variable[values] assign[=] name[index].values
variable[indices_dup] assign[=] call[name[index].duplicated, parameter[]]
variable[values_dup] assign[=] call[name[values]][name[indices_dup]]
variable[counter] assign[=] call[name[defaultdict], parameter[<ast.Lambda object at 0x7da1b206b850>]]
for taget[tuple[[<ast.Name object at 0x7da1b206ba00>, <ast.Name object at 0x7da1b20690c0>]]] in starred[call[name[enumerate], parameter[name[values_dup]]]] begin[:]
<ast.AugAssign object at 0x7da1b206b9a0>
<ast.AugAssign object at 0x7da1b206b2e0>
call[name[values]][name[indices_dup]] assign[=] name[values_dup]
variable[index] assign[=] call[name[pd].Index, parameter[name[values]]]
return[name[index]]
|
keyword[def] identifier[make_index_unique] ( identifier[index] : identifier[pd] . identifier[Index] , identifier[join] : identifier[str] = literal[string] ):
literal[string]
keyword[if] identifier[index] . identifier[is_unique] :
keyword[return] identifier[index]
keyword[from] identifier[collections] keyword[import] identifier[defaultdict]
identifier[values] = identifier[index] . identifier[values]
identifier[indices_dup] = identifier[index] . identifier[duplicated] ( identifier[keep] = literal[string] )
identifier[values_dup] = identifier[values] [ identifier[indices_dup] ]
identifier[counter] = identifier[defaultdict] ( keyword[lambda] : literal[int] )
keyword[for] identifier[i] , identifier[v] keyword[in] identifier[enumerate] ( identifier[values_dup] ):
identifier[counter] [ identifier[v] ]+= literal[int]
identifier[values_dup] [ identifier[i] ]+= identifier[join] + identifier[str] ( identifier[counter] [ identifier[v] ])
identifier[values] [ identifier[indices_dup] ]= identifier[values_dup]
identifier[index] = identifier[pd] . identifier[Index] ( identifier[values] )
keyword[return] identifier[index]
|
def make_index_unique(index: pd.Index, join: str='-'):
"""Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.AnnData(np.ones((3, 2)), {'obs_names': ['a', 'b', 'c']})
>>> adata2 = sc.AnnData(np.zeros((3, 2)), {'obs_names': ['d', 'b', 'b']})
>>> adata = adata1.concatenate(adata2)
>>> adata.obs_names
Index(['a', 'b', 'c', 'd', 'b', 'b'], dtype='object')
>>> adata.obs_names_make_unique()
>>> adata.obs_names
Index(['a', 'b', 'c', 'd', 'b-1', 'b-2'], dtype='object')
"""
if index.is_unique:
return index # depends on [control=['if'], data=[]]
from collections import defaultdict
values = index.values
indices_dup = index.duplicated(keep='first')
values_dup = values[indices_dup]
counter = defaultdict(lambda : 0)
for (i, v) in enumerate(values_dup):
counter[v] += 1
values_dup[i] += join + str(counter[v]) # depends on [control=['for'], data=[]]
values[indices_dup] = values_dup
index = pd.Index(values)
return index
|
def remote_url(self, remotename='origin'):
"""
Determine the primary remote url for this Repository
Returns:
str: primary remote url for this Repository
(``git config remote.origin.url``)
"""
cmd = ['git', 'config', 'remote.%s.url' % remotename]
return self.sh(cmd, shell=False,
ignore_error=True).strip()
|
def function[remote_url, parameter[self, remotename]]:
constant[
Determine the primary remote url for this Repository
Returns:
str: primary remote url for this Repository
(``git config remote.origin.url``)
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b0804280>, <ast.Constant object at 0x7da1b0804460>, <ast.BinOp object at 0x7da1b08075e0>]]
return[call[call[name[self].sh, parameter[name[cmd]]].strip, parameter[]]]
|
keyword[def] identifier[remote_url] ( identifier[self] , identifier[remotename] = literal[string] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] % identifier[remotename] ]
keyword[return] identifier[self] . identifier[sh] ( identifier[cmd] , identifier[shell] = keyword[False] ,
identifier[ignore_error] = keyword[True] ). identifier[strip] ()
|
def remote_url(self, remotename='origin'):
"""
Determine the primary remote url for this Repository
Returns:
str: primary remote url for this Repository
(``git config remote.origin.url``)
"""
cmd = ['git', 'config', 'remote.%s.url' % remotename]
return self.sh(cmd, shell=False, ignore_error=True).strip()
|
def symlink_to(orig, dest):
"""Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
"""
if is_windows:
import subprocess
subprocess.check_call(
["mklink", "/d", path2str(orig), path2str(dest)], shell=True
)
else:
orig.symlink_to(dest)
|
def function[symlink_to, parameter[orig, dest]]:
constant[Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
]
if name[is_windows] begin[:]
import module[subprocess]
call[name[subprocess].check_call, parameter[list[[<ast.Constant object at 0x7da1b1ef9d50>, <ast.Constant object at 0x7da1b1ef9ff0>, <ast.Call object at 0x7da1b1efac20>, <ast.Call object at 0x7da1b1ef8970>]]]]
|
keyword[def] identifier[symlink_to] ( identifier[orig] , identifier[dest] ):
literal[string]
keyword[if] identifier[is_windows] :
keyword[import] identifier[subprocess]
identifier[subprocess] . identifier[check_call] (
[ literal[string] , literal[string] , identifier[path2str] ( identifier[orig] ), identifier[path2str] ( identifier[dest] )], identifier[shell] = keyword[True]
)
keyword[else] :
identifier[orig] . identifier[symlink_to] ( identifier[dest] )
|
def symlink_to(orig, dest):
"""Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
"""
if is_windows:
import subprocess
subprocess.check_call(['mklink', '/d', path2str(orig), path2str(dest)], shell=True) # depends on [control=['if'], data=[]]
else:
orig.symlink_to(dest)
|
def get_panels(self):
"""Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
"""
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(panel_group)
return all_panels
|
def function[get_panels, parameter[self]]:
constant[Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
]
variable[all_panels] assign[=] list[[]]
variable[panel_groups] assign[=] call[name[self].get_panel_groups, parameter[]]
for taget[name[panel_group]] in starred[call[name[panel_groups].values, parameter[]]] begin[:]
call[name[all_panels].extend, parameter[name[panel_group]]]
return[name[all_panels]]
|
keyword[def] identifier[get_panels] ( identifier[self] ):
literal[string]
identifier[all_panels] =[]
identifier[panel_groups] = identifier[self] . identifier[get_panel_groups] ()
keyword[for] identifier[panel_group] keyword[in] identifier[panel_groups] . identifier[values] ():
identifier[all_panels] . identifier[extend] ( identifier[panel_group] )
keyword[return] identifier[all_panels]
|
def get_panels(self):
"""Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
"""
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(panel_group) # depends on [control=['for'], data=['panel_group']]
return all_panels
|
def make_relative(cls, course_locator, block_type, block_id):
"""
Return a new instance which has the given block_id in the given course
:param course_locator: may be a BlockUsageLocator in the same snapshot
"""
if hasattr(course_locator, 'course_key'):
course_locator = course_locator.course_key
return course_locator.make_usage_key(
block_type=block_type,
block_id=block_id
)
|
def function[make_relative, parameter[cls, course_locator, block_type, block_id]]:
constant[
Return a new instance which has the given block_id in the given course
:param course_locator: may be a BlockUsageLocator in the same snapshot
]
if call[name[hasattr], parameter[name[course_locator], constant[course_key]]] begin[:]
variable[course_locator] assign[=] name[course_locator].course_key
return[call[name[course_locator].make_usage_key, parameter[]]]
|
keyword[def] identifier[make_relative] ( identifier[cls] , identifier[course_locator] , identifier[block_type] , identifier[block_id] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[course_locator] , literal[string] ):
identifier[course_locator] = identifier[course_locator] . identifier[course_key]
keyword[return] identifier[course_locator] . identifier[make_usage_key] (
identifier[block_type] = identifier[block_type] ,
identifier[block_id] = identifier[block_id]
)
|
def make_relative(cls, course_locator, block_type, block_id):
"""
Return a new instance which has the given block_id in the given course
:param course_locator: may be a BlockUsageLocator in the same snapshot
"""
if hasattr(course_locator, 'course_key'):
course_locator = course_locator.course_key # depends on [control=['if'], data=[]]
return course_locator.make_usage_key(block_type=block_type, block_id=block_id)
|
def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None
|
def function[find_device_by_name, parameter[name]]:
constant[Tries to find a board by board name.]
if <ast.UnaryOp object at 0x7da2047ebe50> begin[:]
return[name[DEFAULT_DEV]]
with name[DEV_LOCK] begin[:]
for taget[name[dev]] in starred[name[DEVS]] begin[:]
if compare[name[dev].name equal[==] name[name]] begin[:]
return[name[dev]]
return[constant[None]]
|
keyword[def] identifier[find_device_by_name] ( identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[name] :
keyword[return] identifier[DEFAULT_DEV]
keyword[with] identifier[DEV_LOCK] :
keyword[for] identifier[dev] keyword[in] identifier[DEVS] :
keyword[if] identifier[dev] . identifier[name] == identifier[name] :
keyword[return] identifier[dev]
keyword[return] keyword[None]
|
def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV # depends on [control=['if'], data=[]]
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['dev']] # depends on [control=['with'], data=[]]
return None
|
def addImage(self, image, mask=None):
'''
#########
mask -- optional
'''
self._last_diff = diff = image - self.noSTE
ste = diff > self.threshold
removeSinglePixels(ste)
self.mask_clean = clean = ~ste
if mask is not None:
clean = np.logical_and(mask, clean)
self.mma.update(image, clean)
if self.save_ste_indices:
self.mask_STE += ste
return self
|
def function[addImage, parameter[self, image, mask]]:
constant[
#########
mask -- optional
]
name[self]._last_diff assign[=] binary_operation[name[image] - name[self].noSTE]
variable[ste] assign[=] compare[name[diff] greater[>] name[self].threshold]
call[name[removeSinglePixels], parameter[name[ste]]]
name[self].mask_clean assign[=] <ast.UnaryOp object at 0x7da204623220>
if compare[name[mask] is_not constant[None]] begin[:]
variable[clean] assign[=] call[name[np].logical_and, parameter[name[mask], name[clean]]]
call[name[self].mma.update, parameter[name[image], name[clean]]]
if name[self].save_ste_indices begin[:]
<ast.AugAssign object at 0x7da204620cd0>
return[name[self]]
|
keyword[def] identifier[addImage] ( identifier[self] , identifier[image] , identifier[mask] = keyword[None] ):
literal[string]
identifier[self] . identifier[_last_diff] = identifier[diff] = identifier[image] - identifier[self] . identifier[noSTE]
identifier[ste] = identifier[diff] > identifier[self] . identifier[threshold]
identifier[removeSinglePixels] ( identifier[ste] )
identifier[self] . identifier[mask_clean] = identifier[clean] =~ identifier[ste]
keyword[if] identifier[mask] keyword[is] keyword[not] keyword[None] :
identifier[clean] = identifier[np] . identifier[logical_and] ( identifier[mask] , identifier[clean] )
identifier[self] . identifier[mma] . identifier[update] ( identifier[image] , identifier[clean] )
keyword[if] identifier[self] . identifier[save_ste_indices] :
identifier[self] . identifier[mask_STE] += identifier[ste]
keyword[return] identifier[self]
|
def addImage(self, image, mask=None):
"""
#########
mask -- optional
"""
self._last_diff = diff = image - self.noSTE
ste = diff > self.threshold
removeSinglePixels(ste)
self.mask_clean = clean = ~ste
if mask is not None:
clean = np.logical_and(mask, clean) # depends on [control=['if'], data=['mask']]
self.mma.update(image, clean)
if self.save_ste_indices:
self.mask_STE += ste # depends on [control=['if'], data=[]]
return self
|
def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Args:
response (Response): The dictionary object to convert into a json
object. If the value is a string, a dictionary is created with the
key "message".
headers (dict): optional headers for the flask response.
encoder (Class): The class of the encoder (if any).
Returns:
flask.Response: The flask response with formatted data, headers, and
mimetype.
"""
status_code = response.status
data = response.errors or response.message
mimetype = 'text/plain'
if isinstance(data, list) or isinstance(data, dict):
mimetype = 'application/json'
data = json.dumps(data, cls=encoder)
return flask.Response(
response=data, status=status_code, headers=headers, mimetype=mimetype)
|
def function[flaskify, parameter[response, headers, encoder]]:
constant[Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Args:
response (Response): The dictionary object to convert into a json
object. If the value is a string, a dictionary is created with the
key "message".
headers (dict): optional headers for the flask response.
encoder (Class): The class of the encoder (if any).
Returns:
flask.Response: The flask response with formatted data, headers, and
mimetype.
]
variable[status_code] assign[=] name[response].status
variable[data] assign[=] <ast.BoolOp object at 0x7da1b15d4880>
variable[mimetype] assign[=] constant[text/plain]
if <ast.BoolOp object at 0x7da1b15d4e80> begin[:]
variable[mimetype] assign[=] constant[application/json]
variable[data] assign[=] call[name[json].dumps, parameter[name[data]]]
return[call[name[flask].Response, parameter[]]]
|
keyword[def] identifier[flaskify] ( identifier[response] , identifier[headers] = keyword[None] , identifier[encoder] = keyword[None] ):
literal[string]
identifier[status_code] = identifier[response] . identifier[status]
identifier[data] = identifier[response] . identifier[errors] keyword[or] identifier[response] . identifier[message]
identifier[mimetype] = literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[list] ) keyword[or] identifier[isinstance] ( identifier[data] , identifier[dict] ):
identifier[mimetype] = literal[string]
identifier[data] = identifier[json] . identifier[dumps] ( identifier[data] , identifier[cls] = identifier[encoder] )
keyword[return] identifier[flask] . identifier[Response] (
identifier[response] = identifier[data] , identifier[status] = identifier[status_code] , identifier[headers] = identifier[headers] , identifier[mimetype] = identifier[mimetype] )
|
def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Args:
response (Response): The dictionary object to convert into a json
object. If the value is a string, a dictionary is created with the
key "message".
headers (dict): optional headers for the flask response.
encoder (Class): The class of the encoder (if any).
Returns:
flask.Response: The flask response with formatted data, headers, and
mimetype.
"""
status_code = response.status
data = response.errors or response.message
mimetype = 'text/plain'
if isinstance(data, list) or isinstance(data, dict):
mimetype = 'application/json'
data = json.dumps(data, cls=encoder) # depends on [control=['if'], data=[]]
return flask.Response(response=data, status=status_code, headers=headers, mimetype=mimetype)
|
def catch_osd_errors(conn, logger, args):
"""
Look for possible issues when checking the status of an OSD and
report them back to the user.
"""
logger.info('checking OSD status...')
status = osd_status_check(conn, args.cluster)
osds = int(status.get('num_osds', 0))
up_osds = int(status.get('num_up_osds', 0))
in_osds = int(status.get('num_in_osds', 0))
full = status.get('full', False)
nearfull = status.get('nearfull', False)
if osds > up_osds:
difference = osds - up_osds
logger.warning('there %s %d OSD%s down' % (
['is', 'are'][difference != 1],
difference,
"s"[difference == 1:])
)
if osds > in_osds:
difference = osds - in_osds
logger.warning('there %s %d OSD%s out' % (
['is', 'are'][difference != 1],
difference,
"s"[difference == 1:])
)
if full:
logger.warning('OSDs are full!')
if nearfull:
logger.warning('OSDs are near full!')
|
def function[catch_osd_errors, parameter[conn, logger, args]]:
constant[
Look for possible issues when checking the status of an OSD and
report them back to the user.
]
call[name[logger].info, parameter[constant[checking OSD status...]]]
variable[status] assign[=] call[name[osd_status_check], parameter[name[conn], name[args].cluster]]
variable[osds] assign[=] call[name[int], parameter[call[name[status].get, parameter[constant[num_osds], constant[0]]]]]
variable[up_osds] assign[=] call[name[int], parameter[call[name[status].get, parameter[constant[num_up_osds], constant[0]]]]]
variable[in_osds] assign[=] call[name[int], parameter[call[name[status].get, parameter[constant[num_in_osds], constant[0]]]]]
variable[full] assign[=] call[name[status].get, parameter[constant[full], constant[False]]]
variable[nearfull] assign[=] call[name[status].get, parameter[constant[nearfull], constant[False]]]
if compare[name[osds] greater[>] name[up_osds]] begin[:]
variable[difference] assign[=] binary_operation[name[osds] - name[up_osds]]
call[name[logger].warning, parameter[binary_operation[constant[there %s %d OSD%s down] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Subscript object at 0x7da1b16b6860>, <ast.Name object at 0x7da204566470>, <ast.Subscript object at 0x7da1b16bd570>]]]]]
if compare[name[osds] greater[>] name[in_osds]] begin[:]
variable[difference] assign[=] binary_operation[name[osds] - name[in_osds]]
call[name[logger].warning, parameter[binary_operation[constant[there %s %d OSD%s out] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Subscript object at 0x7da1b16bc3a0>, <ast.Name object at 0x7da1b16bc6d0>, <ast.Subscript object at 0x7da1b16bf340>]]]]]
if name[full] begin[:]
call[name[logger].warning, parameter[constant[OSDs are full!]]]
if name[nearfull] begin[:]
call[name[logger].warning, parameter[constant[OSDs are near full!]]]
|
keyword[def] identifier[catch_osd_errors] ( identifier[conn] , identifier[logger] , identifier[args] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[status] = identifier[osd_status_check] ( identifier[conn] , identifier[args] . identifier[cluster] )
identifier[osds] = identifier[int] ( identifier[status] . identifier[get] ( literal[string] , literal[int] ))
identifier[up_osds] = identifier[int] ( identifier[status] . identifier[get] ( literal[string] , literal[int] ))
identifier[in_osds] = identifier[int] ( identifier[status] . identifier[get] ( literal[string] , literal[int] ))
identifier[full] = identifier[status] . identifier[get] ( literal[string] , keyword[False] )
identifier[nearfull] = identifier[status] . identifier[get] ( literal[string] , keyword[False] )
keyword[if] identifier[osds] > identifier[up_osds] :
identifier[difference] = identifier[osds] - identifier[up_osds]
identifier[logger] . identifier[warning] ( literal[string] %(
[ literal[string] , literal[string] ][ identifier[difference] != literal[int] ],
identifier[difference] ,
literal[string] [ identifier[difference] == literal[int] :])
)
keyword[if] identifier[osds] > identifier[in_osds] :
identifier[difference] = identifier[osds] - identifier[in_osds]
identifier[logger] . identifier[warning] ( literal[string] %(
[ literal[string] , literal[string] ][ identifier[difference] != literal[int] ],
identifier[difference] ,
literal[string] [ identifier[difference] == literal[int] :])
)
keyword[if] identifier[full] :
identifier[logger] . identifier[warning] ( literal[string] )
keyword[if] identifier[nearfull] :
identifier[logger] . identifier[warning] ( literal[string] )
|
def catch_osd_errors(conn, logger, args):
"""
Look for possible issues when checking the status of an OSD and
report them back to the user.
"""
logger.info('checking OSD status...')
status = osd_status_check(conn, args.cluster)
osds = int(status.get('num_osds', 0))
up_osds = int(status.get('num_up_osds', 0))
in_osds = int(status.get('num_in_osds', 0))
full = status.get('full', False)
nearfull = status.get('nearfull', False)
if osds > up_osds:
difference = osds - up_osds
logger.warning('there %s %d OSD%s down' % (['is', 'are'][difference != 1], difference, 's'[difference == 1:])) # depends on [control=['if'], data=['osds', 'up_osds']]
if osds > in_osds:
difference = osds - in_osds
logger.warning('there %s %d OSD%s out' % (['is', 'are'][difference != 1], difference, 's'[difference == 1:])) # depends on [control=['if'], data=['osds', 'in_osds']]
if full:
logger.warning('OSDs are full!') # depends on [control=['if'], data=[]]
if nearfull:
logger.warning('OSDs are near full!') # depends on [control=['if'], data=[]]
|
def to_dict(self):
"""Convert back to the pstats dictionary representation (used for saving back as pstats binary file)"""
if self.subcall is not None:
if isinstance(self.subcall, dict):
subcalls = self.subcall
else:
subcalls = {}
for s in self.subcall:
subcalls.update(s.to_dict())
return {(self.filename, self.line_number, self.name): \
(self.ncalls, self.nonrecursive_calls, self.own_time_s, self.cummulative_time_s, subcalls)}
else:
return {(self.filename, self.line_number, self.name): \
(self.ncalls, self.nonrecursive_calls, self.own_time_s, self.cummulative_time_s)}
|
def function[to_dict, parameter[self]]:
constant[Convert back to the pstats dictionary representation (used for saving back as pstats binary file)]
if compare[name[self].subcall is_not constant[None]] begin[:]
if call[name[isinstance], parameter[name[self].subcall, name[dict]]] begin[:]
variable[subcalls] assign[=] name[self].subcall
return[dictionary[[<ast.Tuple object at 0x7da1b0bda260>], [<ast.Tuple object at 0x7da1b0bda140>]]]
|
keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[subcall] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[isinstance] ( identifier[self] . identifier[subcall] , identifier[dict] ):
identifier[subcalls] = identifier[self] . identifier[subcall]
keyword[else] :
identifier[subcalls] ={}
keyword[for] identifier[s] keyword[in] identifier[self] . identifier[subcall] :
identifier[subcalls] . identifier[update] ( identifier[s] . identifier[to_dict] ())
keyword[return] {( identifier[self] . identifier[filename] , identifier[self] . identifier[line_number] , identifier[self] . identifier[name] ):( identifier[self] . identifier[ncalls] , identifier[self] . identifier[nonrecursive_calls] , identifier[self] . identifier[own_time_s] , identifier[self] . identifier[cummulative_time_s] , identifier[subcalls] )}
keyword[else] :
keyword[return] {( identifier[self] . identifier[filename] , identifier[self] . identifier[line_number] , identifier[self] . identifier[name] ):( identifier[self] . identifier[ncalls] , identifier[self] . identifier[nonrecursive_calls] , identifier[self] . identifier[own_time_s] , identifier[self] . identifier[cummulative_time_s] )}
|
def to_dict(self):
"""Convert back to the pstats dictionary representation (used for saving back as pstats binary file)"""
if self.subcall is not None:
if isinstance(self.subcall, dict):
subcalls = self.subcall # depends on [control=['if'], data=[]]
else:
subcalls = {}
for s in self.subcall:
subcalls.update(s.to_dict()) # depends on [control=['for'], data=['s']]
return {(self.filename, self.line_number, self.name): (self.ncalls, self.nonrecursive_calls, self.own_time_s, self.cummulative_time_s, subcalls)} # depends on [control=['if'], data=[]]
else:
return {(self.filename, self.line_number, self.name): (self.ncalls, self.nonrecursive_calls, self.own_time_s, self.cummulative_time_s)}
|
def QA_util_get_trade_datetime(dt=datetime.datetime.now()):
"""交易的真实日期
Returns:
[type] -- [description]
"""
#dt= datetime.datetime.now()
if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0):
return str(dt.date())
else:
return QA_util_get_real_date(str(dt.date()), trade_date_sse, 1)
|
def function[QA_util_get_trade_datetime, parameter[dt]]:
constant[交易的真实日期
Returns:
[type] -- [description]
]
if <ast.BoolOp object at 0x7da1b1f770d0> begin[:]
return[call[name[str], parameter[call[name[dt].date, parameter[]]]]]
|
keyword[def] identifier[QA_util_get_trade_datetime] ( identifier[dt] = identifier[datetime] . identifier[datetime] . identifier[now] ()):
literal[string]
keyword[if] identifier[QA_util_if_trade] ( identifier[str] ( identifier[dt] . identifier[date] ())) keyword[and] identifier[dt] . identifier[time] ()< identifier[datetime] . identifier[time] ( literal[int] , literal[int] , literal[int] ):
keyword[return] identifier[str] ( identifier[dt] . identifier[date] ())
keyword[else] :
keyword[return] identifier[QA_util_get_real_date] ( identifier[str] ( identifier[dt] . identifier[date] ()), identifier[trade_date_sse] , literal[int] )
|
def QA_util_get_trade_datetime(dt=datetime.datetime.now()):
"""交易的真实日期
Returns:
[type] -- [description]
"""
#dt= datetime.datetime.now()
if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0):
return str(dt.date()) # depends on [control=['if'], data=[]]
else:
return QA_util_get_real_date(str(dt.date()), trade_date_sse, 1)
|
def calc_dewpoint(temp, hum):
'''
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
'''
c = fahrenheit_to_celsius(temp)
x = 1 - 0.01 * hum;
dewpoint = (14.55 + 0.114 * c) * x;
dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3;
dewpoint = dewpoint + (15.9 + 0.117 * c) * x ** 14;
dewpoint = c - dewpoint;
return celsius_to_fahrenheit(dewpoint)
|
def function[calc_dewpoint, parameter[temp, hum]]:
constant[
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
]
variable[c] assign[=] call[name[fahrenheit_to_celsius], parameter[name[temp]]]
variable[x] assign[=] binary_operation[constant[1] - binary_operation[constant[0.01] * name[hum]]]
variable[dewpoint] assign[=] binary_operation[binary_operation[constant[14.55] + binary_operation[constant[0.114] * name[c]]] * name[x]]
variable[dewpoint] assign[=] binary_operation[name[dewpoint] + binary_operation[binary_operation[binary_operation[constant[2.5] + binary_operation[constant[0.007] * name[c]]] * name[x]] ** constant[3]]]
variable[dewpoint] assign[=] binary_operation[name[dewpoint] + binary_operation[binary_operation[constant[15.9] + binary_operation[constant[0.117] * name[c]]] * binary_operation[name[x] ** constant[14]]]]
variable[dewpoint] assign[=] binary_operation[name[c] - name[dewpoint]]
return[call[name[celsius_to_fahrenheit], parameter[name[dewpoint]]]]
|
keyword[def] identifier[calc_dewpoint] ( identifier[temp] , identifier[hum] ):
literal[string]
identifier[c] = identifier[fahrenheit_to_celsius] ( identifier[temp] )
identifier[x] = literal[int] - literal[int] * identifier[hum] ;
identifier[dewpoint] =( literal[int] + literal[int] * identifier[c] )* identifier[x] ;
identifier[dewpoint] = identifier[dewpoint] +(( literal[int] + literal[int] * identifier[c] )* identifier[x] )** literal[int] ;
identifier[dewpoint] = identifier[dewpoint] +( literal[int] + literal[int] * identifier[c] )* identifier[x] ** literal[int] ;
identifier[dewpoint] = identifier[c] - identifier[dewpoint] ;
keyword[return] identifier[celsius_to_fahrenheit] ( identifier[dewpoint] )
|
def calc_dewpoint(temp, hum):
"""
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
"""
c = fahrenheit_to_celsius(temp)
x = 1 - 0.01 * hum
dewpoint = (14.55 + 0.114 * c) * x
dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3
dewpoint = dewpoint + (15.9 + 0.117 * c) * x ** 14
dewpoint = c - dewpoint
return celsius_to_fahrenheit(dewpoint)
|
def get_objective_requisite_assignment_session(self, *args, **kwargs):
"""Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request
raise: Unimplemented -
supports_objective_requisite_assignment() is false
compliance: optional - This method must be implemented if
supports_objective_requisite_assignment() is true.
"""
if not self.supports_objective_requisite_assignment():
raise Unimplemented()
try:
from . import sessions
except ImportError:
raise OperationFailed()
try:
session = sessions.ObjectiveRequisiteAssignmentSession(runtime=self._runtime)
except AttributeError:
raise OperationFailed()
return session
|
def function[get_objective_requisite_assignment_session, parameter[self]]:
constant[Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request
raise: Unimplemented -
supports_objective_requisite_assignment() is false
compliance: optional - This method must be implemented if
supports_objective_requisite_assignment() is true.
]
if <ast.UnaryOp object at 0x7da1b0a20400> begin[:]
<ast.Raise object at 0x7da1b0a21840>
<ast.Try object at 0x7da1b0a21600>
<ast.Try object at 0x7da1b092ebc0>
return[name[session]]
|
keyword[def] identifier[get_objective_requisite_assignment_session] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_objective_requisite_assignment] ():
keyword[raise] identifier[Unimplemented] ()
keyword[try] :
keyword[from] . keyword[import] identifier[sessions]
keyword[except] identifier[ImportError] :
keyword[raise] identifier[OperationFailed] ()
keyword[try] :
identifier[session] = identifier[sessions] . identifier[ObjectiveRequisiteAssignmentSession] ( identifier[runtime] = identifier[self] . identifier[_runtime] )
keyword[except] identifier[AttributeError] :
keyword[raise] identifier[OperationFailed] ()
keyword[return] identifier[session]
|
def get_objective_requisite_assignment_session(self, *args, **kwargs):
"""Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request
raise: Unimplemented -
supports_objective_requisite_assignment() is false
compliance: optional - This method must be implemented if
supports_objective_requisite_assignment() is true.
"""
if not self.supports_objective_requisite_assignment():
raise Unimplemented() # depends on [control=['if'], data=[]]
try:
from . import sessions # depends on [control=['try'], data=[]]
except ImportError:
raise OperationFailed() # depends on [control=['except'], data=[]]
try:
session = sessions.ObjectiveRequisiteAssignmentSession(runtime=self._runtime) # depends on [control=['try'], data=[]]
except AttributeError:
raise OperationFailed() # depends on [control=['except'], data=[]]
return session
|
def _get_9q_square_qvm(name: str, noisy: bool,
connection: ForestConnection = None,
qvm_type: str = 'qvm') -> QuantumComputer:
"""
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough to simulate quickly.
:param name: The name of this QVM
:param connection: The connection to use to talk to external services
:param noisy: Whether to construct a noisy quantum computer
:param qvm_type: The type of QVM. Either 'qvm' or 'pyqvm'.
:return: A pre-configured QuantumComputer
"""
topology = nx.convert_node_labels_to_integers(nx.grid_2d_graph(3, 3))
return _get_qvm_with_topology(name=name, connection=connection,
topology=topology,
noisy=noisy,
requires_executable=True,
qvm_type=qvm_type)
|
def function[_get_9q_square_qvm, parameter[name, noisy, connection, qvm_type]]:
constant[
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough to simulate quickly.
:param name: The name of this QVM
:param connection: The connection to use to talk to external services
:param noisy: Whether to construct a noisy quantum computer
:param qvm_type: The type of QVM. Either 'qvm' or 'pyqvm'.
:return: A pre-configured QuantumComputer
]
variable[topology] assign[=] call[name[nx].convert_node_labels_to_integers, parameter[call[name[nx].grid_2d_graph, parameter[constant[3], constant[3]]]]]
return[call[name[_get_qvm_with_topology], parameter[]]]
|
keyword[def] identifier[_get_9q_square_qvm] ( identifier[name] : identifier[str] , identifier[noisy] : identifier[bool] ,
identifier[connection] : identifier[ForestConnection] = keyword[None] ,
identifier[qvm_type] : identifier[str] = literal[string] )-> identifier[QuantumComputer] :
literal[string]
identifier[topology] = identifier[nx] . identifier[convert_node_labels_to_integers] ( identifier[nx] . identifier[grid_2d_graph] ( literal[int] , literal[int] ))
keyword[return] identifier[_get_qvm_with_topology] ( identifier[name] = identifier[name] , identifier[connection] = identifier[connection] ,
identifier[topology] = identifier[topology] ,
identifier[noisy] = identifier[noisy] ,
identifier[requires_executable] = keyword[True] ,
identifier[qvm_type] = identifier[qvm_type] )
|
def _get_9q_square_qvm(name: str, noisy: bool, connection: ForestConnection=None, qvm_type: str='qvm') -> QuantumComputer:
"""
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough to simulate quickly.
:param name: The name of this QVM
:param connection: The connection to use to talk to external services
:param noisy: Whether to construct a noisy quantum computer
:param qvm_type: The type of QVM. Either 'qvm' or 'pyqvm'.
:return: A pre-configured QuantumComputer
"""
topology = nx.convert_node_labels_to_integers(nx.grid_2d_graph(3, 3))
return _get_qvm_with_topology(name=name, connection=connection, topology=topology, noisy=noisy, requires_executable=True, qvm_type=qvm_type)
|
def cluster_replicate(self, node_id):
"""Reconfigure a node as a slave of the specified master node."""
fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)
return wait_ok(fut)
|
def function[cluster_replicate, parameter[self, node_id]]:
constant[Reconfigure a node as a slave of the specified master node.]
variable[fut] assign[=] call[name[self].execute, parameter[constant[b'CLUSTER'], constant[b'REPLICATE'], name[node_id]]]
return[call[name[wait_ok], parameter[name[fut]]]]
|
keyword[def] identifier[cluster_replicate] ( identifier[self] , identifier[node_id] ):
literal[string]
identifier[fut] = identifier[self] . identifier[execute] ( literal[string] , literal[string] , identifier[node_id] )
keyword[return] identifier[wait_ok] ( identifier[fut] )
|
def cluster_replicate(self, node_id):
"""Reconfigure a node as a slave of the specified master node."""
fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)
return wait_ok(fut)
|
def _get_specifications(specifications):
"""
Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found
"""
if not specifications or specifications is object:
raise ValueError("No specifications given")
elif inspect.isclass(specifications):
if Provides.USE_MODULE_QUALNAME:
if sys.version_info < (3, 3, 0):
raise ValueError(
"Qualified name capability requires Python 3.3+"
)
# Get the name of the class
if not specifications.__module__:
return [specifications.__qualname__]
return [
"{0}.{1}".format(
specifications.__module__, specifications.__qualname__
)
]
else:
# Legacy behavior
return [specifications.__name__]
elif is_string(specifications):
# Specification name
specifications = specifications.strip()
if not specifications:
raise ValueError("Empty specification given")
return [specifications]
elif isinstance(specifications, (list, tuple)):
# List given: normalize its content
results = []
for specification in specifications:
results.extend(_get_specifications(specification))
return results
else:
raise ValueError(
"Unhandled specifications type : {0}".format(
type(specifications).__name__
)
)
|
def function[_get_specifications, parameter[specifications]]:
constant[
Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found
]
if <ast.BoolOp object at 0x7da18f720520> begin[:]
<ast.Raise object at 0x7da18f722dd0>
|
keyword[def] identifier[_get_specifications] ( identifier[specifications] ):
literal[string]
keyword[if] keyword[not] identifier[specifications] keyword[or] identifier[specifications] keyword[is] identifier[object] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[elif] identifier[inspect] . identifier[isclass] ( identifier[specifications] ):
keyword[if] identifier[Provides] . identifier[USE_MODULE_QUALNAME] :
keyword[if] identifier[sys] . identifier[version_info] <( literal[int] , literal[int] , literal[int] ):
keyword[raise] identifier[ValueError] (
literal[string]
)
keyword[if] keyword[not] identifier[specifications] . identifier[__module__] :
keyword[return] [ identifier[specifications] . identifier[__qualname__] ]
keyword[return] [
literal[string] . identifier[format] (
identifier[specifications] . identifier[__module__] , identifier[specifications] . identifier[__qualname__]
)
]
keyword[else] :
keyword[return] [ identifier[specifications] . identifier[__name__] ]
keyword[elif] identifier[is_string] ( identifier[specifications] ):
identifier[specifications] = identifier[specifications] . identifier[strip] ()
keyword[if] keyword[not] identifier[specifications] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] [ identifier[specifications] ]
keyword[elif] identifier[isinstance] ( identifier[specifications] ,( identifier[list] , identifier[tuple] )):
identifier[results] =[]
keyword[for] identifier[specification] keyword[in] identifier[specifications] :
identifier[results] . identifier[extend] ( identifier[_get_specifications] ( identifier[specification] ))
keyword[return] identifier[results]
keyword[else] :
keyword[raise] identifier[ValueError] (
literal[string] . identifier[format] (
identifier[type] ( identifier[specifications] ). identifier[__name__]
)
)
|
def _get_specifications(specifications):
"""
Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found
"""
if not specifications or specifications is object:
raise ValueError('No specifications given') # depends on [control=['if'], data=[]]
elif inspect.isclass(specifications):
if Provides.USE_MODULE_QUALNAME:
if sys.version_info < (3, 3, 0):
raise ValueError('Qualified name capability requires Python 3.3+') # depends on [control=['if'], data=[]]
# Get the name of the class
if not specifications.__module__:
return [specifications.__qualname__] # depends on [control=['if'], data=[]]
return ['{0}.{1}'.format(specifications.__module__, specifications.__qualname__)] # depends on [control=['if'], data=[]]
else:
# Legacy behavior
return [specifications.__name__] # depends on [control=['if'], data=[]]
elif is_string(specifications):
# Specification name
specifications = specifications.strip()
if not specifications:
raise ValueError('Empty specification given') # depends on [control=['if'], data=[]]
return [specifications] # depends on [control=['if'], data=[]]
elif isinstance(specifications, (list, tuple)):
# List given: normalize its content
results = []
for specification in specifications:
results.extend(_get_specifications(specification)) # depends on [control=['for'], data=['specification']]
return results # depends on [control=['if'], data=[]]
else:
raise ValueError('Unhandled specifications type : {0}'.format(type(specifications).__name__))
|
def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias,
sampled_values, remove_accidental_hits=True):
""" Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
"""
# inputs = (n, in_dim)
sample, prob_sample, prob_target = sampled_values
# (num_samples, )
sample = S.var('sample', shape=(num_samples,), dtype='float32')
# (n, )
label = S.var('label')
label = S.reshape(label, shape=(-1,), name="label_reshape")
# (num_samples+n, )
sample_label = S.concat(sample, label, dim=0)
# lookup weights and biases
# (num_samples+n, dim)
sample_target_w = S.sparse.Embedding(data=sample_label, weight=weight,
input_dim=num_classes, output_dim=in_dim,
sparse_grad=True)
# (num_samples+n, 1)
sample_target_b = S.sparse.Embedding(data=sample_label, weight=bias,
input_dim=num_classes, output_dim=1,
sparse_grad=True)
# (num_samples, dim)
sample_w = S.slice(sample_target_w, begin=(0, 0), end=(num_samples, None))
target_w = S.slice(sample_target_w, begin=(num_samples, 0), end=(None, None))
sample_b = S.slice(sample_target_b, begin=(0, 0), end=(num_samples, None))
target_b = S.slice(sample_target_b, begin=(num_samples, 0), end=(None, None))
# target
# (n, 1)
true_pred = S.sum(target_w * inputs, axis=1, keepdims=True) + target_b
# samples
# (n, num_samples)
sample_b = S.reshape(sample_b, (-1,))
sample_pred = S.FullyConnected(inputs, weight=sample_w, bias=sample_b,
num_hidden=num_samples)
# remove accidental hits
if remove_accidental_hits:
label_v = S.reshape(label, (-1, 1))
sample_v = S.reshape(sample, (1, -1))
neg = S.broadcast_equal(label_v, sample_v) * -1e37
sample_pred = sample_pred + neg
prob_sample = S.reshape(prob_sample, shape=(1, num_samples))
p_target = true_pred - S.log(prob_target)
p_sample = S.broadcast_sub(sample_pred, S.log(prob_sample))
# return logits and new_labels
# (n, 1+num_samples)
logits = S.concat(p_target, p_sample, dim=1)
new_targets = S.zeros_like(label)
return logits, new_targets
|
def function[sampled_softmax, parameter[num_classes, num_samples, in_dim, inputs, weight, bias, sampled_values, remove_accidental_hits]]:
constant[ Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
]
<ast.Tuple object at 0x7da1b1fe20b0> assign[=] name[sampled_values]
variable[sample] assign[=] call[name[S].var, parameter[constant[sample]]]
variable[label] assign[=] call[name[S].var, parameter[constant[label]]]
variable[label] assign[=] call[name[S].reshape, parameter[name[label]]]
variable[sample_label] assign[=] call[name[S].concat, parameter[name[sample], name[label]]]
variable[sample_target_w] assign[=] call[name[S].sparse.Embedding, parameter[]]
variable[sample_target_b] assign[=] call[name[S].sparse.Embedding, parameter[]]
variable[sample_w] assign[=] call[name[S].slice, parameter[name[sample_target_w]]]
variable[target_w] assign[=] call[name[S].slice, parameter[name[sample_target_w]]]
variable[sample_b] assign[=] call[name[S].slice, parameter[name[sample_target_b]]]
variable[target_b] assign[=] call[name[S].slice, parameter[name[sample_target_b]]]
variable[true_pred] assign[=] binary_operation[call[name[S].sum, parameter[binary_operation[name[target_w] * name[inputs]]]] + name[target_b]]
variable[sample_b] assign[=] call[name[S].reshape, parameter[name[sample_b], tuple[[<ast.UnaryOp object at 0x7da1b204eef0>]]]]
variable[sample_pred] assign[=] call[name[S].FullyConnected, parameter[name[inputs]]]
if name[remove_accidental_hits] begin[:]
variable[label_v] assign[=] call[name[S].reshape, parameter[name[label], tuple[[<ast.UnaryOp object at 0x7da1b204d870>, <ast.Constant object at 0x7da1b204ece0>]]]]
variable[sample_v] assign[=] call[name[S].reshape, parameter[name[sample], tuple[[<ast.Constant object at 0x7da1b204ca30>, <ast.UnaryOp object at 0x7da1b204cbb0>]]]]
variable[neg] assign[=] binary_operation[call[name[S].broadcast_equal, parameter[name[label_v], name[sample_v]]] * <ast.UnaryOp object at 0x7da1b204fa00>]
variable[sample_pred] assign[=] binary_operation[name[sample_pred] + name[neg]]
variable[prob_sample] assign[=] call[name[S].reshape, parameter[name[prob_sample]]]
variable[p_target] assign[=] binary_operation[name[true_pred] - call[name[S].log, parameter[name[prob_target]]]]
variable[p_sample] assign[=] call[name[S].broadcast_sub, parameter[name[sample_pred], call[name[S].log, parameter[name[prob_sample]]]]]
variable[logits] assign[=] call[name[S].concat, parameter[name[p_target], name[p_sample]]]
variable[new_targets] assign[=] call[name[S].zeros_like, parameter[name[label]]]
return[tuple[[<ast.Name object at 0x7da1b204ec20>, <ast.Name object at 0x7da1b204ff10>]]]
|
keyword[def] identifier[sampled_softmax] ( identifier[num_classes] , identifier[num_samples] , identifier[in_dim] , identifier[inputs] , identifier[weight] , identifier[bias] ,
identifier[sampled_values] , identifier[remove_accidental_hits] = keyword[True] ):
literal[string]
identifier[sample] , identifier[prob_sample] , identifier[prob_target] = identifier[sampled_values]
identifier[sample] = identifier[S] . identifier[var] ( literal[string] , identifier[shape] =( identifier[num_samples] ,), identifier[dtype] = literal[string] )
identifier[label] = identifier[S] . identifier[var] ( literal[string] )
identifier[label] = identifier[S] . identifier[reshape] ( identifier[label] , identifier[shape] =(- literal[int] ,), identifier[name] = literal[string] )
identifier[sample_label] = identifier[S] . identifier[concat] ( identifier[sample] , identifier[label] , identifier[dim] = literal[int] )
identifier[sample_target_w] = identifier[S] . identifier[sparse] . identifier[Embedding] ( identifier[data] = identifier[sample_label] , identifier[weight] = identifier[weight] ,
identifier[input_dim] = identifier[num_classes] , identifier[output_dim] = identifier[in_dim] ,
identifier[sparse_grad] = keyword[True] )
identifier[sample_target_b] = identifier[S] . identifier[sparse] . identifier[Embedding] ( identifier[data] = identifier[sample_label] , identifier[weight] = identifier[bias] ,
identifier[input_dim] = identifier[num_classes] , identifier[output_dim] = literal[int] ,
identifier[sparse_grad] = keyword[True] )
identifier[sample_w] = identifier[S] . identifier[slice] ( identifier[sample_target_w] , identifier[begin] =( literal[int] , literal[int] ), identifier[end] =( identifier[num_samples] , keyword[None] ))
identifier[target_w] = identifier[S] . identifier[slice] ( identifier[sample_target_w] , identifier[begin] =( identifier[num_samples] , literal[int] ), identifier[end] =( keyword[None] , keyword[None] ))
identifier[sample_b] = identifier[S] . identifier[slice] ( identifier[sample_target_b] , identifier[begin] =( literal[int] , literal[int] ), identifier[end] =( identifier[num_samples] , keyword[None] ))
identifier[target_b] = identifier[S] . identifier[slice] ( identifier[sample_target_b] , identifier[begin] =( identifier[num_samples] , literal[int] ), identifier[end] =( keyword[None] , keyword[None] ))
identifier[true_pred] = identifier[S] . identifier[sum] ( identifier[target_w] * identifier[inputs] , identifier[axis] = literal[int] , identifier[keepdims] = keyword[True] )+ identifier[target_b]
identifier[sample_b] = identifier[S] . identifier[reshape] ( identifier[sample_b] ,(- literal[int] ,))
identifier[sample_pred] = identifier[S] . identifier[FullyConnected] ( identifier[inputs] , identifier[weight] = identifier[sample_w] , identifier[bias] = identifier[sample_b] ,
identifier[num_hidden] = identifier[num_samples] )
keyword[if] identifier[remove_accidental_hits] :
identifier[label_v] = identifier[S] . identifier[reshape] ( identifier[label] ,(- literal[int] , literal[int] ))
identifier[sample_v] = identifier[S] . identifier[reshape] ( identifier[sample] ,( literal[int] ,- literal[int] ))
identifier[neg] = identifier[S] . identifier[broadcast_equal] ( identifier[label_v] , identifier[sample_v] )*- literal[int]
identifier[sample_pred] = identifier[sample_pred] + identifier[neg]
identifier[prob_sample] = identifier[S] . identifier[reshape] ( identifier[prob_sample] , identifier[shape] =( literal[int] , identifier[num_samples] ))
identifier[p_target] = identifier[true_pred] - identifier[S] . identifier[log] ( identifier[prob_target] )
identifier[p_sample] = identifier[S] . identifier[broadcast_sub] ( identifier[sample_pred] , identifier[S] . identifier[log] ( identifier[prob_sample] ))
identifier[logits] = identifier[S] . identifier[concat] ( identifier[p_target] , identifier[p_sample] , identifier[dim] = literal[int] )
identifier[new_targets] = identifier[S] . identifier[zeros_like] ( identifier[label] )
keyword[return] identifier[logits] , identifier[new_targets]
|
def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias, sampled_values, remove_accidental_hits=True):
""" Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
"""
# inputs = (n, in_dim)
(sample, prob_sample, prob_target) = sampled_values
# (num_samples, )
sample = S.var('sample', shape=(num_samples,), dtype='float32')
# (n, )
label = S.var('label')
label = S.reshape(label, shape=(-1,), name='label_reshape')
# (num_samples+n, )
sample_label = S.concat(sample, label, dim=0)
# lookup weights and biases
# (num_samples+n, dim)
sample_target_w = S.sparse.Embedding(data=sample_label, weight=weight, input_dim=num_classes, output_dim=in_dim, sparse_grad=True)
# (num_samples+n, 1)
sample_target_b = S.sparse.Embedding(data=sample_label, weight=bias, input_dim=num_classes, output_dim=1, sparse_grad=True)
# (num_samples, dim)
sample_w = S.slice(sample_target_w, begin=(0, 0), end=(num_samples, None))
target_w = S.slice(sample_target_w, begin=(num_samples, 0), end=(None, None))
sample_b = S.slice(sample_target_b, begin=(0, 0), end=(num_samples, None))
target_b = S.slice(sample_target_b, begin=(num_samples, 0), end=(None, None))
# target
# (n, 1)
true_pred = S.sum(target_w * inputs, axis=1, keepdims=True) + target_b
# samples
# (n, num_samples)
sample_b = S.reshape(sample_b, (-1,))
sample_pred = S.FullyConnected(inputs, weight=sample_w, bias=sample_b, num_hidden=num_samples)
# remove accidental hits
if remove_accidental_hits:
label_v = S.reshape(label, (-1, 1))
sample_v = S.reshape(sample, (1, -1))
neg = S.broadcast_equal(label_v, sample_v) * -1e+37
sample_pred = sample_pred + neg # depends on [control=['if'], data=[]]
prob_sample = S.reshape(prob_sample, shape=(1, num_samples))
p_target = true_pred - S.log(prob_target)
p_sample = S.broadcast_sub(sample_pred, S.log(prob_sample))
# return logits and new_labels
# (n, 1+num_samples)
logits = S.concat(p_target, p_sample, dim=1)
new_targets = S.zeros_like(label)
return (logits, new_targets)
|
def cast_object(self, interface_object, interface_class):
"""Cast the obj to the interface class
:rtype: interface_class(interface_object)
"""
name = interface_class.__name__
i = self.manager.queryInterface(interface_object._i, name)
return interface_class(interface=i)
|
def function[cast_object, parameter[self, interface_object, interface_class]]:
constant[Cast the obj to the interface class
:rtype: interface_class(interface_object)
]
variable[name] assign[=] name[interface_class].__name__
variable[i] assign[=] call[name[self].manager.queryInterface, parameter[name[interface_object]._i, name[name]]]
return[call[name[interface_class], parameter[]]]
|
keyword[def] identifier[cast_object] ( identifier[self] , identifier[interface_object] , identifier[interface_class] ):
literal[string]
identifier[name] = identifier[interface_class] . identifier[__name__]
identifier[i] = identifier[self] . identifier[manager] . identifier[queryInterface] ( identifier[interface_object] . identifier[_i] , identifier[name] )
keyword[return] identifier[interface_class] ( identifier[interface] = identifier[i] )
|
def cast_object(self, interface_object, interface_class):
"""Cast the obj to the interface class
:rtype: interface_class(interface_object)
"""
name = interface_class.__name__
i = self.manager.queryInterface(interface_object._i, name)
return interface_class(interface=i)
|
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att` attribute until the `desired` value
is reached, or until the maximum number of attempts is reached. The updated
object is returned. It is up to the calling program to check the returned
object to make sure that it successfully reached the desired state.
Once the desired value of the attribute is reached, the method returns. If
not, it will re-try until the attribute's value matches one of the
`desired` values. By default (attempts=0) it will loop infinitely until the
attribute reaches the desired value. You can optionally limit the number of
times that the object is reloaded by passing a positive value to
`attempts`. If the attribute has not reached the desired value by then, the
method will exit.
If `verbose` is True, each attempt will print out the current value of the
watched attribute and the time that has elapsed since the original request.
Also, if `verbose_atts` is specified, the values of those attributes will
also be output. If `verbose` is False, then `verbose_atts` has no effect.
Note that `desired` can be a list of values; if the attribute becomes equal
to any of those values, this will succeed. For example, when creating a new
cloud server, it will initially have a status of 'BUILD', and you can't
work with it until its status is 'ACTIVE'. However, there might be a
problem with the build process, and the server will change to a status of
'ERROR'. So for this case you need to set the `desired` parameter to
`['ACTIVE', 'ERROR']`. If you simply pass 'ACTIVE' as the desired state,
this will loop indefinitely if a build fails, as the server will never
reach a status of 'ACTIVE'.
Since this process of waiting can take a potentially long time, and will
block your program's execution until the desired state of the object is
reached, you may specify a callback function. The callback can be any
callable that accepts a single parameter; the parameter it receives will be
either the updated object (success), or None (failure). If a callback is
specified, the program will return immediately after spawning the wait
process in a separate thread.
"""
if callback:
waiter = _WaitThread(obj=obj, att=att, desired=desired, callback=callback,
interval=interval, attempts=attempts, verbose=verbose,
verbose_atts=verbose_atts)
waiter.start()
return waiter
else:
return _wait_until(obj=obj, att=att, desired=desired, callback=None,
interval=interval, attempts=attempts, verbose=verbose,
verbose_atts=verbose_atts)
|
def function[wait_until, parameter[obj, att, desired, callback, interval, attempts, verbose, verbose_atts]]:
constant[
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att` attribute until the `desired` value
is reached, or until the maximum number of attempts is reached. The updated
object is returned. It is up to the calling program to check the returned
object to make sure that it successfully reached the desired state.
Once the desired value of the attribute is reached, the method returns. If
not, it will re-try until the attribute's value matches one of the
`desired` values. By default (attempts=0) it will loop infinitely until the
attribute reaches the desired value. You can optionally limit the number of
times that the object is reloaded by passing a positive value to
`attempts`. If the attribute has not reached the desired value by then, the
method will exit.
If `verbose` is True, each attempt will print out the current value of the
watched attribute and the time that has elapsed since the original request.
Also, if `verbose_atts` is specified, the values of those attributes will
also be output. If `verbose` is False, then `verbose_atts` has no effect.
Note that `desired` can be a list of values; if the attribute becomes equal
to any of those values, this will succeed. For example, when creating a new
cloud server, it will initially have a status of 'BUILD', and you can't
work with it until its status is 'ACTIVE'. However, there might be a
problem with the build process, and the server will change to a status of
'ERROR'. So for this case you need to set the `desired` parameter to
`['ACTIVE', 'ERROR']`. If you simply pass 'ACTIVE' as the desired state,
this will loop indefinitely if a build fails, as the server will never
reach a status of 'ACTIVE'.
Since this process of waiting can take a potentially long time, and will
block your program's execution until the desired state of the object is
reached, you may specify a callback function. The callback can be any
callable that accepts a single parameter; the parameter it receives will be
either the updated object (success), or None (failure). If a callback is
specified, the program will return immediately after spawning the wait
process in a separate thread.
]
if name[callback] begin[:]
variable[waiter] assign[=] call[name[_WaitThread], parameter[]]
call[name[waiter].start, parameter[]]
return[name[waiter]]
|
keyword[def] identifier[wait_until] ( identifier[obj] , identifier[att] , identifier[desired] , identifier[callback] = keyword[None] , identifier[interval] = literal[int] , identifier[attempts] = literal[int] ,
identifier[verbose] = keyword[False] , identifier[verbose_atts] = keyword[None] ):
literal[string]
keyword[if] identifier[callback] :
identifier[waiter] = identifier[_WaitThread] ( identifier[obj] = identifier[obj] , identifier[att] = identifier[att] , identifier[desired] = identifier[desired] , identifier[callback] = identifier[callback] ,
identifier[interval] = identifier[interval] , identifier[attempts] = identifier[attempts] , identifier[verbose] = identifier[verbose] ,
identifier[verbose_atts] = identifier[verbose_atts] )
identifier[waiter] . identifier[start] ()
keyword[return] identifier[waiter]
keyword[else] :
keyword[return] identifier[_wait_until] ( identifier[obj] = identifier[obj] , identifier[att] = identifier[att] , identifier[desired] = identifier[desired] , identifier[callback] = keyword[None] ,
identifier[interval] = identifier[interval] , identifier[attempts] = identifier[attempts] , identifier[verbose] = identifier[verbose] ,
identifier[verbose_atts] = identifier[verbose_atts] )
|
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0, verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att` attribute until the `desired` value
is reached, or until the maximum number of attempts is reached. The updated
object is returned. It is up to the calling program to check the returned
object to make sure that it successfully reached the desired state.
Once the desired value of the attribute is reached, the method returns. If
not, it will re-try until the attribute's value matches one of the
`desired` values. By default (attempts=0) it will loop infinitely until the
attribute reaches the desired value. You can optionally limit the number of
times that the object is reloaded by passing a positive value to
`attempts`. If the attribute has not reached the desired value by then, the
method will exit.
If `verbose` is True, each attempt will print out the current value of the
watched attribute and the time that has elapsed since the original request.
Also, if `verbose_atts` is specified, the values of those attributes will
also be output. If `verbose` is False, then `verbose_atts` has no effect.
Note that `desired` can be a list of values; if the attribute becomes equal
to any of those values, this will succeed. For example, when creating a new
cloud server, it will initially have a status of 'BUILD', and you can't
work with it until its status is 'ACTIVE'. However, there might be a
problem with the build process, and the server will change to a status of
'ERROR'. So for this case you need to set the `desired` parameter to
`['ACTIVE', 'ERROR']`. If you simply pass 'ACTIVE' as the desired state,
this will loop indefinitely if a build fails, as the server will never
reach a status of 'ACTIVE'.
Since this process of waiting can take a potentially long time, and will
block your program's execution until the desired state of the object is
reached, you may specify a callback function. The callback can be any
callable that accepts a single parameter; the parameter it receives will be
either the updated object (success), or None (failure). If a callback is
specified, the program will return immediately after spawning the wait
process in a separate thread.
"""
if callback:
waiter = _WaitThread(obj=obj, att=att, desired=desired, callback=callback, interval=interval, attempts=attempts, verbose=verbose, verbose_atts=verbose_atts)
waiter.start()
return waiter # depends on [control=['if'], data=[]]
else:
return _wait_until(obj=obj, att=att, desired=desired, callback=None, interval=interval, attempts=attempts, verbose=verbose, verbose_atts=verbose_atts)
|
def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _absent and key in self._map:
return self.getlist(key)
return list(self.itervalues())
|
def function[values, parameter[self, key]]:
constant[
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
]
if <ast.BoolOp object at 0x7da1b1e8c310> begin[:]
return[call[name[self].getlist, parameter[name[key]]]]
return[call[name[list], parameter[call[name[self].itervalues, parameter[]]]]]
|
keyword[def] identifier[values] ( identifier[self] , identifier[key] = identifier[_absent] ):
literal[string]
keyword[if] identifier[key] keyword[is] keyword[not] identifier[_absent] keyword[and] identifier[key] keyword[in] identifier[self] . identifier[_map] :
keyword[return] identifier[self] . identifier[getlist] ( identifier[key] )
keyword[return] identifier[list] ( identifier[self] . identifier[itervalues] ())
|
def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _absent and key in self._map:
return self.getlist(key) # depends on [control=['if'], data=[]]
return list(self.itervalues())
|
def _options_protobuf(self, retry_id):
"""Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Args:
retry_id (Union[bytes, NoneType]): Transaction ID of a transaction
to be retried.
Returns:
Optional[google.cloud.firestore_v1beta1.types.TransactionOptions]:
The protobuf ``TransactionOptions`` if ``read_only==True`` or if
there is a transaction ID to be retried, else :data:`None`.
Raises:
ValueError: If ``retry_id`` is not :data:`None` but the
transaction is read-only.
"""
if retry_id is not None:
if self._read_only:
raise ValueError(_CANT_RETRY_READ_ONLY)
return types.TransactionOptions(
read_write=types.TransactionOptions.ReadWrite(
retry_transaction=retry_id
)
)
elif self._read_only:
return types.TransactionOptions(
read_only=types.TransactionOptions.ReadOnly()
)
else:
return None
|
def function[_options_protobuf, parameter[self, retry_id]]:
constant[Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Args:
retry_id (Union[bytes, NoneType]): Transaction ID of a transaction
to be retried.
Returns:
Optional[google.cloud.firestore_v1beta1.types.TransactionOptions]:
The protobuf ``TransactionOptions`` if ``read_only==True`` or if
there is a transaction ID to be retried, else :data:`None`.
Raises:
ValueError: If ``retry_id`` is not :data:`None` but the
transaction is read-only.
]
if compare[name[retry_id] is_not constant[None]] begin[:]
if name[self]._read_only begin[:]
<ast.Raise object at 0x7da20e9558a0>
return[call[name[types].TransactionOptions, parameter[]]]
|
keyword[def] identifier[_options_protobuf] ( identifier[self] , identifier[retry_id] ):
literal[string]
keyword[if] identifier[retry_id] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[self] . identifier[_read_only] :
keyword[raise] identifier[ValueError] ( identifier[_CANT_RETRY_READ_ONLY] )
keyword[return] identifier[types] . identifier[TransactionOptions] (
identifier[read_write] = identifier[types] . identifier[TransactionOptions] . identifier[ReadWrite] (
identifier[retry_transaction] = identifier[retry_id]
)
)
keyword[elif] identifier[self] . identifier[_read_only] :
keyword[return] identifier[types] . identifier[TransactionOptions] (
identifier[read_only] = identifier[types] . identifier[TransactionOptions] . identifier[ReadOnly] ()
)
keyword[else] :
keyword[return] keyword[None]
|
def _options_protobuf(self, retry_id):
"""Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Args:
retry_id (Union[bytes, NoneType]): Transaction ID of a transaction
to be retried.
Returns:
Optional[google.cloud.firestore_v1beta1.types.TransactionOptions]:
The protobuf ``TransactionOptions`` if ``read_only==True`` or if
there is a transaction ID to be retried, else :data:`None`.
Raises:
ValueError: If ``retry_id`` is not :data:`None` but the
transaction is read-only.
"""
if retry_id is not None:
if self._read_only:
raise ValueError(_CANT_RETRY_READ_ONLY) # depends on [control=['if'], data=[]]
return types.TransactionOptions(read_write=types.TransactionOptions.ReadWrite(retry_transaction=retry_id)) # depends on [control=['if'], data=['retry_id']]
elif self._read_only:
return types.TransactionOptions(read_only=types.TransactionOptions.ReadOnly()) # depends on [control=['if'], data=[]]
else:
return None
|
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(SingleWidgetWindowController, self).register_view(view)
self.shortcut_manager = ShortcutManager(self.view['main_window'])
self.register_actions(self.shortcut_manager)
view['main_window'].connect('destroy', Gtk.main_quit)
|
def function[register_view, parameter[self, view]]:
constant[Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
]
call[call[name[super], parameter[name[SingleWidgetWindowController], name[self]]].register_view, parameter[name[view]]]
name[self].shortcut_manager assign[=] call[name[ShortcutManager], parameter[call[name[self].view][constant[main_window]]]]
call[name[self].register_actions, parameter[name[self].shortcut_manager]]
call[call[name[view]][constant[main_window]].connect, parameter[constant[destroy], name[Gtk].main_quit]]
|
keyword[def] identifier[register_view] ( identifier[self] , identifier[view] ):
literal[string]
identifier[super] ( identifier[SingleWidgetWindowController] , identifier[self] ). identifier[register_view] ( identifier[view] )
identifier[self] . identifier[shortcut_manager] = identifier[ShortcutManager] ( identifier[self] . identifier[view] [ literal[string] ])
identifier[self] . identifier[register_actions] ( identifier[self] . identifier[shortcut_manager] )
identifier[view] [ literal[string] ]. identifier[connect] ( literal[string] , identifier[Gtk] . identifier[main_quit] )
|
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(SingleWidgetWindowController, self).register_view(view)
self.shortcut_manager = ShortcutManager(self.view['main_window'])
self.register_actions(self.shortcut_manager)
view['main_window'].connect('destroy', Gtk.main_quit)
|
def split_lists(d, split_keys, new_name='split',
check_length=True, deepcopy=True):
"""split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_name : str
top level key for split items
check_length : bool
if true, raise error if any lists are of a different length
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'path_key':{'x':[1,2],'y':[3,4],'a':1}}
>>> new_d = split_lists(d,['x','y'])
>>> pprint(new_d)
{'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}}
>>> split_lists(d,['x','a'])
Traceback (most recent call last):
...
ValueError: "a" data at the following path is not a list ('path_key',)
>>> d2 = {'path_key':{'x':[1,7],'y':[3,4,5]}}
>>> split_lists(d2,['x','y'])
Traceback (most recent call last):
...
ValueError: lists at the following path do not have the same size ('path_key',)
""" # noqa: E501
flattened = flatten2d(d)
new_d = {}
for key, value in flattened.items():
if set(split_keys).issubset(value.keys()):
# combine_d = {}
combine_d = []
sub_d = {}
length = None
for subkey, subvalue in value.items():
if subkey in split_keys:
if not isinstance(subvalue, list):
raise ValueError(
'"{0}" data at the following path is not a list '
'{1}'.format(subkey, key))
if check_length and length is not None:
if len(subvalue) != length:
raise ValueError(
'lists at the following path '
'do not have the same size {0}'.format(key))
if length is None:
combine_d = [{subkey: v} for v in subvalue]
else:
for item, val in zip(combine_d, subvalue):
item[subkey] = val
length = len(subvalue)
# new_combine = {k:{subkey:v}
# for k,v in enumerate(subvalue)}
# combine_d = merge([combine_d,new_combine])
else:
sub_d[subkey] = subvalue
try:
new_d[key] = merge([sub_d, {new_name: combine_d}])
except ValueError:
raise ValueError(
'split data key: {0}, already exists at '
'this level for {1}'.format(new_name, key))
else:
new_d[key] = value
return unflatten(new_d, deepcopy=deepcopy)
|
def function[split_lists, parameter[d, split_keys, new_name, check_length, deepcopy]]:
constant[split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_name : str
top level key for split items
check_length : bool
if true, raise error if any lists are of a different length
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'path_key':{'x':[1,2],'y':[3,4],'a':1}}
>>> new_d = split_lists(d,['x','y'])
>>> pprint(new_d)
{'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}}
>>> split_lists(d,['x','a'])
Traceback (most recent call last):
...
ValueError: "a" data at the following path is not a list ('path_key',)
>>> d2 = {'path_key':{'x':[1,7],'y':[3,4,5]}}
>>> split_lists(d2,['x','y'])
Traceback (most recent call last):
...
ValueError: lists at the following path do not have the same size ('path_key',)
]
variable[flattened] assign[=] call[name[flatten2d], parameter[name[d]]]
variable[new_d] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da20e961cc0>, <ast.Name object at 0x7da20e9626e0>]]] in starred[call[name[flattened].items, parameter[]]] begin[:]
if call[call[name[set], parameter[name[split_keys]]].issubset, parameter[call[name[value].keys, parameter[]]]] begin[:]
variable[combine_d] assign[=] list[[]]
variable[sub_d] assign[=] dictionary[[], []]
variable[length] assign[=] constant[None]
for taget[tuple[[<ast.Name object at 0x7da18bc715d0>, <ast.Name object at 0x7da18bc731c0>]]] in starred[call[name[value].items, parameter[]]] begin[:]
if compare[name[subkey] in name[split_keys]] begin[:]
if <ast.UnaryOp object at 0x7da18bc70df0> begin[:]
<ast.Raise object at 0x7da18bc72860>
if <ast.BoolOp object at 0x7da18bc71180> begin[:]
if compare[call[name[len], parameter[name[subvalue]]] not_equal[!=] name[length]] begin[:]
<ast.Raise object at 0x7da18bc70430>
if compare[name[length] is constant[None]] begin[:]
variable[combine_d] assign[=] <ast.ListComp object at 0x7da18bc734c0>
variable[length] assign[=] call[name[len], parameter[name[subvalue]]]
<ast.Try object at 0x7da20e962830>
return[call[name[unflatten], parameter[name[new_d]]]]
|
keyword[def] identifier[split_lists] ( identifier[d] , identifier[split_keys] , identifier[new_name] = literal[string] ,
identifier[check_length] = keyword[True] , identifier[deepcopy] = keyword[True] ):
literal[string]
identifier[flattened] = identifier[flatten2d] ( identifier[d] )
identifier[new_d] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[flattened] . identifier[items] ():
keyword[if] identifier[set] ( identifier[split_keys] ). identifier[issubset] ( identifier[value] . identifier[keys] ()):
identifier[combine_d] =[]
identifier[sub_d] ={}
identifier[length] = keyword[None]
keyword[for] identifier[subkey] , identifier[subvalue] keyword[in] identifier[value] . identifier[items] ():
keyword[if] identifier[subkey] keyword[in] identifier[split_keys] :
keyword[if] keyword[not] identifier[isinstance] ( identifier[subvalue] , identifier[list] ):
keyword[raise] identifier[ValueError] (
literal[string]
literal[string] . identifier[format] ( identifier[subkey] , identifier[key] ))
keyword[if] identifier[check_length] keyword[and] identifier[length] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[len] ( identifier[subvalue] )!= identifier[length] :
keyword[raise] identifier[ValueError] (
literal[string]
literal[string] . identifier[format] ( identifier[key] ))
keyword[if] identifier[length] keyword[is] keyword[None] :
identifier[combine_d] =[{ identifier[subkey] : identifier[v] } keyword[for] identifier[v] keyword[in] identifier[subvalue] ]
keyword[else] :
keyword[for] identifier[item] , identifier[val] keyword[in] identifier[zip] ( identifier[combine_d] , identifier[subvalue] ):
identifier[item] [ identifier[subkey] ]= identifier[val]
identifier[length] = identifier[len] ( identifier[subvalue] )
keyword[else] :
identifier[sub_d] [ identifier[subkey] ]= identifier[subvalue]
keyword[try] :
identifier[new_d] [ identifier[key] ]= identifier[merge] ([ identifier[sub_d] ,{ identifier[new_name] : identifier[combine_d] }])
keyword[except] identifier[ValueError] :
keyword[raise] identifier[ValueError] (
literal[string]
literal[string] . identifier[format] ( identifier[new_name] , identifier[key] ))
keyword[else] :
identifier[new_d] [ identifier[key] ]= identifier[value]
keyword[return] identifier[unflatten] ( identifier[new_d] , identifier[deepcopy] = identifier[deepcopy] )
|
def split_lists(d, split_keys, new_name='split', check_length=True, deepcopy=True):
"""split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_name : str
top level key for split items
check_length : bool
if true, raise error if any lists are of a different length
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'path_key':{'x':[1,2],'y':[3,4],'a':1}}
>>> new_d = split_lists(d,['x','y'])
>>> pprint(new_d)
{'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}}
>>> split_lists(d,['x','a'])
Traceback (most recent call last):
...
ValueError: "a" data at the following path is not a list ('path_key',)
>>> d2 = {'path_key':{'x':[1,7],'y':[3,4,5]}}
>>> split_lists(d2,['x','y'])
Traceback (most recent call last):
...
ValueError: lists at the following path do not have the same size ('path_key',)
""" # noqa: E501
flattened = flatten2d(d)
new_d = {}
for (key, value) in flattened.items():
if set(split_keys).issubset(value.keys()):
# combine_d = {}
combine_d = []
sub_d = {}
length = None
for (subkey, subvalue) in value.items():
if subkey in split_keys:
if not isinstance(subvalue, list):
raise ValueError('"{0}" data at the following path is not a list {1}'.format(subkey, key)) # depends on [control=['if'], data=[]]
if check_length and length is not None:
if len(subvalue) != length:
raise ValueError('lists at the following path do not have the same size {0}'.format(key)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
if length is None:
combine_d = [{subkey: v} for v in subvalue] # depends on [control=['if'], data=[]]
else:
for (item, val) in zip(combine_d, subvalue):
item[subkey] = val # depends on [control=['for'], data=[]]
length = len(subvalue) # depends on [control=['if'], data=['subkey']]
else:
# new_combine = {k:{subkey:v}
# for k,v in enumerate(subvalue)}
# combine_d = merge([combine_d,new_combine])
sub_d[subkey] = subvalue
try:
new_d[key] = merge([sub_d, {new_name: combine_d}]) # depends on [control=['try'], data=[]]
except ValueError:
raise ValueError('split data key: {0}, already exists at this level for {1}'.format(new_name, key)) # depends on [control=['except'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
else:
new_d[key] = value # depends on [control=['for'], data=[]]
return unflatten(new_d, deepcopy=deepcopy)
|
def reward_battery(self):
"""
Add a battery level reward
"""
if not 'battery' in self.mode:
return
mode = self.mode['battery']
if mode and mode and self.__test_cond(mode):
self.logger.debug('Battery out')
self.player.stats['reward'] += mode['reward']
self.player.game_over = self.player.game_over or mode['terminal']
|
def function[reward_battery, parameter[self]]:
constant[
Add a battery level reward
]
if <ast.UnaryOp object at 0x7da1b2554730> begin[:]
return[None]
variable[mode] assign[=] call[name[self].mode][constant[battery]]
if <ast.BoolOp object at 0x7da1b2554a30> begin[:]
call[name[self].logger.debug, parameter[constant[Battery out]]]
<ast.AugAssign object at 0x7da1b25549a0>
name[self].player.game_over assign[=] <ast.BoolOp object at 0x7da1b2554ac0>
|
keyword[def] identifier[reward_battery] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[self] . identifier[mode] :
keyword[return]
identifier[mode] = identifier[self] . identifier[mode] [ literal[string] ]
keyword[if] identifier[mode] keyword[and] identifier[mode] keyword[and] identifier[self] . identifier[__test_cond] ( identifier[mode] ):
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
identifier[self] . identifier[player] . identifier[stats] [ literal[string] ]+= identifier[mode] [ literal[string] ]
identifier[self] . identifier[player] . identifier[game_over] = identifier[self] . identifier[player] . identifier[game_over] keyword[or] identifier[mode] [ literal[string] ]
|
def reward_battery(self):
"""
Add a battery level reward
"""
if not 'battery' in self.mode:
return # depends on [control=['if'], data=[]]
mode = self.mode['battery']
if mode and mode and self.__test_cond(mode):
self.logger.debug('Battery out')
self.player.stats['reward'] += mode['reward']
self.player.game_over = self.player.game_over or mode['terminal'] # depends on [control=['if'], data=[]]
|
def get_vnetwork_vms_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vms = ET.Element("get_vnetwork_vms")
config = get_vnetwork_vms
input = ET.SubElement(get_vnetwork_vms, "input")
vcenter = ET.SubElement(input, "vcenter")
vcenter.text = kwargs.pop('vcenter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
|
def function[get_vnetwork_vms_input_vcenter, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vnetwork_vms] assign[=] call[name[ET].Element, parameter[constant[get_vnetwork_vms]]]
variable[config] assign[=] name[get_vnetwork_vms]
variable[input] assign[=] call[name[ET].SubElement, parameter[name[get_vnetwork_vms], constant[input]]]
variable[vcenter] assign[=] call[name[ET].SubElement, parameter[name[input], constant[vcenter]]]
name[vcenter].text assign[=] call[name[kwargs].pop, parameter[constant[vcenter]]]
variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]]
return[call[name[callback], parameter[name[config]]]]
|
keyword[def] identifier[get_vnetwork_vms_input_vcenter] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vnetwork_vms] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[config] = identifier[get_vnetwork_vms]
identifier[input] = identifier[ET] . identifier[SubElement] ( identifier[get_vnetwork_vms] , literal[string] )
identifier[vcenter] = identifier[ET] . identifier[SubElement] ( identifier[input] , literal[string] )
identifier[vcenter] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] )
keyword[return] identifier[callback] ( identifier[config] )
|
def get_vnetwork_vms_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vnetwork_vms = ET.Element('get_vnetwork_vms')
config = get_vnetwork_vms
input = ET.SubElement(get_vnetwork_vms, 'input')
vcenter = ET.SubElement(input, 'vcenter')
vcenter.text = kwargs.pop('vcenter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
|
def hide_shortcuts(self, menu):
"""Hide action shortcuts in menu"""
for element in getattr(self, menu + '_menu_actions'):
if element and isinstance(element, QAction):
if element._shown_shortcut is not None:
element.setShortcut(QKeySequence())
|
def function[hide_shortcuts, parameter[self, menu]]:
constant[Hide action shortcuts in menu]
for taget[name[element]] in starred[call[name[getattr], parameter[name[self], binary_operation[name[menu] + constant[_menu_actions]]]]] begin[:]
if <ast.BoolOp object at 0x7da18bcc95d0> begin[:]
if compare[name[element]._shown_shortcut is_not constant[None]] begin[:]
call[name[element].setShortcut, parameter[call[name[QKeySequence], parameter[]]]]
|
keyword[def] identifier[hide_shortcuts] ( identifier[self] , identifier[menu] ):
literal[string]
keyword[for] identifier[element] keyword[in] identifier[getattr] ( identifier[self] , identifier[menu] + literal[string] ):
keyword[if] identifier[element] keyword[and] identifier[isinstance] ( identifier[element] , identifier[QAction] ):
keyword[if] identifier[element] . identifier[_shown_shortcut] keyword[is] keyword[not] keyword[None] :
identifier[element] . identifier[setShortcut] ( identifier[QKeySequence] ())
|
def hide_shortcuts(self, menu):
"""Hide action shortcuts in menu"""
for element in getattr(self, menu + '_menu_actions'):
if element and isinstance(element, QAction):
if element._shown_shortcut is not None:
element.setShortcut(QKeySequence()) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['element']]
|
def CmdAuthenticate(self,
challenge_param,
app_param,
key_handle,
check_only=False):
"""Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 hash of client_data object as a bytes
object.
app_param: SHA-256 hash of the app id as a bytes object.
key_handle: The key handle to use to issue the signature as a bytes
object.
check_only: If true, only check if key_handle is valid.
Returns:
A binary structure containing the key handle, attestation, and a
signature over that by the attestation key. The precise format
is dictated by the FIDO U2F specs.
Raises:
TUPRequiredError: If check_only is False, a Test of User Precense
is required to proceed. If check_only is True, this means
the key_handle is valid.
InvalidKeyHandleError: The key_handle is not valid for this device.
ApduError: Something else went wrong on the device.
"""
self.logger.debug('CmdAuthenticate')
if len(challenge_param) != 32 or len(app_param) != 32:
raise errors.InvalidRequestError()
control = 0x07 if check_only else 0x03
body = bytearray(challenge_param + app_param +
bytearray([len(key_handle)]) + key_handle)
response = self.InternalSendApdu(apdu.CommandApdu(
0, apdu.CMD_AUTH, control, 0x00, body))
response.CheckSuccessOrRaise()
return response.body
|
def function[CmdAuthenticate, parameter[self, challenge_param, app_param, key_handle, check_only]]:
constant[Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 hash of client_data object as a bytes
object.
app_param: SHA-256 hash of the app id as a bytes object.
key_handle: The key handle to use to issue the signature as a bytes
object.
check_only: If true, only check if key_handle is valid.
Returns:
A binary structure containing the key handle, attestation, and a
signature over that by the attestation key. The precise format
is dictated by the FIDO U2F specs.
Raises:
TUPRequiredError: If check_only is False, a Test of User Precense
is required to proceed. If check_only is True, this means
the key_handle is valid.
InvalidKeyHandleError: The key_handle is not valid for this device.
ApduError: Something else went wrong on the device.
]
call[name[self].logger.debug, parameter[constant[CmdAuthenticate]]]
if <ast.BoolOp object at 0x7da18fe927d0> begin[:]
<ast.Raise object at 0x7da18fe93d60>
variable[control] assign[=] <ast.IfExp object at 0x7da204621f30>
variable[body] assign[=] call[name[bytearray], parameter[binary_operation[binary_operation[binary_operation[name[challenge_param] + name[app_param]] + call[name[bytearray], parameter[list[[<ast.Call object at 0x7da204621c90>]]]]] + name[key_handle]]]]
variable[response] assign[=] call[name[self].InternalSendApdu, parameter[call[name[apdu].CommandApdu, parameter[constant[0], name[apdu].CMD_AUTH, name[control], constant[0], name[body]]]]]
call[name[response].CheckSuccessOrRaise, parameter[]]
return[name[response].body]
|
keyword[def] identifier[CmdAuthenticate] ( identifier[self] ,
identifier[challenge_param] ,
identifier[app_param] ,
identifier[key_handle] ,
identifier[check_only] = keyword[False] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identifier[len] ( identifier[challenge_param] )!= literal[int] keyword[or] identifier[len] ( identifier[app_param] )!= literal[int] :
keyword[raise] identifier[errors] . identifier[InvalidRequestError] ()
identifier[control] = literal[int] keyword[if] identifier[check_only] keyword[else] literal[int]
identifier[body] = identifier[bytearray] ( identifier[challenge_param] + identifier[app_param] +
identifier[bytearray] ([ identifier[len] ( identifier[key_handle] )])+ identifier[key_handle] )
identifier[response] = identifier[self] . identifier[InternalSendApdu] ( identifier[apdu] . identifier[CommandApdu] (
literal[int] , identifier[apdu] . identifier[CMD_AUTH] , identifier[control] , literal[int] , identifier[body] ))
identifier[response] . identifier[CheckSuccessOrRaise] ()
keyword[return] identifier[response] . identifier[body]
|
def CmdAuthenticate(self, challenge_param, app_param, key_handle, check_only=False):
"""Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 hash of client_data object as a bytes
object.
app_param: SHA-256 hash of the app id as a bytes object.
key_handle: The key handle to use to issue the signature as a bytes
object.
check_only: If true, only check if key_handle is valid.
Returns:
A binary structure containing the key handle, attestation, and a
signature over that by the attestation key. The precise format
is dictated by the FIDO U2F specs.
Raises:
TUPRequiredError: If check_only is False, a Test of User Precense
is required to proceed. If check_only is True, this means
the key_handle is valid.
InvalidKeyHandleError: The key_handle is not valid for this device.
ApduError: Something else went wrong on the device.
"""
self.logger.debug('CmdAuthenticate')
if len(challenge_param) != 32 or len(app_param) != 32:
raise errors.InvalidRequestError() # depends on [control=['if'], data=[]]
control = 7 if check_only else 3
body = bytearray(challenge_param + app_param + bytearray([len(key_handle)]) + key_handle)
response = self.InternalSendApdu(apdu.CommandApdu(0, apdu.CMD_AUTH, control, 0, body))
response.CheckSuccessOrRaise()
return response.body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.