code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def update(self, series_list):
"""Updates widget content from series_list
Parameters
----------
series_list: List of dict
\tList of dicts with data from all series
"""
if not series_list:
self.series_notebook.AddPage(wx.Panel(self, -1), _("+"))
... | def function[update, parameter[self, series_list]]:
constant[Updates widget content from series_list
Parameters
----------
series_list: List of dict
List of dicts with data from all series
]
if <ast.UnaryOp object at 0x7da1b2347ac0> begin[:]
cal... | keyword[def] identifier[update] ( identifier[self] , identifier[series_list] ):
literal[string]
keyword[if] keyword[not] identifier[series_list] :
identifier[self] . identifier[series_notebook] . identifier[AddPage] ( identifier[wx] . identifier[Panel] ( identifier[self] ,- literal[... | def update(self, series_list):
"""Updates widget content from series_list
Parameters
----------
series_list: List of dict
List of dicts with data from all series
"""
if not series_list:
self.series_notebook.AddPage(wx.Panel(self, -1), _('+'))
return # ... |
def unbind_key(pymux, variables):
"""
Remove key binding.
"""
key = variables['<key>']
needs_prefix = not variables['-n']
pymux.key_bindings_manager.remove_custom_binding(
key, needs_prefix=needs_prefix) | def function[unbind_key, parameter[pymux, variables]]:
constant[
Remove key binding.
]
variable[key] assign[=] call[name[variables]][constant[<key>]]
variable[needs_prefix] assign[=] <ast.UnaryOp object at 0x7da20e954c70>
call[name[pymux].key_bindings_manager.remove_custom_bindin... | keyword[def] identifier[unbind_key] ( identifier[pymux] , identifier[variables] ):
literal[string]
identifier[key] = identifier[variables] [ literal[string] ]
identifier[needs_prefix] = keyword[not] identifier[variables] [ literal[string] ]
identifier[pymux] . identifier[key_bindings_manager] .... | def unbind_key(pymux, variables):
"""
Remove key binding.
"""
key = variables['<key>']
needs_prefix = not variables['-n']
pymux.key_bindings_manager.remove_custom_binding(key, needs_prefix=needs_prefix) |
def list_custom_images(call=None):
'''
Return a dict of all custom VM images on the cloud provider.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
ret = {}
conn = get_conn('SoftLayer_Account')
... | def function[list_custom_images, parameter[call]]:
constant[
Return a dict of all custom VM images on the cloud provider.
]
if compare[name[call] not_equal[!=] constant[function]] begin[:]
<ast.Raise object at 0x7da1b1c23340>
variable[ret] assign[=] dictionary[[], []]
var... | keyword[def] identifier[list_custom_images] ( identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
)
identifier[ret] ={}
identifier[conn] = identifier[ge... | def list_custom_images(call=None):
"""
Return a dict of all custom VM images on the cloud provider.
"""
if call != 'function':
raise SaltCloudSystemExit('The list_vlans function must be called with -f or --function.') # depends on [control=['if'], data=[]]
ret = {}
conn = get_conn('Soft... |
def get_create_security_group_commands(self, sg_id, sg_rules):
"""Commands for creating ACL"""
cmds = []
in_rules, eg_rules = self._format_rules_for_eos(sg_rules)
cmds.append("ip access-list %s dynamic" %
self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
for i... | def function[get_create_security_group_commands, parameter[self, sg_id, sg_rules]]:
constant[Commands for creating ACL]
variable[cmds] assign[=] list[[]]
<ast.Tuple object at 0x7da1b1952410> assign[=] call[name[self]._format_rules_for_eos, parameter[name[sg_rules]]]
call[name[cmds].appen... | keyword[def] identifier[get_create_security_group_commands] ( identifier[self] , identifier[sg_id] , identifier[sg_rules] ):
literal[string]
identifier[cmds] =[]
identifier[in_rules] , identifier[eg_rules] = identifier[self] . identifier[_format_rules_for_eos] ( identifier[sg_rules] )
... | def get_create_security_group_commands(self, sg_id, sg_rules):
"""Commands for creating ACL"""
cmds = []
(in_rules, eg_rules) = self._format_rules_for_eos(sg_rules)
cmds.append('ip access-list %s dynamic' % self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
for in_rule in in_rules:
cmds.appen... |
def forward(self, x, **kwargs):
"""
Perform a forward pass through the network.
The forward pass in recursive som is based on a combination between
the activation in the last time-step and the current time-step.
Parameters
----------
x : numpy array
... | def function[forward, parameter[self, x]]:
constant[
Perform a forward pass through the network.
The forward pass in recursive som is based on a combination between
the activation in the last time-step and the current time-step.
Parameters
----------
x : numpy a... | keyword[def] identifier[forward] ( identifier[self] , identifier[x] ,** identifier[kwargs] ):
literal[string]
identifier[prev] = identifier[kwargs] [ literal[string] ]
identifier[distance_x] , identifier[diff_x] = identifier[self] . identifier[distance_function] ( identi... | def forward(self, x, **kwargs):
"""
Perform a forward pass through the network.
The forward pass in recursive som is based on a combination between
the activation in the last time-step and the current time-step.
Parameters
----------
x : numpy array
The ... |
def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] =... | def function[get_op_or_tensor_by_name, parameter[name]]:
constant[
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
]
variable[G] assign[=] call[name[tfv1].get_def... | keyword[def] identifier[get_op_or_tensor_by_name] ( identifier[name] ):
literal[string]
identifier[G] = identifier[tfv1] . identifier[get_default_graph] ()
keyword[def] identifier[f] ( identifier[n] ):
keyword[if] identifier[len] ( identifier[n] )>= literal[int] keyword[and] identifier[n... | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] =... |
def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info("Creating schema for %s", self.table)
self.create_schema(connection)
... | def function[init_copy, parameter[self, connection]]:
constant[
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
]
if <ast.UnaryOp object at 0x7da18f723700> begin[:]
call[name[logger].info, parameter[constant[Creating schema for %s... | keyword[def] identifier[init_copy] ( identifier[self] , identifier[connection] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[does_schema_exist] ( identifier[connection] ):
identifier[logger] . identifier[info] ( literal[string] , identifier[self] . identif... | def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info('Creating schema for %s', self.table)
self.create_schema(connection) # depends on [control=['... |
def update_safety_check(first_dict: MutableMapping[K, V],
second_dict: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent) -> None:
"""Check the safety of updating one dictionary with another.
Raises ValueError if dictionaries have non-compatible values f... | def function[update_safety_check, parameter[first_dict, second_dict, compat]]:
constant[Check the safety of updating one dictionary with another.
Raises ValueError if dictionaries have non-compatible values for any key,
where compatibility is determined by identity (they are the same item) or
the `... | keyword[def] identifier[update_safety_check] ( identifier[first_dict] : identifier[MutableMapping] [ identifier[K] , identifier[V] ],
identifier[second_dict] : identifier[Mapping] [ identifier[K] , identifier[V] ],
identifier[compat] : identifier[Callable] [[ identifier[V] , identifier[V] ], identifier[bool] ]= ide... | def update_safety_check(first_dict: MutableMapping[K, V], second_dict: Mapping[K, V], compat: Callable[[V, V], bool]=equivalent) -> None:
"""Check the safety of updating one dictionary with another.
Raises ValueError if dictionaries have non-compatible values for any key,
where compatibility is determined ... |
def setM1Coast(self, device=DEFAULT_DEVICE_ID):
"""
Set motor 1 to coast.
:Keywords:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol. Defaults to the hardware's
default value.
... | def function[setM1Coast, parameter[self, device]]:
constant[
Set motor 1 to coast.
:Keywords:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol. Defaults to the hardware's
default va... | keyword[def] identifier[setM1Coast] ( identifier[self] , identifier[device] = identifier[DEFAULT_DEVICE_ID] ):
literal[string]
identifier[cmd] = identifier[self] . identifier[_COMMAND] . identifier[get] ( literal[string] )
identifier[self] . identifier[_writeData] ( identifier[cmd] , ident... | def setM1Coast(self, device=DEFAULT_DEVICE_ID):
"""
Set motor 1 to coast.
:Keywords:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol. Defaults to the hardware's
default value.
... |
def propagate(self, assumptions=[], phase_saving=0):
"""
Propagate a given set of assumption literals.
"""
if self.maplesat:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
def_sigint_handler = signal... | def function[propagate, parameter[self, assumptions, phase_saving]]:
constant[
Propagate a given set of assumption literals.
]
if name[self].maplesat begin[:]
if name[self].use_timer begin[:]
variable[start_time] assign[=] call[name[time].clock... | keyword[def] identifier[propagate] ( identifier[self] , identifier[assumptions] =[], identifier[phase_saving] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[maplesat] :
keyword[if] identifier[self] . identifier[use_timer] :
identifier[s... | def propagate(self, assumptions=[], phase_saving=0):
"""
Propagate a given set of assumption literals.
"""
if self.maplesat:
if self.use_timer:
start_time = time.clock() # depends on [control=['if'], data=[]]
# saving default SIGINT handler
def_sigint_han... |
def destroy(self):
"""
Delete the page. May delete the whole document if it's actually the
last page.
"""
logger.info("Destroying page: %s" % self)
if self.doc.nb_pages <= 1:
self.doc.destroy()
return
doc_pages = self.doc.pages[:]
c... | def function[destroy, parameter[self]]:
constant[
Delete the page. May delete the whole document if it's actually the
last page.
]
call[name[logger].info, parameter[binary_operation[constant[Destroying page: %s] <ast.Mod object at 0x7da2590d6920> name[self]]]]
if compare[... | keyword[def] identifier[destroy] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] % identifier[self] )
keyword[if] identifier[self] . identifier[doc] . identifier[nb_pages] <= literal[int] :
identifier[self] . identifier[doc] . ide... | def destroy(self):
"""
Delete the page. May delete the whole document if it's actually the
last page.
"""
logger.info('Destroying page: %s' % self)
if self.doc.nb_pages <= 1:
self.doc.destroy()
return # depends on [control=['if'], data=[]]
doc_pages = self.doc.pa... |
def read(self):
"""Iterate over all JSON input (Generator)"""
for line in self.io.read():
with self.parse_line(line) as j:
yield j | def function[read, parameter[self]]:
constant[Iterate over all JSON input (Generator)]
for taget[name[line]] in starred[call[name[self].io.read, parameter[]]] begin[:]
with call[name[self].parse_line, parameter[name[line]]] begin[:]
<ast.Yield object at 0x7da20434... | keyword[def] identifier[read] ( identifier[self] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[self] . identifier[io] . identifier[read] ():
keyword[with] identifier[self] . identifier[parse_line] ( identifier[line] ) keyword[as] identifier[j] :
... | def read(self):
"""Iterate over all JSON input (Generator)"""
for line in self.io.read():
with self.parse_line(line) as j:
yield j # depends on [control=['with'], data=['j']] # depends on [control=['for'], data=['line']] |
def put(self, key, data):
"""Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
"""
try:
return self._dstore.pu... | def function[put, parameter[self, key, data]]:
constant[Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
]
<ast.Try object at... | keyword[def] identifier[put] ( identifier[self] , identifier[key] , identifier[data] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_dstore] . identifier[put] ( identifier[key] , identifier[data] )
keyword[finally] :
identifier[se... | def put(self, key, data):
"""Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
"""
try:
return self._dstore.put(key, data)... |
def error(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into m... | def function[error, parameter[cls, name, message]]:
constant[
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that a... | keyword[def] identifier[error] ( identifier[cls] , identifier[name] , identifier[message] ,* identifier[args] ):
literal[string]
identifier[cls] . identifier[getLogger] ( identifier[name] ). identifier[error] ( identifier[message] ,* identifier[args] ) | def error(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg u... |
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
s... | <ast.AsyncFunctionDef object at 0x7da1b276b160> | keyword[async] keyword[def] identifier[turn_on] ( identifier[self] , identifier[switch] = keyword[None] ):
literal[string]
keyword[if] identifier[switch] keyword[is] keyword[not] keyword[None] :
identifier[switch] = identifier[codecs] . identifier[decode] ( identifier[switch] . id... | async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b'\x10' + switch + b'\x01') # depends on [control=['if'], data=['switch']]
else:
packet = self.protocol.format_p... |
def read_core_register(self, reg):
"""
read CPU register
Unpack floating point register values
"""
regIndex = register_name_to_index(reg)
regValue = self.read_core_register_raw(regIndex)
# Convert int to float.
if is_single_float_register(regIndex):
... | def function[read_core_register, parameter[self, reg]]:
constant[
read CPU register
Unpack floating point register values
]
variable[regIndex] assign[=] call[name[register_name_to_index], parameter[name[reg]]]
variable[regValue] assign[=] call[name[self].read_core_registe... | keyword[def] identifier[read_core_register] ( identifier[self] , identifier[reg] ):
literal[string]
identifier[regIndex] = identifier[register_name_to_index] ( identifier[reg] )
identifier[regValue] = identifier[self] . identifier[read_core_register_raw] ( identifier[regIndex] )
... | def read_core_register(self, reg):
"""
read CPU register
Unpack floating point register values
"""
regIndex = register_name_to_index(reg)
regValue = self.read_core_register_raw(regIndex)
# Convert int to float.
if is_single_float_register(regIndex):
regValue = convers... |
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False,
draw=False, remove=False, priority=None):
"""
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that ... | def function[initialize_plot, parameter[self, data, ax, make_plot, clear, draw, remove, priority]]:
constant[
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
-... | keyword[def] identifier[initialize_plot] ( identifier[self] , identifier[data] = keyword[None] , identifier[ax] = keyword[None] , identifier[make_plot] = keyword[True] , identifier[clear] = keyword[False] ,
identifier[draw] = keyword[False] , identifier[remove] = keyword[False] , identifier[priority] = keyword[None]... | def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False, draw=False, remove=False, priority=None):
"""
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
... |
def extract(archive, directory, suffix=None, unpack_single_dir=False,
check_extract_file=None, progress_callback=None, default_mode='755'):
"""
Extract the contents of *archive* to the specified *directory*. This
function ensures that no file is extracted outside of the target directory
(which can theoretic... | def function[extract, parameter[archive, directory, suffix, unpack_single_dir, check_extract_file, progress_callback, default_mode]]:
constant[
Extract the contents of *archive* to the specified *directory*. This
function ensures that no file is extracted outside of the target directory
(which can theoret... | keyword[def] identifier[extract] ( identifier[archive] , identifier[directory] , identifier[suffix] = keyword[None] , identifier[unpack_single_dir] = keyword[False] ,
identifier[check_extract_file] = keyword[None] , identifier[progress_callback] = keyword[None] , identifier[default_mode] = literal[string] ):
lite... | def extract(archive, directory, suffix=None, unpack_single_dir=False, check_extract_file=None, progress_callback=None, default_mode='755'):
"""
Extract the contents of *archive* to the specified *directory*. This
function ensures that no file is extracted outside of the target directory
(which can theoretical... |
def _populateFromVariantFile(self, varFile, dataUrl, indexFile):
"""
Populates the instance variables of this VariantSet from the specified
pysam VariantFile object.
"""
if varFile.index is None:
raise exceptions.NotIndexedException(dataUrl)
for chrom in varFi... | def function[_populateFromVariantFile, parameter[self, varFile, dataUrl, indexFile]]:
constant[
Populates the instance variables of this VariantSet from the specified
pysam VariantFile object.
]
if compare[name[varFile].index is constant[None]] begin[:]
<ast.Raise object ... | keyword[def] identifier[_populateFromVariantFile] ( identifier[self] , identifier[varFile] , identifier[dataUrl] , identifier[indexFile] ):
literal[string]
keyword[if] identifier[varFile] . identifier[index] keyword[is] keyword[None] :
keyword[raise] identifier[exceptions] . identi... | def _populateFromVariantFile(self, varFile, dataUrl, indexFile):
"""
Populates the instance variables of this VariantSet from the specified
pysam VariantFile object.
"""
if varFile.index is None:
raise exceptions.NotIndexedException(dataUrl) # depends on [control=['if'], data=[]... |
def _assign_clusters(self):
"""Assign the samples to the closest centroids to create clusters
"""
self.clusters = np.array([self._closest_centroid(x) for x in self._X]) | def function[_assign_clusters, parameter[self]]:
constant[Assign the samples to the closest centroids to create clusters
]
name[self].clusters assign[=] call[name[np].array, parameter[<ast.ListComp object at 0x7da18fe92e60>]] | keyword[def] identifier[_assign_clusters] ( identifier[self] ):
literal[string]
identifier[self] . identifier[clusters] = identifier[np] . identifier[array] ([ identifier[self] . identifier[_closest_centroid] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[self] . identifier[... | def _assign_clusters(self):
"""Assign the samples to the closest centroids to create clusters
"""
self.clusters = np.array([self._closest_centroid(x) for x in self._X]) |
def cytherize(args, file):
"""
Used by core to integrate all the pieces of information, and to interface
with the user. Compiles and cleans up.
"""
if isOutDated(file):
if isUpdated(file):
response = initiateCompilation(args, file)
else:
response = {'returncod... | def function[cytherize, parameter[args, file]]:
constant[
Used by core to integrate all the pieces of information, and to interface
with the user. Compiles and cleans up.
]
if call[name[isOutDated], parameter[name[file]]] begin[:]
if call[name[isUpdated], parameter[name[file]... | keyword[def] identifier[cytherize] ( identifier[args] , identifier[file] ):
literal[string]
keyword[if] identifier[isOutDated] ( identifier[file] ):
keyword[if] identifier[isUpdated] ( identifier[file] ):
identifier[response] = identifier[initiateCompilation] ( identifier[args] , id... | def cytherize(args, file):
"""
Used by core to integrate all the pieces of information, and to interface
with the user. Compiles and cleans up.
"""
if isOutDated(file):
if isUpdated(file):
response = initiateCompilation(args, file) # depends on [control=['if'], data=[]]
... |
def _apply_orthogonal_view(self):
"""Orthogonal view with respect to current aspect ratio
"""
left, right, bottom, top = self.get_view_coordinates()
glOrtho(left, right, bottom, top, -10, 0) | def function[_apply_orthogonal_view, parameter[self]]:
constant[Orthogonal view with respect to current aspect ratio
]
<ast.Tuple object at 0x7da2041daef0> assign[=] call[name[self].get_view_coordinates, parameter[]]
call[name[glOrtho], parameter[name[left], name[right], name[bottom], na... | keyword[def] identifier[_apply_orthogonal_view] ( identifier[self] ):
literal[string]
identifier[left] , identifier[right] , identifier[bottom] , identifier[top] = identifier[self] . identifier[get_view_coordinates] ()
identifier[glOrtho] ( identifier[left] , identifier[right] , identifier... | def _apply_orthogonal_view(self):
"""Orthogonal view with respect to current aspect ratio
"""
(left, right, bottom, top) = self.get_view_coordinates()
glOrtho(left, right, bottom, top, -10, 0) |
async def cache_instruments(self,
require: Dict[top_types.Mount, str] = None):
"""
- Get the attached instrument on each mount and
- Cache their pipette configs from pipette-config.json
If specified, the require element should be a dict of mounts to
... | <ast.AsyncFunctionDef object at 0x7da1b086ec50> | keyword[async] keyword[def] identifier[cache_instruments] ( identifier[self] ,
identifier[require] : identifier[Dict] [ identifier[top_types] . identifier[Mount] , identifier[str] ]= keyword[None] ):
literal[string]
identifier[checked_require] = identifier[require] keyword[or] {}
identi... | async def cache_instruments(self, require: Dict[top_types.Mount, str]=None):
"""
- Get the attached instrument on each mount and
- Cache their pipette configs from pipette-config.json
If specified, the require element should be a dict of mounts to
instrument models describing the ... |
def qc_data(self, tests, alias=None):
"""
Run a series of tests against the data and return the corresponding
results.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
"""
# We'... | def function[qc_data, parameter[self, tests, alias]]:
constant[
Run a series of tests against the data and return the corresponding
results.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
... | keyword[def] identifier[qc_data] ( identifier[self] , identifier[tests] , identifier[alias] = keyword[None] ):
literal[string]
identifier[r] ={ identifier[m] : identifier[c] . identifier[quality] ( identifier[tests] , identifier[alias] ) keyword[for] identifier[m] , identifier[c] keyword... | def qc_data(self, tests, alias=None):
"""
Run a series of tests against the data and return the corresponding
results.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
"""
# We'll get a... |
def stream_subsegments(self):
"""
Stream all closed subsegments to the daemon
and remove reference to the parent segment.
No-op for a not sampled segment.
"""
segment = self.current_segment()
if self.streaming.is_eligible(segment):
self.streaming.stre... | def function[stream_subsegments, parameter[self]]:
constant[
Stream all closed subsegments to the daemon
and remove reference to the parent segment.
No-op for a not sampled segment.
]
variable[segment] assign[=] call[name[self].current_segment, parameter[]]
if cal... | keyword[def] identifier[stream_subsegments] ( identifier[self] ):
literal[string]
identifier[segment] = identifier[self] . identifier[current_segment] ()
keyword[if] identifier[self] . identifier[streaming] . identifier[is_eligible] ( identifier[segment] ):
identifier[self] ... | def stream_subsegments(self):
"""
Stream all closed subsegments to the daemon
and remove reference to the parent segment.
No-op for a not sampled segment.
"""
segment = self.current_segment()
if self.streaming.is_eligible(segment):
self.streaming.stream(segment, self.... |
def workspace_from_nothing(self, directory, mets_basename='mets.xml', clobber_mets=False):
"""
Create an empty workspace.
"""
if directory is None:
directory = tempfile.mkdtemp(prefix=TMP_PREFIX)
if not exists(directory):
makedirs(directory)
mets_... | def function[workspace_from_nothing, parameter[self, directory, mets_basename, clobber_mets]]:
constant[
Create an empty workspace.
]
if compare[name[directory] is constant[None]] begin[:]
variable[directory] assign[=] call[name[tempfile].mkdtemp, parameter[]]
if ... | keyword[def] identifier[workspace_from_nothing] ( identifier[self] , identifier[directory] , identifier[mets_basename] = literal[string] , identifier[clobber_mets] = keyword[False] ):
literal[string]
keyword[if] identifier[directory] keyword[is] keyword[None] :
identifier[directory]... | def workspace_from_nothing(self, directory, mets_basename='mets.xml', clobber_mets=False):
"""
Create an empty workspace.
"""
if directory is None:
directory = tempfile.mkdtemp(prefix=TMP_PREFIX) # depends on [control=['if'], data=['directory']]
if not exists(directory):
mak... |
def ipvoid_check(ip):
"""Checks IPVoid.com for info on an IP address"""
if not is_IPv4Address(ip):
return None
return_dict = {}
headers = {'User-Agent': useragent}
url = 'http://ipvoid.com/scan/%s/' % ip
response = requests.get(url, headers=headers)
data = BeautifulSoup(response.tex... | def function[ipvoid_check, parameter[ip]]:
constant[Checks IPVoid.com for info on an IP address]
if <ast.UnaryOp object at 0x7da1b28ae8f0> begin[:]
return[constant[None]]
variable[return_dict] assign[=] dictionary[[], []]
variable[headers] assign[=] dictionary[[<ast.Constant obje... | keyword[def] identifier[ipvoid_check] ( identifier[ip] ):
literal[string]
keyword[if] keyword[not] identifier[is_IPv4Address] ( identifier[ip] ):
keyword[return] keyword[None]
identifier[return_dict] ={}
identifier[headers] ={ literal[string] : identifier[useragent] }
identifie... | def ipvoid_check(ip):
"""Checks IPVoid.com for info on an IP address"""
if not is_IPv4Address(ip):
return None # depends on [control=['if'], data=[]]
return_dict = {}
headers = {'User-Agent': useragent}
url = 'http://ipvoid.com/scan/%s/' % ip
response = requests.get(url, headers=headers... |
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in configuration files"""
device = '0.0.%s' % fcp
set_zfcp_conf = 'echo "%(device)s %(wwpn)s %(lun)s" >> /etc/zfcp.conf'\
% {'device': device, 'wwpn': target_wwpn,
... | def function[_set_zfcp_config_files, parameter[self, fcp, target_wwpn, target_lun]]:
constant[rhel6 set WWPN and LUN in configuration files]
variable[device] assign[=] binary_operation[constant[0.0.%s] <ast.Mod object at 0x7da2590d6920> name[fcp]]
variable[set_zfcp_conf] assign[=] binary_operati... | keyword[def] identifier[_set_zfcp_config_files] ( identifier[self] , identifier[fcp] , identifier[target_wwpn] , identifier[target_lun] ):
literal[string]
identifier[device] = literal[string] % identifier[fcp]
identifier[set_zfcp_conf] = literal[string] %{ literal[string] : identifier[dev... | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in configuration files"""
device = '0.0.%s' % fcp
set_zfcp_conf = 'echo "%(device)s %(wwpn)s %(lun)s" >> /etc/zfcp.conf' % {'device': device, 'wwpn': target_wwpn, 'lun': target_lun}
trigger_uevent = 'echo "add" >> ... |
def nanfill(a, f_a, *args, **kwargs):
"""Fill masked areas with np.nan
Wrapper for functions that can't handle ma (e.g. scipy.ndimage)
This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155
"""
a = checkma(a)
... | def function[nanfill, parameter[a, f_a]]:
constant[Fill masked areas with np.nan
Wrapper for functions that can't handle ma (e.g. scipy.ndimage)
This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155
]
va... | keyword[def] identifier[nanfill] ( identifier[a] , identifier[f_a] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[a] = identifier[checkma] ( identifier[a] )
identifier[ndv] = identifier[a] . identifier[fill_value]
identifier[b] = identifier[f_a] ( identifier[a] . i... | def nanfill(a, f_a, *args, **kwargs):
"""Fill masked areas with np.nan
Wrapper for functions that can't handle ma (e.g. scipy.ndimage)
This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155
"""
a = checkma(a)
... |
def camel_to_snake(name):
"""Converts CamelCase to snake_case.
Args:
name (string): The name to convert from CamelCase to snake_case.
Returns:
string: Converted string.
"""
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() | def function[camel_to_snake, parameter[name]]:
constant[Converts CamelCase to snake_case.
Args:
name (string): The name to convert from CamelCase to snake_case.
Returns:
string: Converted string.
]
variable[s1] assign[=] call[name[re].sub, parameter[constant[(.)([A-Z][a-z]+... | keyword[def] identifier[camel_to_snake] ( identifier[name] ):
literal[string]
identifier[s1] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[name] )
keyword[return] identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[s1] ). identifier[... | def camel_to_snake(name):
"""Converts CamelCase to snake_case.
Args:
name (string): The name to convert from CamelCase to snake_case.
Returns:
string: Converted string.
"""
s1 = re.sub('(.)([A-Z][a-z]+)', '\\1_\\2', name)
return re.sub('([a-z0-9])([A-Z])', '\\1_\\2', s1).lower(... |
def cursor_after(self):
"""Return the cursor after the current item.
You must pass a QueryOptions object with produce_cursors=True
for this to work.
If there is no cursor or no current item, raise BadArgumentError.
Before next() has returned there is no cursor. Once the loop is
exhausted, t... | def function[cursor_after, parameter[self]]:
constant[Return the cursor after the current item.
You must pass a QueryOptions object with produce_cursors=True
for this to work.
If there is no cursor or no current item, raise BadArgumentError.
Before next() has returned there is no cursor. On... | keyword[def] identifier[cursor_after] ( identifier[self] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[_cursor_after] , identifier[BaseException] ):
keyword[raise] identifier[self] . identifier[_cursor_after]
keyword[return] identifier[self] . identif... | def cursor_after(self):
"""Return the cursor after the current item.
You must pass a QueryOptions object with produce_cursors=True
for this to work.
If there is no cursor or no current item, raise BadArgumentError.
Before next() has returned there is no cursor. Once the loop is
exhausted, t... |
def delete(self, ids):
"""
Method to undeploy pool's by their ids
:param ids: Identifiers of deployed pool's
:return: Empty Dict
"""
url = build_uri_with_ids('api/v3/pool/deploy/%s/', ids)
return super(ApiPoolDeploy, self).delete(url) | def function[delete, parameter[self, ids]]:
constant[
Method to undeploy pool's by their ids
:param ids: Identifiers of deployed pool's
:return: Empty Dict
]
variable[url] assign[=] call[name[build_uri_with_ids], parameter[constant[api/v3/pool/deploy/%s/], name[ids]]]
... | keyword[def] identifier[delete] ( identifier[self] , identifier[ids] ):
literal[string]
identifier[url] = identifier[build_uri_with_ids] ( literal[string] , identifier[ids] )
keyword[return] identifier[super] ( identifier[ApiPoolDeploy] , identifier[self] ). identifier[delete] ( identifi... | def delete(self, ids):
"""
Method to undeploy pool's by their ids
:param ids: Identifiers of deployed pool's
:return: Empty Dict
"""
url = build_uri_with_ids('api/v3/pool/deploy/%s/', ids)
return super(ApiPoolDeploy, self).delete(url) |
def create_threadpool_executed_func(original_func):
"""
Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception
or backtrace in the caller's context.
:param original_func: function to wrap
:returns: wrapper function
"""
def wrapped_fun... | def function[create_threadpool_executed_func, parameter[original_func]]:
constant[
Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception
or backtrace in the caller's context.
:param original_func: function to wrap
:returns: wrapper funct... | keyword[def] identifier[create_threadpool_executed_func] ( identifier[original_func] ):
literal[string]
keyword[def] identifier[wrapped_func] (* identifier[args] ,** identifier[kwargs] ):
keyword[try] :
identifier[result] = identifier[original_func] (* identifier[args] ,** identifier... | def create_threadpool_executed_func(original_func):
"""
Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception
or backtrace in the caller's context.
:param original_func: function to wrap
:returns: wrapper function
"""
def wrapped_fu... |
async def generate_license(self, title, avatar, badges=None, widgets=None):
"""Generate a license.
This function is a coroutine.
Parameters:
title: str - title of the license
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link ... | <ast.AsyncFunctionDef object at 0x7da1b26ae9b0> | keyword[async] keyword[def] identifier[generate_license] ( identifier[self] , identifier[title] , identifier[avatar] , identifier[badges] = keyword[None] , identifier[widgets] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[title] , identifier[str]... | async def generate_license(self, title, avatar, badges=None, widgets=None):
"""Generate a license.
This function is a coroutine.
Parameters:
title: str - title of the license
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to a... |
def directionality(image, min_distance = 4, threshold = 0.1, voxelspacing = None, mask = slice(None)):
r"""
Takes a simple or multi-spectral image and returns the directionality of the image texture.
It is just a value representing the strength of directionality, not the specific direction.
An edg... | def function[directionality, parameter[image, min_distance, threshold, voxelspacing, mask]]:
constant[
Takes a simple or multi-spectral image and returns the directionality of the image texture.
It is just a value representing the strength of directionality, not the specific direction.
An edge... | keyword[def] identifier[directionality] ( identifier[image] , identifier[min_distance] = literal[int] , identifier[threshold] = literal[int] , identifier[voxelspacing] = keyword[None] , identifier[mask] = identifier[slice] ( keyword[None] )):
literal[string]
identifier[image] = identifier[numpy] . identifi... | def directionality(image, min_distance=4, threshold=0.1, voxelspacing=None, mask=slice(None)):
"""
Takes a simple or multi-spectral image and returns the directionality of the image texture.
It is just a value representing the strength of directionality, not the specific direction.
An edge detecti... |
def cc(self, args=None, ret_val=None, sp_delta=None, func_ty=None):
"""
Return a SimCC (calling convention) parametrized for this project and, optionally, a given function.
:param args: A list of argument storage locations, as SimFunctionArguments.
:param ret_val: The return ... | def function[cc, parameter[self, args, ret_val, sp_delta, func_ty]]:
constant[
Return a SimCC (calling convention) parametrized for this project and, optionally, a given function.
:param args: A list of argument storage locations, as SimFunctionArguments.
:param ret_val: The ... | keyword[def] identifier[cc] ( identifier[self] , identifier[args] = keyword[None] , identifier[ret_val] = keyword[None] , identifier[sp_delta] = keyword[None] , identifier[func_ty] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_default_cc] ( identifier[arch] = i... | def cc(self, args=None, ret_val=None, sp_delta=None, func_ty=None):
"""
Return a SimCC (calling convention) parametrized for this project and, optionally, a given function.
:param args: A list of argument storage locations, as SimFunctionArguments.
:param ret_val: The return valu... |
def build_columns(self, X, term=-1, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy s... | def function[build_columns, parameter[self, X, term, verbose]]:
constant[construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-----... | keyword[def] identifier[build_columns] ( identifier[self] , identifier[X] , identifier[term] =- literal[int] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[if] identifier[term] ==- literal[int] :
identifier[term] = identifier[range] ( identifier[len] ( identifier[se... | def build_columns(self, X, term=-1, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy spars... |
def detect_complex_func(func):
"""Detect the cyclomatic complexity of the contract functions
shouldn't be greater than 7
"""
result = []
code_complexity = compute_cyclomatic_complexity(func)
if code_complexity > ComplexFunction.MAX_CYCLOMATIC_COMPLEXITY:
r... | def function[detect_complex_func, parameter[func]]:
constant[Detect the cyclomatic complexity of the contract functions
shouldn't be greater than 7
]
variable[result] assign[=] list[[]]
variable[code_complexity] assign[=] call[name[compute_cyclomatic_complexity], parameter[nam... | keyword[def] identifier[detect_complex_func] ( identifier[func] ):
literal[string]
identifier[result] =[]
identifier[code_complexity] = identifier[compute_cyclomatic_complexity] ( identifier[func] )
keyword[if] identifier[code_complexity] > identifier[ComplexFunction] . identifi... | def detect_complex_func(func):
"""Detect the cyclomatic complexity of the contract functions
shouldn't be greater than 7
"""
result = []
code_complexity = compute_cyclomatic_complexity(func)
if code_complexity > ComplexFunction.MAX_CYCLOMATIC_COMPLEXITY:
result.append({'func':... |
def post_process_fieldsets(context, fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
Additionally, it ensures that dynamically added fields (i.e.
``ApplicationContent``'s ``admin_fields`` option) are shown.
"""
# abort if... | def function[post_process_fieldsets, parameter[context, fieldset]]:
constant[
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
Additionally, it ensures that dynamically added fields (i.e.
``ApplicationContent``'s ``admin_fields`` option) ar... | keyword[def] identifier[post_process_fieldsets] ( identifier[context] , identifier[fieldset] ):
literal[string]
keyword[if] identifier[fieldset] . identifier[model_admin] . identifier[fieldsets] :
keyword[return] identifier[fieldset]
identifier[fields_to_include] = identifier[set] ( ... | def post_process_fieldsets(context, fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
Additionally, it ensures that dynamically added fields (i.e.
``ApplicationContent``'s ``admin_fields`` option) are shown.
"""
# abort if... |
def fost_hmac_url_signature(
key, secret, host, path, query_string, expires):
"""
Return a signature that corresponds to the signed URL.
"""
if query_string:
document = '%s%s?%s\n%s' % (host, path, query_string, expires)
else:
document = '%s%s\n%s' % (host, path, expires)
... | def function[fost_hmac_url_signature, parameter[key, secret, host, path, query_string, expires]]:
constant[
Return a signature that corresponds to the signed URL.
]
if name[query_string] begin[:]
variable[document] assign[=] binary_operation[constant[%s%s?%s
%s] <ast.Mod obje... | keyword[def] identifier[fost_hmac_url_signature] (
identifier[key] , identifier[secret] , identifier[host] , identifier[path] , identifier[query_string] , identifier[expires] ):
literal[string]
keyword[if] identifier[query_string] :
identifier[document] = literal[string] %( identifier[host] , id... | def fost_hmac_url_signature(key, secret, host, path, query_string, expires):
"""
Return a signature that corresponds to the signed URL.
"""
if query_string:
document = '%s%s?%s\n%s' % (host, path, query_string, expires) # depends on [control=['if'], data=[]]
else:
document = '%s... |
def deserialize_base64(attr):
"""Deserialize base64 encoded string into string.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
if isinstance(attr, ET.Element):
attr = attr.text
p... | def function[deserialize_base64, parameter[attr]]:
constant[Deserialize base64 encoded string into string.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid.
]
if call[name[isinstance], parameter[name[attr]... | keyword[def] identifier[deserialize_base64] ( identifier[attr] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[attr] , identifier[ET] . identifier[Element] ):
identifier[attr] = identifier[attr] . identifier[text]
identifier[padding] = literal[string] *( l... | def deserialize_base64(attr):
"""Deserialize base64 encoded string into string.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
if isinstance(attr, ET.Element):
attr = attr.text # depends on [contro... |
def _deserialize(self, value, attr, data):
"""Deserialize string by sanitizing HTML."""
value = super(SanitizedHTML, self)._deserialize(value, attr, data)
return bleach.clean(
value,
tags=self.tags,
attributes=self.attrs,
strip=True,
).stri... | def function[_deserialize, parameter[self, value, attr, data]]:
constant[Deserialize string by sanitizing HTML.]
variable[value] assign[=] call[call[name[super], parameter[name[SanitizedHTML], name[self]]]._deserialize, parameter[name[value], name[attr], name[data]]]
return[call[call[name[bleach].cl... | keyword[def] identifier[_deserialize] ( identifier[self] , identifier[value] , identifier[attr] , identifier[data] ):
literal[string]
identifier[value] = identifier[super] ( identifier[SanitizedHTML] , identifier[self] ). identifier[_deserialize] ( identifier[value] , identifier[attr] , identifier[... | def _deserialize(self, value, attr, data):
"""Deserialize string by sanitizing HTML."""
value = super(SanitizedHTML, self)._deserialize(value, attr, data)
return bleach.clean(value, tags=self.tags, attributes=self.attrs, strip=True).strip() |
def timedcall(executable_function, *args):
"""!
@brief Executes specified method or function with measuring of execution time.
@param[in] executable_function (pointer): Pointer to function or method.
@param[in] args (*): Arguments of called function or method.
@return (tuple) Execut... | def function[timedcall, parameter[executable_function]]:
constant[!
@brief Executes specified method or function with measuring of execution time.
@param[in] executable_function (pointer): Pointer to function or method.
@param[in] args (*): Arguments of called function or method.
@retu... | keyword[def] identifier[timedcall] ( identifier[executable_function] ,* identifier[args] ):
literal[string]
identifier[time_start] = identifier[time] . identifier[clock] ();
identifier[result] = identifier[executable_function] (* identifier[args] );
identifier[time_end] = identifier[time] .... | def timedcall(executable_function, *args):
"""!
@brief Executes specified method or function with measuring of execution time.
@param[in] executable_function (pointer): Pointer to function or method.
@param[in] args (*): Arguments of called function or method.
@return (tuple) Execution tim... |
def process_result_value(self, value, dialect):
"""convert value from json to a python object"""
if value is not None:
value = simplejson.loads(value)
return value | def function[process_result_value, parameter[self, value, dialect]]:
constant[convert value from json to a python object]
if compare[name[value] is_not constant[None]] begin[:]
variable[value] assign[=] call[name[simplejson].loads, parameter[name[value]]]
return[name[value]] | keyword[def] identifier[process_result_value] ( identifier[self] , identifier[value] , identifier[dialect] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
identifier[value] = identifier[simplejson] . identifier[loads] ( identifier[value] )
... | def process_result_value(self, value, dialect):
"""convert value from json to a python object"""
if value is not None:
value = simplejson.loads(value) # depends on [control=['if'], data=['value']]
return value |
def create_patches(destination, root, settings=None, traverse_bases=True,
filter=default_filter, recursive=True, use_decorators=True):
"""Create a patch for each member of a module or a class.
Parameters
----------
destination : object
Patch destination.
root : object
... | def function[create_patches, parameter[destination, root, settings, traverse_bases, filter, recursive, use_decorators]]:
constant[Create a patch for each member of a module or a class.
Parameters
----------
destination : object
Patch destination.
root : object
Root object, eithe... | keyword[def] identifier[create_patches] ( identifier[destination] , identifier[root] , identifier[settings] = keyword[None] , identifier[traverse_bases] = keyword[True] ,
identifier[filter] = identifier[default_filter] , identifier[recursive] = keyword[True] , identifier[use_decorators] = keyword[True] ):
liter... | def create_patches(destination, root, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True):
"""Create a patch for each member of a module or a class.
Parameters
----------
destination : object
Patch destination.
root : object
Root object, e... |
def run(self):
"""Run command and wait until it finishes."""
_check_directory(self.directory)
with DirectoryContextManager(self.directory):
process = subprocess.Popen(self.arguments, shell=self._shell, env=self.env)
_, _ = process.communicate()
returncode = pro... | def function[run, parameter[self]]:
constant[Run command and wait until it finishes.]
call[name[_check_directory], parameter[name[self].directory]]
with call[name[DirectoryContextManager], parameter[name[self].directory]] begin[:]
variable[process] assign[=] call[name[subprocess]... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[_check_directory] ( identifier[self] . identifier[directory] )
keyword[with] identifier[DirectoryContextManager] ( identifier[self] . identifier[directory] ):
identifier[process] = identifier[subpr... | def run(self):
"""Run command and wait until it finishes."""
_check_directory(self.directory)
with DirectoryContextManager(self.directory):
process = subprocess.Popen(self.arguments, shell=self._shell, env=self.env)
(_, _) = process.communicate() # depends on [control=['with'], data=[]]
... |
def set_cwd(new_path):
"""
Usage:
with set_cwd('/some/dir'):
walk_around_the_filesystem()
"""
try:
curdir = os.getcwd()
except OSError:
curdir = new_path
try:
os.chdir(new_path)
yield
finally:
os.chdir(curdir) | def function[set_cwd, parameter[new_path]]:
constant[
Usage:
with set_cwd('/some/dir'):
walk_around_the_filesystem()
]
<ast.Try object at 0x7da1b0089c60>
<ast.Try object at 0x7da1b00da230> | keyword[def] identifier[set_cwd] ( identifier[new_path] ):
literal[string]
keyword[try] :
identifier[curdir] = identifier[os] . identifier[getcwd] ()
keyword[except] identifier[OSError] :
identifier[curdir] = identifier[new_path]
keyword[try] :
identifier[os] . identi... | def set_cwd(new_path):
"""
Usage:
with set_cwd('/some/dir'):
walk_around_the_filesystem()
"""
try:
curdir = os.getcwd() # depends on [control=['try'], data=[]]
except OSError:
curdir = new_path # depends on [control=['except'], data=[]]
try:
os.chdi... |
def system_generate_batch_inputs(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/generateBatchInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method:-/system/generateBatchInputs
"""
return DXHTTPRequest('/system/generateBat... | def function[system_generate_batch_inputs, parameter[input_params, always_retry]]:
constant[
Invokes the /system/generateBatchInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method:-/system/generateBatchInputs
]
return[call[name[DXHTTPRequest... | keyword[def] identifier[system_generate_batch_inputs] ( identifier[input_params] ={}, identifier[always_retry] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[DXHTTPRequest] ( literal[string] , identifier[input_params] , identifier[always_retry] = identifier[always_ret... | def system_generate_batch_inputs(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/generateBatchInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method:-/system/generateBatchInputs
"""
return DXHTTPRequest('/system/generateBat... |
def _GetImportTimestamps(self, pefile_object):
"""Retrieves timestamps from the import directory, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[int]: import timestamps.
"""
import_timestamps = []
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_IMPORT'):... | def function[_GetImportTimestamps, parameter[self, pefile_object]]:
constant[Retrieves timestamps from the import directory, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[int]: import timestamps.
]
variable[import_timestamps] assign[=] list[[]]
... | keyword[def] identifier[_GetImportTimestamps] ( identifier[self] , identifier[pefile_object] ):
literal[string]
identifier[import_timestamps] =[]
keyword[if] keyword[not] identifier[hasattr] ( identifier[pefile_object] , literal[string] ):
keyword[return] identifier[import_timestamps]
... | def _GetImportTimestamps(self, pefile_object):
"""Retrieves timestamps from the import directory, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[int]: import timestamps.
"""
import_timestamps = []
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_IMPORT'):... |
def next_history(self, current): # (C-n)
u'''Move forward through the history list, fetching the next command. '''
if self.history_cursor < len(self.history) - 1:
self.history_cursor += 1
current.set_line(self.history[self.history_cursor].get_line_text()) | def function[next_history, parameter[self, current]]:
constant[Move forward through the history list, fetching the next command. ]
if compare[name[self].history_cursor less[<] binary_operation[call[name[len], parameter[name[self].history]] - constant[1]]] begin[:]
<ast.AugAssign object at 0x7da1... | keyword[def] identifier[next_history] ( identifier[self] , identifier[current] ):
literal[string]
keyword[if] identifier[self] . identifier[history_cursor] < identifier[len] ( identifier[self] . identifier[history] )- literal[int] :
identifier[self] . identifier[history_cursor] += ... | def next_history(self, current): # (C-n)
u'Move forward through the history list, fetching the next command. '
if self.history_cursor < len(self.history) - 1:
self.history_cursor += 1
current.set_line(self.history[self.history_cursor].get_line_text()) # depends on [control=['if'], data=[]] |
def is_alive(self):
"""
Test Function to check WHAT IF servers are up and running.
"""
u = urllib.urlopen("http://wiws.cmbi.ru.nl/rest/TestEmpty/id/1crn/")
x = xml.dom.minidom.parse(u)
self.alive = len(x.getElementsByTagName("TestEmptyResponse"))
return ... | def function[is_alive, parameter[self]]:
constant[
Test Function to check WHAT IF servers are up and running.
]
variable[u] assign[=] call[name[urllib].urlopen, parameter[constant[http://wiws.cmbi.ru.nl/rest/TestEmpty/id/1crn/]]]
variable[x] assign[=] call[name[xml].dom.minidom.p... | keyword[def] identifier[is_alive] ( identifier[self] ):
literal[string]
identifier[u] = identifier[urllib] . identifier[urlopen] ( literal[string] )
identifier[x] = identifier[xml] . identifier[dom] . identifier[minidom] . identifier[parse] ( identifier[u] )
identifier[self] . id... | def is_alive(self):
"""
Test Function to check WHAT IF servers are up and running.
"""
u = urllib.urlopen('http://wiws.cmbi.ru.nl/rest/TestEmpty/id/1crn/')
x = xml.dom.minidom.parse(u)
self.alive = len(x.getElementsByTagName('TestEmptyResponse'))
return self.alive |
def _normalize_json_search_response(self, json):
"""
Normalizes a JSON search response so that PB and HTTP have the
same return value
"""
result = {}
if 'facet_counts' in json:
result['facet_counts'] = json[u'facet_counts']
if 'grouped' in json:
... | def function[_normalize_json_search_response, parameter[self, json]]:
constant[
Normalizes a JSON search response so that PB and HTTP have the
same return value
]
variable[result] assign[=] dictionary[[], []]
if compare[constant[facet_counts] in name[json]] begin[:]
... | keyword[def] identifier[_normalize_json_search_response] ( identifier[self] , identifier[json] ):
literal[string]
identifier[result] ={}
keyword[if] literal[string] keyword[in] identifier[json] :
identifier[result] [ literal[string] ]= identifier[json] [ literal[string] ]
... | def _normalize_json_search_response(self, json):
"""
Normalizes a JSON search response so that PB and HTTP have the
same return value
"""
result = {}
if 'facet_counts' in json:
result['facet_counts'] = json[u'facet_counts'] # depends on [control=['if'], data=['json']]
if... |
def remote(view, block=None, **flags):
"""Turn a function into a remote function.
This method can be used for map:
In [1]: @remote(view,block=True)
...: def func(a):
...: pass
"""
def remote_function(f):
return RemoteFunction(view, f, block=block, **flags)
return remo... | def function[remote, parameter[view, block]]:
constant[Turn a function into a remote function.
This method can be used for map:
In [1]: @remote(view,block=True)
...: def func(a):
...: pass
]
def function[remote_function, parameter[f]]:
return[call[name[RemoteFuncti... | keyword[def] identifier[remote] ( identifier[view] , identifier[block] = keyword[None] ,** identifier[flags] ):
literal[string]
keyword[def] identifier[remote_function] ( identifier[f] ):
keyword[return] identifier[RemoteFunction] ( identifier[view] , identifier[f] , identifier[block] = identif... | def remote(view, block=None, **flags):
"""Turn a function into a remote function.
This method can be used for map:
In [1]: @remote(view,block=True)
...: def func(a):
...: pass
"""
def remote_function(f):
return RemoteFunction(view, f, block=block, **flags)
return remo... |
def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded | def function[round_to_int, parameter[number, precision]]:
constant[Round a number to a precision]
variable[precision] assign[=] call[name[int], parameter[name[precision]]]
variable[rounded] assign[=] binary_operation[binary_operation[binary_operation[call[name[int], parameter[name[number]]] + bi... | keyword[def] identifier[round_to_int] ( identifier[number] , identifier[precision] ):
literal[string]
identifier[precision] = identifier[int] ( identifier[precision] )
identifier[rounded] =( identifier[int] ( identifier[number] )+ identifier[precision] / literal[int] )// identifier[precision] * identi... | def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded |
def _async_sub_acc_push(self, acc_id_list):
"""
异步连接指定要接收送的acc id
:param acc_id:
:return:
"""
kargs = {
'acc_id_list': acc_id_list,
'conn_id': self.get_async_conn_id(),
}
ret_code, msg, push_req_str = SubAccPush.pack_req(**kargs)
... | def function[_async_sub_acc_push, parameter[self, acc_id_list]]:
constant[
异步连接指定要接收送的acc id
:param acc_id:
:return:
]
variable[kargs] assign[=] dictionary[[<ast.Constant object at 0x7da2045647f0>, <ast.Constant object at 0x7da2045671f0>], [<ast.Name object at 0x7da204566... | keyword[def] identifier[_async_sub_acc_push] ( identifier[self] , identifier[acc_id_list] ):
literal[string]
identifier[kargs] ={
literal[string] : identifier[acc_id_list] ,
literal[string] : identifier[self] . identifier[get_async_conn_id] (),
}
identifier[ret_co... | def _async_sub_acc_push(self, acc_id_list):
"""
异步连接指定要接收送的acc id
:param acc_id:
:return:
"""
kargs = {'acc_id_list': acc_id_list, 'conn_id': self.get_async_conn_id()}
(ret_code, msg, push_req_str) = SubAccPush.pack_req(**kargs)
if ret_code == RET_OK:
self._send_a... |
def sum_of_squares(obs, pred):
"""
Sum of squares between observed and predicted data
Parameters
----------
obs : iterable
Observed data
pred : iterable
Predicted data
Returns
-------
float
Sum of squares
Notes
-----
The length of observed and p... | def function[sum_of_squares, parameter[obs, pred]]:
constant[
Sum of squares between observed and predicted data
Parameters
----------
obs : iterable
Observed data
pred : iterable
Predicted data
Returns
-------
float
Sum of squares
Notes
-----
... | keyword[def] identifier[sum_of_squares] ( identifier[obs] , identifier[pred] ):
literal[string]
keyword[return] identifier[np] . identifier[sum] (( identifier[np] . identifier[array] ( identifier[obs] )- identifier[np] . identifier[array] ( identifier[pred] ))** literal[int] ) | def sum_of_squares(obs, pred):
"""
Sum of squares between observed and predicted data
Parameters
----------
obs : iterable
Observed data
pred : iterable
Predicted data
Returns
-------
float
Sum of squares
Notes
-----
The length of observed and p... |
def execute_get_text(command, raise_errors=False): # type: (str, bool) -> str
"""
Execute a shell commmand
:param command:
:return:
"""
try:
result = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
# print(result.decode())
except subprocess.CalledProce... | def function[execute_get_text, parameter[command, raise_errors]]:
constant[
Execute a shell commmand
:param command:
:return:
]
<ast.Try object at 0x7da18fe933d0>
if name[result] begin[:]
return[call[name[result].decode, parameter[constant[utf-8]]]]
return[constant[]] | keyword[def] identifier[execute_get_text] ( identifier[command] , identifier[raise_errors] = keyword[False] ):
literal[string]
keyword[try] :
identifier[result] = identifier[subprocess] . identifier[check_output] ( identifier[command] , identifier[stderr] = identifier[subprocess] . identifier[STDO... | def execute_get_text(command, raise_errors=False): # type: (str, bool) -> str
'\n Execute a shell commmand\n :param command:\n :return:\n '
try:
result = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) # depends on [control=['try'], data=[]]
# print(result.decode... |
def get_frame(frame_id, rows=10, rows_offset=0, cols=-1, full_cols=-1, cols_offset=0, light=False):
"""
Retrieve an existing H2OFrame from the H2O cluster using the frame's id.
:param str frame_id: id of the frame to retrieve
:param int rows: number of rows to fetch for preview (10 by d... | def function[get_frame, parameter[frame_id, rows, rows_offset, cols, full_cols, cols_offset, light]]:
constant[
Retrieve an existing H2OFrame from the H2O cluster using the frame's id.
:param str frame_id: id of the frame to retrieve
:param int rows: number of rows to fetch for preview ... | keyword[def] identifier[get_frame] ( identifier[frame_id] , identifier[rows] = literal[int] , identifier[rows_offset] = literal[int] , identifier[cols] =- literal[int] , identifier[full_cols] =- literal[int] , identifier[cols_offset] = literal[int] , identifier[light] = keyword[False] ):
literal[string]
... | def get_frame(frame_id, rows=10, rows_offset=0, cols=-1, full_cols=-1, cols_offset=0, light=False):
"""
Retrieve an existing H2OFrame from the H2O cluster using the frame's id.
:param str frame_id: id of the frame to retrieve
:param int rows: number of rows to fetch for preview (10 by defau... |
def read(cls, fname):
""" read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format.
"""
#... | def function[read, parameter[cls, fname]]:
constant[ read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file fo... | keyword[def] identifier[read] ( identifier[cls] , identifier[fname] ):
literal[string]
identifier[fmt] = identifier[op] . identifier[splitext] ( identifier[fname] )[ literal[int] ]. identifier[lower] ()
keyword[assert] identifier[fmt] keyword[in] ( literal[string] , literal[stri... | def read(cls, fname):
""" read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format.
"""
# Open fi... |
def sbar(Ss):
"""
calculate average s,sigma from list of "s"s.
"""
if type(Ss) == list:
Ss = np.array(Ss)
npts = Ss.shape[0]
Ss = Ss.transpose()
avd, avs = [], []
# D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+Ss[2]),Ss[5]+0.5*(Ss[0]+Ss[2])]).transpose(... | def function[sbar, parameter[Ss]]:
constant[
calculate average s,sigma from list of "s"s.
]
if compare[call[name[type], parameter[name[Ss]]] equal[==] name[list]] begin[:]
variable[Ss] assign[=] call[name[np].array, parameter[name[Ss]]]
variable[npts] assign[=] call[name[... | keyword[def] identifier[sbar] ( identifier[Ss] ):
literal[string]
keyword[if] identifier[type] ( identifier[Ss] )== identifier[list] :
identifier[Ss] = identifier[np] . identifier[array] ( identifier[Ss] )
identifier[npts] = identifier[Ss] . identifier[shape] [ literal[int] ]
identifier... | def sbar(Ss):
"""
calculate average s,sigma from list of "s"s.
"""
if type(Ss) == list:
Ss = np.array(Ss) # depends on [control=['if'], data=[]]
npts = Ss.shape[0]
Ss = Ss.transpose()
(avd, avs) = ([], [])
# D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+... |
def md5sum(self, filename, use_sudo=False):
"""
Compute the MD5 sum of a file.
"""
func = use_sudo and run_as_root or self.run
with self.settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
# Linux (LSB)
if exists(u'/usr/bin/md5sum'):... | def function[md5sum, parameter[self, filename, use_sudo]]:
constant[
Compute the MD5 sum of a file.
]
variable[func] assign[=] <ast.BoolOp object at 0x7da1b00ddc00>
with call[name[self].settings, parameter[call[name[hide], parameter[constant[running], constant[stdout], constant[s... | keyword[def] identifier[md5sum] ( identifier[self] , identifier[filename] , identifier[use_sudo] = keyword[False] ):
literal[string]
identifier[func] = identifier[use_sudo] keyword[and] identifier[run_as_root] keyword[or] identifier[self] . identifier[run]
keyword[with] identifier[se... | def md5sum(self, filename, use_sudo=False):
"""
Compute the MD5 sum of a file.
"""
func = use_sudo and run_as_root or self.run
with self.settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
# Linux (LSB)
if exists(u'/usr/bin/md5sum'):
res = f... |
def do_graphviz(self, args, arguments):
"""
::
Usage:
graphviz FILENAME
Export the data in cvs format to a file. Former cvs command
Arguments:
FILENAME The filename
"""
filename = arguments['FILENAME']
... | def function[do_graphviz, parameter[self, args, arguments]]:
constant[
::
Usage:
graphviz FILENAME
Export the data in cvs format to a file. Former cvs command
Arguments:
FILENAME The filename
]
variable[... | keyword[def] identifier[do_graphviz] ( identifier[self] , identifier[args] , identifier[arguments] ):
literal[string]
identifier[filename] = identifier[arguments] [ literal[string] ]
keyword[if] identifier[platform] . identifier[system] ()== literal[string] :
keyword[if] ide... | def do_graphviz(self, args, arguments):
"""
::
Usage:
graphviz FILENAME
Export the data in cvs format to a file. Former cvs command
Arguments:
FILENAME The filename
"""
filename = arguments['FILENAME']
if pl... |
def switch_to_frame_with_id(self, frame):
"""Swap Selenium's context to the given frame or iframe."""
elem = world.browser.find_element_by_id(frame)
world.browser.switch_to.frame(elem) | def function[switch_to_frame_with_id, parameter[self, frame]]:
constant[Swap Selenium's context to the given frame or iframe.]
variable[elem] assign[=] call[name[world].browser.find_element_by_id, parameter[name[frame]]]
call[name[world].browser.switch_to.frame, parameter[name[elem]]] | keyword[def] identifier[switch_to_frame_with_id] ( identifier[self] , identifier[frame] ):
literal[string]
identifier[elem] = identifier[world] . identifier[browser] . identifier[find_element_by_id] ( identifier[frame] )
identifier[world] . identifier[browser] . identifier[switch_to] . identifier[fram... | def switch_to_frame_with_id(self, frame):
"""Swap Selenium's context to the given frame or iframe."""
elem = world.browser.find_element_by_id(frame)
world.browser.switch_to.frame(elem) |
def add_segments(self, segments):
"""Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment`
"""
self.tracks.update([seg.track for seg in segments])
self.segments.extend(segm... | def function[add_segments, parameter[self, segments]]:
constant[Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment`
]
call[name[self].tracks.update, parameter[<ast.ListComp objec... | keyword[def] identifier[add_segments] ( identifier[self] , identifier[segments] ):
literal[string]
identifier[self] . identifier[tracks] . identifier[update] ([ identifier[seg] . identifier[track] keyword[for] identifier[seg] keyword[in] identifier[segments] ])
identifier[self] . ident... | def add_segments(self, segments):
"""Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment`
"""
self.tracks.update([seg.track for seg in segments])
self.segments.extend(segments) |
def fetch_package_version(dist_name):
"""
>>> fetch_package_version('sentry')
"""
try:
# Importing pkg_resources can be slow, so only import it
# if we need it.
import pkg_resources
except ImportError:
# pkg_resource is not available on Google App Engine
raise... | def function[fetch_package_version, parameter[dist_name]]:
constant[
>>> fetch_package_version('sentry')
]
<ast.Try object at 0x7da1b17cf100>
variable[dist] assign[=] call[name[pkg_resources].get_distribution, parameter[name[dist_name]]]
return[name[dist].version] | keyword[def] identifier[fetch_package_version] ( identifier[dist_name] ):
literal[string]
keyword[try] :
keyword[import] identifier[pkg_resources]
keyword[except] identifier[ImportError] :
keyword[raise] identifier[NotImplementedError] ( literal[string]
l... | def fetch_package_version(dist_name):
"""
>>> fetch_package_version('sentry')
"""
try:
# Importing pkg_resources can be slow, so only import it
# if we need it.
import pkg_resources # depends on [control=['try'], data=[]]
except ImportError:
# pkg_resource is not ava... |
def username_validator(self, form, field):
"""Ensure that Usernames contains at least 3 alphanumeric characters.
Override this method to customize the username validator.
"""
username = field.data
if len(username) < 3:
raise ValidationError(
_('Userna... | def function[username_validator, parameter[self, form, field]]:
constant[Ensure that Usernames contains at least 3 alphanumeric characters.
Override this method to customize the username validator.
]
variable[username] assign[=] name[field].data
if compare[call[name[len], parame... | keyword[def] identifier[username_validator] ( identifier[self] , identifier[form] , identifier[field] ):
literal[string]
identifier[username] = identifier[field] . identifier[data]
keyword[if] identifier[len] ( identifier[username] )< literal[int] :
keyword[raise] identifie... | def username_validator(self, form, field):
"""Ensure that Usernames contains at least 3 alphanumeric characters.
Override this method to customize the username validator.
"""
username = field.data
if len(username) < 3:
raise ValidationError(_('Username must be at least 3 characters ... |
def str_value(self):
"""
See the class documentation.
"""
if self._cached_str_val is not None:
return self._cached_str_val
if self.orig_type in _BOOL_TRISTATE:
# Also calculates the visibility, so invalidation safe
self._cached_str_val = TRI_T... | def function[str_value, parameter[self]]:
constant[
See the class documentation.
]
if compare[name[self]._cached_str_val is_not constant[None]] begin[:]
return[name[self]._cached_str_val]
if compare[name[self].orig_type in name[_BOOL_TRISTATE]] begin[:]
na... | keyword[def] identifier[str_value] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_cached_str_val] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_cached_str_val]
keyword[if] identifier[self] . id... | def str_value(self):
"""
See the class documentation.
"""
if self._cached_str_val is not None:
return self._cached_str_val # depends on [control=['if'], data=[]]
if self.orig_type in _BOOL_TRISTATE:
# Also calculates the visibility, so invalidation safe
self._cached_... |
def transform(self, maps):
"""This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from... | def function[transform, parameter[self, maps]]:
constant[This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> im... | keyword[def] identifier[transform] ( identifier[self] , identifier[maps] ):
literal[string]
identifier[out] ={}
identifier[out] [ identifier[parameters] . identifier[mass1] ]= identifier[conversions] . identifier[mass1_from_mchirp_eta] (
identifier[maps] [ identifier[parameters] .... | def transform(self, maps):
"""This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pyc... |
def map_noreturn(targ, argslist):
"""
parallel_call_noreturn(targ, argslist)
:Parameters:
- targ : function
- argslist : list of tuples
Does [targ(*args) for args in argslist] using the threadpool.
"""
# Thanks to Anne Archibald's handythread.py for the exception handling
# me... | def function[map_noreturn, parameter[targ, argslist]]:
constant[
parallel_call_noreturn(targ, argslist)
:Parameters:
- targ : function
- argslist : list of tuples
Does [targ(*args) for args in argslist] using the threadpool.
]
variable[exceptions] assign[=] list[[]]
... | keyword[def] identifier[map_noreturn] ( identifier[targ] , identifier[argslist] ):
literal[string]
identifier[exceptions] =[]
identifier[n_threads] = identifier[len] ( identifier[argslist] )
identifier[exc_lock] = identifier[threading] . identifier[Lock] ()
identifier[done_lock] ... | def map_noreturn(targ, argslist):
"""
parallel_call_noreturn(targ, argslist)
:Parameters:
- targ : function
- argslist : list of tuples
Does [targ(*args) for args in argslist] using the threadpool.
"""
# Thanks to Anne Archibald's handythread.py for the exception handling
# mec... |
def overview():
"""
Creates a overview of the hosts per range.
"""
range_search = RangeSearch()
ranges = range_search.get_ranges()
if ranges:
formatted_ranges = []
tags_lookup = {}
for r in ranges:
formatted_ranges.append({'mask': r.range})
tag... | def function[overview, parameter[]]:
constant[
Creates a overview of the hosts per range.
]
variable[range_search] assign[=] call[name[RangeSearch], parameter[]]
variable[ranges] assign[=] call[name[range_search].get_ranges, parameter[]]
if name[ranges] begin[:]
... | keyword[def] identifier[overview] ():
literal[string]
identifier[range_search] = identifier[RangeSearch] ()
identifier[ranges] = identifier[range_search] . identifier[get_ranges] ()
keyword[if] identifier[ranges] :
identifier[formatted_ranges] =[]
identifier[tags_lookup] ={}
... | def overview():
"""
Creates a overview of the hosts per range.
"""
range_search = RangeSearch()
ranges = range_search.get_ranges()
if ranges:
formatted_ranges = []
tags_lookup = {}
for r in ranges:
formatted_ranges.append({'mask': r.range})
tag... |
def evaluate_model_single_recording_multisymbol(model_file, recording):
"""
Evaluate a model for a single recording where possibly multiple symbols
are.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten recording.
"""
(preprocess... | def function[evaluate_model_single_recording_multisymbol, parameter[model_file, recording]]:
constant[
Evaluate a model for a single recording where possibly multiple symbols
are.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten rec... | keyword[def] identifier[evaluate_model_single_recording_multisymbol] ( identifier[model_file] , identifier[recording] ):
literal[string]
( identifier[preprocessing_queue] , identifier[feature_list] , identifier[model] ,
identifier[output_semantics] )= identifier[load_model] ( identifier[model_file] )
... | def evaluate_model_single_recording_multisymbol(model_file, recording):
"""
Evaluate a model for a single recording where possibly multiple symbols
are.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten recording.
"""
(preprocess... |
def service_unavailable(cls, errors=None):
"""Shortcut API for HTTP 503 `Service Unavailable` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
"""
if cls.expose_status: # pragma: no cover
cls.response.con... | def function[service_unavailable, parameter[cls, errors]]:
constant[Shortcut API for HTTP 503 `Service Unavailable` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
]
if name[cls].expose_status begin[:]
... | keyword[def] identifier[service_unavailable] ( identifier[cls] , identifier[errors] = keyword[None] ):
literal[string]
keyword[if] identifier[cls] . identifier[expose_status] :
identifier[cls] . identifier[response] . identifier[content_type] = literal[string]
identifier... | def service_unavailable(cls, errors=None):
"""Shortcut API for HTTP 503 `Service Unavailable` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
"""
if cls.expose_status: # pragma: no cover
cls.response.content_type = ... |
def var_deleted(self, v):
"""
var was added in the bot
:param v:
:return:
"""
widget = self.widgets[v.name]
# widgets are all in a single container ..
parent = widget.get_parent()
self.container.remove(parent)
del self.widgets[v.name]
... | def function[var_deleted, parameter[self, v]]:
constant[
var was added in the bot
:param v:
:return:
]
variable[widget] assign[=] call[name[self].widgets][name[v].name]
variable[parent] assign[=] call[name[widget].get_parent, parameter[]]
call[name[self].... | keyword[def] identifier[var_deleted] ( identifier[self] , identifier[v] ):
literal[string]
identifier[widget] = identifier[self] . identifier[widgets] [ identifier[v] . identifier[name] ]
identifier[parent] = identifier[widget] . identifier[get_parent] ()
identifier[self... | def var_deleted(self, v):
"""
var was added in the bot
:param v:
:return:
"""
widget = self.widgets[v.name]
# widgets are all in a single container ..
parent = widget.get_parent()
self.container.remove(parent)
del self.widgets[v.name]
self.window.set_size_req... |
def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr... | def function[move_point_num, parameter[point, to_clust, from_clust, cl_attr_sum, cl_memb_sum]]:
constant[Move point between clusters, numerical attributes.]
for taget[tuple[[<ast.Name object at 0x7da1b1834550>, <ast.Name object at 0x7da1b1834520>]]] in starred[call[name[enumerate], parameter[name[point]... | keyword[def] identifier[move_point_num] ( identifier[point] , identifier[to_clust] , identifier[from_clust] , identifier[cl_attr_sum] , identifier[cl_memb_sum] ):
literal[string]
keyword[for] identifier[iattr] , identifier[curattr] keyword[in] identifier[enumerate] ( identifier[point] ):
i... | def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for (iattr, curattr) in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curat... |
def VerifyStructure(self, parser_mediator, line):
"""Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
"""... | def function[VerifyStructure, parameter[self, parser_mediator, line]]:
constant[Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expecte... | keyword[def] identifier[VerifyStructure] ( identifier[self] , identifier[parser_mediator] , identifier[line] ):
literal[string]
keyword[try] :
identifier[structure] = identifier[self] . identifier[_DPKG_LOG_LINE] . identifier[parseString] ( identifier[line] )
keyword[except] identifier[pyparsi... | def VerifyStructure(self, parser_mediator, line):
"""Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
"""... |
def sync(self, localpath, href, exclude=None, block=True):
"""
Sync local and remote folders
:param localpath: local folder
:param href: remote folder
:param exclude: filter folder which need to exlude
:return: respose
"""
logger.info(u("sync: %s %s") % (l... | def function[sync, parameter[self, localpath, href, exclude, block]]:
constant[
Sync local and remote folders
:param localpath: local folder
:param href: remote folder
:param exclude: filter folder which need to exlude
:return: respose
]
call[name[logger].... | keyword[def] identifier[sync] ( identifier[self] , identifier[localpath] , identifier[href] , identifier[exclude] = keyword[None] , identifier[block] = keyword[True] ):
literal[string]
identifier[logger] . identifier[info] ( identifier[u] ( literal[string] )%( identifier[localpath] , identifier[hre... | def sync(self, localpath, href, exclude=None, block=True):
"""
Sync local and remote folders
:param localpath: local folder
:param href: remote folder
:param exclude: filter folder which need to exlude
:return: respose
"""
logger.info(u('sync: %s %s') % (localpath... |
def _shortcut_open(
uri,
mode,
ignore_ext=False,
buffering=-1,
encoding=None,
errors=None,
):
"""Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.... | def function[_shortcut_open, parameter[uri, mode, ignore_ext, buffering, encoding, errors]]:
constant[Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following... | keyword[def] identifier[_shortcut_open] (
identifier[uri] ,
identifier[mode] ,
identifier[ignore_ext] = keyword[False] ,
identifier[buffering] =- literal[int] ,
identifier[encoding] = keyword[None] ,
identifier[errors] = keyword[None] ,
):
literal[string]
keyword[if] keyword[not] identifier[isinsta... | def _shortcut_open(uri, mode, ignore_ext=False, buffering=-1, encoding=None, errors=None):
"""Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following conditions:... |
def connect(self, address):
"""
Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to.
"""
self.sock.connect(address)
ClientHandshake(self).perform()
self.hand... | def function[connect, parameter[self, address]]:
constant[
Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to.
]
call[name[self].sock.connect, parameter[name[address]]]
... | keyword[def] identifier[connect] ( identifier[self] , identifier[address] ):
literal[string]
identifier[self] . identifier[sock] . identifier[connect] ( identifier[address] )
identifier[ClientHandshake] ( identifier[self] ). identifier[perform] ()
identifier[self] . identifier[han... | def connect(self, address):
"""
Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to.
"""
self.sock.connect(address)
ClientHandshake(self).perform()
self.handshake_sent = Tru... |
def set_default_locators_and_formatters(self, axis):
"""
Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters.
"""
axis.set_major_locator(_LogicleLocator(self._tra... | def function[set_default_locators_and_formatters, parameter[self, axis]]:
constant[
Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters.
]
call[name[axis].set_maj... | keyword[def] identifier[set_default_locators_and_formatters] ( identifier[self] , identifier[axis] ):
literal[string]
identifier[axis] . identifier[set_major_locator] ( identifier[_LogicleLocator] ( identifier[self] . identifier[_transform] ))
identifier[axis] . identifier[set_minor_locato... | def set_default_locators_and_formatters(self, axis):
"""
Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters.
"""
axis.set_major_locator(_LogicleLocator(self._transform))... |
def calculate(self, T, P, zs, ws, method):
r'''Method to calculate thermal conductivity of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
... | def function[calculate, parameter[self, T, P, zs, ws, method]]:
constant[Method to calculate thermal conductivity of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_pr... | keyword[def] identifier[calculate] ( identifier[self] , identifier[T] , identifier[P] , identifier[zs] , identifier[ws] , identifier[method] ):
literal[string]
keyword[if] identifier[method] == identifier[SIMPLE] :
identifier[ks] =[ identifier[i] ( identifier[T] , identifier[P] ) keyw... | def calculate(self, T, P, zs, ws, method):
"""Method to calculate thermal conductivity of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
... |
def resolve(self, notes=None):
'''Save all changes and resolve this issue'''
self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes) | def function[resolve, parameter[self, notes]]:
constant[Save all changes and resolve this issue]
call[name[self].set_status, parameter[name[self]._redmine.ISSUE_STATUS_ID_RESOLVED]] | keyword[def] identifier[resolve] ( identifier[self] , identifier[notes] = keyword[None] ):
literal[string]
identifier[self] . identifier[set_status] ( identifier[self] . identifier[_redmine] . identifier[ISSUE_STATUS_ID_RESOLVED] , identifier[notes] = identifier[notes] ) | def resolve(self, notes=None):
"""Save all changes and resolve this issue"""
self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes) |
def device(self, name):
""" Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified.
Parameters:
name (str): Name to match against.
"""
for device in self.devices():
if device.name.lower() == name.lower():
return ... | def function[device, parameter[self, name]]:
constant[ Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified.
Parameters:
name (str): Name to match against.
]
for taget[name[device]] in starred[call[name[self].devices, parameter[]]] begin[... | keyword[def] identifier[device] ( identifier[self] , identifier[name] ):
literal[string]
keyword[for] identifier[device] keyword[in] identifier[self] . identifier[devices] ():
keyword[if] identifier[device] . identifier[name] . identifier[lower] ()== identifier[name] . identifier[l... | def device(self, name):
""" Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified.
Parameters:
name (str): Name to match against.
"""
for device in self.devices():
if device.name.lower() == name.lower():
return device # depend... |
def add(self, song):
"""往播放列表末尾添加一首歌曲"""
if song in self._songs:
return
self._songs.append(song)
logger.debug('Add %s to player playlist', song) | def function[add, parameter[self, song]]:
constant[往播放列表末尾添加一首歌曲]
if compare[name[song] in name[self]._songs] begin[:]
return[None]
call[name[self]._songs.append, parameter[name[song]]]
call[name[logger].debug, parameter[constant[Add %s to player playlist], name[song]]] | keyword[def] identifier[add] ( identifier[self] , identifier[song] ):
literal[string]
keyword[if] identifier[song] keyword[in] identifier[self] . identifier[_songs] :
keyword[return]
identifier[self] . identifier[_songs] . identifier[append] ( identifier[song] )
i... | def add(self, song):
"""往播放列表末尾添加一首歌曲"""
if song in self._songs:
return # depends on [control=['if'], data=[]]
self._songs.append(song)
logger.debug('Add %s to player playlist', song) |
def tag_begin(self, tag_name, attributes=None):
"""Marks the beginning of the ``tag_name`` structure.
Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...".
Values may be boolean (tru... | def function[tag_begin, parameter[self, tag_name, attributes]]:
constant[Marks the beginning of the ``tag_name`` structure.
Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...".
Valu... | keyword[def] identifier[tag_begin] ( identifier[self] , identifier[tag_name] , identifier[attributes] = keyword[None] ):
literal[string]
keyword[if] identifier[attributes] keyword[is] keyword[None] :
identifier[attributes] = literal[string]
identifier[cairo] . identifier[c... | def tag_begin(self, tag_name, attributes=None):
"""Marks the beginning of the ``tag_name`` structure.
Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...".
Values may be boolean (true/fa... |
def proj_path(*path_parts):
# type: (str) -> str
""" Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path.
"""
path_parts = p... | def function[proj_path, parameter[]]:
constant[ Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path.
]
variable[path_par... | keyword[def] identifier[proj_path] (* identifier[path_parts] ):
literal[string]
identifier[path_parts] = identifier[path_parts] keyword[or] [ literal[string] ]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isabs] ( identifier[path_parts] [ literal[int] ]):
... | def proj_path(*path_parts):
# type: (str) -> str
' Return absolute path to the repo dir (root project directory).\n\n Args:\n path (str):\n The path relative to the project root (pelconf.yaml).\n\n Returns:\n str: The given path converted to an absolute path.\n '
path_parts... |
def getIndxOps(self, valu, cmpr='='):
'''
Return a list of index operation tuples to lift values in a table.
Valid index operations include:
('eq', <indx>)
('pref', <indx>)
('range', (<minindx>, <maxindx>))
'''
func = self.indxcmpr.get(cmpr)
... | def function[getIndxOps, parameter[self, valu, cmpr]]:
constant[
Return a list of index operation tuples to lift values in a table.
Valid index operations include:
('eq', <indx>)
('pref', <indx>)
('range', (<minindx>, <maxindx>))
]
variable[fu... | keyword[def] identifier[getIndxOps] ( identifier[self] , identifier[valu] , identifier[cmpr] = literal[string] ):
literal[string]
identifier[func] = identifier[self] . identifier[indxcmpr] . identifier[get] ( identifier[cmpr] )
keyword[if] identifier[func] keyword[is] keyword[None] :
... | def getIndxOps(self, valu, cmpr='='):
"""
Return a list of index operation tuples to lift values in a table.
Valid index operations include:
('eq', <indx>)
('pref', <indx>)
('range', (<minindx>, <maxindx>))
"""
func = self.indxcmpr.get(cmpr)
if fu... |
def preview(df,preview_rows = 20):#,preview_max_cols = 0):
""" Returns a preview of a dataframe, which contains both header
rows and tail rows.
"""
if preview_rows < 4:
preview_rows = 4
preview_rows = min(preview_rows,df.shape[0])
outer = math.floor(preview_rows / 4)
return pd.concat... | def function[preview, parameter[df, preview_rows]]:
constant[ Returns a preview of a dataframe, which contains both header
rows and tail rows.
]
if compare[name[preview_rows] less[<] constant[4]] begin[:]
variable[preview_rows] assign[=] constant[4]
variable[preview_rows]... | keyword[def] identifier[preview] ( identifier[df] , identifier[preview_rows] = literal[int] ):
literal[string]
keyword[if] identifier[preview_rows] < literal[int] :
identifier[preview_rows] = literal[int]
identifier[preview_rows] = identifier[min] ( identifier[preview_rows] , identifier[df]... | def preview(df, preview_rows=20): #,preview_max_cols = 0):
' Returns a preview of a dataframe, which contains both header\n rows and tail rows.\n '
if preview_rows < 4:
preview_rows = 4 # depends on [control=['if'], data=['preview_rows']]
preview_rows = min(preview_rows, df.shape[0])
out... |
def set_marksize(self):
"""Set size/radius of marking."""
try:
sz = float(self.w.mark_size.get_text())
except ValueError:
self.logger.error('Cannot set mark size')
self.w.mark_size.set_text(str(self.marksize))
else:
self.marksize = sz | def function[set_marksize, parameter[self]]:
constant[Set size/radius of marking.]
<ast.Try object at 0x7da18dc05150> | keyword[def] identifier[set_marksize] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[sz] = identifier[float] ( identifier[self] . identifier[w] . identifier[mark_size] . identifier[get_text] ())
keyword[except] identifier[ValueError] :
identifier... | def set_marksize(self):
"""Set size/radius of marking."""
try:
sz = float(self.w.mark_size.get_text()) # depends on [control=['try'], data=[]]
except ValueError:
self.logger.error('Cannot set mark size')
self.w.mark_size.set_text(str(self.marksize)) # depends on [control=['except']... |
def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll."""
_validate_pianoroll(pianoroll)
if np.issubdtype(pianoroll.dtype, np.bool_):
pianoroll = pianoro... | def function[qualified_note_rate, parameter[pianoroll, threshold]]:
constant[Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll.]
call[name[_validate_pianoroll], parameter[name[pianoroll]]]
if call[... | keyword[def] identifier[qualified_note_rate] ( identifier[pianoroll] , identifier[threshold] = literal[int] ):
literal[string]
identifier[_validate_pianoroll] ( identifier[pianoroll] )
keyword[if] identifier[np] . identifier[issubdtype] ( identifier[pianoroll] . identifier[dtype] , identifier[np] . i... | def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll."""
_validate_pianoroll(pianoroll)
if np.issubdtype(pianoroll.dtype, np.bool_):
pianoroll = pianoro... |
def get_next_property(self):
"""Gets the next ``Property`` in this list.
:return: the next ``Property`` in this list. The ``has_next()`` method should be used to test that a next ``Property`` is available before calling this method.
:rtype: ``osid.Property``
:raise: ``IllegalState`` -- ... | def function[get_next_property, parameter[self]]:
constant[Gets the next ``Property`` in this list.
:return: the next ``Property`` in this list. The ``has_next()`` method should be used to test that a next ``Property`` is available before calling this method.
:rtype: ``osid.Property``
:... | keyword[def] identifier[get_next_property] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[next_object] = identifier[self] . identifier[next] ()
keyword[except] identifier[StopIteration] :
keyword[raise] identifier[IllegalState] ( literal[string]... | def get_next_property(self):
"""Gets the next ``Property`` in this list.
:return: the next ``Property`` in this list. The ``has_next()`` method should be used to test that a next ``Property`` is available before calling this method.
:rtype: ``osid.Property``
:raise: ``IllegalState`` -- no m... |
def _send_accum_trace(self, device_uuid):
"""Send whatever accumulated tracing data we have for the device."""
if device_uuid not in self._connections:
self._logger.debug("Dropping trace data for device without an active connection, uuid=0x%X", device_uuid)
return
conn_... | def function[_send_accum_trace, parameter[self, device_uuid]]:
constant[Send whatever accumulated tracing data we have for the device.]
if compare[name[device_uuid] <ast.NotIn object at 0x7da2590d7190> name[self]._connections] begin[:]
call[name[self]._logger.debug, parameter[constant[Dr... | keyword[def] identifier[_send_accum_trace] ( identifier[self] , identifier[device_uuid] ):
literal[string]
keyword[if] identifier[device_uuid] keyword[not] keyword[in] identifier[self] . identifier[_connections] :
identifier[self] . identifier[_logger] . identifier[debug] ( litera... | def _send_accum_trace(self, device_uuid):
"""Send whatever accumulated tracing data we have for the device."""
if device_uuid not in self._connections:
self._logger.debug('Dropping trace data for device without an active connection, uuid=0x%X', device_uuid)
return # depends on [control=['if'], ... |
def find_module_defining_flag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: str, name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module ... | def function[find_module_defining_flag, parameter[self, flagname, default]]:
constant[Return the name of the module defining this flag, or default.
Args:
flagname: str, name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
... | keyword[def] identifier[find_module_defining_flag] ( identifier[self] , identifier[flagname] , identifier[default] = keyword[None] ):
literal[string]
identifier[registered_flag] = identifier[self] . identifier[_flags] (). identifier[get] ( identifier[flagname] )
keyword[if] identifier[registered_flag... | def find_module_defining_flag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: str, name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module ... |
def float_to_decimal(f):
""" Convert a float to a 38-precision Decimal """
n, d = f.as_integer_ratio()
numerator, denominator = Decimal(n), Decimal(d)
return DECIMAL_CONTEXT.divide(numerator, denominator) | def function[float_to_decimal, parameter[f]]:
constant[ Convert a float to a 38-precision Decimal ]
<ast.Tuple object at 0x7da1b2407820> assign[=] call[name[f].as_integer_ratio, parameter[]]
<ast.Tuple object at 0x7da1b2406650> assign[=] tuple[[<ast.Call object at 0x7da1b2405000>, <ast.Call obje... | keyword[def] identifier[float_to_decimal] ( identifier[f] ):
literal[string]
identifier[n] , identifier[d] = identifier[f] . identifier[as_integer_ratio] ()
identifier[numerator] , identifier[denominator] = identifier[Decimal] ( identifier[n] ), identifier[Decimal] ( identifier[d] )
keyword[retur... | def float_to_decimal(f):
""" Convert a float to a 38-precision Decimal """
(n, d) = f.as_integer_ratio()
(numerator, denominator) = (Decimal(n), Decimal(d))
return DECIMAL_CONTEXT.divide(numerator, denominator) |
def write_xmlbif(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
"""
with open(filename,... | def function[write_xmlbif, parameter[self, filename]]:
constant[
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
]
... | keyword[def] identifier[write_xmlbif] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[fout] :
identifier[fout] . identifier[write] ( identifier[self] . identifier[__str__] ()... | def write_xmlbif(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
"""
with open(filename, 'w') as... |
def define_bucket_batch_sizes(buckets: List[Tuple[int, int]],
batch_size: int,
batch_by_words: bool,
batch_num_devices: int,
data_target_average_len: List[Optional[float]]) -> List[BucketBatchSize]:
... | def function[define_bucket_batch_sizes, parameter[buckets, batch_size, batch_by_words, batch_num_devices, data_target_average_len]]:
constant[
Computes bucket-specific batch sizes (sentences, average_words).
If sentence-based batching: number of sentences is the same for each batch, determines the
... | keyword[def] identifier[define_bucket_batch_sizes] ( identifier[buckets] : identifier[List] [ identifier[Tuple] [ identifier[int] , identifier[int] ]],
identifier[batch_size] : identifier[int] ,
identifier[batch_by_words] : identifier[bool] ,
identifier[batch_num_devices] : identifier[int] ,
identifier[data_targe... | def define_bucket_batch_sizes(buckets: List[Tuple[int, int]], batch_size: int, batch_by_words: bool, batch_num_devices: int, data_target_average_len: List[Optional[float]]) -> List[BucketBatchSize]:
"""
Computes bucket-specific batch sizes (sentences, average_words).
If sentence-based batching: number of s... |
def cli(ctx, id_number, new_key, metadata=""):
"""Update a canned key
Output:
an empty dictionary
"""
return ctx.gi.cannedkeys.update_key(id_number, new_key, metadata=metadata) | def function[cli, parameter[ctx, id_number, new_key, metadata]]:
constant[Update a canned key
Output:
an empty dictionary
]
return[call[name[ctx].gi.cannedkeys.update_key, parameter[name[id_number], name[new_key]]]] | keyword[def] identifier[cli] ( identifier[ctx] , identifier[id_number] , identifier[new_key] , identifier[metadata] = literal[string] ):
literal[string]
keyword[return] identifier[ctx] . identifier[gi] . identifier[cannedkeys] . identifier[update_key] ( identifier[id_number] , identifier[new_key] , identi... | def cli(ctx, id_number, new_key, metadata=''):
"""Update a canned key
Output:
an empty dictionary
"""
return ctx.gi.cannedkeys.update_key(id_number, new_key, metadata=metadata) |
def get_seaborn_clustermap(dfr, params, title=None, annot=True):
"""Returns a Seaborn clustermap."""
fig = sns.clustermap(
dfr,
cmap=params.cmap,
vmin=params.vmin,
vmax=params.vmax,
col_colors=params.colorbar,
row_colors=params.colorbar,
figsize=(params.fi... | def function[get_seaborn_clustermap, parameter[dfr, params, title, annot]]:
constant[Returns a Seaborn clustermap.]
variable[fig] assign[=] call[name[sns].clustermap, parameter[name[dfr]]]
call[name[fig].cax.yaxis.set_label_position, parameter[constant[left]]]
if name[title] begin[:]
... | keyword[def] identifier[get_seaborn_clustermap] ( identifier[dfr] , identifier[params] , identifier[title] = keyword[None] , identifier[annot] = keyword[True] ):
literal[string]
identifier[fig] = identifier[sns] . identifier[clustermap] (
identifier[dfr] ,
identifier[cmap] = identifier[params] . ... | def get_seaborn_clustermap(dfr, params, title=None, annot=True):
"""Returns a Seaborn clustermap."""
fig = sns.clustermap(dfr, cmap=params.cmap, vmin=params.vmin, vmax=params.vmax, col_colors=params.colorbar, row_colors=params.colorbar, figsize=(params.figsize, params.figsize), linewidths=params.linewidths, xti... |
def _insert(self, docs, ordered=True, check_keys=True,
manipulate=False, write_concern=None, op_id=None,
bypass_doc_val=False, session=None):
"""Internal insert helper."""
if isinstance(docs, abc.Mapping):
return self._insert_one(
docs, ordered... | def function[_insert, parameter[self, docs, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val, session]]:
constant[Internal insert helper.]
if call[name[isinstance], parameter[name[docs], name[abc].Mapping]] begin[:]
return[call[name[self]._insert_one, parameter[name[docs], n... | keyword[def] identifier[_insert] ( identifier[self] , identifier[docs] , identifier[ordered] = keyword[True] , identifier[check_keys] = keyword[True] ,
identifier[manipulate] = keyword[False] , identifier[write_concern] = keyword[None] , identifier[op_id] = keyword[None] ,
identifier[bypass_doc_val] = keyword[False... | def _insert(self, docs, ordered=True, check_keys=True, manipulate=False, write_concern=None, op_id=None, bypass_doc_val=False, session=None):
"""Internal insert helper."""
if isinstance(docs, abc.Mapping):
return self._insert_one(docs, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_va... |
def get_me(self) -> "pyrogram.User":
"""A simple method for testing your authorization. Requires no parameters.
Returns:
Basic information about the user or bot in form of a :obj:`User` object
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error... | def function[get_me, parameter[self]]:
constant[A simple method for testing your authorization. Requires no parameters.
Returns:
Basic information about the user or bot in form of a :obj:`User` object
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram R... | keyword[def] identifier[get_me] ( identifier[self] )-> literal[string] :
literal[string]
keyword[return] identifier[pyrogram] . identifier[User] . identifier[_parse] (
identifier[self] ,
identifier[self] . identifier[send] (
identifier[functions] . identifier[users] . id... | def get_me(self) -> 'pyrogram.User':
"""A simple method for testing your authorization. Requires no parameters.
Returns:
Basic information about the user or bot in form of a :obj:`User` object
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
... |
def eval_string(stri):
'evaluate expressions passed as string'
tokens = shlex.split(stri)
return run_write_read(['plash', 'eval'], '\n'.join(tokens).encode()).decode() | def function[eval_string, parameter[stri]]:
constant[evaluate expressions passed as string]
variable[tokens] assign[=] call[name[shlex].split, parameter[name[stri]]]
return[call[call[name[run_write_read], parameter[list[[<ast.Constant object at 0x7da18f09ebc0>, <ast.Constant object at 0x7da18f09dd50... | keyword[def] identifier[eval_string] ( identifier[stri] ):
literal[string]
identifier[tokens] = identifier[shlex] . identifier[split] ( identifier[stri] )
keyword[return] identifier[run_write_read] ([ literal[string] , literal[string] ], literal[string] . identifier[join] ( identifier[tokens] ). ide... | def eval_string(stri):
"""evaluate expressions passed as string"""
tokens = shlex.split(stri)
return run_write_read(['plash', 'eval'], '\n'.join(tokens).encode()).decode() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.