code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def run_script(self, filename, start_opts=None, globals_=None,
locals_=None):
""" Run debugger on Python script `filename'. The script may
inspect sys.argv for command arguments. `globals_' and
`locals_' are the dictionaries to use for local and global
variables. If `g... | def function[run_script, parameter[self, filename, start_opts, globals_, locals_]]:
constant[ Run debugger on Python script `filename'. The script may
inspect sys.argv for command arguments. `globals_' and
`locals_' are the dictionaries to use for local and global
variables. If `globals'... | keyword[def] identifier[run_script] ( identifier[self] , identifier[filename] , identifier[start_opts] = keyword[None] , identifier[globals_] = keyword[None] ,
identifier[locals_] = keyword[None] ):
literal[string]
identifier[self] . identifier[mainpyfile] = identifier[self] . identifier[core] . i... | def run_script(self, filename, start_opts=None, globals_=None, locals_=None):
""" Run debugger on Python script `filename'. The script may
inspect sys.argv for command arguments. `globals_' and
`locals_' are the dictionaries to use for local and global
variables. If `globals' is not given, g... |
def cli(ctx, transcript_id, organism="", sequence=""):
"""Duplicate a transcripte
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.duplicate_transcript(transcript_id, organism=organism, sequence=sequence) | def function[cli, parameter[ctx, transcript_id, organism, sequence]]:
constant[Duplicate a transcripte
Output:
A standard apollo feature dictionary ({"features": [{...}]})
]
return[call[name[ctx].gi.annotations.duplicate_transcript, parameter[name[transcript_id]]]] | keyword[def] identifier[cli] ( identifier[ctx] , identifier[transcript_id] , identifier[organism] = literal[string] , identifier[sequence] = literal[string] ):
literal[string]
keyword[return] identifier[ctx] . identifier[gi] . identifier[annotations] . identifier[duplicate_transcript] ( identifier[transcr... | def cli(ctx, transcript_id, organism='', sequence=''):
"""Duplicate a transcripte
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.duplicate_transcript(transcript_id, organism=organism, sequence=sequence) |
def process_corpus(self, corpus, output_path, frame_size=400, hop_size=160, sr=None):
"""
Process all utterances of the given corpus and save the processed features in a feature-container.
The utterances are processed in **offline** mode so the full utterance in one go.
Args:
... | def function[process_corpus, parameter[self, corpus, output_path, frame_size, hop_size, sr]]:
constant[
Process all utterances of the given corpus and save the processed features in a feature-container.
The utterances are processed in **offline** mode so the full utterance in one go.
Ar... | keyword[def] identifier[process_corpus] ( identifier[self] , identifier[corpus] , identifier[output_path] , identifier[frame_size] = literal[int] , identifier[hop_size] = literal[int] , identifier[sr] = keyword[None] ):
literal[string]
keyword[def] identifier[processing_func] ( identifier[utteran... | def process_corpus(self, corpus, output_path, frame_size=400, hop_size=160, sr=None):
"""
Process all utterances of the given corpus and save the processed features in a feature-container.
The utterances are processed in **offline** mode so the full utterance in one go.
Args:
co... |
def chebyshev_distance_numpy(object1, object2):
"""!
@brief Calculate Chebyshev distance between two objects using numpy.
@param[in] object1 (array_like): The first array_like object.
@param[in] object2 (array_like): The second array_like object.
@return (double) Chebyshev distance between ... | def function[chebyshev_distance_numpy, parameter[object1, object2]]:
constant[!
@brief Calculate Chebyshev distance between two objects using numpy.
@param[in] object1 (array_like): The first array_like object.
@param[in] object2 (array_like): The second array_like object.
@return (double) Che... | keyword[def] identifier[chebyshev_distance_numpy] ( identifier[object1] , identifier[object2] ):
literal[string]
keyword[return] identifier[numpy] . identifier[max] ( identifier[numpy] . identifier[absolute] ( identifier[object1] - identifier[object2] ), identifier[axis] = literal[int] ). identifier[T] | def chebyshev_distance_numpy(object1, object2):
"""!
@brief Calculate Chebyshev distance between two objects using numpy.
@param[in] object1 (array_like): The first array_like object.
@param[in] object2 (array_like): The second array_like object.
@return (double) Chebyshev distance between two obj... |
def getTaskTypes(self):
""" Return the current list of task types
"""
types = [
('Calibration', safe_unicode(_('Calibration')).encode('utf-8')),
('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')),
('Preventive', safe_unicode(_('Preventive')).encod... | def function[getTaskTypes, parameter[self]]:
constant[ Return the current list of task types
]
variable[types] assign[=] list[[<ast.Tuple object at 0x7da18eb568f0>, <ast.Tuple object at 0x7da18eb55e40>, <ast.Tuple object at 0x7da2047e85e0>, <ast.Tuple object at 0x7da2047eaad0>, <ast.Tuple object... | keyword[def] identifier[getTaskTypes] ( identifier[self] ):
literal[string]
identifier[types] =[
( literal[string] , identifier[safe_unicode] ( identifier[_] ( literal[string] )). identifier[encode] ( literal[string] )),
( literal[string] , identifier[safe_unicode] ( identifier[_] (... | def getTaskTypes(self):
""" Return the current list of task types
"""
types = [('Calibration', safe_unicode(_('Calibration')).encode('utf-8')), ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')), ('Preventive', safe_unicode(_('Preventive')).encode('utf-8')), ('Repair', safe_unicode(_('Repai... |
def edit(self, config, state, name, value=None):
"""
Change all occurrences of `name` in a kernel boot line in the
given `config` text.
It is expected that `config` is the contents of a file following
the syntax of ``/etc/default/grub``:file:.
.. warning::
Th... | def function[edit, parameter[self, config, state, name, value]]:
constant[
Change all occurrences of `name` in a kernel boot line in the
given `config` text.
It is expected that `config` is the contents of a file following
the syntax of ``/etc/default/grub``:file:.
.. w... | keyword[def] identifier[edit] ( identifier[self] , identifier[config] , identifier[state] , identifier[name] , identifier[value] = keyword[None] ):
literal[string]
identifier[config] = identifier[str] ( identifier[config] )
identifier[pos] = identifier[config] . identifier[find] ( identifi... | def edit(self, config, state, name, value=None):
"""
Change all occurrences of `name` in a kernel boot line in the
given `config` text.
It is expected that `config` is the contents of a file following
the syntax of ``/etc/default/grub``:file:.
.. warning::
This m... |
def _handle_response(response, server_config, synchronous=False, timeout=None):
"""Handle a server's response in a typical fashion.
Do the following:
1. Check the server's response for an HTTP status code indicating an error.
2. Poll the server for a foreman task to complete if an HTTP 202 (accepted)
... | def function[_handle_response, parameter[response, server_config, synchronous, timeout]]:
constant[Handle a server's response in a typical fashion.
Do the following:
1. Check the server's response for an HTTP status code indicating an error.
2. Poll the server for a foreman task to complete if an ... | keyword[def] identifier[_handle_response] ( identifier[response] , identifier[server_config] , identifier[synchronous] = keyword[False] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[response] . identifier[raise_for_status] ()
keyword[if] identifier[synchronous] keyword[is] key... | def _handle_response(response, server_config, synchronous=False, timeout=None):
"""Handle a server's response in a typical fashion.
Do the following:
1. Check the server's response for an HTTP status code indicating an error.
2. Poll the server for a foreman task to complete if an HTTP 202 (accepted)
... |
def get_vnetwork_portgroups_output_vnetwork_pgs_vs_nn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
output = ET.SubElement(get_vnetwork_portgroups,... | def function[get_vnetwork_portgroups_output_vnetwork_pgs_vs_nn, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vnetwork_portgroups] assign[=] call[name[ET].Element, parameter[constant[get_vnetwo... | keyword[def] identifier[get_vnetwork_portgroups_output_vnetwork_pgs_vs_nn] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vnetwork_portgroups] = identifier[ET] . identifier[Element] (... | def get_vnetwork_portgroups_output_vnetwork_pgs_vs_nn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vnetwork_portgroups = ET.Element('get_vnetwork_portgroups')
config = get_vnetwork_portgroups
output = ET.SubElement(get_vnetwork_portgroups, 'output')
vnetw... |
def parse_midi_file(self, file):
"""Parse a MIDI file.
Return the header -as a tuple containing respectively the MIDI
format, the number of tracks and the time division-, the parsed
track data and the number of bytes read.
"""
try:
f = open(file, 'r')
... | def function[parse_midi_file, parameter[self, file]]:
constant[Parse a MIDI file.
Return the header -as a tuple containing respectively the MIDI
format, the number of tracks and the time division-, the parsed
track data and the number of bytes read.
]
<ast.Try object at 0x7d... | keyword[def] identifier[parse_midi_file] ( identifier[self] , identifier[file] ):
literal[string]
keyword[try] :
identifier[f] = identifier[open] ( identifier[file] , literal[string] )
keyword[except] :
keyword[raise] identifier[IOError] ( literal[string] )
... | def parse_midi_file(self, file):
"""Parse a MIDI file.
Return the header -as a tuple containing respectively the MIDI
format, the number of tracks and the time division-, the parsed
track data and the number of bytes read.
"""
try:
f = open(file, 'r') # depends on [cont... |
def _apply(self, plan):
"""Required function of manager.py to actually apply a record change.
:param plan: Contains the zones and changes to be made
:type plan: octodns.provider.base.Plan
:type return: void
"""
desired = plan.desired
changes = plan.... | def function[_apply, parameter[self, plan]]:
constant[Required function of manager.py to actually apply a record change.
:param plan: Contains the zones and changes to be made
:type plan: octodns.provider.base.Plan
:type return: void
]
variable[desired] ass... | keyword[def] identifier[_apply] ( identifier[self] , identifier[plan] ):
literal[string]
identifier[desired] = identifier[plan] . identifier[desired]
identifier[changes] = identifier[plan] . identifier[changes]
identifier[self] . identifier[log] . identifier[debug] ( literal[st... | def _apply(self, plan):
"""Required function of manager.py to actually apply a record change.
:param plan: Contains the zones and changes to be made
:type plan: octodns.provider.base.Plan
:type return: void
"""
desired = plan.desired
changes = plan.changes
... |
def bind(self, data):
""" Bind a VertexBuffer that has structured data
Parameters
----------
data : VertexBuffer
The vertex buffer to bind. The field names of the array
are mapped to attribute names in GLSL.
"""
# Check
if not isin... | def function[bind, parameter[self, data]]:
constant[ Bind a VertexBuffer that has structured data
Parameters
----------
data : VertexBuffer
The vertex buffer to bind. The field names of the array
are mapped to attribute names in GLSL.
]
if... | keyword[def] identifier[bind] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[data] , identifier[VertexBuffer] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[fo... | def bind(self, data):
""" Bind a VertexBuffer that has structured data
Parameters
----------
data : VertexBuffer
The vertex buffer to bind. The field names of the array
are mapped to attribute names in GLSL.
"""
# Check
if not isinstance(data,... |
def _install_container_bcbio_system(datadir):
"""Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container.
"""
base_file = os.path.join(datadir, "config", "bc... | def function[_install_container_bcbio_system, parameter[datadir]]:
constant[Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container.
]
variable[base_... | keyword[def] identifier[_install_container_bcbio_system] ( identifier[datadir] ):
literal[string]
identifier[base_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[datadir] , literal[string] , literal[string] )
keyword[if] keyword[not] identifier[os] . identifier[path] . iden... | def _install_container_bcbio_system(datadir):
"""Install limited bcbio_system.yaml file for setting core and memory usage.
Adds any non-specific programs to the exposed bcbio_system.yaml file, only
when upgrade happening inside a docker container.
"""
base_file = os.path.join(datadir, 'config', 'bc... |
def stats(path, hash_type='sha256', follow_symlinks=True):
'''
Return a dict containing the stats about a given file
Under Windows, `gid` will equal `uid` and `group` will equal `user`.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on perm... | def function[stats, parameter[path, hash_type, follow_symlinks]]:
constant[
Return a dict containing the stats about a given file
Under Windows, `gid` will equal `uid` and `group` will equal `user`.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has n... | keyword[def] identifier[stats] ( identifier[path] , identifier[hash_type] = literal[string] , identifier[follow_symlinks] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ):
keyword[raise] identifier[... | def stats(path, hash_type='sha256', follow_symlinks=True):
"""
Return a dict containing the stats about a given file
Under Windows, `gid` will equal `uid` and `group` will equal `user`.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on perm... |
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info() | def function[info, parameter[host, port, db, password]]:
constant[
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
]
variable[server] assign[=] call[name[_connect], parameter[name[host], name[port], name[db], name[password]... | keyword[def] identifier[info] ( identifier[host] = keyword[None] , identifier[port] = keyword[None] , identifier[db] = keyword[None] , identifier[password] = keyword[None] ):
literal[string]
identifier[server] = identifier[_connect] ( identifier[host] , identifier[port] , identifier[db] , identifier[passwo... | def info(host=None, port=None, db=None, password=None):
"""
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
"""
server = _connect(host, port, db, password)
return server.info() |
def launchQueryForMode(self, query=None, mode=None):
"""
Method that launches an i3Browser to collect data.
Args:
-----
query: The query to be performed
mode: The mode to be used to build the query.
Return:
-------
A string containing... | def function[launchQueryForMode, parameter[self, query, mode]]:
constant[
Method that launches an i3Browser to collect data.
Args:
-----
query: The query to be performed
mode: The mode to be used to build the query.
Return:
-------
A ... | keyword[def] identifier[launchQueryForMode] ( identifier[self] , identifier[query] = keyword[None] , identifier[mode] = keyword[None] ):
literal[string]
identifier[qURL] = identifier[self] . identifier[createURL] ( identifier[word] = identifier[query] , identifier[mode] = identifier[mode] ... | def launchQueryForMode(self, query=None, mode=None):
"""
Method that launches an i3Browser to collect data.
Args:
-----
query: The query to be performed
mode: The mode to be used to build the query.
Return:
-------
A string containing the... |
def xml_marshal_bucket_constraint(region):
"""
Marshal's bucket constraint based on *region*.
:param region: Region name of a given bucket.
:return: Marshalled XML data.
"""
root = s3_xml.Element('CreateBucketConfiguration', {'xmlns': _S3_NAMESPACE})
location_constraint = s3_xml.SubElement(... | def function[xml_marshal_bucket_constraint, parameter[region]]:
constant[
Marshal's bucket constraint based on *region*.
:param region: Region name of a given bucket.
:return: Marshalled XML data.
]
variable[root] assign[=] call[name[s3_xml].Element, parameter[constant[CreateBucketConfi... | keyword[def] identifier[xml_marshal_bucket_constraint] ( identifier[region] ):
literal[string]
identifier[root] = identifier[s3_xml] . identifier[Element] ( literal[string] ,{ literal[string] : identifier[_S3_NAMESPACE] })
identifier[location_constraint] = identifier[s3_xml] . identifier[SubElement] (... | def xml_marshal_bucket_constraint(region):
"""
Marshal's bucket constraint based on *region*.
:param region: Region name of a given bucket.
:return: Marshalled XML data.
"""
root = s3_xml.Element('CreateBucketConfiguration', {'xmlns': _S3_NAMESPACE})
location_constraint = s3_xml.SubElement(... |
def get_command(self, ctx, name):
"""
Get a bound command method
@type ctx: Context
@param name: Command name
@type name: str
@rtype: object
"""
try:
mod = importlib.import_module('ips_vagrant.commands.{name}'.format(name=name))
... | def function[get_command, parameter[self, ctx, name]]:
constant[
Get a bound command method
@type ctx: Context
@param name: Command name
@type name: str
@rtype: object
]
<ast.Try object at 0x7da18f00ed70> | keyword[def] identifier[get_command] ( identifier[self] , identifier[ctx] , identifier[name] ):
literal[string]
keyword[try] :
identifier[mod] = identifier[importlib] . identifier[import_module] ( literal[string] . identifier[format] ( identifier[name] = identifier[name] ))
... | def get_command(self, ctx, name):
"""
Get a bound command method
@type ctx: Context
@param name: Command name
@type name: str
@rtype: object
"""
try:
mod = importlib.import_module('ips_vagrant.commands.{name}'.format(name=name))
return ... |
def _readResponse(self):
"""
Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received.
"""
traps = []
reply_word = None
while reply_word != '!done':
repl... | def function[_readResponse, parameter[self]]:
constant[
Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received.
]
variable[traps] assign[=] list[[]]
variable[reply_word] a... | keyword[def] identifier[_readResponse] ( identifier[self] ):
literal[string]
identifier[traps] =[]
identifier[reply_word] = keyword[None]
keyword[while] identifier[reply_word] != literal[string] :
identifier[reply_word] , identifier[words] = identifier[self] . ident... | def _readResponse(self):
"""
Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received.
"""
traps = []
reply_word = None
while reply_word != '!done':
(reply_word, words) = se... |
def adjust_privileges(state, privileges):
"""
Requests or drops privileges.
@type state: bool
@param state: C{True} to request, C{False} to drop.
@type privileges: list(int)
@param privileges: Privileges to request or drop.
@raise WindowsError: Raises an exce... | def function[adjust_privileges, parameter[state, privileges]]:
constant[
Requests or drops privileges.
@type state: bool
@param state: C{True} to request, C{False} to drop.
@type privileges: list(int)
@param privileges: Privileges to request or drop.
@raise W... | keyword[def] identifier[adjust_privileges] ( identifier[state] , identifier[privileges] ):
literal[string]
keyword[with] identifier[win32] . identifier[OpenProcessToken] ( identifier[win32] . identifier[GetCurrentProcess] (),
identifier[win32] . identifier[TOKEN_ADJUST_PRIVILEGES] ) keywo... | def adjust_privileges(state, privileges):
"""
Requests or drops privileges.
@type state: bool
@param state: C{True} to request, C{False} to drop.
@type privileges: list(int)
@param privileges: Privileges to request or drop.
@raise WindowsError: Raises an exceptio... |
def download(ctx):
"""Download data."""
log.debug('chemdataextractor.data.download')
count = 0
for package in PACKAGES:
success = package.download()
if success:
count += 1
click.echo('Successfully downloaded %s new data packages (%s existing)' % (count, len(PACKAGES) - co... | def function[download, parameter[ctx]]:
constant[Download data.]
call[name[log].debug, parameter[constant[chemdataextractor.data.download]]]
variable[count] assign[=] constant[0]
for taget[name[package]] in starred[name[PACKAGES]] begin[:]
variable[success] assign[=] call... | keyword[def] identifier[download] ( identifier[ctx] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[count] = literal[int]
keyword[for] identifier[package] keyword[in] identifier[PACKAGES] :
identifier[success] = identifier[package] . identifier[d... | def download(ctx):
"""Download data."""
log.debug('chemdataextractor.data.download')
count = 0
for package in PACKAGES:
success = package.download()
if success:
count += 1 # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['package']]
click.echo... |
def better_exchook(etype, value, tb, debugshell=False, autodebugshell=True, file=None, with_color=None):
"""
Replacement for sys.excepthook.
:param etype: exception type
:param value: exception value
:param tb: traceback
:param bool debugshell: spawn a debug shell at the context of the exceptio... | def function[better_exchook, parameter[etype, value, tb, debugshell, autodebugshell, file, with_color]]:
constant[
Replacement for sys.excepthook.
:param etype: exception type
:param value: exception value
:param tb: traceback
:param bool debugshell: spawn a debug shell at the context of th... | keyword[def] identifier[better_exchook] ( identifier[etype] , identifier[value] , identifier[tb] , identifier[debugshell] = keyword[False] , identifier[autodebugshell] = keyword[True] , identifier[file] = keyword[None] , identifier[with_color] = keyword[None] ):
literal[string]
keyword[if] identifier[file... | def better_exchook(etype, value, tb, debugshell=False, autodebugshell=True, file=None, with_color=None):
"""
Replacement for sys.excepthook.
:param etype: exception type
:param value: exception value
:param tb: traceback
:param bool debugshell: spawn a debug shell at the context of the exceptio... |
def parse_java_version(cls, version):
"""Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
versioning information after t... | def function[parse_java_version, parameter[cls, version]]:
constant[Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
... | keyword[def] identifier[parse_java_version] ( identifier[cls] , identifier[version] ):
literal[string]
identifier[conversion] ={ identifier[str] ( identifier[i] ): literal[string] . identifier[format] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[cls] . identifier[SUPPORTED_CONVERS... | def parse_java_version(cls, version):
"""Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
versioning information after t... |
def get_value(self) -> Decimal:
""" Returns the current value of stocks """
quantity = self.get_quantity()
price = self.get_last_available_price()
if not price:
# raise ValueError("no price found for", self.full_symbol)
return Decimal(0)
value = quantity ... | def function[get_value, parameter[self]]:
constant[ Returns the current value of stocks ]
variable[quantity] assign[=] call[name[self].get_quantity, parameter[]]
variable[price] assign[=] call[name[self].get_last_available_price, parameter[]]
if <ast.UnaryOp object at 0x7da1b1289870> beg... | keyword[def] identifier[get_value] ( identifier[self] )-> identifier[Decimal] :
literal[string]
identifier[quantity] = identifier[self] . identifier[get_quantity] ()
identifier[price] = identifier[self] . identifier[get_last_available_price] ()
keyword[if] keyword[not] identifie... | def get_value(self) -> Decimal:
""" Returns the current value of stocks """
quantity = self.get_quantity()
price = self.get_last_available_price()
if not price:
# raise ValueError("no price found for", self.full_symbol)
return Decimal(0) # depends on [control=['if'], data=[]]
value ... |
def version(ruby=None, runas=None, gem_bin=None):
'''
Print out the version of gem
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.... | def function[version, parameter[ruby, runas, gem_bin]]:
constant[
Print out the version of gem
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin... | keyword[def] identifier[version] ( identifier[ruby] = keyword[None] , identifier[runas] = keyword[None] , identifier[gem_bin] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] ]
identifier[stdout] = identifier[_gem] ( identifier[cmd] ,
identifier[ruby] ,
identifier[gem_bi... | def version(ruby=None, runas=None, gem_bin=None):
"""
Print out the version of gem
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.... |
def invoke(self,
function_config,
event,
debug_context=None,
stdout=None,
stderr=None):
"""
Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until ei... | def function[invoke, parameter[self, function_config, event, debug_context, stdout, stderr]]:
constant[
Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until either the Lambda function completes or timed out, which could be... | keyword[def] identifier[invoke] ( identifier[self] ,
identifier[function_config] ,
identifier[event] ,
identifier[debug_context] = keyword[None] ,
identifier[stdout] = keyword[None] ,
identifier[stderr] = keyword[None] ):
literal[string]
identifier[timer] = keyword[None]
id... | def invoke(self, function_config, event, debug_context=None, stdout=None, stderr=None):
"""
Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until either the Lambda function completes or timed out, which could be seconds.
... |
def send_signal(self, signal):
"""
Send signal from this node to all connected receivers unless the node is in spectator mode.
signal -- (hashable) signal value, see `dispatcher` connect for details
Return a list of tuple pairs [(receiver, response), ... ]
or None if the node i... | def function[send_signal, parameter[self, signal]]:
constant[
Send signal from this node to all connected receivers unless the node is in spectator mode.
signal -- (hashable) signal value, see `dispatcher` connect for details
Return a list of tuple pairs [(receiver, response), ... ]
... | keyword[def] identifier[send_signal] ( identifier[self] , identifier[signal] ):
literal[string]
keyword[if] identifier[self] . identifier[in_spectator_mode] : keyword[return] keyword[None]
identifier[logger] . identifier[debug] ( literal[string] %( identifier[self] , identifier[signal] ... | def send_signal(self, signal):
"""
Send signal from this node to all connected receivers unless the node is in spectator mode.
signal -- (hashable) signal value, see `dispatcher` connect for details
Return a list of tuple pairs [(receiver, response), ... ]
or None if the node is in... |
def color(self, color):
"""
Updates the security labels color.
Args:
color:
"""
self._data['color'] = color
request = self._base_request
request['color'] = color
return self._tc_requests.update(request, owner=self.owner) | def function[color, parameter[self, color]]:
constant[
Updates the security labels color.
Args:
color:
]
call[name[self]._data][constant[color]] assign[=] name[color]
variable[request] assign[=] name[self]._base_request
call[name[request]][constant[c... | keyword[def] identifier[color] ( identifier[self] , identifier[color] ):
literal[string]
identifier[self] . identifier[_data] [ literal[string] ]= identifier[color]
identifier[request] = identifier[self] . identifier[_base_request]
identifier[request] [ literal[string] ]= identi... | def color(self, color):
"""
Updates the security labels color.
Args:
color:
"""
self._data['color'] = color
request = self._base_request
request['color'] = color
return self._tc_requests.update(request, owner=self.owner) |
def plot_meshes(self, ax=None, marker='+', color='blue', outlines=False,
**kwargs):
"""
Plot the low-resolution mesh boxes on a matplotlib Axes
instance.
Parameters
----------
ax : `matplotlib.axes.Axes` instance, optional
If `None`, then ... | def function[plot_meshes, parameter[self, ax, marker, color, outlines]]:
constant[
Plot the low-resolution mesh boxes on a matplotlib Axes
instance.
Parameters
----------
ax : `matplotlib.axes.Axes` instance, optional
If `None`, then the current ``Axes`` inst... | keyword[def] identifier[plot_meshes] ( identifier[self] , identifier[ax] = keyword[None] , identifier[marker] = literal[string] , identifier[color] = literal[string] , identifier[outlines] = keyword[False] ,
** identifier[kwargs] ):
literal[string]
keyword[import] identifier[matplotlib] . identif... | def plot_meshes(self, ax=None, marker='+', color='blue', outlines=False, **kwargs):
"""
Plot the low-resolution mesh boxes on a matplotlib Axes
instance.
Parameters
----------
ax : `matplotlib.axes.Axes` instance, optional
If `None`, then the current ``Axes`` ins... |
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': ... | def function[processlist, parameter[]]:
constant[
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
... | keyword[def] identifier[processlist] (** identifier[connection_args] ):
literal[string]
identifier[ret] =[]
identifier[dbc] = identifier[_connect] (** identifier[connection_args] )
keyword[if] identifier[dbc] keyword[is] keyword[None] :
keyword[return] []
identifier[cur] = ident... | def processlist(**connection_args):
"""
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': ... |
def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan("Git Synced!")) | def function[sync, parameter[remote, branch]]:
constant[git pull and push commit]
call[name[pull], parameter[name[branch], name[remote]]]
call[name[push], parameter[name[branch], name[remote]]]
call[name[print], parameter[call[name[cyan], parameter[constant[Git Synced!]]]]] | keyword[def] identifier[sync] ( identifier[remote] = literal[string] , identifier[branch] = literal[string] ):
literal[string]
identifier[pull] ( identifier[branch] , identifier[remote] )
identifier[push] ( identifier[branch] , identifier[remote] )
identifier[print] ( identifier[cyan] ( literal[s... | def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan('Git Synced!')) |
def list(self):
"""Returns a list of the users gists as GistInfo objects
Returns:
a list of GistInfo objects
"""
# Define the basic request. The per_page parameter is set to 100, which
# is the maximum github allows. If the user has more than one page of
# g... | def function[list, parameter[self]]:
constant[Returns a list of the users gists as GistInfo objects
Returns:
a list of GistInfo objects
]
variable[request] assign[=] call[name[requests].Request, parameter[constant[GET], constant[https://api.github.com/gists]]]
varia... | keyword[def] identifier[list] ( identifier[self] ):
literal[string]
identifier[request] = identifier[requests] . identifier[Request] (
literal[string] ,
literal[string] ,
identifier[headers] ={
literal[string] : literal[string]... | def list(self):
"""Returns a list of the users gists as GistInfo objects
Returns:
a list of GistInfo objects
"""
# Define the basic request. The per_page parameter is set to 100, which
# is the maximum github allows. If the user has more than one page of
# gists, this reque... |
def connect_producer(self, bootstrap_servers='127.0.0.1:9092', client_id='Robot', **kwargs):
"""A Kafka client that publishes records to the Kafka cluster.
Keyword Arguments:
- ``bootstrap_servers``: 'host[:port]' string (or list of 'host[:port]'
strings) that the producer should ... | def function[connect_producer, parameter[self, bootstrap_servers, client_id]]:
constant[A Kafka client that publishes records to the Kafka cluster.
Keyword Arguments:
- ``bootstrap_servers``: 'host[:port]' string (or list of 'host[:port]'
strings) that the producer should contact ... | keyword[def] identifier[connect_producer] ( identifier[self] , identifier[bootstrap_servers] = literal[string] , identifier[client_id] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[producer] = identifier[KafkaProducer] ( identifier[bootstrap_servers] = id... | def connect_producer(self, bootstrap_servers='127.0.0.1:9092', client_id='Robot', **kwargs):
"""A Kafka client that publishes records to the Kafka cluster.
Keyword Arguments:
- ``bootstrap_servers``: 'host[:port]' string (or list of 'host[:port]'
strings) that the producer should cont... |
def stop_and_reset_thread(self, ignore_results=False):
"""Stop current search thread and clean-up"""
if self.search_thread is not None:
if self.search_thread.isRunning():
if ignore_results:
self.search_thread.sig_finished.disconnect(
... | def function[stop_and_reset_thread, parameter[self, ignore_results]]:
constant[Stop current search thread and clean-up]
if compare[name[self].search_thread is_not constant[None]] begin[:]
if call[name[self].search_thread.isRunning, parameter[]] begin[:]
if name[ig... | keyword[def] identifier[stop_and_reset_thread] ( identifier[self] , identifier[ignore_results] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[search_thread] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[self] . identifier[search_... | def stop_and_reset_thread(self, ignore_results=False):
"""Stop current search thread and clean-up"""
if self.search_thread is not None:
if self.search_thread.isRunning():
if ignore_results:
self.search_thread.sig_finished.disconnect(self.search_complete) # depends on [contro... |
def get_port(self, adapter_number, port_number):
"""
Return the port for this adapter_number and port_number
or returns None if the port is not found
"""
for port in self.ports:
if port.adapter_number == adapter_number and port.port_number == port_number:
... | def function[get_port, parameter[self, adapter_number, port_number]]:
constant[
Return the port for this adapter_number and port_number
or returns None if the port is not found
]
for taget[name[port]] in starred[name[self].ports] begin[:]
if <ast.BoolOp object at ... | keyword[def] identifier[get_port] ( identifier[self] , identifier[adapter_number] , identifier[port_number] ):
literal[string]
keyword[for] identifier[port] keyword[in] identifier[self] . identifier[ports] :
keyword[if] identifier[port] . identifier[adapter_number] == identifier[ad... | def get_port(self, adapter_number, port_number):
"""
Return the port for this adapter_number and port_number
or returns None if the port is not found
"""
for port in self.ports:
if port.adapter_number == adapter_number and port.port_number == port_number:
return port ... |
def all_enclosing_scopes(scope, allow_global=True):
"""Utility function to return all scopes up to the global scope enclosing a
given scope."""
_validate_full_scope(scope)
# TODO: validate scopes here and/or in `enclosing_scope()` instead of assuming correctness.
def scope_within_range(tentative_scope):
... | def function[all_enclosing_scopes, parameter[scope, allow_global]]:
constant[Utility function to return all scopes up to the global scope enclosing a
given scope.]
call[name[_validate_full_scope], parameter[name[scope]]]
def function[scope_within_range, parameter[tentative_scope]]:
... | keyword[def] identifier[all_enclosing_scopes] ( identifier[scope] , identifier[allow_global] = keyword[True] ):
literal[string]
identifier[_validate_full_scope] ( identifier[scope] )
keyword[def] identifier[scope_within_range] ( identifier[tentative_scope] ):
keyword[if] identifier[tentative_sco... | def all_enclosing_scopes(scope, allow_global=True):
"""Utility function to return all scopes up to the global scope enclosing a
given scope."""
_validate_full_scope(scope)
# TODO: validate scopes here and/or in `enclosing_scope()` instead of assuming correctness.
def scope_within_range(tentative_scop... |
def remove_edge(self, u, v):
"""Version of remove_edge that's much like normal networkx but only
deletes once, since the database doesn't keep separate adj and
succ mappings
"""
try:
del self.succ[u][v]
except KeyError:
raise NetworkXError(
... | def function[remove_edge, parameter[self, u, v]]:
constant[Version of remove_edge that's much like normal networkx but only
deletes once, since the database doesn't keep separate adj and
succ mappings
]
<ast.Try object at 0x7da1b0e27400> | keyword[def] identifier[remove_edge] ( identifier[self] , identifier[u] , identifier[v] ):
literal[string]
keyword[try] :
keyword[del] identifier[self] . identifier[succ] [ identifier[u] ][ identifier[v] ]
keyword[except] identifier[KeyError] :
keyword[raise] i... | def remove_edge(self, u, v):
"""Version of remove_edge that's much like normal networkx but only
deletes once, since the database doesn't keep separate adj and
succ mappings
"""
try:
del self.succ[u][v] # depends on [control=['try'], data=[]]
except KeyError:
raise ... |
def get_pastml_parameter_file(method, model, column):
"""
Get the filename where the PastML parameters are saved
(for non-ML methods and input parameters will be None, as they have no parameters).
This file is inside the work_dir that can be specified for the pastml_pipeline method.
:param method: ... | def function[get_pastml_parameter_file, parameter[method, model, column]]:
constant[
Get the filename where the PastML parameters are saved
(for non-ML methods and input parameters will be None, as they have no parameters).
This file is inside the work_dir that can be specified for the pastml_pipeli... | keyword[def] identifier[get_pastml_parameter_file] ( identifier[method] , identifier[model] , identifier[column] ):
literal[string]
identifier[ml] = identifier[is_ml] ( identifier[method] )
identifier[template] = identifier[PASTML_ML_PARAMS_TAB] keyword[if] identifier[ml] keyword[else] identifier[... | def get_pastml_parameter_file(method, model, column):
"""
Get the filename where the PastML parameters are saved
(for non-ML methods and input parameters will be None, as they have no parameters).
This file is inside the work_dir that can be specified for the pastml_pipeline method.
:param method: ... |
def create_bodies(self, translate=(0, 1, 0), size=0.1):
'''Traverse the bone hierarchy and create physics bodies.'''
stack = [('root', 0, self.root['position'] + translate)]
while stack:
name, depth, end = stack.pop()
for child in self.hierarchy.get(name, ()):
... | def function[create_bodies, parameter[self, translate, size]]:
constant[Traverse the bone hierarchy and create physics bodies.]
variable[stack] assign[=] list[[<ast.Tuple object at 0x7da1b008e650>]]
while name[stack] begin[:]
<ast.Tuple object at 0x7da1b008d7e0> assign[=] call[na... | keyword[def] identifier[create_bodies] ( identifier[self] , identifier[translate] =( literal[int] , literal[int] , literal[int] ), identifier[size] = literal[int] ):
literal[string]
identifier[stack] =[( literal[string] , literal[int] , identifier[self] . identifier[root] [ literal[string] ]+ ident... | def create_bodies(self, translate=(0, 1, 0), size=0.1):
"""Traverse the bone hierarchy and create physics bodies."""
stack = [('root', 0, self.root['position'] + translate)]
while stack:
(name, depth, end) = stack.pop()
for child in self.hierarchy.get(name, ()):
stack.append((chi... |
def split_in_tiles(self, hint):
"""
Split a SiteCollection into a set of tiles (SiteCollection instances).
:param hint: hint for how many tiles to generate
"""
tiles = []
for seq in split_in_blocks(range(len(self)), hint or 1):
sc = SiteCollection.__new__(Sit... | def function[split_in_tiles, parameter[self, hint]]:
constant[
Split a SiteCollection into a set of tiles (SiteCollection instances).
:param hint: hint for how many tiles to generate
]
variable[tiles] assign[=] list[[]]
for taget[name[seq]] in starred[call[name[split_in_... | keyword[def] identifier[split_in_tiles] ( identifier[self] , identifier[hint] ):
literal[string]
identifier[tiles] =[]
keyword[for] identifier[seq] keyword[in] identifier[split_in_blocks] ( identifier[range] ( identifier[len] ( identifier[self] )), identifier[hint] keyword[or] literal... | def split_in_tiles(self, hint):
"""
Split a SiteCollection into a set of tiles (SiteCollection instances).
:param hint: hint for how many tiles to generate
"""
tiles = []
for seq in split_in_blocks(range(len(self)), hint or 1):
sc = SiteCollection.__new__(SiteCollection)
... |
def dump_dict_of_nested_lists_to_h5(fname, data):
"""
Take nested list structure and dump it in hdf5 file.
Parameters
----------
fname : str
Filename
data : dict(list(numpy.ndarray))
Dict of nested lists with variable len arrays.
Returns
-------
None
... | def function[dump_dict_of_nested_lists_to_h5, parameter[fname, data]]:
constant[
Take nested list structure and dump it in hdf5 file.
Parameters
----------
fname : str
Filename
data : dict(list(numpy.ndarray))
Dict of nested lists with variable len arrays.
Re... | keyword[def] identifier[dump_dict_of_nested_lists_to_h5] ( identifier[fname] , identifier[data] ):
literal[string]
identifier[print] ( literal[string] % identifier[fname] )
identifier[f] = identifier[h5py] . identifier[File] ( identifier[fname] )
keyword[for] identifier[i] , identifier... | def dump_dict_of_nested_lists_to_h5(fname, data):
"""
Take nested list structure and dump it in hdf5 file.
Parameters
----------
fname : str
Filename
data : dict(list(numpy.ndarray))
Dict of nested lists with variable len arrays.
Returns
-------
None
... |
def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
"""
if changeset_id not i... | def function[pop_changeset, parameter[self, changeset_id]]:
constant[
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
]
if compare[name[changeset_id] <ast.NotIn object at... | keyword[def] identifier[pop_changeset] ( identifier[self] , identifier[changeset_id] : identifier[uuid] . identifier[UUID] )-> identifier[Dict] [ identifier[bytes] , identifier[Union] [ identifier[bytes] , identifier[DeletedEntry] ]]:
literal[string]
keyword[if] identifier[changeset_id] keyword[n... | def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
"""
if changeset_id not in self.j... |
def count(self, index="_all", type='', source='', parameters=None, callback=None):
"""
The query can either be provided using a simple query string as a parameter 'q',
or using the Query DSL defined within the request body (source).
Notice there are additional query string parameters tha... | def function[count, parameter[self, index, type, source, parameters, callback]]:
constant[
The query can either be provided using a simple query string as a parameter 'q',
or using the Query DSL defined within the request body (source).
Notice there are additional query string parameters... | keyword[def] identifier[count] ( identifier[self] , identifier[index] = literal[string] , identifier[type] = literal[string] , identifier[source] = literal[string] , identifier[parameters] = keyword[None] , identifier[callback] = keyword[None] ):
literal[string]
identifier[parameters] = identifier[... | def count(self, index='_all', type='', source='', parameters=None, callback=None):
"""
The query can either be provided using a simple query string as a parameter 'q',
or using the Query DSL defined within the request body (source).
Notice there are additional query string parameters that co... |
def analysis(analysis_id):
"""Display a single analysis."""
analysis_obj = store.analysis(analysis_id)
if analysis_obj is None:
return abort(404)
if request.method == 'PUT':
analysis_obj.update(request.json)
store.commit()
data = analysis_obj.to_dict()
data['failed_jobs... | def function[analysis, parameter[analysis_id]]:
constant[Display a single analysis.]
variable[analysis_obj] assign[=] call[name[store].analysis, parameter[name[analysis_id]]]
if compare[name[analysis_obj] is constant[None]] begin[:]
return[call[name[abort], parameter[constant[404]]]]
... | keyword[def] identifier[analysis] ( identifier[analysis_id] ):
literal[string]
identifier[analysis_obj] = identifier[store] . identifier[analysis] ( identifier[analysis_id] )
keyword[if] identifier[analysis_obj] keyword[is] keyword[None] :
keyword[return] identifier[abort] ( literal[int] ... | def analysis(analysis_id):
"""Display a single analysis."""
analysis_obj = store.analysis(analysis_id)
if analysis_obj is None:
return abort(404) # depends on [control=['if'], data=[]]
if request.method == 'PUT':
analysis_obj.update(request.json)
store.commit() # depends on [co... |
def init_UI(self):
"""
Builds User Interface for the interpretation Editor
"""
#set fonts
FONT_WEIGHT=1
if sys.platform.startswith('win'): FONT_WEIGHT=-1
font1 = wx.Font(9+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type)
font2 = wx.Font... | def function[init_UI, parameter[self]]:
constant[
Builds User Interface for the interpretation Editor
]
variable[FONT_WEIGHT] assign[=] constant[1]
if call[name[sys].platform.startswith, parameter[constant[win]]] begin[:]
variable[FONT_WEIGHT] assign[=] <ast.Unary... | keyword[def] identifier[init_UI] ( identifier[self] ):
literal[string]
identifier[FONT_WEIGHT] = literal[int]
keyword[if] identifier[sys] . identifier[platform] . identifier[startswith] ( literal[string] ): identifier[FONT_WEIGHT] =- literal[int]
identifier[font1] = i... | def init_UI(self):
"""
Builds User Interface for the interpretation Editor
"""
#set fonts
FONT_WEIGHT = 1
if sys.platform.startswith('win'):
FONT_WEIGHT = -1 # depends on [control=['if'], data=[]]
font1 = wx.Font(9 + FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.f... |
def _check_methods(cls, subclass): # pylint: disable=too-many-branches
"""
Args:
cls(:py:class:`Plugin`): Parent class
subclass(:py:class:`Plugin`): Subclass to evaluate
Returns:
Result: Named tuple
Validate abstract methods are defined in subclass
For error codes see _ins... | def function[_check_methods, parameter[cls, subclass]]:
constant[
Args:
cls(:py:class:`Plugin`): Parent class
subclass(:py:class:`Plugin`): Subclass to evaluate
Returns:
Result: Named tuple
Validate abstract methods are defined in subclass
For error codes see _inspect_c... | keyword[def] identifier[_check_methods] ( identifier[cls] , identifier[subclass] ):
literal[string]
keyword[for] identifier[meth] , identifier[methobj] keyword[in] identifier[cls] . identifier[__abstractmethods__] . identifier[items] ():
keyword[for] identifier[base] keyword[in] ident... | def _check_methods(cls, subclass): # pylint: disable=too-many-branches
'\n Args:\n cls(:py:class:`Plugin`): Parent class\n subclass(:py:class:`Plugin`): Subclass to evaluate\n\n Returns:\n Result: Named tuple\n\n Validate abstract methods are defined in subclass\n For error codes s... |
def warning(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``WARNING`` level."""
add_message(request, constants.WARNING, message, extra_tags=extra_tags,
fail_silently=fail_silently) | def function[warning, parameter[request, message, extra_tags, fail_silently]]:
constant[Adds a message with the ``WARNING`` level.]
call[name[add_message], parameter[name[request], name[constants].WARNING, name[message]]] | keyword[def] identifier[warning] ( identifier[request] , identifier[message] , identifier[extra_tags] = literal[string] , identifier[fail_silently] = keyword[False] ):
literal[string]
identifier[add_message] ( identifier[request] , identifier[constants] . identifier[WARNING] , identifier[message] , identif... | def warning(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``WARNING`` level."""
add_message(request, constants.WARNING, message, extra_tags=extra_tags, fail_silently=fail_silently) |
def listDatasets(self, dataset="", parent_dataset="", is_dataset_valid=1,
release_version="", pset_hash="", app_name="", output_module_label="", global_tag="",
processing_version=0, acquisition_era_name="", run_num=-1,
physics_group_name="", logical_file_name="", primary_ds_name="", primary_ds_t... | def function[listDatasets, parameter[self, dataset, parent_dataset, is_dataset_valid, release_version, pset_hash, app_name, output_module_label, global_tag, processing_version, acquisition_era_name, run_num, physics_group_name, logical_file_name, primary_ds_name, primary_ds_type, processed_ds_name, data_tier_name, data... | keyword[def] identifier[listDatasets] ( identifier[self] , identifier[dataset] = literal[string] , identifier[parent_dataset] = literal[string] , identifier[is_dataset_valid] = literal[int] ,
identifier[release_version] = literal[string] , identifier[pset_hash] = literal[string] , identifier[app_name] = literal[stri... | def listDatasets(self, dataset='', parent_dataset='', is_dataset_valid=1, release_version='', pset_hash='', app_name='', output_module_label='', global_tag='', processing_version=0, acquisition_era_name='', run_num=-1, physics_group_name='', logical_file_name='', primary_ds_name='', primary_ds_type='', processed_ds_nam... |
def update_one(self, update=None, validate=True, **kw):
"""Update this document in the database. Local representations will not be affected.
A single positional parameter, `update`, may be provided as a mapping. Keyword arguments (other than those
identified in UPDATE_MAPPING) are interpreted as parametric upd... | def function[update_one, parameter[self, update, validate]]:
constant[Update this document in the database. Local representations will not be affected.
A single positional parameter, `update`, may be provided as a mapping. Keyword arguments (other than those
identified in UPDATE_MAPPING) are interpreted ... | keyword[def] identifier[update_one] ( identifier[self] , identifier[update] = keyword[None] , identifier[validate] = keyword[True] ,** identifier[kw] ):
literal[string]
identifier[D] = identifier[self] . identifier[__class__]
identifier[collection] = identifier[self] . identifier[get_collection] ( identif... | def update_one(self, update=None, validate=True, **kw):
"""Update this document in the database. Local representations will not be affected.
A single positional parameter, `update`, may be provided as a mapping. Keyword arguments (other than those
identified in UPDATE_MAPPING) are interpreted as parametric u... |
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmode... | def function[baremetal_models, parameter[call]]:
constant[
Return a dict of all available baremetal models with relevant data.
]
if compare[name[call] equal[==] constant[action]] begin[:]
<ast.Raise object at 0x7da18bccaec0>
variable[conn] assign[=] call[name[get_conn], parameter... | keyword[def] identifier[baremetal_models] ( identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
)
identifier[conn] = identifier[get... | def baremetal_models(call=None):
"""
Return a dict of all available baremetal models with relevant data.
"""
if call == 'action':
raise SaltCloudSystemExit('The baremetal_models function must be called with -f or --function') # depends on [control=['if'], data=[]]
conn = get_conn()
bmod... |
def random_partition(n, n_data):
"""return n random rows of data (and also the other len(data)-n rows)"""
all_idxs = np.arange(n_data)
np.random.shuffle(all_idxs)
idxs1 = all_idxs[:n]
idxs2 = all_idxs[n:]
return idxs1, idxs2 | def function[random_partition, parameter[n, n_data]]:
constant[return n random rows of data (and also the other len(data)-n rows)]
variable[all_idxs] assign[=] call[name[np].arange, parameter[name[n_data]]]
call[name[np].random.shuffle, parameter[name[all_idxs]]]
variable[idxs1] assign[=... | keyword[def] identifier[random_partition] ( identifier[n] , identifier[n_data] ):
literal[string]
identifier[all_idxs] = identifier[np] . identifier[arange] ( identifier[n_data] )
identifier[np] . identifier[random] . identifier[shuffle] ( identifier[all_idxs] )
identifier[idxs1] = identifier[all... | def random_partition(n, n_data):
"""return n random rows of data (and also the other len(data)-n rows)"""
all_idxs = np.arange(n_data)
np.random.shuffle(all_idxs)
idxs1 = all_idxs[:n]
idxs2 = all_idxs[n:]
return (idxs1, idxs2) |
def volatility(tnet, distance_func_name='default', calc='global', communities=None, event_displacement=None):
r"""
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
---... | def function[volatility, parameter[tnet, distance_func_name, calc, communities, event_displacement]]:
constant[
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
--... | keyword[def] identifier[volatility] ( identifier[tnet] , identifier[distance_func_name] = literal[string] , identifier[calc] = literal[string] , identifier[communities] = keyword[None] , identifier[event_displacement] = keyword[None] ):
literal[string]
identifier[tnet] , identifier[netinfo] = identif... | def volatility(tnet, distance_func_name='default', calc='global', communities=None, event_displacement=None):
"""
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
----... |
def get_all_user_objects(self):
"""
Fetches all user objects from the AD, and returns MSADUser object
"""
logger.debug('Polling AD for all user objects')
ldap_filter = r'(objectClass=user)'
attributes = MSADUser.ATTRS
for entry in self.pagedsearch(ldap_filter, attributes):
# TODO: return ldapuser obje... | def function[get_all_user_objects, parameter[self]]:
constant[
Fetches all user objects from the AD, and returns MSADUser object
]
call[name[logger].debug, parameter[constant[Polling AD for all user objects]]]
variable[ldap_filter] assign[=] constant[(objectClass=user)]
variable[attr... | keyword[def] identifier[get_all_user_objects] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[ldap_filter] = literal[string]
identifier[attributes] = identifier[MSADUser] . identifier[ATTRS]
keyword[for] identifier[entry] keyword[in] id... | def get_all_user_objects(self):
"""
Fetches all user objects from the AD, and returns MSADUser object
"""
logger.debug('Polling AD for all user objects')
ldap_filter = '(objectClass=user)'
attributes = MSADUser.ATTRS
for entry in self.pagedsearch(ldap_filter, attributes): # TODO: return ldapuse... |
def hide_element(self, selector, by=By.CSS_SELECTOR):
""" Hide the first element on the page that matches the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_onl... | def function[hide_element, parameter[self, selector, by]]:
constant[ Hide the first element on the page that matches the selector. ]
<ast.Tuple object at 0x7da1b1b15cc0> assign[=] call[name[self].__recalculate_selector, parameter[name[selector], name[by]]]
variable[selector] assign[=] call[name[... | keyword[def] identifier[hide_element] ( identifier[self] , identifier[selector] , identifier[by] = identifier[By] . identifier[CSS_SELECTOR] ):
literal[string]
identifier[selector] , identifier[by] = identifier[self] . identifier[__recalculate_selector] ( identifier[selector] , identifier[by] )
... | def hide_element(self, selector, by=By.CSS_SELECTOR):
""" Hide the first element on the page that matches the selector. """
(selector, by) = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
... |
def arc_center(points):
"""
Given three points on an arc find:
center, radius, normal, and angle.
This uses the fact that the intersection of the perp
bisectors of the segments between the control points
is the center of the arc.
Parameters
---------
points : (3, dimension) float
... | def function[arc_center, parameter[points]]:
constant[
Given three points on an arc find:
center, radius, normal, and angle.
This uses the fact that the intersection of the perp
bisectors of the segments between the control points
is the center of the arc.
Parameters
---------
... | keyword[def] identifier[arc_center] ( identifier[points] ):
literal[string]
identifier[points] , identifier[is_2D] = identifier[util] . identifier[stack_3D] ( identifier[points] , identifier[return_2D] = keyword[True] )
identifier[edge_direction] = identifier[np] . identifier[diff] ( identi... | def arc_center(points):
"""
Given three points on an arc find:
center, radius, normal, and angle.
This uses the fact that the intersection of the perp
bisectors of the segments between the control points
is the center of the arc.
Parameters
---------
points : (3, dimension) float
... |
def do_rewind(self, line):
"""
rewind
"""
self.print_response("Rewinding from frame %s to 0" % self.bot._frame)
self.bot._frame = 0 | def function[do_rewind, parameter[self, line]]:
constant[
rewind
]
call[name[self].print_response, parameter[binary_operation[constant[Rewinding from frame %s to 0] <ast.Mod object at 0x7da2590d6920> name[self].bot._frame]]]
name[self].bot._frame assign[=] constant[0] | keyword[def] identifier[do_rewind] ( identifier[self] , identifier[line] ):
literal[string]
identifier[self] . identifier[print_response] ( literal[string] % identifier[self] . identifier[bot] . identifier[_frame] )
identifier[self] . identifier[bot] . identifier[_frame] = literal[int] | def do_rewind(self, line):
"""
rewind
"""
self.print_response('Rewinding from frame %s to 0' % self.bot._frame)
self.bot._frame = 0 |
def prime_generator(p_min=2, p_max=None):
""" Generator of prime numbers using the sieve of Eratosthenes.
Args:
p_min (int): prime numbers lower than p_min will not be in the resulting primes
p_max (int): the generator will stop when this value is reached, it means that there
will ... | def function[prime_generator, parameter[p_min, p_max]]:
constant[ Generator of prime numbers using the sieve of Eratosthenes.
Args:
p_min (int): prime numbers lower than p_min will not be in the resulting primes
p_max (int): the generator will stop when this value is reached, it means that ... | keyword[def] identifier[prime_generator] ( identifier[p_min] = literal[int] , identifier[p_max] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[p_min] , identifier[int] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[if]... | def prime_generator(p_min=2, p_max=None):
""" Generator of prime numbers using the sieve of Eratosthenes.
Args:
p_min (int): prime numbers lower than p_min will not be in the resulting primes
p_max (int): the generator will stop when this value is reached, it means that there
will b... |
def write_inj_snrs(page, ifos, injList, grbtag):
"""
Write injection chisq plots to markup.page object page
"""
if injList:
th = ['']+injList + ['OFFSOURCE']
else:
th= ['','OFFSOURCE']
injList = ['OFFSOURCE']
td = []
ifos = [ifos[i:i+2] for i in range(0, len(if... | def function[write_inj_snrs, parameter[page, ifos, injList, grbtag]]:
constant[
Write injection chisq plots to markup.page object page
]
if name[injList] begin[:]
variable[th] assign[=] binary_operation[binary_operation[list[[<ast.Constant object at 0x7da20c76f820>]] + name[i... | keyword[def] identifier[write_inj_snrs] ( identifier[page] , identifier[ifos] , identifier[injList] , identifier[grbtag] ):
literal[string]
keyword[if] identifier[injList] :
identifier[th] =[ literal[string] ]+ identifier[injList] +[ literal[string] ]
keyword[else] :
identifier[th... | def write_inj_snrs(page, ifos, injList, grbtag):
"""
Write injection chisq plots to markup.page object page
"""
if injList:
th = [''] + injList + ['OFFSOURCE'] # depends on [control=['if'], data=[]]
else:
th = ['', 'OFFSOURCE']
injList = ['OFFSOURCE']
td = []
ifo... |
def fitNullTraitByTrait(self, verbose=False, cache=False, out_dir='./cache', fname=None, rewrite=False):
"""
Fit null model trait by trait
"""
read_from_file = False
if cache:
assert fname is not None, 'MultiTraitSetTest:: specify fname'
if not os.path.exi... | def function[fitNullTraitByTrait, parameter[self, verbose, cache, out_dir, fname, rewrite]]:
constant[
Fit null model trait by trait
]
variable[read_from_file] assign[=] constant[False]
if name[cache] begin[:]
assert[compare[name[fname] is_not constant[None]]]
... | keyword[def] identifier[fitNullTraitByTrait] ( identifier[self] , identifier[verbose] = keyword[False] , identifier[cache] = keyword[False] , identifier[out_dir] = literal[string] , identifier[fname] = keyword[None] , identifier[rewrite] = keyword[False] ):
literal[string]
identifier[read_from_file... | def fitNullTraitByTrait(self, verbose=False, cache=False, out_dir='./cache', fname=None, rewrite=False):
"""
Fit null model trait by trait
"""
read_from_file = False
if cache:
assert fname is not None, 'MultiTraitSetTest:: specify fname'
if not os.path.exists(out_dir):
... |
def lists(self, uid=0, **kwargs):
"""
Returns a list of :class:`List` objects (lists which Contact belongs to) and a pager dict.
:Example:
lists, pager = client.contacts.lists(uid=1901010)
:param int uid: The unique id of the Contact to update. Required.
:param int p... | def function[lists, parameter[self, uid]]:
constant[
Returns a list of :class:`List` objects (lists which Contact belongs to) and a pager dict.
:Example:
lists, pager = client.contacts.lists(uid=1901010)
:param int uid: The unique id of the Contact to update. Required.
... | keyword[def] identifier[lists] ( identifier[self] , identifier[uid] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[lists] = identifier[Lists] ( identifier[self] . identifier[base_uri] , identifier[self] . identifier[auth] )
keyword[return] identifier[self] . identifie... | def lists(self, uid=0, **kwargs):
"""
Returns a list of :class:`List` objects (lists which Contact belongs to) and a pager dict.
:Example:
lists, pager = client.contacts.lists(uid=1901010)
:param int uid: The unique id of the Contact to update. Required.
:param int page:... |
def SetWindowLong(handle: int, index: int, value: int) -> int:
"""
SetWindowLong from Win32.
handle: int, the handle of a native window.
index: int.
value: int.
Return int, the previous value before set.
"""
return ctypes.windll.user32.SetWindowLongW(ctypes.c_void_p(handle), index, value... | def function[SetWindowLong, parameter[handle, index, value]]:
constant[
SetWindowLong from Win32.
handle: int, the handle of a native window.
index: int.
value: int.
Return int, the previous value before set.
]
return[call[name[ctypes].windll.user32.SetWindowLongW, parameter[call[nam... | keyword[def] identifier[SetWindowLong] ( identifier[handle] : identifier[int] , identifier[index] : identifier[int] , identifier[value] : identifier[int] )-> identifier[int] :
literal[string]
keyword[return] identifier[ctypes] . identifier[windll] . identifier[user32] . identifier[SetWindowLongW] ( identi... | def SetWindowLong(handle: int, index: int, value: int) -> int:
"""
SetWindowLong from Win32.
handle: int, the handle of a native window.
index: int.
value: int.
Return int, the previous value before set.
"""
return ctypes.windll.user32.SetWindowLongW(ctypes.c_void_p(handle), index, value... |
def get_uninvoiced_hours(entries, billable=None):
"""Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
"""
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
... | def function[get_uninvoiced_hours, parameter[entries, billable]]:
constant[Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
]
variable[statuses] assign[=] tuple[[<ast.Co... | keyword[def] identifier[get_uninvoiced_hours] ( identifier[entries] , identifier[billable] = keyword[None] ):
literal[string]
identifier[statuses] =( literal[string] , literal[string] )
keyword[if] identifier[billable] keyword[is] keyword[not] keyword[None] :
identifier[billable] =( ident... | def get_uninvoiced_hours(entries, billable=None):
"""Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
"""
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
... |
def load_domain_config(self, loaded_config):
'''
Loads the domain_config and sets up queue_dict
@param loaded_config: the yaml loaded config dict from zookeeper
'''
self.domain_config = {}
# vetting process to ensure correct configs
if loaded_config:
i... | def function[load_domain_config, parameter[self, loaded_config]]:
constant[
Loads the domain_config and sets up queue_dict
@param loaded_config: the yaml loaded config dict from zookeeper
]
name[self].domain_config assign[=] dictionary[[], []]
if name[loaded_config] begin... | keyword[def] identifier[load_domain_config] ( identifier[self] , identifier[loaded_config] ):
literal[string]
identifier[self] . identifier[domain_config] ={}
keyword[if] identifier[loaded_config] :
keyword[if] literal[string] keyword[in] identifier[loaded_config]... | def load_domain_config(self, loaded_config):
"""
Loads the domain_config and sets up queue_dict
@param loaded_config: the yaml loaded config dict from zookeeper
"""
self.domain_config = {}
# vetting process to ensure correct configs
if loaded_config:
if 'domains' in loade... |
def sphere_analytical_gaussian(dr, a, alpha=0.2765):
"""
Analytically calculate the sphere's functional form by convolving the
Heavyside function with first order approximation to the sinc, a Gaussian.
The alpha parameters controls the width of the approximation -- should be
1, but is fit to be roug... | def function[sphere_analytical_gaussian, parameter[dr, a, alpha]]:
constant[
Analytically calculate the sphere's functional form by convolving the
Heavyside function with first order approximation to the sinc, a Gaussian.
The alpha parameters controls the width of the approximation -- should be
... | keyword[def] identifier[sphere_analytical_gaussian] ( identifier[dr] , identifier[a] , identifier[alpha] = literal[int] ):
literal[string]
identifier[term1] = literal[int] *( identifier[erf] (( identifier[dr] + literal[int] * identifier[a] )/( identifier[alpha] * identifier[np] . identifier[sqrt] ( literal... | def sphere_analytical_gaussian(dr, a, alpha=0.2765):
"""
Analytically calculate the sphere's functional form by convolving the
Heavyside function with first order approximation to the sinc, a Gaussian.
The alpha parameters controls the width of the approximation -- should be
1, but is fit to be roug... |
def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None... | def function[get_assign_annotation, parameter[node]]:
constant[Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does no... | keyword[def] identifier[get_assign_annotation] ( identifier[node] ):
literal[string]
identifier[annotation] = keyword[None]
identifier[annotation_node] = keyword[None]
keyword[try] :
identifier[annotation_node] = identifier[node] . identifier[annotation]
keyword[except] identif... | def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None... |
def local_path(path):
"""
Return the absolute path relative to the root of this project
"""
current = os.path.dirname(__file__)
root = current
return os.path.abspath(os.path.join(root, path)) | def function[local_path, parameter[path]]:
constant[
Return the absolute path relative to the root of this project
]
variable[current] assign[=] call[name[os].path.dirname, parameter[name[__file__]]]
variable[root] assign[=] name[current]
return[call[name[os].path.abspath, parameter[... | keyword[def] identifier[local_path] ( identifier[path] ):
literal[string]
identifier[current] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] )
identifier[root] = identifier[current]
keyword[return] identifier[os] . identifier[path] . identifier[abspath] ( ident... | def local_path(path):
"""
Return the absolute path relative to the root of this project
"""
current = os.path.dirname(__file__)
root = current
return os.path.abspath(os.path.join(root, path)) |
def save(self, filename, metadata={}, **data):
"""
The implementation in the base class simply checks there is no
clash between the metadata and data keys.
"""
intersection = set(metadata.keys()) & set(data.keys())
if intersection:
msg = 'Key(s) overlap betwe... | def function[save, parameter[self, filename, metadata]]:
constant[
The implementation in the base class simply checks there is no
clash between the metadata and data keys.
]
variable[intersection] assign[=] binary_operation[call[name[set], parameter[call[name[metadata].keys, para... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] , identifier[metadata] ={},** identifier[data] ):
literal[string]
identifier[intersection] = identifier[set] ( identifier[metadata] . identifier[keys] ())& identifier[set] ( identifier[data] . identifier[keys] ())
keyw... | def save(self, filename, metadata={}, **data):
"""
The implementation in the base class simply checks there is no
clash between the metadata and data keys.
"""
intersection = set(metadata.keys()) & set(data.keys())
if intersection:
msg = 'Key(s) overlap between data and metad... |
def setDisabledBorderColor( self ):
"""
Returns the base color for this node.
:return <QColor>
"""
color = QColor(color)
if self._palette is None:
self._palette = XNodePalette(self._scenePalette)
self._palette.setColor(self._palet... | def function[setDisabledBorderColor, parameter[self]]:
constant[
Returns the base color for this node.
:return <QColor>
]
variable[color] assign[=] call[name[QColor], parameter[name[color]]]
if compare[name[self]._palette is constant[None]] begin[:]
... | keyword[def] identifier[setDisabledBorderColor] ( identifier[self] ):
literal[string]
identifier[color] = identifier[QColor] ( identifier[color] )
keyword[if] identifier[self] . identifier[_palette] keyword[is] keyword[None] :
identifier[self] . identifier[_palette] = ident... | def setDisabledBorderColor(self):
"""
Returns the base color for this node.
:return <QColor>
"""
color = QColor(color)
if self._palette is None:
self._palette = XNodePalette(self._scenePalette) # depends on [control=['if'], data=[]]
self._palette.setColor(se... |
def add_reshape(self, name, input_name, output_name, target_shape, mode):
"""
Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
target_shape: tuple
Shape of the output blo... | def function[add_reshape, parameter[self, name, input_name, output_name, target_shape, mode]]:
constant[
Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
target_shape: tuple
... | keyword[def] identifier[add_reshape] ( identifier[self] , identifier[name] , identifier[input_name] , identifier[output_name] , identifier[target_shape] , identifier[mode] ):
literal[string]
identifier[spec] = identifier[self] . identifier[spec]
identifier[nn_spec] = identifier[self] . i... | def add_reshape(self, name, input_name, output_name, target_shape, mode):
"""
Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
target_shape: tuple
Shape of the output blob. T... |
def run(
self,
program: Union[circuits.Circuit, schedules.Schedule],
param_resolver: 'study.ParamResolverOrSimilarType' = None,
repetitions: int = 1,
) -> study.TrialResult:
"""Samples from the given Circuit or Schedule.
Args:
program: The... | def function[run, parameter[self, program, param_resolver, repetitions]]:
constant[Samples from the given Circuit or Schedule.
Args:
program: The circuit or schedule to simulate.
param_resolver: Parameters to run with the program.
repetitions: The number of repetitio... | keyword[def] identifier[run] (
identifier[self] ,
identifier[program] : identifier[Union] [ identifier[circuits] . identifier[Circuit] , identifier[schedules] . identifier[Schedule] ],
identifier[param_resolver] : literal[string] = keyword[None] ,
identifier[repetitions] : identifier[int] = literal[int] ,
)-> ide... | def run(self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType'=None, repetitions: int=1) -> study.TrialResult:
"""Samples from the given Circuit or Schedule.
Args:
program: The circuit or schedule to simulate.
param_resolver: P... |
def get_xpath_frequencydistribution(paths):
""" Build and return a frequency distribution over xpath occurrences."""
# "html/body/div/div/text" -> [ "html", "body", "div", "div", "text" ]
splitpaths = [p.split('/') for p in paths]
# get list of "parentpaths" by right-stripping off the last xpath-n... | def function[get_xpath_frequencydistribution, parameter[paths]]:
constant[ Build and return a frequency distribution over xpath occurrences.]
variable[splitpaths] assign[=] <ast.ListComp object at 0x7da18fe93550>
variable[parentpaths] assign[=] <ast.ListComp object at 0x7da18fe93e80>
var... | keyword[def] identifier[get_xpath_frequencydistribution] ( identifier[paths] ):
literal[string]
identifier[splitpaths] =[ identifier[p] . identifier[split] ( literal[string] ) keyword[for] identifier[p] keyword[in] identifier[paths] ]
identifier[parentpaths] =[ literal[string... | def get_xpath_frequencydistribution(paths):
""" Build and return a frequency distribution over xpath occurrences.""" # "html/body/div/div/text" -> [ "html", "body", "div", "div", "text" ]
splitpaths = [p.split('/') for p in paths] # get list of "parentpaths" by right-stripping off the last xpath-node,
# e... |
def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order) | def function[_sort, parameter[self]]:
constant[sort sprites by z_order]
call[name[self].__dict__][constant[_z_ordered_sprites]] assign[=] call[name[sorted], parameter[name[self].sprites]] | keyword[def] identifier[_sort] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__dict__] [ literal[string] ]= identifier[sorted] ( identifier[self] . identifier[sprites] , identifier[key] = keyword[lambda] identifier[sprite] : identifier[sprite] . identifier[z_order] ) | def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite: sprite.z_order) |
def index(self, row, column=0, parent=QModelIndex()):
"""
Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
:return: ... | def function[index, parameter[self, row, column, parent]]:
constant[
Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
... | keyword[def] identifier[index] ( identifier[self] , identifier[row] , identifier[column] = literal[int] , identifier[parent] = identifier[QModelIndex] ()):
literal[string]
identifier[parent_node] = identifier[self] . identifier[get_node] ( identifier[parent] )
identifier[child] = identifi... | def index(self, row, column=0, parent=QModelIndex()):
"""
Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
:return: Inde... |
def _handle_universal(self, X):
"""
Scan through the corpus to compute counts of each Universal
Dependencies part-of-speech.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of... | def function[_handle_universal, parameter[self, X]]:
constant[
Scan through the corpus to compute counts of each Universal
Dependencies part-of-speech.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
... | keyword[def] identifier[_handle_universal] ( identifier[self] , identifier[X] ):
literal[string]
identifier[jump] ={
literal[string] : literal[string] , literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
... | def _handle_universal(self, X):
"""
Scan through the corpus to compute counts of each Universal
Dependencies part-of-speech.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of doc... |
def start(self):
"""
function to initialize thread for downloading
"""
global parallel
for self.i in range(0, self.length):
if parallel:
self.thread.append(myThread(self.url[ self.i ], self.directory, self.i,
self.min_file_size, self.max_file_size, self.no_redirects))
else:
# if not ... | def function[start, parameter[self]]:
constant[
function to initialize thread for downloading
]
<ast.Global object at 0x7da1b0f0d7b0>
for taget[name[self].i] in starred[call[name[range], parameter[constant[0], name[self].length]]] begin[:]
if name[parallel] begin[:]
... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
keyword[global] identifier[parallel]
keyword[for] identifier[self] . identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[self] . identifier[length] ):
keyword[if] identifier[parallel] :
identifier[self] .... | def start(self):
"""
function to initialize thread for downloading
"""
global parallel
for self.i in range(0, self.length):
if parallel:
self.thread.append(myThread(self.url[self.i], self.directory, self.i, self.min_file_size, self.max_file_size, self.no_redirects)) # depends on [co... |
def fqdn(self):
"""
Returns the string used to identify the client when initiating a SMTP
session.
RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do:
- Use the client FQDN ;
- If it isn't available, we SHOULD fall back to an address literal.
Returns:
... | def function[fqdn, parameter[self]]:
constant[
Returns the string used to identify the client when initiating a SMTP
session.
RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do:
- Use the client FQDN ;
- If it isn't available, we SHOULD fall back to an address lite... | keyword[def] identifier[fqdn] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_fqdn] keyword[is] keyword[None] :
identifier[self] . identifier[_fqdn] = identifier[socket] . identifier[getfqdn] ()
keyword[if] literal[string] ke... | def fqdn(self):
"""
Returns the string used to identify the client when initiating a SMTP
session.
RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do:
- Use the client FQDN ;
- If it isn't available, we SHOULD fall back to an address literal.
Returns:
... |
def pisaPreLoop(node, context, collect=False):
"""
Collect all CSS definitions
"""
data = u""
if node.nodeType == Node.TEXT_NODE and collect:
data = node.data
elif node.nodeType == Node.ELEMENT_NODE:
name = node.tagName.lower()
if name in ("style", "link"):
... | def function[pisaPreLoop, parameter[node, context, collect]]:
constant[
Collect all CSS definitions
]
variable[data] assign[=] constant[]
if <ast.BoolOp object at 0x7da1b12cbf10> begin[:]
variable[data] assign[=] name[node].data
for taget[name[node]] in starred[na... | keyword[def] identifier[pisaPreLoop] ( identifier[node] , identifier[context] , identifier[collect] = keyword[False] ):
literal[string]
identifier[data] = literal[string]
keyword[if] identifier[node] . identifier[nodeType] == identifier[Node] . identifier[TEXT_NODE] keyword[and] identifier[collec... | def pisaPreLoop(node, context, collect=False):
"""
Collect all CSS definitions
"""
data = u''
if node.nodeType == Node.TEXT_NODE and collect:
data = node.data # depends on [control=['if'], data=[]]
elif node.nodeType == Node.ELEMENT_NODE:
name = node.tagName.lower()
if n... |
def resolve(self):
'Resolve pathname shell variables and ~userdir'
return os.path.expandvars(os.path.expanduser(self.fqpn)) | def function[resolve, parameter[self]]:
constant[Resolve pathname shell variables and ~userdir]
return[call[name[os].path.expandvars, parameter[call[name[os].path.expanduser, parameter[name[self].fqpn]]]]] | keyword[def] identifier[resolve] ( identifier[self] ):
literal[string]
keyword[return] identifier[os] . identifier[path] . identifier[expandvars] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[self] . identifier[fqpn] )) | def resolve(self):
"""Resolve pathname shell variables and ~userdir"""
return os.path.expandvars(os.path.expanduser(self.fqpn)) |
def build_user_requested_parameters(request, meta):
"""Build the list of parameters requested by the plugit server"""
postParameters = {}
getParameters = {}
files = {}
# Add parameters requested by the server
if 'user_info' in meta:
for prop in meta['user_info']:
# Test if... | def function[build_user_requested_parameters, parameter[request, meta]]:
constant[Build the list of parameters requested by the plugit server]
variable[postParameters] assign[=] dictionary[[], []]
variable[getParameters] assign[=] dictionary[[], []]
variable[files] assign[=] dictionary[[... | keyword[def] identifier[build_user_requested_parameters] ( identifier[request] , identifier[meta] ):
literal[string]
identifier[postParameters] ={}
identifier[getParameters] ={}
identifier[files] ={}
keyword[if] literal[string] keyword[in] identifier[meta] :
keyword[for] ... | def build_user_requested_parameters(request, meta):
"""Build the list of parameters requested by the plugit server"""
postParameters = {}
getParameters = {}
files = {}
# Add parameters requested by the server
if 'user_info' in meta:
for prop in meta['user_info']:
# Test if th... |
def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,
notfound_ok=None, head_only=False):
"""
Get a bucket/key from the server
"""
# We could detect quorum_controls here but HTTP ignores
# unknown flags/params.
params = {'r': r, 'pr': pr, 'time... | def function[get, parameter[self, robj, r, pr, timeout, basic_quorum, notfound_ok, head_only]]:
constant[
Get a bucket/key from the server
]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da18f722b30>, <ast.Constant object at 0x7da18f723df0>, <ast.Constant object at 0x... | keyword[def] identifier[get] ( identifier[self] , identifier[robj] , identifier[r] = keyword[None] , identifier[pr] = keyword[None] , identifier[timeout] = keyword[None] , identifier[basic_quorum] = keyword[None] ,
identifier[notfound_ok] = keyword[None] , identifier[head_only] = keyword[False] ):
literal[s... | def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None, notfound_ok=None, head_only=False):
"""
Get a bucket/key from the server
"""
# We could detect quorum_controls here but HTTP ignores
# unknown flags/params.
params = {'r': r, 'pr': pr, 'timeout': timeout, 'basic_quorum... |
def changed_get(self, start_time, nick=None, page_size=200, page_no=1):
'''taobao.simba.creativeids.changed.get
===================================
获取修改的创意ID'''
request = TOPRequest('taobao.simba.creativeids.changed.get')
request['start_time'] = start_time
request['page_s... | def function[changed_get, parameter[self, start_time, nick, page_size, page_no]]:
constant[taobao.simba.creativeids.changed.get
===================================
获取修改的创意ID]
variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.simba.creativeids.changed.get]]]
... | keyword[def] identifier[changed_get] ( identifier[self] , identifier[start_time] , identifier[nick] = keyword[None] , identifier[page_size] = literal[int] , identifier[page_no] = literal[int] ):
literal[string]
identifier[request] = identifier[TOPRequest] ( literal[string] )
identifier[req... | def changed_get(self, start_time, nick=None, page_size=200, page_no=1):
"""taobao.simba.creativeids.changed.get
===================================
获取修改的创意ID"""
request = TOPRequest('taobao.simba.creativeids.changed.get')
request['start_time'] = start_time
request['page_size'] = page_siz... |
async def nextset(self):
"""Get the next query set"""
conn = self._get_db()
current_result = self._result
if current_result is None or current_result is not conn._result:
return
if not current_result.has_next:
return
self._result = None
sel... | <ast.AsyncFunctionDef object at 0x7da20c6a93f0> | keyword[async] keyword[def] identifier[nextset] ( identifier[self] ):
literal[string]
identifier[conn] = identifier[self] . identifier[_get_db] ()
identifier[current_result] = identifier[self] . identifier[_result]
keyword[if] identifier[current_result] keyword[is] keyword[No... | async def nextset(self):
"""Get the next query set"""
conn = self._get_db()
current_result = self._result
if current_result is None or current_result is not conn._result:
return # depends on [control=['if'], data=[]]
if not current_result.has_next:
return # depends on [control=['if... |
def _set_show_mpls_ldp_statistics(self, v, load=False):
"""
Setter method for show_mpls_ldp_statistics, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_statistics (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp_statistics is considered as a ... | def function[_set_show_mpls_ldp_statistics, parameter[self, v, load]]:
constant[
Setter method for show_mpls_ldp_statistics, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_statistics (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp_stati... | keyword[def] identifier[_set_show_mpls_ldp_statistics] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try... | def _set_show_mpls_ldp_statistics(self, v, load=False):
"""
Setter method for show_mpls_ldp_statistics, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_statistics (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp_statistics is considered as a ... |
def _update_representative(self, index_cluster, point):
"""!
@brief Update cluster representative in line with new cluster size and added point to it.
@param[in] index_cluster (uint): Index of cluster whose representative should be updated.
@param[in] point (list): Point that was added ... | def function[_update_representative, parameter[self, index_cluster, point]]:
constant[!
@brief Update cluster representative in line with new cluster size and added point to it.
@param[in] index_cluster (uint): Index of cluster whose representative should be updated.
@param[in] point (l... | keyword[def] identifier[_update_representative] ( identifier[self] , identifier[index_cluster] , identifier[point] ):
literal[string]
identifier[length] = identifier[len] ( identifier[self] . identifier[_clusters] [ identifier[index_cluster] ]);
identifier[rep] = identifier[self] . identif... | def _update_representative(self, index_cluster, point):
"""!
@brief Update cluster representative in line with new cluster size and added point to it.
@param[in] index_cluster (uint): Index of cluster whose representative should be updated.
@param[in] point (list): Point that was added to c... |
def get_cn_dict(self, structure, n, use_weights=False):
"""
Get coordination number, CN, of each element bonded to site with index n in structure
Args:
structure (Structure): input structure
n (integer): index of site for which to determine CN.
use_weights (b... | def function[get_cn_dict, parameter[self, structure, n, use_weights]]:
constant[
Get coordination number, CN, of each element bonded to site with index n in structure
Args:
structure (Structure): input structure
n (integer): index of site for which to determine CN.
... | keyword[def] identifier[get_cn_dict] ( identifier[self] , identifier[structure] , identifier[n] , identifier[use_weights] = keyword[False] ):
literal[string]
identifier[siw] = identifier[self] . identifier[get_nn_info] ( identifier[structure] , identifier[n] )
identifier[cn_dict] ={}
... | def get_cn_dict(self, structure, n, use_weights=False):
"""
Get coordination number, CN, of each element bonded to site with index n in structure
Args:
structure (Structure): input structure
n (integer): index of site for which to determine CN.
use_weights (boole... |
def parse_args(self, args=None, namespace=None):
"""
Reparses new arguments when _DemoAction (triggering parser.demo_args())
or _WizardAction (triggering input_args()) was called.
"""
if not namespace: # use the new Namespace class for handling _config
namespace = N... | def function[parse_args, parameter[self, args, namespace]]:
constant[
Reparses new arguments when _DemoAction (triggering parser.demo_args())
or _WizardAction (triggering input_args()) was called.
]
if <ast.UnaryOp object at 0x7da1b19b54e0> begin[:]
variable[name... | keyword[def] identifier[parse_args] ( identifier[self] , identifier[args] = keyword[None] , identifier[namespace] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[namespace] :
identifier[namespace] = identifier[Namespace] ( identifier[self] )
identifier... | def parse_args(self, args=None, namespace=None):
"""
Reparses new arguments when _DemoAction (triggering parser.demo_args())
or _WizardAction (triggering input_args()) was called.
"""
if not namespace: # use the new Namespace class for handling _config
namespace = Namespace(sel... |
def step(self, step, total, label='STEP', speed_label='STEPS/S', size=1):
"""
Increase the step indicator, which is a sub progress circle of the actual
main progress circle (epoch, progress() method).
"""
self.lock.acquire()
try:
time_diff = time.time() - sel... | def function[step, parameter[self, step, total, label, speed_label, size]]:
constant[
Increase the step indicator, which is a sub progress circle of the actual
main progress circle (epoch, progress() method).
]
call[name[self].lock.acquire, parameter[]]
<ast.Try object at 0x7... | keyword[def] identifier[step] ( identifier[self] , identifier[step] , identifier[total] , identifier[label] = literal[string] , identifier[speed_label] = literal[string] , identifier[size] = literal[int] ):
literal[string]
identifier[self] . identifier[lock] . identifier[acquire] ()
keywo... | def step(self, step, total, label='STEP', speed_label='STEPS/S', size=1):
"""
Increase the step indicator, which is a sub progress circle of the actual
main progress circle (epoch, progress() method).
"""
self.lock.acquire()
try:
time_diff = time.time() - self.last_step_time
... |
def default_grid(n_items, max_cols=4, min_cols=3): # noqa: D202
"""Make a grid for subplots.
Tries to get as close to sqrt(n_items) x sqrt(n_items) as it can,
but allows for custom logic
Parameters
----------
n_items : int
Number of panels required
max_cols : int
Maximum n... | def function[default_grid, parameter[n_items, max_cols, min_cols]]:
constant[Make a grid for subplots.
Tries to get as close to sqrt(n_items) x sqrt(n_items) as it can,
but allows for custom logic
Parameters
----------
n_items : int
Number of panels required
max_cols : int
... | keyword[def] identifier[default_grid] ( identifier[n_items] , identifier[max_cols] = literal[int] , identifier[min_cols] = literal[int] ):
literal[string]
keyword[def] identifier[in_bounds] ( identifier[val] ):
keyword[return] identifier[np] . identifier[clip] ( identifier[val] , identifier[min... | def default_grid(n_items, max_cols=4, min_cols=3): # noqa: D202
'Make a grid for subplots.\n\n Tries to get as close to sqrt(n_items) x sqrt(n_items) as it can,\n but allows for custom logic\n\n Parameters\n ----------\n n_items : int\n Number of panels required\n max_cols : int\n M... |
def sampleLocationFromFeature(self, feature):
"""
Samples a location from one specific feature.
This is only supported with three dimensions.
"""
if feature == "face":
return self._sampleFromFaces()
elif feature == "edge":
return self._sampleFromEdges()
elif feature == "vertex":... | def function[sampleLocationFromFeature, parameter[self, feature]]:
constant[
Samples a location from one specific feature.
This is only supported with three dimensions.
]
if compare[name[feature] equal[==] constant[face]] begin[:]
return[call[name[self]._sampleFromFaces, parameter[]... | keyword[def] identifier[sampleLocationFromFeature] ( identifier[self] , identifier[feature] ):
literal[string]
keyword[if] identifier[feature] == literal[string] :
keyword[return] identifier[self] . identifier[_sampleFromFaces] ()
keyword[elif] identifier[feature] == literal[string] :
... | def sampleLocationFromFeature(self, feature):
"""
Samples a location from one specific feature.
This is only supported with three dimensions.
"""
if feature == 'face':
return self._sampleFromFaces() # depends on [control=['if'], data=[]]
elif feature == 'edge':
return self._sam... |
def import_patches(self, patches):
""" Import several patches into the patch queue """
dest_dir = self.quilt_patches
patch_names = []
for patch in patches:
patch_name = os.path.basename(patch)
patch_file = File(patch)
dest_file = dest_dir + File(patc... | def function[import_patches, parameter[self, patches]]:
constant[ Import several patches into the patch queue ]
variable[dest_dir] assign[=] name[self].quilt_patches
variable[patch_names] assign[=] list[[]]
for taget[name[patch]] in starred[name[patches]] begin[:]
variabl... | keyword[def] identifier[import_patches] ( identifier[self] , identifier[patches] ):
literal[string]
identifier[dest_dir] = identifier[self] . identifier[quilt_patches]
identifier[patch_names] =[]
keyword[for] identifier[patch] keyword[in] identifier[patches] :
i... | def import_patches(self, patches):
""" Import several patches into the patch queue """
dest_dir = self.quilt_patches
patch_names = []
for patch in patches:
patch_name = os.path.basename(patch)
patch_file = File(patch)
dest_file = dest_dir + File(patch_name)
patch_file.cop... |
def _run(self, line):
''' everything from RUN goes into the install list
Parameters
==========
line: the line from the recipe file to parse for FROM
'''
line = self._setup('RUN', line)
self.install += line | def function[_run, parameter[self, line]]:
constant[ everything from RUN goes into the install list
Parameters
==========
line: the line from the recipe file to parse for FROM
]
variable[line] assign[=] call[name[self]._setup, parameter[constant[RUN], name[line... | keyword[def] identifier[_run] ( identifier[self] , identifier[line] ):
literal[string]
identifier[line] = identifier[self] . identifier[_setup] ( literal[string] , identifier[line] )
identifier[self] . identifier[install] += identifier[line] | def _run(self, line):
""" everything from RUN goes into the install list
Parameters
==========
line: the line from the recipe file to parse for FROM
"""
line = self._setup('RUN', line)
self.install += line |
def from_yaml(cls, yaml_str=None, str_or_buffer=None):
"""
Create a DiscreteChoiceModel instance from a saved YAML configuration.
Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
s... | def function[from_yaml, parameter[cls, yaml_str, str_or_buffer]]:
constant[
Create a DiscreteChoiceModel instance from a saved YAML configuration.
Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load... | keyword[def] identifier[from_yaml] ( identifier[cls] , identifier[yaml_str] = keyword[None] , identifier[str_or_buffer] = keyword[None] ):
literal[string]
identifier[cfg] = identifier[yamlio] . identifier[yaml_to_dict] ( identifier[yaml_str] , identifier[str_or_buffer] )
identifier[model]... | def from_yaml(cls, yaml_str=None, str_or_buffer=None):
"""
Create a DiscreteChoiceModel instance from a saved YAML configuration.
Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
str_o... |
def check_rev_options(self, rev, dest, rev_options):
"""Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found.
"""
revisions = self.get_refs(dest)
origin_rev = 'origin/... | def function[check_rev_options, parameter[self, rev, dest, rev_options]]:
constant[Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found.
]
variable[revisions] assign[=] call[na... | keyword[def] identifier[check_rev_options] ( identifier[self] , identifier[rev] , identifier[dest] , identifier[rev_options] ):
literal[string]
identifier[revisions] = identifier[self] . identifier[get_refs] ( identifier[dest] )
identifier[origin_rev] = literal[string] % identifier[rev]
... | def check_rev_options(self, rev, dest, rev_options):
"""Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found.
"""
revisions = self.get_refs(dest)
origin_rev = 'origin/%s' % rev
... |
def add_keyword(self, keyword, schema=None, source=None):
"""Add a keyword.
Args:
keyword(str): keyword to add.
schema(str): schema to which the keyword belongs.
source(str): source for the keyword.
"""
keyword_dict = self._sourced_dict(source, value=... | def function[add_keyword, parameter[self, keyword, schema, source]]:
constant[Add a keyword.
Args:
keyword(str): keyword to add.
schema(str): schema to which the keyword belongs.
source(str): source for the keyword.
]
variable[keyword_dict] assign[=] ... | keyword[def] identifier[add_keyword] ( identifier[self] , identifier[keyword] , identifier[schema] = keyword[None] , identifier[source] = keyword[None] ):
literal[string]
identifier[keyword_dict] = identifier[self] . identifier[_sourced_dict] ( identifier[source] , identifier[value] = identifier[ke... | def add_keyword(self, keyword, schema=None, source=None):
"""Add a keyword.
Args:
keyword(str): keyword to add.
schema(str): schema to which the keyword belongs.
source(str): source for the keyword.
"""
keyword_dict = self._sourced_dict(source, value=keyword)... |
def _remove_exact(self, needle, keep_field):
"""Remove a specific parameter, *needle*, from the template."""
for i, param in enumerate(self.params):
if param is needle:
if keep_field:
self._blank_param_value(param.value)
else:
... | def function[_remove_exact, parameter[self, needle, keep_field]]:
constant[Remove a specific parameter, *needle*, from the template.]
for taget[tuple[[<ast.Name object at 0x7da20c990430>, <ast.Name object at 0x7da20c990670>]]] in starred[call[name[enumerate], parameter[name[self].params]]] begin[:]
... | keyword[def] identifier[_remove_exact] ( identifier[self] , identifier[needle] , identifier[keep_field] ):
literal[string]
keyword[for] identifier[i] , identifier[param] keyword[in] identifier[enumerate] ( identifier[self] . identifier[params] ):
keyword[if] identifier[param] keyw... | def _remove_exact(self, needle, keep_field):
"""Remove a specific parameter, *needle*, from the template."""
for (i, param) in enumerate(self.params):
if param is needle:
if keep_field:
self._blank_param_value(param.value) # depends on [control=['if'], data=[]]
e... |
def _republish_displaypub(self, content, eid):
"""republish individual displaypub content dicts"""
try:
ip = get_ipython()
except NameError:
# displaypub is meaningless outside IPython
return
md = content['metadata'] or {}
md['engine'] = eid
... | def function[_republish_displaypub, parameter[self, content, eid]]:
constant[republish individual displaypub content dicts]
<ast.Try object at 0x7da1b2345de0>
variable[md] assign[=] <ast.BoolOp object at 0x7da1b2345360>
call[name[md]][constant[engine]] assign[=] name[eid]
call[name[i... | keyword[def] identifier[_republish_displaypub] ( identifier[self] , identifier[content] , identifier[eid] ):
literal[string]
keyword[try] :
identifier[ip] = identifier[get_ipython] ()
keyword[except] identifier[NameError] :
keyword[return]
iden... | def _republish_displaypub(self, content, eid):
"""republish individual displaypub content dicts"""
try:
ip = get_ipython() # depends on [control=['try'], data=[]]
except NameError:
# displaypub is meaningless outside IPython
return # depends on [control=['except'], data=[]]
md ... |
def eoq(I,F,h,d,w,W,a0,aK,K):
"""eoq -- multi-item capacitated economic ordering quantity model
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit weight for item i
- W: capacity (... | def function[eoq, parameter[I, F, h, d, w, W, a0, aK, K]]:
constant[eoq -- multi-item capacitated economic ordering quantity model
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit we... | keyword[def] identifier[eoq] ( identifier[I] , identifier[F] , identifier[h] , identifier[d] , identifier[w] , identifier[W] , identifier[a0] , identifier[aK] , identifier[K] ):
literal[string]
identifier[a] , identifier[b] ={},{}
identifier[delta] = identifier[float] ( identifier[aK] - identifi... | def eoq(I, F, h, d, w, W, a0, aK, K):
"""eoq -- multi-item capacitated economic ordering quantity model
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit weight for item i
- W: ca... |
def serialize(func):
"""
Falcon response serialization
"""
def wrapped(instance, req, resp, **kwargs):
assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed"
resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate");
r... | def function[serialize, parameter[func]]:
constant[
Falcon response serialization
]
def function[wrapped, parameter[instance, req, resp]]:
assert[<ast.BoolOp object at 0x7da1b0a6d720>]
call[name[resp].set_header, parameter[constant[Cache-Control], constant[no-cache, no-st... | keyword[def] identifier[serialize] ( identifier[func] ):
literal[string]
keyword[def] identifier[wrapped] ( identifier[instance] , identifier[req] , identifier[resp] ,** identifier[kwargs] ):
keyword[assert] keyword[not] identifier[req] . identifier[get_param] ( literal[string] ) keyword[or] i... | def serialize(func):
"""
Falcon response serialization
"""
def wrapped(instance, req, resp, **kwargs):
assert not req.get_param('unicode') or req.get_param('unicode') == u'✓', 'Unicode sanity check failed'
resp.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
r... |
def list(self, id=None):
"""
List all running jobs
:param id: optional ID for the job to list
"""
args = {'id': id}
self._job_chk.check(args)
return self._client.json('job.list', args) | def function[list, parameter[self, id]]:
constant[
List all running jobs
:param id: optional ID for the job to list
]
variable[args] assign[=] dictionary[[<ast.Constant object at 0x7da1b04dae90>], [<ast.Name object at 0x7da1b04d9420>]]
call[name[self]._job_chk.check, par... | keyword[def] identifier[list] ( identifier[self] , identifier[id] = keyword[None] ):
literal[string]
identifier[args] ={ literal[string] : identifier[id] }
identifier[self] . identifier[_job_chk] . identifier[check] ( identifier[args] )
keyword[return] identifier[self] . identifi... | def list(self, id=None):
"""
List all running jobs
:param id: optional ID for the job to list
"""
args = {'id': id}
self._job_chk.check(args)
return self._client.json('job.list', args) |
def valid_remainder(cntxt: Context, n: Node, matchables: RDFGraph, S: ShExJ.Shape) -> bool:
"""
Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`.
Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If
`expression` is absen... | def function[valid_remainder, parameter[cntxt, n, matchables, S]]:
constant[
Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`.
Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If
`expression` is absent, matchables =... | keyword[def] identifier[valid_remainder] ( identifier[cntxt] : identifier[Context] , identifier[n] : identifier[Node] , identifier[matchables] : identifier[RDFGraph] , identifier[S] : identifier[ShExJ] . identifier[Shape] )-> identifier[bool] :
literal[string]
identifier[outs] = identifier[arcsOu... | def valid_remainder(cntxt: Context, n: Node, matchables: RDFGraph, S: ShExJ.Shape) -> bool:
"""
Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`.
Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If
`expression` is absen... |
def iptag_clear(self, iptag, x, y):
"""Clear an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to clear.
"""
self._send_scp(x, y, 0, SCPCommands.iptag,
int(consts.IPTagCommands.clear) << 16 | iptag) | def function[iptag_clear, parameter[self, iptag, x, y]]:
constant[Clear an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to clear.
]
call[name[self]._send_scp, parameter[name[x], name[y], constant[0], name[SCPCommands].iptag, binary_operation[bi... | keyword[def] identifier[iptag_clear] ( identifier[self] , identifier[iptag] , identifier[x] , identifier[y] ):
literal[string]
identifier[self] . identifier[_send_scp] ( identifier[x] , identifier[y] , literal[int] , identifier[SCPCommands] . identifier[iptag] ,
identifier[int] ( identifie... | def iptag_clear(self, iptag, x, y):
"""Clear an IPTag.
Parameters
----------
iptag : int
Index of the IPTag to clear.
"""
self._send_scp(x, y, 0, SCPCommands.iptag, int(consts.IPTagCommands.clear) << 16 | iptag) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.