code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def format_servers(servers):
"""
:param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','por... | def function[format_servers, parameter[servers]]:
constant[
:param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':... | keyword[def] identifier[format_servers] ( identifier[servers] ):
literal[string]
identifier[configs] =[]
keyword[if] keyword[not] identifier[isinstance] ( identifier[servers] , identifier[list] ):
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[_type] = identifier... | def format_servers(servers):
"""
:param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','por... |
def get_video_transcript_data(video_id, language_code):
"""
Get video transcript data
Arguments:
video_id(unicode): An id identifying the Video.
language_code(unicode): it will be the language code of the requested transcript.
Returns:
A dict containing transcript file name and... | def function[get_video_transcript_data, parameter[video_id, language_code]]:
constant[
Get video transcript data
Arguments:
video_id(unicode): An id identifying the Video.
language_code(unicode): it will be the language code of the requested transcript.
Returns:
A dict cont... | keyword[def] identifier[get_video_transcript_data] ( identifier[video_id] , identifier[language_code] ):
literal[string]
identifier[video_transcript] = identifier[VideoTranscript] . identifier[get_or_none] ( identifier[video_id] , identifier[language_code] )
keyword[if] identifier[video_transcript] :... | def get_video_transcript_data(video_id, language_code):
"""
Get video transcript data
Arguments:
video_id(unicode): An id identifying the Video.
language_code(unicode): it will be the language code of the requested transcript.
Returns:
A dict containing transcript file name and... |
def is_valid_ip(self, ip):
"""Return true if the given address in amongst the usable addresses,
or if the given CIDR is contained in this one."""
if not isinstance(ip, (IPv4Address, CIDR)):
if str(ip).find('/') == -1:
ip = IPv4Address(ip)
else:
... | def function[is_valid_ip, parameter[self, ip]]:
constant[Return true if the given address in amongst the usable addresses,
or if the given CIDR is contained in this one.]
if <ast.UnaryOp object at 0x7da2047e9f60> begin[:]
if compare[call[call[name[str], parameter[name[ip]]].find,... | keyword[def] identifier[is_valid_ip] ( identifier[self] , identifier[ip] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[ip] ,( identifier[IPv4Address] , identifier[CIDR] )):
keyword[if] identifier[str] ( identifier[ip] ). identifier[find] ( literal[s... | def is_valid_ip(self, ip):
"""Return true if the given address in amongst the usable addresses,
or if the given CIDR is contained in this one."""
if not isinstance(ip, (IPv4Address, CIDR)):
if str(ip).find('/') == -1:
ip = IPv4Address(ip) # depends on [control=['if'], data=[]]
... |
def get_avatar(self):
"""Gets the asset.
return: (osid.repository.Asset) - the asset
raise: IllegalState - ``has_avatar()`` is ``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Imple... | def function[get_avatar, parameter[self]]:
constant[Gets the asset.
return: (osid.repository.Asset) - the asset
raise: IllegalState - ``has_avatar()`` is ``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
... | keyword[def] identifier[get_avatar] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[bool] ( identifier[self] . identifier[_my_map] [ literal[string] ]):
keyword[raise] identifier[errors] . identifier[IllegalState] ( literal[string] )
ident... | def get_avatar(self):
"""Gets the asset.
return: (osid.repository.Asset) - the asset
raise: IllegalState - ``has_avatar()`` is ``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented f... |
def range_to_numeric(ranges):
"""Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0]
"""
values, units = zip(*(r.split() for r in ranges))
# Detect common unit.
unit = os.path.commonprefix([u[::-... | def function[range_to_numeric, parameter[ranges]]:
constant[Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0]
]
<ast.Tuple object at 0x7da1b0b12d40> assign[=] call[name[zip], parameter[<ast.Sta... | keyword[def] identifier[range_to_numeric] ( identifier[ranges] ):
literal[string]
identifier[values] , identifier[units] = identifier[zip] (*( identifier[r] . identifier[split] () keyword[for] identifier[r] keyword[in] identifier[ranges] ))
identifier[unit] = identifier[os] . identifier[path] ... | def range_to_numeric(ranges):
"""Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0]
"""
(values, units) = zip(*(r.split() for r in ranges))
# Detect common unit.
unit = os.path.commonprefix([u[:... |
def make_template_name(self, model_type, sourcekey):
""" Make the name of a template file for particular component
Parameters
----------
model_type : str
Type of model to use for this component
sourcekey : str
Key to identify this component
Retu... | def function[make_template_name, parameter[self, model_type, sourcekey]]:
constant[ Make the name of a template file for particular component
Parameters
----------
model_type : str
Type of model to use for this component
sourcekey : str
Key to identify t... | keyword[def] identifier[make_template_name] ( identifier[self] , identifier[model_type] , identifier[sourcekey] ):
literal[string]
identifier[format_dict] = identifier[self] . identifier[__dict__] . identifier[copy] ()
identifier[format_dict] [ literal[string] ]= identifier[sourcekey]
... | def make_template_name(self, model_type, sourcekey):
""" Make the name of a template file for particular component
Parameters
----------
model_type : str
Type of model to use for this component
sourcekey : str
Key to identify this component
Returns ... |
def authority(self, column=None, value=None, **kwargs):
"""Provides codes and associated authorizing statutes."""
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs) | def function[authority, parameter[self, column, value]]:
constant[Provides codes and associated authorizing statutes.]
return[call[name[self]._resolve_call, parameter[constant[GIC_AUTHORITY], name[column], name[value]]]] | keyword[def] identifier[authority] ( identifier[self] , identifier[column] = keyword[None] , identifier[value] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_resolve_call] ( literal[string] , identifier[column] , identifier[value] ,** ident... | def authority(self, column=None, value=None, **kwargs):
"""Provides codes and associated authorizing statutes."""
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs) |
def refetch(self):
'''Reload children.'''
# Reset children
for child in self.children[:]:
self.removeChild(child)
# Enable children fetching
self._fetched = False | def function[refetch, parameter[self]]:
constant[Reload children.]
for taget[name[child]] in starred[call[name[self].children][<ast.Slice object at 0x7da1b03ba020>]] begin[:]
call[name[self].removeChild, parameter[name[child]]]
name[self]._fetched assign[=] constant[False] | keyword[def] identifier[refetch] ( identifier[self] ):
literal[string]
keyword[for] identifier[child] keyword[in] identifier[self] . identifier[children] [:]:
identifier[self] . identifier[removeChild] ( identifier[child] )
identifier[self] . identifi... | def refetch(self):
"""Reload children."""
# Reset children
for child in self.children[:]:
self.removeChild(child) # depends on [control=['for'], data=['child']]
# Enable children fetching
self._fetched = False |
def set_wait(self, wait):
"""
set the waiting time.
:Parameters:
#. wait (number): The time delay between each attempt to lock. By default it's
set to 0 to keeping the aquiring mechanism trying to acquire the lock without
losing any time waiting. Settin... | def function[set_wait, parameter[self, wait]]:
constant[
set the waiting time.
:Parameters:
#. wait (number): The time delay between each attempt to lock. By default it's
set to 0 to keeping the aquiring mechanism trying to acquire the lock without
losi... | keyword[def] identifier[set_wait] ( identifier[self] , identifier[wait] ):
literal[string]
keyword[try] :
identifier[wait] = identifier[float] ( identifier[wait] )
keyword[assert] identifier[wait] >= literal[int]
keyword[except] :
keyword[raise] id... | def set_wait(self, wait):
"""
set the waiting time.
:Parameters:
#. wait (number): The time delay between each attempt to lock. By default it's
set to 0 to keeping the aquiring mechanism trying to acquire the lock without
losing any time waiting. Setting wa... |
def woven(fun):
'''Decorator that will initialize and eventually start nested fibers.'''
def wrapper(*args, **kwargs):
section = WovenSection()
section.enter()
result = fun(*args, **kwargs)
return section.exit(result)
return wrapper | def function[woven, parameter[fun]]:
constant[Decorator that will initialize and eventually start nested fibers.]
def function[wrapper, parameter[]]:
variable[section] assign[=] call[name[WovenSection], parameter[]]
call[name[section].enter, parameter[]]
v... | keyword[def] identifier[woven] ( identifier[fun] ):
literal[string]
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[section] = identifier[WovenSection] ()
identifier[section] . identifier[enter] ()
identifier[result] = identifier[fun] (... | def woven(fun):
"""Decorator that will initialize and eventually start nested fibers."""
def wrapper(*args, **kwargs):
section = WovenSection()
section.enter()
result = fun(*args, **kwargs)
return section.exit(result)
return wrapper |
def as_dictionary(self):
"""Return the key as a python dictionary."""
values = {
'id': self._id,
'type': self._type
}
if self._owner:
values['owner'] = self._owner
return values | def function[as_dictionary, parameter[self]]:
constant[Return the key as a python dictionary.]
variable[values] assign[=] dictionary[[<ast.Constant object at 0x7da18bccbb80>, <ast.Constant object at 0x7da18bcc99f0>], [<ast.Attribute object at 0x7da18bcc9510>, <ast.Attribute object at 0x7da18bcc8190>]]
... | keyword[def] identifier[as_dictionary] ( identifier[self] ):
literal[string]
identifier[values] ={
literal[string] : identifier[self] . identifier[_id] ,
literal[string] : identifier[self] . identifier[_type]
}
keyword[if] identifier[self] . identifier[_owner] ... | def as_dictionary(self):
"""Return the key as a python dictionary."""
values = {'id': self._id, 'type': self._type}
if self._owner:
values['owner'] = self._owner # depends on [control=['if'], data=[]]
return values |
def table_present(name, db, schema, force=False):
'''
Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
If the name of the ta... | def function[table_present, parameter[name, db, schema, force]]:
constant[
Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
... | keyword[def] identifier[table_present] ( identifier[name] , identifier[db] , identifier[schema] , identifier[force] = keyword[False] ):
literal[string]
identifier[changes] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : keyword[None] ,
literal[string] : literal... | def table_present(name, db, schema, force=False):
"""
Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
If the name of the ta... |
def start_child_span(operation_name, tracer=None, parent=None, tags=None):
"""
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Sp... | def function[start_child_span, parameter[operation_name, tracer, parent, tags]]:
constant[
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param p... | keyword[def] identifier[start_child_span] ( identifier[operation_name] , identifier[tracer] = keyword[None] , identifier[parent] = keyword[None] , identifier[tags] = keyword[None] ):
literal[string]
identifier[tracer] = identifier[tracer] keyword[or] identifier[opentracing] . identifier[tracer]
key... | def start_child_span(operation_name, tracer=None, parent=None, tags=None):
"""
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Sp... |
async def jsk_vc_volume(self, ctx: commands.Context, *, percentage: float):
"""
Adjusts the volume of an audio source if it is supported.
"""
volume = max(0.0, min(1.0, percentage / 100))
source = ctx.guild.voice_client.source
if not isinstance(source, discord.PCMVolum... | <ast.AsyncFunctionDef object at 0x7da1b1edafe0> | keyword[async] keyword[def] identifier[jsk_vc_volume] ( identifier[self] , identifier[ctx] : identifier[commands] . identifier[Context] ,*, identifier[percentage] : identifier[float] ):
literal[string]
identifier[volume] = identifier[max] ( literal[int] , identifier[min] ( literal[int] , identifi... | async def jsk_vc_volume(self, ctx: commands.Context, *, percentage: float):
"""
Adjusts the volume of an audio source if it is supported.
"""
volume = max(0.0, min(1.0, percentage / 100))
source = ctx.guild.voice_client.source
if not isinstance(source, discord.PCMVolumeTransformer):
... |
def start(self):
"""
This function determines node and NAT type, saves connectivity details,
and starts any needed servers to be a part of the network. This is
usually the first function called after initialising the Net class.
"""
self.debug_print("Starting netwo... | def function[start, parameter[self]]:
constant[
This function determines node and NAT type, saves connectivity details,
and starts any needed servers to be a part of the network. This is
usually the first function called after initialising the Net class.
]
call[name[self]... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[self] . identifier[debug_print] ( literal[string] )
identifier[self] . identifier[debug_print] ( literal[string]
literal[string] )
identifier[signal] . identifier[signal] (... | def start(self):
"""
This function determines node and NAT type, saves connectivity details,
and starts any needed servers to be a part of the network. This is
usually the first function called after initialising the Net class.
"""
self.debug_print('Starting networking.')
sel... |
def dhcp_options_present(name, dhcp_options_id=None, vpc_name=None, vpc_id=None,
domain_name=None, domain_name_servers=None, ntp_servers=None,
netbios_name_servers=None, netbios_node_type=None,
tags=None, region=None, key=None, keyid=None, profi... | def function[dhcp_options_present, parameter[name, dhcp_options_id, vpc_name, vpc_id, domain_name, domain_name_servers, ntp_servers, netbios_name_servers, netbios_node_type, tags, region, key, keyid, profile]]:
constant[
Ensure a set of DHCP options with the given settings exist.
Note that the current i... | keyword[def] identifier[dhcp_options_present] ( identifier[name] , identifier[dhcp_options_id] = keyword[None] , identifier[vpc_name] = keyword[None] , identifier[vpc_id] = keyword[None] ,
identifier[domain_name] = keyword[None] , identifier[domain_name_servers] = keyword[None] , identifier[ntp_servers] = keyword[No... | def dhcp_options_present(name, dhcp_options_id=None, vpc_name=None, vpc_id=None, domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, tags=None, region=None, key=None, keyid=None, profile=None):
"""
Ensure a set of DHCP options with the given settings ... |
def _save_history_to_file(history, path, size=-1):
"""Save a history list to a file for later loading (possibly in another
session).
:param history: the history list to save
:type history: list(str)
:param path: the path to the file where to save the history
:param size:... | def function[_save_history_to_file, parameter[history, path, size]]:
constant[Save a history list to a file for later loading (possibly in another
session).
:param history: the history list to save
:type history: list(str)
:param path: the path to the file where to save the hist... | keyword[def] identifier[_save_history_to_file] ( identifier[history] , identifier[path] , identifier[size] =- literal[int] ):
literal[string]
keyword[if] identifier[size] == literal[int] :
keyword[return]
keyword[if] identifier[size] > literal[int] :
identifier... | def _save_history_to_file(history, path, size=-1):
"""Save a history list to a file for later loading (possibly in another
session).
:param history: the history list to save
:type history: list(str)
:param path: the path to the file where to save the history
:param size: the... |
def _renumber(a: np.ndarray, keys: np.ndarray, values: np.ndarray) -> np.ndarray:
"""
Renumber 'a' by replacing any occurrence of 'keys' by the corresponding 'values'
"""
ordering = np.argsort(keys)
keys = keys[ordering]
values = keys[ordering]
index = np.digitize(a.ravel(), keys, right=True)
return(values[inde... | def function[_renumber, parameter[a, keys, values]]:
constant[
Renumber 'a' by replacing any occurrence of 'keys' by the corresponding 'values'
]
variable[ordering] assign[=] call[name[np].argsort, parameter[name[keys]]]
variable[keys] assign[=] call[name[keys]][name[ordering]]
variabl... | keyword[def] identifier[_renumber] ( identifier[a] : identifier[np] . identifier[ndarray] , identifier[keys] : identifier[np] . identifier[ndarray] , identifier[values] : identifier[np] . identifier[ndarray] )-> identifier[np] . identifier[ndarray] :
literal[string]
identifier[ordering] = identifier[np] . identi... | def _renumber(a: np.ndarray, keys: np.ndarray, values: np.ndarray) -> np.ndarray:
"""
Renumber 'a' by replacing any occurrence of 'keys' by the corresponding 'values'
"""
ordering = np.argsort(keys)
keys = keys[ordering]
values = keys[ordering]
index = np.digitize(a.ravel(), keys, right=True)
... |
def parse_selection(lexer: Lexer) -> SelectionNode:
"""Selection: Field or FragmentSpread or InlineFragment"""
return (parse_fragment if peek(lexer, TokenKind.SPREAD) else parse_field)(lexer) | def function[parse_selection, parameter[lexer]]:
constant[Selection: Field or FragmentSpread or InlineFragment]
return[call[<ast.IfExp object at 0x7da1b22e84f0>, parameter[name[lexer]]]] | keyword[def] identifier[parse_selection] ( identifier[lexer] : identifier[Lexer] )-> identifier[SelectionNode] :
literal[string]
keyword[return] ( identifier[parse_fragment] keyword[if] identifier[peek] ( identifier[lexer] , identifier[TokenKind] . identifier[SPREAD] ) keyword[else] identifier[parse_fie... | def parse_selection(lexer: Lexer) -> SelectionNode:
"""Selection: Field or FragmentSpread or InlineFragment"""
return (parse_fragment if peek(lexer, TokenKind.SPREAD) else parse_field)(lexer) |
def add_input(self, **kwargs):
"""Add workflow input.
Args:
kwargs (dict): A dict with a `name: type` item
and optionally a `default: value` item, where name is the
name (id) of the workflow input (e.g., `dir_in`) and type is
the type of the i... | def function[add_input, parameter[self]]:
constant[Add workflow input.
Args:
kwargs (dict): A dict with a `name: type` item
and optionally a `default: value` item, where name is the
name (id) of the workflow input (e.g., `dir_in`) and type is
... | keyword[def] identifier[add_input] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_closed] ()
keyword[def] identifier[_get_item] ( identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[args] :
... | def add_input(self, **kwargs):
"""Add workflow input.
Args:
kwargs (dict): A dict with a `name: type` item
and optionally a `default: value` item, where name is the
name (id) of the workflow input (e.g., `dir_in`) and type is
the type of the input... |
def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(
index=index_name,
doc_type=doc_type or index_name,
id=identifier,
body=json.load(body),
op_type='index' if force or identifier is None else 'crea... | def function[put, parameter[index_name, doc_type, identifier, body, force, verbose]]:
constant[Index input data.]
variable[result] assign[=] call[name[current_search_client].index, parameter[]]
if name[verbose] begin[:]
call[name[click].echo, parameter[call[name[json].dumps, para... | keyword[def] identifier[put] ( identifier[index_name] , identifier[doc_type] , identifier[identifier] , identifier[body] , identifier[force] , identifier[verbose] ):
literal[string]
identifier[result] = identifier[current_search_client] . identifier[index] (
identifier[index] = identifier[index_name] ... | def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(index=index_name, doc_type=doc_type or index_name, id=identifier, body=json.load(body), op_type='index' if force or identifier is None else 'create')
if verbose:
click.echo(j... |
def decode_text(s):
"""Decodes a PDFDocEncoding string to Unicode."""
if s.startswith(b'\xfe\xff'):
return unicode(s[2:], 'utf-16be', 'ignore')
else:
return ''.join(PDFDocEncoding[ord(c)] for c in s) | def function[decode_text, parameter[s]]:
constant[Decodes a PDFDocEncoding string to Unicode.]
if call[name[s].startswith, parameter[constant[b'\xfe\xff']]] begin[:]
return[call[name[unicode], parameter[call[name[s]][<ast.Slice object at 0x7da2041dbd90>], constant[utf-16be], constant[ignore]]]] | keyword[def] identifier[decode_text] ( identifier[s] ):
literal[string]
keyword[if] identifier[s] . identifier[startswith] ( literal[string] ):
keyword[return] identifier[unicode] ( identifier[s] [ literal[int] :], literal[string] , literal[string] )
keyword[else] :
keyword[return]... | def decode_text(s):
"""Decodes a PDFDocEncoding string to Unicode."""
if s.startswith(b'\xfe\xff'):
return unicode(s[2:], 'utf-16be', 'ignore') # depends on [control=['if'], data=[]]
else:
return ''.join((PDFDocEncoding[ord(c)] for c in s)) |
def sequence_names(fasta):
"""
return a list of the sequence IDs in a FASTA file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = [record.id for record in sequences]
return records | def function[sequence_names, parameter[fasta]]:
constant[
return a list of the sequence IDs in a FASTA file
]
variable[sequences] assign[=] call[name[SeqIO].parse, parameter[name[fasta], constant[fasta]]]
variable[records] assign[=] <ast.ListComp object at 0x7da1b18a11e0>
return[name... | keyword[def] identifier[sequence_names] ( identifier[fasta] ):
literal[string]
identifier[sequences] = identifier[SeqIO] . identifier[parse] ( identifier[fasta] , literal[string] )
identifier[records] =[ identifier[record] . identifier[id] keyword[for] identifier[record] keyword[in] identifier[seq... | def sequence_names(fasta):
"""
return a list of the sequence IDs in a FASTA file
"""
sequences = SeqIO.parse(fasta, 'fasta')
records = [record.id for record in sequences]
return records |
def data_filler_user_agent(self, number_of_rows, db):
'''creates and fills the table with user agent data
'''
try:
user_agent = db
data_list = list()
for i in range(0, number_of_rows):
post_uo_reg = {
"id": rnd_id_generator... | def function[data_filler_user_agent, parameter[self, number_of_rows, db]]:
constant[creates and fills the table with user agent data
]
<ast.Try object at 0x7da1b0716260> | keyword[def] identifier[data_filler_user_agent] ( identifier[self] , identifier[number_of_rows] , identifier[db] ):
literal[string]
keyword[try] :
identifier[user_agent] = identifier[db]
identifier[data_list] = identifier[list] ()
keyword[for] identifier[i]... | def data_filler_user_agent(self, number_of_rows, db):
"""creates and fills the table with user agent data
"""
try:
user_agent = db
data_list = list()
for i in range(0, number_of_rows):
post_uo_reg = {'id': rnd_id_generator(self), 'ip': self.faker.ipv4(), 'countrycode'... |
def add_done_callback(self, fn):
"""Attaches the given callback to the `Future`.
It will be invoked with the `Future` as its argument when the Future
has finished running and its result is available. In Tornado
consider using `.IOLoop.add_future` instead of calling
`add_done_ca... | def function[add_done_callback, parameter[self, fn]]:
constant[Attaches the given callback to the `Future`.
It will be invoked with the `Future` as its argument when the Future
has finished running and its result is available. In Tornado
consider using `.IOLoop.add_future` instead of c... | keyword[def] identifier[add_done_callback] ( identifier[self] , identifier[fn] ):
literal[string]
keyword[if] identifier[self] . identifier[_done] :
identifier[fn] ( identifier[self] )
keyword[else] :
identifier[self] . identifier[_callbacks] . identifier[append]... | def add_done_callback(self, fn):
"""Attaches the given callback to the `Future`.
It will be invoked with the `Future` as its argument when the Future
has finished running and its result is available. In Tornado
consider using `.IOLoop.add_future` instead of calling
`add_done_callba... |
def format_(blocks):
"""Produce Python module from blocks of tests
Arguments:
blocks (list): Blocks of tests from func:`parse()`
"""
tests = list()
function_count = 0 # For each test to have a unique name
for block in blocks:
# Validate docstring format of body
if n... | def function[format_, parameter[blocks]]:
constant[Produce Python module from blocks of tests
Arguments:
blocks (list): Blocks of tests from func:`parse()`
]
variable[tests] assign[=] call[name[list], parameter[]]
variable[function_count] assign[=] constant[0]
for taget... | keyword[def] identifier[format_] ( identifier[blocks] ):
literal[string]
identifier[tests] = identifier[list] ()
identifier[function_count] = literal[int]
keyword[for] identifier[block] keyword[in] identifier[blocks] :
keyword[if] keyword[not] identifier[any] ( identifier[l... | def format_(blocks):
"""Produce Python module from blocks of tests
Arguments:
blocks (list): Blocks of tests from func:`parse()`
"""
tests = list()
function_count = 0 # For each test to have a unique name
for block in blocks:
# Validate docstring format of body
if not ... |
def setup(self, context):
"""Implements TextFile Generator's setup method"""
myindex = context.get_partition_index()
self._files_to_consume = self._files[myindex::context.get_num_partitions()]
self.logger.info("TextFileSpout files to consume %s" % self._files_to_consume)
self._lines_to_consume = sel... | def function[setup, parameter[self, context]]:
constant[Implements TextFile Generator's setup method]
variable[myindex] assign[=] call[name[context].get_partition_index, parameter[]]
name[self]._files_to_consume assign[=] call[name[self]._files][<ast.Slice object at 0x7da20c76e6b0>]
call... | keyword[def] identifier[setup] ( identifier[self] , identifier[context] ):
literal[string]
identifier[myindex] = identifier[context] . identifier[get_partition_index] ()
identifier[self] . identifier[_files_to_consume] = identifier[self] . identifier[_files] [ identifier[myindex] :: identifier[context... | def setup(self, context):
"""Implements TextFile Generator's setup method"""
myindex = context.get_partition_index()
self._files_to_consume = self._files[myindex::context.get_num_partitions()]
self.logger.info('TextFileSpout files to consume %s' % self._files_to_consume)
self._lines_to_consume = sel... |
def related_tags(self,release_id=None,tag_names=None,response_type=None,params=None):
"""
Function to request FRED related tags for a particular release.
FRED tags are attributes assigned to series.
Series are assigned tags and releases. Indirectly through series,
it is possible ... | def function[related_tags, parameter[self, release_id, tag_names, response_type, params]]:
constant[
Function to request FRED related tags for a particular release.
FRED tags are attributes assigned to series.
Series are assigned tags and releases. Indirectly through series,
it i... | keyword[def] identifier[related_tags] ( identifier[self] , identifier[release_id] = keyword[None] , identifier[tag_names] = keyword[None] , identifier[response_type] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
identifier[path] = literal[string]
identifier[param... | def related_tags(self, release_id=None, tag_names=None, response_type=None, params=None):
"""
Function to request FRED related tags for a particular release.
FRED tags are attributes assigned to series.
Series are assigned tags and releases. Indirectly through series,
it is possible ... |
def __add_shared(self, original_token):
"""Adds a token, normalizing the SID and import reference to this table."""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, self.__import_location(sid))
self.__add(token)
return token | def function[__add_shared, parameter[self, original_token]]:
constant[Adds a token, normalizing the SID and import reference to this table.]
variable[sid] assign[=] call[name[self].__new_sid, parameter[]]
variable[token] assign[=] call[name[SymbolToken], parameter[name[original_token].text, name... | keyword[def] identifier[__add_shared] ( identifier[self] , identifier[original_token] ):
literal[string]
identifier[sid] = identifier[self] . identifier[__new_sid] ()
identifier[token] = identifier[SymbolToken] ( identifier[original_token] . identifier[text] , identifier[sid] , identifier[... | def __add_shared(self, original_token):
"""Adds a token, normalizing the SID and import reference to this table."""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, self.__import_location(sid))
self.__add(token)
return token |
def returnValue(self, key, last=False):
'''Return the key's value for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty or the key is missing.
Example of use:
>>> test = [
... {"name": "Jim", ... | def function[returnValue, parameter[self, key, last]]:
constant[Return the key's value for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty or the key is missing.
Example of use:
>>> test = [
...... | keyword[def] identifier[returnValue] ( identifier[self] , identifier[key] , identifier[last] = keyword[False] ):
literal[string]
identifier[row] = identifier[self] . identifier[returnOneEntry] ( identifier[last] = identifier[last] )
keyword[if] keyword[not] identifier[row] :
... | def returnValue(self, key, last=False):
"""Return the key's value for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty or the key is missing.
Example of use:
>>> test = [
... {"name": "Jim", "ag... |
def find_version(file_path):
"""
Scrape version information from specified file path.
"""
with open(file_path, 'r') as f:
file_contents = f.read()
version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]",
file_contents, re.M)
if version_match:
... | def function[find_version, parameter[file_path]]:
constant[
Scrape version information from specified file path.
]
with call[name[open], parameter[name[file_path], constant[r]]] begin[:]
variable[file_contents] assign[=] call[name[f].read, parameter[]]
variable[version_m... | keyword[def] identifier[find_version] ( identifier[file_path] ):
literal[string]
keyword[with] identifier[open] ( identifier[file_path] , literal[string] ) keyword[as] identifier[f] :
identifier[file_contents] = identifier[f] . identifier[read] ()
identifier[version_match] = identifier[re] ... | def find_version(file_path):
"""
Scrape version information from specified file path.
"""
with open(file_path, 'r') as f:
file_contents = f.read() # depends on [control=['with'], data=['f']]
version_match = re.search('^__version__\\s*=\\s*[\'\\"]([^\'\\"]*)[\'\\"]', file_contents, re.M)
... |
def run(
cmd,
env=None,
return_object=False,
block=True,
cwd=None,
verbose=False,
nospin=False,
spinner_name=None,
combine_stderr=True,
display_limit=200,
write_to_stdout=True,
):
"""Use `subprocess.Popen` to get the output of a command and decode it.
:param list cmd... | def function[run, parameter[cmd, env, return_object, block, cwd, verbose, nospin, spinner_name, combine_stderr, display_limit, write_to_stdout]]:
constant[Use `subprocess.Popen` to get the output of a command and decode it.
:param list cmd: A list representing the command you want to run.
:param dict e... | keyword[def] identifier[run] (
identifier[cmd] ,
identifier[env] = keyword[None] ,
identifier[return_object] = keyword[False] ,
identifier[block] = keyword[True] ,
identifier[cwd] = keyword[None] ,
identifier[verbose] = keyword[False] ,
identifier[nospin] = keyword[False] ,
identifier[spinner_name] = keyword[... | def run(cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True):
"""Use `subprocess.Popen` to get the output of a command and decode it.
:param list cmd: A list representing the command you want to r... |
def applet_set_properties(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/setProperties API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties
"""
return DXHTTPRequest('/%s/setP... | def function[applet_set_properties, parameter[object_id, input_params, always_retry]]:
constant[
Invokes the /applet-xxxx/setProperties API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties
]
return[call[name[DX... | keyword[def] identifier[applet_set_properties] ( identifier[object_id] , identifier[input_params] ={}, identifier[always_retry] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[DXHTTPRequest] ( literal[string] % identifier[object_id] , identifier[input_params] , identif... | def applet_set_properties(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/setProperties API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties
"""
return DXHTTPRequest('/%s/setP... |
def _admx_policy_parent_walk(path,
policy_namespace,
parent_category,
policy_nsmap,
return_full_policy_names,
adml_language):
'''
helper function to recursively walk u... | def function[_admx_policy_parent_walk, parameter[path, policy_namespace, parent_category, policy_nsmap, return_full_policy_names, adml_language]]:
constant[
helper function to recursively walk up the ADMX namespaces and build the
hierarchy for the policy
]
variable[admx_policy_definitions] a... | keyword[def] identifier[_admx_policy_parent_walk] ( identifier[path] ,
identifier[policy_namespace] ,
identifier[parent_category] ,
identifier[policy_nsmap] ,
identifier[return_full_policy_names] ,
identifier[adml_language] ):
literal[string]
identifier[admx_policy_definitions] = identifier[_get_polic... | def _admx_policy_parent_walk(path, policy_namespace, parent_category, policy_nsmap, return_full_policy_names, adml_language):
"""
helper function to recursively walk up the ADMX namespaces and build the
hierarchy for the policy
"""
admx_policy_definitions = _get_policy_definitions(language=adml_lang... |
def _rpc_action_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle rpc or action statement."""
self._handle_child(RpcActionNode(), stmt, sctx) | def function[_rpc_action_stmt, parameter[self, stmt, sctx]]:
constant[Handle rpc or action statement.]
call[name[self]._handle_child, parameter[call[name[RpcActionNode], parameter[]], name[stmt], name[sctx]]] | keyword[def] identifier[_rpc_action_stmt] ( identifier[self] , identifier[stmt] : identifier[Statement] , identifier[sctx] : identifier[SchemaContext] )-> keyword[None] :
literal[string]
identifier[self] . identifier[_handle_child] ( identifier[RpcActionNode] (), identifier[stmt] , identifier[sctx]... | def _rpc_action_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle rpc or action statement."""
self._handle_child(RpcActionNode(), stmt, sctx) |
def expand(args):
"""
%prog expand bes.fasta reads.fastq
Expand sequences using short reads. Useful, for example for getting BAC-end
sequences. The template to use, in `bes.fasta` may just contain the junction
sequences, then align the reads to get the 'flanks' for such sequences.
"""
impor... | def function[expand, parameter[args]]:
constant[
%prog expand bes.fasta reads.fastq
Expand sequences using short reads. Useful, for example for getting BAC-end
sequences. The template to use, in `bes.fasta` may just contain the junction
sequences, then align the reads to get the 'flanks' for su... | keyword[def] identifier[expand] ( identifier[args] ):
literal[string]
keyword[import] identifier[math]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[fasta] keyword[import] identifier[Fasta] , identifier[SeqIO]
keyword[from] identifier[jcvi] . identifier[formats] . iden... | def expand(args):
"""
%prog expand bes.fasta reads.fastq
Expand sequences using short reads. Useful, for example for getting BAC-end
sequences. The template to use, in `bes.fasta` may just contain the junction
sequences, then align the reads to get the 'flanks' for such sequences.
"""
impor... |
def import_xml(self, xml_gzipped_file_path, taxids=None, silent=False):
"""Imports XML
:param str xml_gzipped_file_path: path to XML file
:param Optional[list[int]] taxids: NCBI taxonomy identifier
:param bool silent: no output if True
"""
version = self.session.query(mo... | def function[import_xml, parameter[self, xml_gzipped_file_path, taxids, silent]]:
constant[Imports XML
:param str xml_gzipped_file_path: path to XML file
:param Optional[list[int]] taxids: NCBI taxonomy identifier
:param bool silent: no output if True
]
variable[version]... | keyword[def] identifier[import_xml] ( identifier[self] , identifier[xml_gzipped_file_path] , identifier[taxids] = keyword[None] , identifier[silent] = keyword[False] ):
literal[string]
identifier[version] = identifier[self] . identifier[session] . identifier[query] ( identifier[models] . identifier... | def import_xml(self, xml_gzipped_file_path, taxids=None, silent=False):
"""Imports XML
:param str xml_gzipped_file_path: path to XML file
:param Optional[list[int]] taxids: NCBI taxonomy identifier
:param bool silent: no output if True
"""
version = self.session.query(models.Ver... |
def packages(self):
"""
Property for accessing :class:`PackageManager` instance, which is used to manage packages.
:rtype: yagocd.resources.package.PackageManager
"""
if self._package_manager is None:
self._package_manager = PackageManager(session=self._session)
... | def function[packages, parameter[self]]:
constant[
Property for accessing :class:`PackageManager` instance, which is used to manage packages.
:rtype: yagocd.resources.package.PackageManager
]
if compare[name[self]._package_manager is constant[None]] begin[:]
name... | keyword[def] identifier[packages] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_package_manager] keyword[is] keyword[None] :
identifier[self] . identifier[_package_manager] = identifier[PackageManager] ( identifier[session] = identifier[self] . ide... | def packages(self):
"""
Property for accessing :class:`PackageManager` instance, which is used to manage packages.
:rtype: yagocd.resources.package.PackageManager
"""
if self._package_manager is None:
self._package_manager = PackageManager(session=self._session) # depends on [c... |
def D_dt(self, H_0, Om0, Ode0=None):
"""
time delay distance
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
"""
lensCosmo = self._get_cosom(H_0, Om0, Ode0)
return lensCosmo.D_dt | def function[D_dt, parameter[self, H_0, Om0, Ode0]]:
constant[
time delay distance
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
]
variable[lensCosmo] assign[=] call[name[self]._get_cosom, parame... | keyword[def] identifier[D_dt] ( identifier[self] , identifier[H_0] , identifier[Om0] , identifier[Ode0] = keyword[None] ):
literal[string]
identifier[lensCosmo] = identifier[self] . identifier[_get_cosom] ( identifier[H_0] , identifier[Om0] , identifier[Ode0] )
keyword[return] identifier[... | def D_dt(self, H_0, Om0, Ode0=None):
"""
time delay distance
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
"""
lensCosmo = self._get_cosom(H_0, Om0, Ode0)
return lensCosmo.D_dt |
def del_option_by_number(self, number):
"""
Delete an option from the message by number
:type number: Integer
:param number: option naumber
"""
for o in list(self._options):
assert isinstance(o, Option)
if o.number == number:
self.... | def function[del_option_by_number, parameter[self, number]]:
constant[
Delete an option from the message by number
:type number: Integer
:param number: option naumber
]
for taget[name[o]] in starred[call[name[list], parameter[name[self]._options]]] begin[:]
asser... | keyword[def] identifier[del_option_by_number] ( identifier[self] , identifier[number] ):
literal[string]
keyword[for] identifier[o] keyword[in] identifier[list] ( identifier[self] . identifier[_options] ):
keyword[assert] identifier[isinstance] ( identifier[o] , identifier[Option] ... | def del_option_by_number(self, number):
"""
Delete an option from the message by number
:type number: Integer
:param number: option naumber
"""
for o in list(self._options):
assert isinstance(o, Option)
if o.number == number:
self._options.remove(o) ... |
def updatePools(self,
pool1,
username1,
password1,
pool2=None,
username2=None,
password2=None,
pool3=None,
username3=None,
password3=None):
... | def function[updatePools, parameter[self, pool1, username1, password1, pool2, username2, password2, pool3, username3, password3]]:
constant[Change the pools of the miner. This call will restart cgminer.]
return[call[name[self].__post, parameter[constant[/api/updatePools]]]] | keyword[def] identifier[updatePools] ( identifier[self] ,
identifier[pool1] ,
identifier[username1] ,
identifier[password1] ,
identifier[pool2] = keyword[None] ,
identifier[username2] = keyword[None] ,
identifier[password2] = keyword[None] ,
identifier[pool3] = keyword[None] ,
identifier[username3] = keyword[... | def updatePools(self, pool1, username1, password1, pool2=None, username2=None, password2=None, pool3=None, username3=None, password3=None):
"""Change the pools of the miner. This call will restart cgminer."""
return self.__post('/api/updatePools', data={'Pool1': pool1, 'UserName1': username1, 'Password1': passw... |
def package_remove(name):
'''
Remove a "package" on the REST server
'''
DETAILS = _load_state()
DETAILS['packages'].pop(name)
_save_state(DETAILS)
return DETAILS['packages'] | def function[package_remove, parameter[name]]:
constant[
Remove a "package" on the REST server
]
variable[DETAILS] assign[=] call[name[_load_state], parameter[]]
call[call[name[DETAILS]][constant[packages]].pop, parameter[name[name]]]
call[name[_save_state], parameter[name[DETAIL... | keyword[def] identifier[package_remove] ( identifier[name] ):
literal[string]
identifier[DETAILS] = identifier[_load_state] ()
identifier[DETAILS] [ literal[string] ]. identifier[pop] ( identifier[name] )
identifier[_save_state] ( identifier[DETAILS] )
keyword[return] identifier[DETAILS] [ ... | def package_remove(name):
"""
Remove a "package" on the REST server
"""
DETAILS = _load_state()
DETAILS['packages'].pop(name)
_save_state(DETAILS)
return DETAILS['packages'] |
def generate_help(config_cls, **kwargs):
"""
Autogenerate a help string for a config class.
If a callable is provided via the "formatter" kwarg it
will be provided with the help dictionaries as an argument
and any other kwargs provided to this function. That callable
should return the help text... | def function[generate_help, parameter[config_cls]]:
constant[
Autogenerate a help string for a config class.
If a callable is provided via the "formatter" kwarg it
will be provided with the help dictionaries as an argument
and any other kwargs provided to this function. That callable
should... | keyword[def] identifier[generate_help] ( identifier[config_cls] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[formatter] = identifier[kwargs] . identifier[pop] ( literal[string] )
keyword[except] identifier[KeyError] :
identifier[formatter] = identifier[_format... | def generate_help(config_cls, **kwargs):
"""
Autogenerate a help string for a config class.
If a callable is provided via the "formatter" kwarg it
will be provided with the help dictionaries as an argument
and any other kwargs provided to this function. That callable
should return the help text... |
def load_window_opener(self, item):
"""Load window opener from JSON."""
window = Window.from_config(self.pyvlx, item)
self.add(window) | def function[load_window_opener, parameter[self, item]]:
constant[Load window opener from JSON.]
variable[window] assign[=] call[name[Window].from_config, parameter[name[self].pyvlx, name[item]]]
call[name[self].add, parameter[name[window]]] | keyword[def] identifier[load_window_opener] ( identifier[self] , identifier[item] ):
literal[string]
identifier[window] = identifier[Window] . identifier[from_config] ( identifier[self] . identifier[pyvlx] , identifier[item] )
identifier[self] . identifier[add] ( identifier[window] ) | def load_window_opener(self, item):
"""Load window opener from JSON."""
window = Window.from_config(self.pyvlx, item)
self.add(window) |
def spec_compliant_decrypt(jwe, jwk, validate_claims=True,
expiry_seconds=None):
""" Decrypts a deserialized :class:`~jose.JWE`
:param jwe: An instance of :class:`~jose.JWE`
:param jwk: A `dict` representing the JWK required to decrypt the content
of the :class:`~... | def function[spec_compliant_decrypt, parameter[jwe, jwk, validate_claims, expiry_seconds]]:
constant[ Decrypts a deserialized :class:`~jose.JWE`
:param jwe: An instance of :class:`~jose.JWE`
:param jwk: A `dict` representing the JWK required to decrypt the content
of the :class:`~jose.J... | keyword[def] identifier[spec_compliant_decrypt] ( identifier[jwe] , identifier[jwk] , identifier[validate_claims] = keyword[True] ,
identifier[expiry_seconds] = keyword[None] ):
literal[string]
identifier[protected_header] , identifier[encrypted_key] , identifier[iv] , identifier[ciphertext] , identifier[... | def spec_compliant_decrypt(jwe, jwk, validate_claims=True, expiry_seconds=None):
""" Decrypts a deserialized :class:`~jose.JWE`
:param jwe: An instance of :class:`~jose.JWE`
:param jwk: A `dict` representing the JWK required to decrypt the content
of the :class:`~jose.JWE`.
:param valid... |
def get_included_resources(request, serializer=None):
""" Build a list of included resources. """
include_resources_param = request.query_params.get('include') if request else None
if include_resources_param:
return include_resources_param.split(',')
else:
return get_default_included_res... | def function[get_included_resources, parameter[request, serializer]]:
constant[ Build a list of included resources. ]
variable[include_resources_param] assign[=] <ast.IfExp object at 0x7da1b180c760>
if name[include_resources_param] begin[:]
return[call[name[include_resources_param].split... | keyword[def] identifier[get_included_resources] ( identifier[request] , identifier[serializer] = keyword[None] ):
literal[string]
identifier[include_resources_param] = identifier[request] . identifier[query_params] . identifier[get] ( literal[string] ) keyword[if] identifier[request] keyword[else] keywo... | def get_included_resources(request, serializer=None):
""" Build a list of included resources. """
include_resources_param = request.query_params.get('include') if request else None
if include_resources_param:
return include_resources_param.split(',') # depends on [control=['if'], data=[]]
else:... |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Delete Storage Group."""
assert wait_for_completion is True # async not supported yet
# The URI is a POST operation, so we need to construct the SG URI
storage_group_oid = uri_pa... | def function[post, parameter[method, hmc, uri, uri_parms, body, logon_required, wait_for_completion]]:
constant[Operation: Delete Storage Group.]
assert[compare[name[wait_for_completion] is constant[True]]]
variable[storage_group_oid] assign[=] call[name[uri_parms]][constant[0]]
variable[sto... | keyword[def] identifier[post] ( identifier[method] , identifier[hmc] , identifier[uri] , identifier[uri_parms] , identifier[body] , identifier[logon_required] ,
identifier[wait_for_completion] ):
literal[string]
keyword[assert] identifier[wait_for_completion] keyword[is] keyword[True]
... | def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion):
"""Operation: Delete Storage Group."""
assert wait_for_completion is True # async not supported yet
# The URI is a POST operation, so we need to construct the SG URI
storage_group_oid = uri_parms[0]
storage_group_uri ... |
def _construct_url(self, base_api, params):
"""
Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL.
"""
params['... | def function[_construct_url, parameter[self, base_api, params]]:
constant[
Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL.
... | keyword[def] identifier[_construct_url] ( identifier[self] , identifier[base_api] , identifier[params] ):
literal[string]
identifier[params] [ literal[string] ]= identifier[self] . identifier[api_key]
keyword[return] identifier[super] ( identifier[OpenMapQuest] , identifier[self] ). iden... | def _construct_url(self, base_api, params):
"""
Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL.
"""
params['key'] = ... |
def _get_ids_from_ip(self, ip): # pylint: disable=inconsistent-return-statements
"""Returns list of matching hardware IDs for a given ip address."""
try:
# Does it look like an ip address?
socket.inet_aton(ip)
except socket.error:
return []
# Find th... | def function[_get_ids_from_ip, parameter[self, ip]]:
constant[Returns list of matching hardware IDs for a given ip address.]
<ast.Try object at 0x7da207f9a2c0>
variable[results] assign[=] call[name[self].list_hardware, parameter[]]
if name[results] begin[:]
return[<ast.ListComp objec... | keyword[def] identifier[_get_ids_from_ip] ( identifier[self] , identifier[ip] ):
literal[string]
keyword[try] :
identifier[socket] . identifier[inet_aton] ( identifier[ip] )
keyword[except] identifier[socket] . identifier[error] :
keyword[return] []
... | def _get_ids_from_ip(self, ip): # pylint: disable=inconsistent-return-statements
'Returns list of matching hardware IDs for a given ip address.'
try:
# Does it look like an ip address?
socket.inet_aton(ip) # depends on [control=['try'], data=[]]
except socket.error:
return [] # de... |
def get_standings(self, league):
"""Queries the API and gets the standings for a particular league"""
league_id = self.league_ids[league]
try:
req = self._get('competitions/{id}/standings'.format(
id=league_id))
self.writer.standings(req.json(), le... | def function[get_standings, parameter[self, league]]:
constant[Queries the API and gets the standings for a particular league]
variable[league_id] assign[=] call[name[self].league_ids][name[league]]
<ast.Try object at 0x7da2054a6b90> | keyword[def] identifier[get_standings] ( identifier[self] , identifier[league] ):
literal[string]
identifier[league_id] = identifier[self] . identifier[league_ids] [ identifier[league] ]
keyword[try] :
identifier[req] = identifier[self] . identifier[_get] ( literal[string] . i... | def get_standings(self, league):
"""Queries the API and gets the standings for a particular league"""
league_id = self.league_ids[league]
try:
req = self._get('competitions/{id}/standings'.format(id=league_id))
self.writer.standings(req.json(), league) # depends on [control=['try'], data=[]... |
def ci(ctx, enable, disable): # pylint:disable=assign-to-new-keyword
"""Enable/Disable CI on this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon project ci --enable
```
\b
```bash
$ polyaxon project ci --disable
```
"""
... | def function[ci, parameter[ctx, enable, disable]]:
constant[Enable/Disable CI on this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
```bash
$ polyaxon project ci --enable
```
```bash
$ polyaxon project ci --disable
```
]
<ast.Tupl... | keyword[def] identifier[ci] ( identifier[ctx] , identifier[enable] , identifier[disable] ):
literal[string]
identifier[user] , identifier[project_name] = identifier[get_project_or_local] ( identifier[ctx] . identifier[obj] . identifier[get] ( literal[string] ))
keyword[def] identifier[enable_ci] ():... | def ci(ctx, enable, disable): # pylint:disable=assign-to-new-keyword
'Enable/Disable CI on this project.\n\n Uses [Caching](/references/polyaxon-cli/#caching)\n\n Example:\n\n \x08\n ```bash\n $ polyaxon project ci --enable\n ```\n\n \x08\n ```bash\n $ polyaxon project ci --disable\n ... |
async def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` seconds. ``time``
can be represented by an integer or a Python timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
re... | <ast.AsyncFunctionDef object at 0x7da1b07cc5e0> | keyword[async] keyword[def] identifier[expire] ( identifier[self] , identifier[name] , identifier[time] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[time] , identifier[datetime] . identifier[timedelta] ):
identifier[time] = identifier[time] . identifier[seconds]... | async def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` seconds. ``time``
can be represented by an integer or a Python timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600 # depends on [control... |
def generate_py(module_name, code, optimizations=None, module_dir=None):
'''python + pythran spec -> py code
Prints and returns the optimized python code.
'''
pm, ir, _, _ = front_middle_end(module_name, code, optimizations,
module_dir)
return pm.dump(Python, ... | def function[generate_py, parameter[module_name, code, optimizations, module_dir]]:
constant[python + pythran spec -> py code
Prints and returns the optimized python code.
]
<ast.Tuple object at 0x7da1b15ba290> assign[=] call[name[front_middle_end], parameter[name[module_name], name[code], nam... | keyword[def] identifier[generate_py] ( identifier[module_name] , identifier[code] , identifier[optimizations] = keyword[None] , identifier[module_dir] = keyword[None] ):
literal[string]
identifier[pm] , identifier[ir] , identifier[_] , identifier[_] = identifier[front_middle_end] ( identifier[module_name]... | def generate_py(module_name, code, optimizations=None, module_dir=None):
"""python + pythran spec -> py code
Prints and returns the optimized python code.
"""
(pm, ir, _, _) = front_middle_end(module_name, code, optimizations, module_dir)
return pm.dump(Python, ir) |
def profile(model_specification, results_directory, process):
"""Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
"""
model_specification = Path(model_specification)
results_directory = Path(results_directory)
out_stats_file = results_directory / f'{model_specific... | def function[profile, parameter[model_specification, results_directory, process]]:
constant[Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
]
variable[model_specification] assign[=] call[name[Path], parameter[name[model_specification]]]
variable[results_di... | keyword[def] identifier[profile] ( identifier[model_specification] , identifier[results_directory] , identifier[process] ):
literal[string]
identifier[model_specification] = identifier[Path] ( identifier[model_specification] )
identifier[results_directory] = identifier[Path] ( identifier[results_direc... | def profile(model_specification, results_directory, process):
"""Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
"""
model_specification = Path(model_specification)
results_directory = Path(results_directory)
out_stats_file = results_directory / f'{model_specifica... |
def get_path_relative_to_module(module_file_path, relative_target_path):
"""
Calculate a path relative to the specified module file.
:param module_file_path: The file path to the module.
"""
module_path = os.path.dirname(module_file_path)
path = os.path.join(module_path, relative_target_path)
... | def function[get_path_relative_to_module, parameter[module_file_path, relative_target_path]]:
constant[
Calculate a path relative to the specified module file.
:param module_file_path: The file path to the module.
]
variable[module_path] assign[=] call[name[os].path.dirname, parameter[name[... | keyword[def] identifier[get_path_relative_to_module] ( identifier[module_file_path] , identifier[relative_target_path] ):
literal[string]
identifier[module_path] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[module_file_path] )
identifier[path] = identifier[os] . identifier[pa... | def get_path_relative_to_module(module_file_path, relative_target_path):
"""
Calculate a path relative to the specified module file.
:param module_file_path: The file path to the module.
"""
module_path = os.path.dirname(module_file_path)
path = os.path.join(module_path, relative_target_path)
... |
def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... | def function[get_smooth_step_function, parameter[min_val, max_val, switch_point, smooth_factor]]:
constant[Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
m... | keyword[def] identifier[get_smooth_step_function] ( identifier[min_val] , identifier[max_val] , identifier[switch_point] , identifier[smooth_factor] ):
literal[string]
identifier[dif] = identifier[max_val] - identifier[min_val]
keyword[def] identifier[_smooth_step] ( identifier[x] ):
keywor... | def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... |
def read_metadata(self, f, objects, previous_segment=None):
"""Read segment metadata section and update object information"""
if not self.toc["kTocMetaData"]:
try:
self.ordered_objects = previous_segment.ordered_objects
except AttributeError:
rais... | def function[read_metadata, parameter[self, f, objects, previous_segment]]:
constant[Read segment metadata section and update object information]
if <ast.UnaryOp object at 0x7da204962380> begin[:]
<ast.Try object at 0x7da204962ef0>
call[name[self].calculate_chunks, parameter[]]
... | keyword[def] identifier[read_metadata] ( identifier[self] , identifier[f] , identifier[objects] , identifier[previous_segment] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[toc] [ literal[string] ]:
keyword[try] :
identifi... | def read_metadata(self, f, objects, previous_segment=None):
"""Read segment metadata section and update object information"""
if not self.toc['kTocMetaData']:
try:
self.ordered_objects = previous_segment.ordered_objects # depends on [control=['try'], data=[]]
except AttributeError:
... |
def aligned_base():
"""Set of hyperparameters.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60
12.0 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00
Returns:
a hparams object
"""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 512
hpa... | def function[aligned_base, parameter[]]:
constant[Set of hyperparameters.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60
12.0 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00
Returns:
a hparams object
]
variable[hparams] assign[=] call[name... | keyword[def] identifier[aligned_base] ():
literal[string]
identifier[hparams] = identifier[common_hparams] . identifier[basic_params1] ()
identifier[hparams] . identifier[hidden_size] = literal[int]
identifier[hparams] . identifier[batch_size] = literal[int]
identifier[hparams] . identifier[max_leng... | def aligned_base():
"""Set of hyperparameters.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60
12.0 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00
Returns:
a hparams object
"""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 512... |
def __process_action(self, action, file_type):
""" Extension point to populate extra action information after an
action has been created.
"""
if getattr(action, "inject_url", False):
self.__inject_url(action, file_type)
if getattr(action, "inject_ssh_properties", Fals... | def function[__process_action, parameter[self, action, file_type]]:
constant[ Extension point to populate extra action information after an
action has been created.
]
if call[name[getattr], parameter[name[action], constant[inject_url], constant[False]]] begin[:]
call[name... | keyword[def] identifier[__process_action] ( identifier[self] , identifier[action] , identifier[file_type] ):
literal[string]
keyword[if] identifier[getattr] ( identifier[action] , literal[string] , keyword[False] ):
identifier[self] . identifier[__inject_url] ( identifier[action] , id... | def __process_action(self, action, file_type):
""" Extension point to populate extra action information after an
action has been created.
"""
if getattr(action, 'inject_url', False):
self.__inject_url(action, file_type) # depends on [control=['if'], data=[]]
if getattr(action, 'inje... |
def empty_directory(self):
"""Remove all contents of a directory
Including any sub-directories and their contents"""
for child in self.walkfiles():
child.remove()
for child in reversed([d for d in self.walkdirs()]):
if child == self or not child.isdir():
... | def function[empty_directory, parameter[self]]:
constant[Remove all contents of a directory
Including any sub-directories and their contents]
for taget[name[child]] in starred[call[name[self].walkfiles, parameter[]]] begin[:]
call[name[child].remove, parameter[]]
for tag... | keyword[def] identifier[empty_directory] ( identifier[self] ):
literal[string]
keyword[for] identifier[child] keyword[in] identifier[self] . identifier[walkfiles] ():
identifier[child] . identifier[remove] ()
keyword[for] identifier[child] keyword[in] identifier[reversed... | def empty_directory(self):
"""Remove all contents of a directory
Including any sub-directories and their contents"""
for child in self.walkfiles():
child.remove() # depends on [control=['for'], data=['child']]
for child in reversed([d for d in self.walkdirs()]):
if child == self or... |
def circular(args):
"""
%prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based.
"""
from jcvi.assembly.goldenpath import overlap
p = Opti... | def function[circular, parameter[args]]:
constant[
%prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based.
]
from relative_module[jcvi.ass... | keyword[def] identifier[circular] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[assembly] . identifier[goldenpath] keyword[import] identifier[overlap]
identifier[p] = identifier[OptionParser] ( identifier[circular] . identifier[__doc__] )
identifier[p] . i... | def circular(args):
"""
%prog circular fastafile startpos
Make circular genome, startpos is the place to start the sequence. This can
be determined by mapping to a reference. Self overlaps are then resolved.
Startpos is 1-based.
"""
from jcvi.assembly.goldenpath import overlap
p = Optio... |
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... | def function[input, parameter[msg, default, title, hidden]]:
constant[ Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. ]
variable[root] assign[=] call[name[tk].Tk, parameter[]]
variable[input_tex... | keyword[def] identifier[input] ( identifier[msg] = literal[string] , identifier[default] = literal[string] , identifier[title] = literal[string] , identifier[hidden] = keyword[False] ):
literal[string]
identifier[root] = identifier[tk] . identifier[Tk] ()
identifier[input_text] = identifier[tk] . iden... | def input(msg='', default='', title='Lackey Input', hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... |
def infer_call_result(self, caller, context=None):
"""infer what a class instance is returning when called"""
context = contextmod.bind_context_to_node(context, self)
inferred = False
for node in self._proxied.igetattr("__call__", context):
if node is util.Uninferable or not ... | def function[infer_call_result, parameter[self, caller, context]]:
constant[infer what a class instance is returning when called]
variable[context] assign[=] call[name[contextmod].bind_context_to_node, parameter[name[context], name[self]]]
variable[inferred] assign[=] constant[False]
for... | keyword[def] identifier[infer_call_result] ( identifier[self] , identifier[caller] , identifier[context] = keyword[None] ):
literal[string]
identifier[context] = identifier[contextmod] . identifier[bind_context_to_node] ( identifier[context] , identifier[self] )
identifier[inferred] = keyw... | def infer_call_result(self, caller, context=None):
"""infer what a class instance is returning when called"""
context = contextmod.bind_context_to_node(context, self)
inferred = False
for node in self._proxied.igetattr('__call__', context):
if node is util.Uninferable or not node.callable():
... |
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bas... | def function[clear_job_cache, parameter[hours]]:
constant[
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Examp... | keyword[def] identifier[clear_job_cache] ( identifier[hours] = literal[int] ):
literal[string]
identifier[threshold] = identifier[time] . identifier[time] ()- identifier[hours] * literal[int] * literal[int]
keyword[for] identifier[root] , identifier[dirs] , identifier[files] keyword[in] identifier... | def clear_job_cache(hours=24):
"""
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bas... |
def tickerId(self, contract_identifier):
"""
returns the tickerId for the symbol or
sets one if it doesn't exits
"""
# contract passed instead of symbol?
symbol = contract_identifier
if isinstance(symbol, Contract):
symbol = self.contractString(symbol)... | def function[tickerId, parameter[self, contract_identifier]]:
constant[
returns the tickerId for the symbol or
sets one if it doesn't exits
]
variable[symbol] assign[=] name[contract_identifier]
if call[name[isinstance], parameter[name[symbol], name[Contract]]] begin[:]
... | keyword[def] identifier[tickerId] ( identifier[self] , identifier[contract_identifier] ):
literal[string]
identifier[symbol] = identifier[contract_identifier]
keyword[if] identifier[isinstance] ( identifier[symbol] , identifier[Contract] ):
identifier[symbol] = iden... | def tickerId(self, contract_identifier):
"""
returns the tickerId for the symbol or
sets one if it doesn't exits
"""
# contract passed instead of symbol?
symbol = contract_identifier
if isinstance(symbol, Contract):
symbol = self.contractString(symbol) # depends on [cont... |
def reload(self, reload_timeout, save_config):
"""Reload the device."""
PROCEED = re.compile(re.escape("Proceed with reload? [confirm]"))
CONTINUE = re.compile(re.escape("Do you wish to continue?[confirm(y/n)]"))
DONE = re.compile(re.escape("[Done]"))
CONFIGURATION_COMPLETED = re... | def function[reload, parameter[self, reload_timeout, save_config]]:
constant[Reload the device.]
variable[PROCEED] assign[=] call[name[re].compile, parameter[call[name[re].escape, parameter[constant[Proceed with reload? [confirm]]]]]]
variable[CONTINUE] assign[=] call[name[re].compile, parameter... | keyword[def] identifier[reload] ( identifier[self] , identifier[reload_timeout] , identifier[save_config] ):
literal[string]
identifier[PROCEED] = identifier[re] . identifier[compile] ( identifier[re] . identifier[escape] ( literal[string] ))
identifier[CONTINUE] = identifier[re] . identif... | def reload(self, reload_timeout, save_config):
"""Reload the device."""
PROCEED = re.compile(re.escape('Proceed with reload? [confirm]'))
CONTINUE = re.compile(re.escape('Do you wish to continue?[confirm(y/n)]'))
DONE = re.compile(re.escape('[Done]'))
CONFIGURATION_COMPLETED = re.compile('SYSTEM CON... |
def rdist(x, y):
"""Reduced Euclidean distance.
Parameters
----------
x: array of shape (embedding_dim,)
y: array of shape (embedding_dim,)
Returns
-------
The squared euclidean distance between x and y
"""
result = 0.0
for i in range(x.shape[0]):
result += (x[i] - ... | def function[rdist, parameter[x, y]]:
constant[Reduced Euclidean distance.
Parameters
----------
x: array of shape (embedding_dim,)
y: array of shape (embedding_dim,)
Returns
-------
The squared euclidean distance between x and y
]
variable[result] assign[=] constant[0.... | keyword[def] identifier[rdist] ( identifier[x] , identifier[y] ):
literal[string]
identifier[result] = literal[int]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[x] . identifier[shape] [ literal[int] ]):
identifier[result] +=( identifier[x] [ identifier[i] ]- ident... | def rdist(x, y):
"""Reduced Euclidean distance.
Parameters
----------
x: array of shape (embedding_dim,)
y: array of shape (embedding_dim,)
Returns
-------
The squared euclidean distance between x and y
"""
result = 0.0
for i in range(x.shape[0]):
result += (x[i] - ... |
def resolve(self, other: Type) -> Type:
"""See ``PlaceholderType.resolve``"""
if not isinstance(other, NltkComplexType):
return None
resolved_second = NUMBER_TYPE.resolve(other.second)
if not resolved_second:
return None
return CountType(other.first) | def function[resolve, parameter[self, other]]:
constant[See ``PlaceholderType.resolve``]
if <ast.UnaryOp object at 0x7da20c991fc0> begin[:]
return[constant[None]]
variable[resolved_second] assign[=] call[name[NUMBER_TYPE].resolve, parameter[name[other].second]]
if <ast.UnaryOp ob... | keyword[def] identifier[resolve] ( identifier[self] , identifier[other] : identifier[Type] )-> identifier[Type] :
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[NltkComplexType] ):
keyword[return] keyword[None]
identifier[r... | def resolve(self, other: Type) -> Type:
"""See ``PlaceholderType.resolve``"""
if not isinstance(other, NltkComplexType):
return None # depends on [control=['if'], data=[]]
resolved_second = NUMBER_TYPE.resolve(other.second)
if not resolved_second:
return None # depends on [control=['if... |
def run(self):
'''
Initialise the runner function with the passed args, kwargs
'''
# Retrieve args/kwargs here; and fire up the processing using them
try:
transcript = self.fn(*self.args, **self.kwargs)
except:
traceback.print_exc()
ex... | def function[run, parameter[self]]:
constant[
Initialise the runner function with the passed args, kwargs
]
<ast.Try object at 0x7da1b20f9060> | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[transcript] = identifier[self] . identifier[fn] (* identifier[self] . identifier[args] ,** identifier[self] . identifier[kwargs] )
keyword[except] :
identifier[t... | def run(self):
"""
Initialise the runner function with the passed args, kwargs
"""
# Retrieve args/kwargs here; and fire up the processing using them
try:
transcript = self.fn(*self.args, **self.kwargs) # depends on [control=['try'], data=[]]
except:
traceback.print_exc(... |
def backwards(self, orm):
"Write your backwards methods here."
from django.contrib.auth.models import Group
projects = orm['samples.Project'].objects.all()
names = [PROJECT_GROUP_TEMPLATE.format(p.name) for p in projects]
# Remove groups named after these teams
Group.ob... | def function[backwards, parameter[self, orm]]:
constant[Write your backwards methods here.]
from relative_module[django.contrib.auth.models] import module[Group]
variable[projects] assign[=] call[call[name[orm]][constant[samples.Project]].objects.all, parameter[]]
variable[names] assign[=] <... | keyword[def] identifier[backwards] ( identifier[self] , identifier[orm] ):
literal[string]
keyword[from] identifier[django] . identifier[contrib] . identifier[auth] . identifier[models] keyword[import] identifier[Group]
identifier[projects] = identifier[orm] [ literal[string] ]. ident... | def backwards(self, orm):
"""Write your backwards methods here."""
from django.contrib.auth.models import Group
projects = orm['samples.Project'].objects.all()
names = [PROJECT_GROUP_TEMPLATE.format(p.name) for p in projects]
# Remove groups named after these teams
Group.objects.filter(name__in=... |
def tokenize(ngrams, min_tf=2, min_df=2, min_len=3, apply_stoplist=False):
"""
Builds a vocabulary, and replaces words with vocab indices.
Parameters
----------
ngrams : dict
Keys are paper DOIs, values are lists of (Ngram, frequency) tuples.
apply_stoplist : bool
If True, will ... | def function[tokenize, parameter[ngrams, min_tf, min_df, min_len, apply_stoplist]]:
constant[
Builds a vocabulary, and replaces words with vocab indices.
Parameters
----------
ngrams : dict
Keys are paper DOIs, values are lists of (Ngram, frequency) tuples.
apply_stoplist : bool
... | keyword[def] identifier[tokenize] ( identifier[ngrams] , identifier[min_tf] = literal[int] , identifier[min_df] = literal[int] , identifier[min_len] = literal[int] , identifier[apply_stoplist] = keyword[False] ):
literal[string]
identifier[vocab] ={}
identifier[vocab_] ={}
identifier[word_tf] = ... | def tokenize(ngrams, min_tf=2, min_df=2, min_len=3, apply_stoplist=False):
"""
Builds a vocabulary, and replaces words with vocab indices.
Parameters
----------
ngrams : dict
Keys are paper DOIs, values are lists of (Ngram, frequency) tuples.
apply_stoplist : bool
If True, will ... |
def cliques(graph, threshold=3):
""" Returns all the cliques in the graph of at least the given size.
"""
cliques = []
for n in graph.nodes:
c = clique(graph, n.id)
if len(c) >= threshold:
c.sort()
if c not in cliques:
cliques.append(c)
... | def function[cliques, parameter[graph, threshold]]:
constant[ Returns all the cliques in the graph of at least the given size.
]
variable[cliques] assign[=] list[[]]
for taget[name[n]] in starred[name[graph].nodes] begin[:]
variable[c] assign[=] call[name[clique], parameter[n... | keyword[def] identifier[cliques] ( identifier[graph] , identifier[threshold] = literal[int] ):
literal[string]
identifier[cliques] =[]
keyword[for] identifier[n] keyword[in] identifier[graph] . identifier[nodes] :
identifier[c] = identifier[clique] ( identifier[graph] , identifier[n] . i... | def cliques(graph, threshold=3):
""" Returns all the cliques in the graph of at least the given size.
"""
cliques = []
for n in graph.nodes:
c = clique(graph, n.id)
if len(c) >= threshold:
c.sort()
if c not in cliques:
cliques.append(c) # depends ... |
def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template
"""
try:
UserService.objects.filter(
... | def function[callback, parameter[self, request]]:
constant[
Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template
]
<ast.Try object at 0x7da1b26ad3f0>
... | keyword[def] identifier[callback] ( identifier[self] , identifier[request] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[UserService] . identifier[objects] . identifier[filter] (
identifier[user] = identifier[request] . identifier[user] ,
... | def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template
"""
try:
UserService.objects.filter(user=request.user,... |
def set(self, option, value):
"""
Sets an option to a value.
"""
if self.config is None:
self.config = {}
self.config[option] = value | def function[set, parameter[self, option, value]]:
constant[
Sets an option to a value.
]
if compare[name[self].config is constant[None]] begin[:]
name[self].config assign[=] dictionary[[], []]
call[name[self].config][name[option]] assign[=] name[value] | keyword[def] identifier[set] ( identifier[self] , identifier[option] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[config] keyword[is] keyword[None] :
identifier[self] . identifier[config] ={}
identifier[self] . identifier[config] [ identi... | def set(self, option, value):
"""
Sets an option to a value.
"""
if self.config is None:
self.config = {} # depends on [control=['if'], data=[]]
self.config[option] = value |
def copy(self):
"""Provides a partial 'deepcopy' of the Model. All of the Metabolite,
Gene, and Reaction objects are created anew but in a faster fashion
than deepcopy
"""
new = self.__class__()
do_not_copy_by_ref = {"metabolites", "reactions", "genes", "notes",
... | def function[copy, parameter[self]]:
constant[Provides a partial 'deepcopy' of the Model. All of the Metabolite,
Gene, and Reaction objects are created anew but in a faster fashion
than deepcopy
]
variable[new] assign[=] call[name[self].__class__, parameter[]]
variable[d... | keyword[def] identifier[copy] ( identifier[self] ):
literal[string]
identifier[new] = identifier[self] . identifier[__class__] ()
identifier[do_not_copy_by_ref] ={ literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] }
... | def copy(self):
"""Provides a partial 'deepcopy' of the Model. All of the Metabolite,
Gene, and Reaction objects are created anew but in a faster fashion
than deepcopy
"""
new = self.__class__()
do_not_copy_by_ref = {'metabolites', 'reactions', 'genes', 'notes', 'annotation', 'group... |
def rename_header(self, old_name, new_name):
"""
This will rename the header. The supplied names need to be strings.
"""
self.hkeys[self.hkeys.index(old_name)] = new_name
self.headers[new_name] = self.headers.pop(old_name)
return self | def function[rename_header, parameter[self, old_name, new_name]]:
constant[
This will rename the header. The supplied names need to be strings.
]
call[name[self].hkeys][call[name[self].hkeys.index, parameter[name[old_name]]]] assign[=] name[new_name]
call[name[self].headers][name... | keyword[def] identifier[rename_header] ( identifier[self] , identifier[old_name] , identifier[new_name] ):
literal[string]
identifier[self] . identifier[hkeys] [ identifier[self] . identifier[hkeys] . identifier[index] ( identifier[old_name] )]= identifier[new_name]
identifier[self] . ide... | def rename_header(self, old_name, new_name):
"""
This will rename the header. The supplied names need to be strings.
"""
self.hkeys[self.hkeys.index(old_name)] = new_name
self.headers[new_name] = self.headers.pop(old_name)
return self |
def _handle_spyder_msg(self, msg):
"""
Handle internal spyder messages
"""
spyder_msg_type = msg['content'].get('spyder_msg_type')
if spyder_msg_type == 'data':
# Deserialize data
try:
if PY2:
value = cloudpickle.loads(m... | def function[_handle_spyder_msg, parameter[self, msg]]:
constant[
Handle internal spyder messages
]
variable[spyder_msg_type] assign[=] call[call[name[msg]][constant[content]].get, parameter[constant[spyder_msg_type]]]
if compare[name[spyder_msg_type] equal[==] constant[data]] be... | keyword[def] identifier[_handle_spyder_msg] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[spyder_msg_type] = identifier[msg] [ literal[string] ]. identifier[get] ( literal[string] )
keyword[if] identifier[spyder_msg_type] == literal[string] :
key... | def _handle_spyder_msg(self, msg):
"""
Handle internal spyder messages
"""
spyder_msg_type = msg['content'].get('spyder_msg_type')
if spyder_msg_type == 'data':
# Deserialize data
try:
if PY2:
value = cloudpickle.loads(msg['buffers'][0]) # depends... |
def item_from_topics(key, topics):
"""Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of required
arguments for t... | def function[item_from_topics, parameter[key, topics]]:
constant[Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of requi... | keyword[def] identifier[item_from_topics] ( identifier[key] , identifier[topics] ):
literal[string]
keyword[if] identifier[re] . identifier[match] ( literal[string] , identifier[key] ):
identifier[pos] = identifier[int] ( identifier[key] . identifier[strip] ( literal[string] ))
keyword[... | def item_from_topics(key, topics):
"""Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of required
arguments for t... |
def hard_bounce(self, unique_id, configs=None):
""" Performs a hard bounce (kill and start) for the specified process
:Parameter unique_id: the name of the process
"""
self.kill(unique_id, configs)
self.start(unique_id, configs) | def function[hard_bounce, parameter[self, unique_id, configs]]:
constant[ Performs a hard bounce (kill and start) for the specified process
:Parameter unique_id: the name of the process
]
call[name[self].kill, parameter[name[unique_id], name[configs]]]
call[name[self].start, parameter[n... | keyword[def] identifier[hard_bounce] ( identifier[self] , identifier[unique_id] , identifier[configs] = keyword[None] ):
literal[string]
identifier[self] . identifier[kill] ( identifier[unique_id] , identifier[configs] )
identifier[self] . identifier[start] ( identifier[unique_id] , identifier[configs... | def hard_bounce(self, unique_id, configs=None):
""" Performs a hard bounce (kill and start) for the specified process
:Parameter unique_id: the name of the process
"""
self.kill(unique_id, configs)
self.start(unique_id, configs) |
def p_expression_lesseq(self, p):
'expression : expression LE expression'
p[0] = LessEq(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | def function[p_expression_lesseq, parameter[self, p]]:
constant[expression : expression LE expression]
call[name[p]][constant[0]] assign[=] call[name[LessEq], parameter[call[name[p]][constant[1]], call[name[p]][constant[3]]]]
call[name[p].set_lineno, parameter[constant[0], call[name[p].lineno, p... | keyword[def] identifier[p_expression_lesseq] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[LessEq] ( identifier[p] [ literal[int] ], identifier[p] [ literal[int] ], identifier[lineno] = identifier[p] . identifier[lineno] ( literal[int] ))
... | def p_expression_lesseq(self, p):
"""expression : expression LE expression"""
p[0] = LessEq(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def set_fig_size(self, width, height=None):
"""Set the figure size in inches.
Sets the figure size with a call to fig.set_size_inches.
Default in code is 8 inches for each.
Args:
width (float): Dimensions for figure width in inches.
height (float, optional): Dim... | def function[set_fig_size, parameter[self, width, height]]:
constant[Set the figure size in inches.
Sets the figure size with a call to fig.set_size_inches.
Default in code is 8 inches for each.
Args:
width (float): Dimensions for figure width in inches.
height ... | keyword[def] identifier[set_fig_size] ( identifier[self] , identifier[width] , identifier[height] = keyword[None] ):
literal[string]
identifier[self] . identifier[figure] . identifier[figure_width] = identifier[width]
identifier[self] . identifier[figure] . identifier[figure_height] = ide... | def set_fig_size(self, width, height=None):
"""Set the figure size in inches.
Sets the figure size with a call to fig.set_size_inches.
Default in code is 8 inches for each.
Args:
width (float): Dimensions for figure width in inches.
height (float, optional): Dimensi... |
def get_glibc_version():
"""
Returns:
Version as a pair of ints (major, minor) or None
"""
# TODO: Look into a nicer way to get the version
try:
out = subprocess.Popen(['ldd', '--version'],
stdout=subprocess.PIPE).communicate()[0]
except OSError:
... | def function[get_glibc_version, parameter[]]:
constant[
Returns:
Version as a pair of ints (major, minor) or None
]
<ast.Try object at 0x7da2041dbf70>
variable[match] assign[=] call[name[re].search, parameter[constant[([0-9]+)\.([0-9]+)\.?[0-9]*], name[out]]]
<ast.Try object at 0... | keyword[def] identifier[get_glibc_version] ():
literal[string]
keyword[try] :
identifier[out] = identifier[subprocess] . identifier[Popen] ([ literal[string] , literal[string] ],
identifier[stdout] = identifier[subprocess] . identifier[PIPE] ). identifier[communicate] ()[ literal[int... | def get_glibc_version():
"""
Returns:
Version as a pair of ints (major, minor) or None
"""
# TODO: Look into a nicer way to get the version
try:
out = subprocess.Popen(['ldd', '--version'], stdout=subprocess.PIPE).communicate()[0] # depends on [control=['try'], data=[]]
except O... |
def create_properties(self): # pylint: disable=no-self-use
"""
Format the properties with which to instantiate the connection.
This acts like a user agent over HTTP.
:rtype: dict
"""
properties = {}
properties["product"] = "eventhub.python"
properties["v... | def function[create_properties, parameter[self]]:
constant[
Format the properties with which to instantiate the connection.
This acts like a user agent over HTTP.
:rtype: dict
]
variable[properties] assign[=] dictionary[[], []]
call[name[properties]][constant[pro... | keyword[def] identifier[create_properties] ( identifier[self] ):
literal[string]
identifier[properties] ={}
identifier[properties] [ literal[string] ]= literal[string]
identifier[properties] [ literal[string] ]= identifier[__version__]
identifier[properties] [ literal[s... | def create_properties(self): # pylint: disable=no-self-use
'\n Format the properties with which to instantiate the connection.\n This acts like a user agent over HTTP.\n\n :rtype: dict\n '
properties = {}
properties['product'] = 'eventhub.python'
properties['version'] = __ve... |
def __updatable():
"""
Function used to output packages update information in the console
"""
# Add argument for console
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')
args = parser.parse_args()
... | def function[__updatable, parameter[]]:
constant[
Function used to output packages update information in the console
]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[file]]]
variable[args] assign[=] c... | keyword[def] identifier[__updatable] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ()
identifier[parser] . identifier[add_argument] ( literal[string] , identifier[nargs] = literal[string] , identifier[type] = identifier[argparse] . identifier[FileType]... | def __updatable():
"""
Function used to output packages update information in the console
"""
# Add argument for console
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')
args = parser.parse_args()
... |
def upload(self, dest_dir, file_handler, filename, callback=None, **kwargs):
"""上传单个文件(<2G).
| 百度PCS服务目前支持最大2G的单个文件上传。
| 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。
:param dest_dir: 网盘中文件的保存路径(不包含文件名)。
必须以 / 开头。
.. warning::
... | def function[upload, parameter[self, dest_dir, file_handler, filename, callback]]:
constant[上传单个文件(<2G).
| 百度PCS服务目前支持最大2G的单个文件上传。
| 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。
:param dest_dir: 网盘中文件的保存路径(不包含文件名)。
必须以 / 开头。
.. warning::... | keyword[def] identifier[upload] ( identifier[self] , identifier[dest_dir] , identifier[file_handler] , identifier[filename] , identifier[callback] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[params] ={
literal[string] : identifier[str] ( identifier[dest_dir] )+ li... | def upload(self, dest_dir, file_handler, filename, callback=None, **kwargs):
"""上传单个文件(<2G).
| 百度PCS服务目前支持最大2G的单个文件上传。
| 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。
:param dest_dir: 网盘中文件的保存路径(不包含文件名)。
必须以 / 开头。
.. warning::
... |
def isHereDoc(self, line, column):
"""Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isHereDoc(self.document().findBlockByNumbe... | def function[isHereDoc, parameter[self, line, column]]:
constant[Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned
]
return[<ast.BoolOp object at 0x7da18f58d5a0>] | keyword[def] identifier[isHereDoc] ( identifier[self] , identifier[line] , identifier[column] ):
literal[string]
keyword[return] identifier[self] . identifier[_highlighter] keyword[is] keyword[not] keyword[None] keyword[and] identifier[self] . identifier[_highlighter] . identifier[isHereDoc] ... | def isHereDoc(self, line, column):
"""Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and self._highlighter.isHereDoc(self.document().findBlockByNumber(line), column) |
def data_interp(self, i, currenttime):
"""
Method to streamline request for data from cache,
Uses linear interpolation bewtween timesteps to
get u,v,w,temp,salt
"""
if self.active.value is True:
while self.get_data.value is True:
lo... | def function[data_interp, parameter[self, i, currenttime]]:
constant[
Method to streamline request for data from cache,
Uses linear interpolation bewtween timesteps to
get u,v,w,temp,salt
]
if compare[name[self].active.value is constant[True]] begin[:]
... | keyword[def] identifier[data_interp] ( identifier[self] , identifier[i] , identifier[currenttime] ):
literal[string]
keyword[if] identifier[self] . identifier[active] . identifier[value] keyword[is] keyword[True] :
keyword[while] identifier[self] . identifier[get_data] . identifier... | def data_interp(self, i, currenttime):
"""
Method to streamline request for data from cache,
Uses linear interpolation bewtween timesteps to
get u,v,w,temp,salt
"""
if self.active.value is True:
while self.get_data.value is True:
logger.debug('Wait... |
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input ... | def function[get_mask_from_sequence_lengths, parameter[sequence_lengths, max_length]]:
constant[
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input was ... | keyword[def] identifier[get_mask_from_sequence_lengths] ( identifier[sequence_lengths] : identifier[torch] . identifier[Tensor] , identifier[max_length] : identifier[int] )-> identifier[torch] . identifier[Tensor] :
literal[string]
identifier[ones] = identifier[sequence_lengths] . identifier[new_ones]... | def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input ... |
def OnTextFont(self, event):
"""Text font choice event handler"""
fontchoice_combobox = event.GetEventObject()
idx = event.GetInt()
try:
font_string = fontchoice_combobox.GetString(idx)
except AttributeError:
font_string = event.GetString()
post... | def function[OnTextFont, parameter[self, event]]:
constant[Text font choice event handler]
variable[fontchoice_combobox] assign[=] call[name[event].GetEventObject, parameter[]]
variable[idx] assign[=] call[name[event].GetInt, parameter[]]
<ast.Try object at 0x7da1b1723070>
call[name[... | keyword[def] identifier[OnTextFont] ( identifier[self] , identifier[event] ):
literal[string]
identifier[fontchoice_combobox] = identifier[event] . identifier[GetEventObject] ()
identifier[idx] = identifier[event] . identifier[GetInt] ()
keyword[try] :
identifier[fo... | def OnTextFont(self, event):
"""Text font choice event handler"""
fontchoice_combobox = event.GetEventObject()
idx = event.GetInt()
try:
font_string = fontchoice_combobox.GetString(idx) # depends on [control=['try'], data=[]]
except AttributeError:
font_string = event.GetString() #... |
def _body(self, full_path, environ, file_like):
"""Return an iterator over the body of the response."""
magic = self._match_magic(full_path)
if magic is not None:
return [_encode(s, self.encoding) for s in magic.body(environ,
... | def function[_body, parameter[self, full_path, environ, file_like]]:
constant[Return an iterator over the body of the response.]
variable[magic] assign[=] call[name[self]._match_magic, parameter[name[full_path]]]
if compare[name[magic] is_not constant[None]] begin[:]
return[<ast.ListComp... | keyword[def] identifier[_body] ( identifier[self] , identifier[full_path] , identifier[environ] , identifier[file_like] ):
literal[string]
identifier[magic] = identifier[self] . identifier[_match_magic] ( identifier[full_path] )
keyword[if] identifier[magic] keyword[is] keyword[not] ke... | def _body(self, full_path, environ, file_like):
"""Return an iterator over the body of the response."""
magic = self._match_magic(full_path)
if magic is not None:
return [_encode(s, self.encoding) for s in magic.body(environ, file_like)] # depends on [control=['if'], data=['magic']]
else:
... |
def logarithmic_profile(wind_speed, wind_speed_height, hub_height,
roughness_length, obstacle_height=0.0):
r"""
Calculates the wind speed at hub height using a logarithmic wind profile.
The logarithmic height equation is used. There is the possibility of
including the height of ... | def function[logarithmic_profile, parameter[wind_speed, wind_speed_height, hub_height, roughness_length, obstacle_height]]:
constant[
Calculates the wind speed at hub height using a logarithmic wind profile.
The logarithmic height equation is used. There is the possibility of
including the height o... | keyword[def] identifier[logarithmic_profile] ( identifier[wind_speed] , identifier[wind_speed_height] , identifier[hub_height] ,
identifier[roughness_length] , identifier[obstacle_height] = literal[int] ):
literal[string]
keyword[if] literal[int] * identifier[obstacle_height] > identifier[wind_speed_heig... | def logarithmic_profile(wind_speed, wind_speed_height, hub_height, roughness_length, obstacle_height=0.0):
"""
Calculates the wind speed at hub height using a logarithmic wind profile.
The logarithmic height equation is used. There is the possibility of
including the height of the surrounding obstacles... |
def i2c_master_read(self, addr, length, flags=I2C_NO_FLAGS):
"""Make an I2C read access.
The given I2C device is addressed and clock cycles for `length` bytes
are generated. A short read will occur if the device generates an early
NAK.
The transaction is finished with an I2C st... | def function[i2c_master_read, parameter[self, addr, length, flags]]:
constant[Make an I2C read access.
The given I2C device is addressed and clock cycles for `length` bytes
are generated. A short read will occur if the device generates an early
NAK.
The transaction is finished ... | keyword[def] identifier[i2c_master_read] ( identifier[self] , identifier[addr] , identifier[length] , identifier[flags] = identifier[I2C_NO_FLAGS] ):
literal[string]
identifier[data] = identifier[array] . identifier[array] ( literal[string] ,( literal[int] ,)* identifier[length] )
identif... | def i2c_master_read(self, addr, length, flags=I2C_NO_FLAGS):
"""Make an I2C read access.
The given I2C device is addressed and clock cycles for `length` bytes
are generated. A short read will occur if the device generates an early
NAK.
The transaction is finished with an I2C stop c... |
def walk_json(d, func):
""" Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result
"""
if isinstance(d, Mapping):
return OrderedDict((k, walk_json(v, func)) for k, v in d.items())
elif isinstance(d, list):
return [walk_json(v, func) for... | def function[walk_json, parameter[d, func]]:
constant[ Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result
]
if call[name[isinstance], parameter[name[d], name[Mapping]]] begin[:]
return[call[name[OrderedDict], parameter[<ast.GeneratorExp... | keyword[def] identifier[walk_json] ( identifier[d] , identifier[func] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[d] , identifier[Mapping] ):
keyword[return] identifier[OrderedDict] (( identifier[k] , identifier[walk_json] ( identifier[v] , identifier[func] )) keyword[for]... | def walk_json(d, func):
""" Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result
"""
if isinstance(d, Mapping):
return OrderedDict(((k, walk_json(v, func)) for (k, v) in d.items())) # depends on [control=['if'], data=[]]
elif isinstance(d, l... |
def __update_cleanup_paths(new_path):
"""
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up.
"""
cleanup_dirs = settings.CFG["cleanup_paths"].value
cleanup_dirs = set(cleanup_dirs)
cleanup_dirs.add(new_path... | def function[__update_cleanup_paths, parameter[new_path]]:
constant[
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up.
]
variable[cleanup_dirs] assign[=] call[name[settings].CFG][constant[cleanup_paths]].v... | keyword[def] identifier[__update_cleanup_paths] ( identifier[new_path] ):
literal[string]
identifier[cleanup_dirs] = identifier[settings] . identifier[CFG] [ literal[string] ]. identifier[value]
identifier[cleanup_dirs] = identifier[set] ( identifier[cleanup_dirs] )
identifier[cleanup_dirs] . id... | def __update_cleanup_paths(new_path):
"""
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up.
"""
cleanup_dirs = settings.CFG['cleanup_paths'].value
cleanup_dirs = set(cleanup_dirs)
cleanup_dirs.add(new_path... |
def clone_version(self, service_id, version_number):
"""Clone the current configuration into a new version."""
content = self._fetch("/service/%s/version/%d/clone" % (service_id, version_number), method="PUT")
return FastlyVersion(self, content) | def function[clone_version, parameter[self, service_id, version_number]]:
constant[Clone the current configuration into a new version.]
variable[content] assign[=] call[name[self]._fetch, parameter[binary_operation[constant[/service/%s/version/%d/clone] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Nam... | keyword[def] identifier[clone_version] ( identifier[self] , identifier[service_id] , identifier[version_number] ):
literal[string]
identifier[content] = identifier[self] . identifier[_fetch] ( literal[string] %( identifier[service_id] , identifier[version_number] ), identifier[method] = literal[string] )
ke... | def clone_version(self, service_id, version_number):
"""Clone the current configuration into a new version."""
content = self._fetch('/service/%s/version/%d/clone' % (service_id, version_number), method='PUT')
return FastlyVersion(self, content) |
def create(name, availability_zones, listeners, subnets=None,
security_groups=None, scheme='internet-facing',
region=None, key=None, keyid=None,
profile=None):
'''
Create an ELB
CLI example to create an ELB:
.. code-block:: bash
salt myminion boto_elb.create m... | def function[create, parameter[name, availability_zones, listeners, subnets, security_groups, scheme, region, key, keyid, profile]]:
constant[
Create an ELB
CLI example to create an ELB:
.. code-block:: bash
salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": ... | keyword[def] identifier[create] ( identifier[name] , identifier[availability_zones] , identifier[listeners] , identifier[subnets] = keyword[None] ,
identifier[security_groups] = keyword[None] , identifier[scheme] = literal[string] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[k... | def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None):
"""
Create an ELB
CLI example to create an ELB:
.. code-block:: bash
salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"... |
def get_caller_name(back: int = 0) -> str:
"""
Return details about the CALLER OF THE CALLER (plus n calls further back)
of this function.
So, if your function calls :func:`get_caller_name`, it will return the
name of the function that called your function! (Or ``back`` calls further
back.)
... | def function[get_caller_name, parameter[back]]:
constant[
Return details about the CALLER OF THE CALLER (plus n calls further back)
of this function.
So, if your function calls :func:`get_caller_name`, it will return the
name of the function that called your function! (Or ``back`` calls further... | keyword[def] identifier[get_caller_name] ( identifier[back] : identifier[int] = literal[int] )-> identifier[str] :
literal[string]
keyword[try] :
identifier[frame] = identifier[sys] . identifier[_getframe] ( identifier[back] + literal[int] )
keyword[except] identifier[ValueError] :... | def get_caller_name(back: int=0) -> str:
"""
Return details about the CALLER OF THE CALLER (plus n calls further back)
of this function.
So, if your function calls :func:`get_caller_name`, it will return the
name of the function that called your function! (Or ``back`` calls further
back.)
... |
def managed(name, table, data, record=None):
'''
Ensures that the specified columns of the named record have the specified
values.
Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing a mapping from column name... | def function[managed, parameter[name, table, data, record]]:
constant[
Ensures that the specified columns of the named record have the specified
values.
Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing ... | keyword[def] identifier[managed] ( identifier[name] , identifier[table] , identifier[data] , identifier[record] = keyword[None] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] :{}, literal[string] : keyword[False] , literal[string] : literal[string] }
keyword... | def managed(name, table, data, record=None):
"""
Ensures that the specified columns of the named record have the specified
values.
Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing a mapping from column name... |
def QA_data_tick_resample(tick, type_='1min'):
"""tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_temp = set(tick.index.date)
for item in _temp:
... | def function[QA_data_tick_resample, parameter[tick, type_]]:
constant[tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
]
variable[tick] assign[=] call[name[tick].assign, parameter[]]
variable[resx] assign[=] call[name[pd].DataF... | keyword[def] identifier[QA_data_tick_resample] ( identifier[tick] , identifier[type_] = literal[string] ):
literal[string]
identifier[tick] = identifier[tick] . identifier[assign] ( identifier[amount] = identifier[tick] . identifier[price] * identifier[tick] . identifier[vol] )
identifier[resx] = iden... | def QA_data_tick_resample(tick, type_='1min'):
"""tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_temp = set(tick.index.date)
for item in _temp:
_... |
def _set_toChange(x):
""" set variables in list x toChange """
for key in list(x.keys()):
self.toChange[key] = True | def function[_set_toChange, parameter[x]]:
constant[ set variables in list x toChange ]
for taget[name[key]] in starred[call[name[list], parameter[call[name[x].keys, parameter[]]]]] begin[:]
call[name[self].toChange][name[key]] assign[=] constant[True] | keyword[def] identifier[_set_toChange] ( identifier[x] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[x] . identifier[keys] ()):
identifier[self] . identifier[toChange] [ identifier[key] ]= keyword[True] | def _set_toChange(x):
""" set variables in list x toChange """
for key in list(x.keys()):
self.toChange[key] = True # depends on [control=['for'], data=['key']] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.