code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _marshal(self, newSerial=True, oobFDs=None):
"""
Encodes the message into binary format. The resulting binary message is
stored in C{self.rawMessage}
"""
flags = 0
if not self.expectReply:
flags |= 0x1
if not self.autoStart:
flags |= ... | def function[_marshal, parameter[self, newSerial, oobFDs]]:
constant[
Encodes the message into binary format. The resulting binary message is
stored in C{self.rawMessage}
]
variable[flags] assign[=] constant[0]
if <ast.UnaryOp object at 0x7da18c4cf370> begin[:]
<a... | keyword[def] identifier[_marshal] ( identifier[self] , identifier[newSerial] = keyword[True] , identifier[oobFDs] = keyword[None] ):
literal[string]
identifier[flags] = literal[int]
keyword[if] keyword[not] identifier[self] . identifier[expectReply] :
identifier[flags] |= ... | def _marshal(self, newSerial=True, oobFDs=None):
"""
Encodes the message into binary format. The resulting binary message is
stored in C{self.rawMessage}
"""
flags = 0
if not self.expectReply:
flags |= 1 # depends on [control=['if'], data=[]]
if not self.autoStart:
... |
def ceil(self):
"""Round `x` and `y` up to integers."""
return Point(int(math.ceil(self.x)), int(math.ceil(self.y))) | def function[ceil, parameter[self]]:
constant[Round `x` and `y` up to integers.]
return[call[name[Point], parameter[call[name[int], parameter[call[name[math].ceil, parameter[name[self].x]]]], call[name[int], parameter[call[name[math].ceil, parameter[name[self].y]]]]]]] | keyword[def] identifier[ceil] ( identifier[self] ):
literal[string]
keyword[return] identifier[Point] ( identifier[int] ( identifier[math] . identifier[ceil] ( identifier[self] . identifier[x] )), identifier[int] ( identifier[math] . identifier[ceil] ( identifier[self] . identifier[y] ))) | def ceil(self):
"""Round `x` and `y` up to integers."""
return Point(int(math.ceil(self.x)), int(math.ceil(self.y))) |
def _get_template(t):
"""Return a single template *t*."""
if os.path.exists(t): # 1) Is it an accessible file?
pass
else:
_t = t
_t_found = False
for d in path: # 2) search config.path
p = os.path.join(d, _t)
if os.path.e... | def function[_get_template, parameter[t]]:
constant[Return a single template *t*.]
if call[name[os].path.exists, parameter[name[t]]] begin[:]
pass
return[call[name[os].path.realpath, parameter[name[t]]]] | keyword[def] identifier[_get_template] ( identifier[t] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[t] ):
keyword[pass]
keyword[else] :
identifier[_t] = identifier[t]
identifier[_t_found] = keyword[False]
... | def _get_template(t):
"""Return a single template *t*."""
if os.path.exists(t): # 1) Is it an accessible file?
pass # depends on [control=['if'], data=[]]
else:
_t = t
_t_found = False
for d in path: # 2) search config.path
p = os.path.join(d, _t)
i... |
def halt(self):
"""
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
"""
if self._callback:
self._thread_continue = False
self._th... | def function[halt, parameter[self]]:
constant[
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
]
if name[self]._callback begin[:]
name[se... | keyword[def] identifier[halt] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_callback] :
identifier[self] . identifier[_thread_continue] = keyword[False]
identifier[self] . identifier[_thread] . identifier[join] () | def halt(self):
"""
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
"""
if self._callback:
self._thread_continue = False
self._thread.join() # d... |
def interpret(self, startpos, args, addr=None, simfd=None):
"""
implement scanf - extract formatted data from memory or a file according to the stored format
specifiers and store them into the pointers extracted from `args`.
:param startpos: The index of the first argument correspond... | def function[interpret, parameter[self, startpos, args, addr, simfd]]:
constant[
implement scanf - extract formatted data from memory or a file according to the stored format
specifiers and store them into the pointers extracted from `args`.
:param startpos: The index of the first ar... | keyword[def] identifier[interpret] ( identifier[self] , identifier[startpos] , identifier[args] , identifier[addr] = keyword[None] , identifier[simfd] = keyword[None] ):
literal[string]
keyword[if] identifier[simfd] keyword[is] keyword[not] keyword[None] keyword[and] identifier[isinstance] ( ... | def interpret(self, startpos, args, addr=None, simfd=None):
"""
implement scanf - extract formatted data from memory or a file according to the stored format
specifiers and store them into the pointers extracted from `args`.
:param startpos: The index of the first argument corresponding ... |
def remove_rm_na(dv=None, within=None, subject=None, data=None,
aggregate='mean'):
"""Remove missing values in long-format repeated-measures dataframe.
Parameters
----------
dv : string or list
Dependent variable(s), from which the missing values should be removed.
If `... | def function[remove_rm_na, parameter[dv, within, subject, data, aggregate]]:
constant[Remove missing values in long-format repeated-measures dataframe.
Parameters
----------
dv : string or list
Dependent variable(s), from which the missing values should be removed.
If ``dv`` is not ... | keyword[def] identifier[remove_rm_na] ( identifier[dv] = keyword[None] , identifier[within] = keyword[None] , identifier[subject] = keyword[None] , identifier[data] = keyword[None] ,
identifier[aggregate] = literal[string] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[aggreg... | def remove_rm_na(dv=None, within=None, subject=None, data=None, aggregate='mean'):
"""Remove missing values in long-format repeated-measures dataframe.
Parameters
----------
dv : string or list
Dependent variable(s), from which the missing values should be removed.
If ``dv`` is not spec... |
def vat_id(self):
"""
:return: Swiss UID number
"""
def _checksum(digits):
code = ['8', '6', '4', '2', '3', '5', '9', '7']
remainder = 11-(sum(map(lambda x, y: int(x) * int(y), code, digits)) % 11)
if remainder == 10:
return 0
... | def function[vat_id, parameter[self]]:
constant[
:return: Swiss UID number
]
def function[_checksum, parameter[digits]]:
variable[code] assign[=] list[[<ast.Constant object at 0x7da18dc9ae90>, <ast.Constant object at 0x7da18dc99390>, <ast.Constant object at 0x7da18dc98280... | keyword[def] identifier[vat_id] ( identifier[self] ):
literal[string]
keyword[def] identifier[_checksum] ( identifier[digits] ):
identifier[code] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[st... | def vat_id(self):
"""
:return: Swiss UID number
"""
def _checksum(digits):
code = ['8', '6', '4', '2', '3', '5', '9', '7']
remainder = 11 - sum(map(lambda x, y: int(x) * int(y), code, digits)) % 11
if remainder == 10:
return 0 # depends on [control=['if'], d... |
def getVals(self):
"""Returns value list for Munin Graph
@return: List of name-value pairs.
"""
return [(name, self._fieldValDict.get(name))
for name in self._fieldNameList] | def function[getVals, parameter[self]]:
constant[Returns value list for Munin Graph
@return: List of name-value pairs.
]
return[<ast.ListComp object at 0x7da1b10c05b0>] | keyword[def] identifier[getVals] ( identifier[self] ):
literal[string]
keyword[return] [( identifier[name] , identifier[self] . identifier[_fieldValDict] . identifier[get] ( identifier[name] ))
keyword[for] identifier[name] keyword[in] identifier[self] . identifier[_fieldNameList] ] | def getVals(self):
"""Returns value list for Munin Graph
@return: List of name-value pairs.
"""
return [(name, self._fieldValDict.get(name)) for name in self._fieldNameList] |
def linear_rref(A, b, Matrix=None, S=None):
""" Transform a linear system to reduced row-echelon form
Transforms both the matrix and right-hand side of a linear
system of equations to reduced row echelon form
Parameters
----------
A : Matrix-like
Iterable of rows.
b : iterable
... | def function[linear_rref, parameter[A, b, Matrix, S]]:
constant[ Transform a linear system to reduced row-echelon form
Transforms both the matrix and right-hand side of a linear
system of equations to reduced row echelon form
Parameters
----------
A : Matrix-like
Iterable of rows.
... | keyword[def] identifier[linear_rref] ( identifier[A] , identifier[b] , identifier[Matrix] = keyword[None] , identifier[S] = keyword[None] ):
literal[string]
keyword[if] identifier[Matrix] keyword[is] keyword[None] :
keyword[from] identifier[sympy] keyword[import] identifier[Matrix]
key... | def linear_rref(A, b, Matrix=None, S=None):
""" Transform a linear system to reduced row-echelon form
Transforms both the matrix and right-hand side of a linear
system of equations to reduced row echelon form
Parameters
----------
A : Matrix-like
Iterable of rows.
b : iterable
... |
def port(self):
"""The port in the URL as an integer if it was present, `None`
otherwise. This does not fill in default ports.
"""
try:
rv = int(to_native(self._split_host()[1]))
if 0 <= rv <= 65535:
return rv
except (ValueError, TypeError... | def function[port, parameter[self]]:
constant[The port in the URL as an integer if it was present, `None`
otherwise. This does not fill in default ports.
]
<ast.Try object at 0x7da204622800> | keyword[def] identifier[port] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[rv] = identifier[int] ( identifier[to_native] ( identifier[self] . identifier[_split_host] ()[ literal[int] ]))
keyword[if] literal[int] <= identifier[rv] <= literal[int] :
... | def port(self):
"""The port in the URL as an integer if it was present, `None`
otherwise. This does not fill in default ports.
"""
try:
rv = int(to_native(self._split_host()[1]))
if 0 <= rv <= 65535:
return rv # depends on [control=['if'], data=['rv']] # depends on... |
def handle_json_GET_stoptrips(self, params):
"""Given a stop_id and time in seconds since midnight return the next
trips to visit the stop."""
schedule = self.server.schedule
stop = schedule.GetStop(params.get('stop', None))
time = int(params.get('time', 0))
date = params.get('date', "")
ti... | def function[handle_json_GET_stoptrips, parameter[self, params]]:
constant[Given a stop_id and time in seconds since midnight return the next
trips to visit the stop.]
variable[schedule] assign[=] name[self].server.schedule
variable[stop] assign[=] call[name[schedule].GetStop, parameter[call... | keyword[def] identifier[handle_json_GET_stoptrips] ( identifier[self] , identifier[params] ):
literal[string]
identifier[schedule] = identifier[self] . identifier[server] . identifier[schedule]
identifier[stop] = identifier[schedule] . identifier[GetStop] ( identifier[params] . identifier[get] ( lite... | def handle_json_GET_stoptrips(self, params):
"""Given a stop_id and time in seconds since midnight return the next
trips to visit the stop."""
schedule = self.server.schedule
stop = schedule.GetStop(params.get('stop', None))
time = int(params.get('time', 0))
date = params.get('date', '')
tim... |
def _load_meta(self, meta):
'''Load data from meta.yaml to a dictionary'''
meta = yaml.load(meta, Loader=Loader)
# Versions are often specified in a format that is convertible to an
# int or a float, so we want to make sure it is interpreted as a str.
# Fix for the bug #300.
... | def function[_load_meta, parameter[self, meta]]:
constant[Load data from meta.yaml to a dictionary]
variable[meta] assign[=] call[name[yaml].load, parameter[name[meta]]]
if compare[constant[version] in name[meta]] begin[:]
call[name[meta]][constant[version]] assign[=] call[name[s... | keyword[def] identifier[_load_meta] ( identifier[self] , identifier[meta] ):
literal[string]
identifier[meta] = identifier[yaml] . identifier[load] ( identifier[meta] , identifier[Loader] = identifier[Loader] )
keyword[if] literal[string] keyword[in] identifi... | def _load_meta(self, meta):
"""Load data from meta.yaml to a dictionary"""
meta = yaml.load(meta, Loader=Loader)
# Versions are often specified in a format that is convertible to an
# int or a float, so we want to make sure it is interpreted as a str.
# Fix for the bug #300.
if 'version' in meta... |
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint, pipeline_option):
"""Preprocess data in Cloud with DataFlow."""
import apache_beam as beam
import google.datalab.utils
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
job_na... | def function[preprocess, parameter[train_dataset, output_dir, eval_dataset, checkpoint, pipeline_option]]:
constant[Preprocess data in Cloud with DataFlow.]
import module[apache_beam] as alias[beam]
import module[google.datalab.utils]
from relative_module[None] import module[_preprocess]
if ... | keyword[def] identifier[preprocess] ( identifier[train_dataset] , identifier[output_dir] , identifier[eval_dataset] , identifier[checkpoint] , identifier[pipeline_option] ):
literal[string]
keyword[import] identifier[apache_beam] keyword[as] identifier[beam]
keyword[import] identifier[google] . ... | def preprocess(train_dataset, output_dir, eval_dataset, checkpoint, pipeline_option):
"""Preprocess data in Cloud with DataFlow."""
import apache_beam as beam
import google.datalab.utils
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL # depends ... |
def create_data_figs(self):
"""
Generate the data and figs files for the report
:return:
"""
logger.info("Generating the report data and figs from %s to %s",
self.start, self.end)
for section in self.sections():
logger.info("Generating %... | def function[create_data_figs, parameter[self]]:
constant[
Generate the data and figs files for the report
:return:
]
call[name[logger].info, parameter[constant[Generating the report data and figs from %s to %s], name[self].start, name[self].end]]
for taget[name[section]... | keyword[def] identifier[create_data_figs] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] ,
identifier[self] . identifier[start] , identifier[self] . identifier[end] )
keyword[for] identifier[section] keyword[in] identifier[self] ... | def create_data_figs(self):
"""
Generate the data and figs files for the report
:return:
"""
logger.info('Generating the report data and figs from %s to %s', self.start, self.end)
for section in self.sections():
logger.info('Generating %s', section)
self.sections()[s... |
def convert_random_normal(node, **kwargs):
"""Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
mean = float(attrs.get("loc", 0))
scale = float(attrs.get(... | def function[convert_random_normal, parameter[node]]:
constant[Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
]
<ast.Tuple object at 0x7da1b204f100> assign[=] call[name[get_inputs], parameter[name[node], name[kwargs]]]
variable[... | keyword[def] identifier[convert_random_normal] ( identifier[node] ,** identifier[kwargs] ):
literal[string]
identifier[name] , identifier[input_nodes] , identifier[attrs] = identifier[get_inputs] ( identifier[node] , identifier[kwargs] )
identifier[mean] = identifier[float] ( identifier[attrs] .... | def convert_random_normal(node, **kwargs):
"""Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
"""
(name, input_nodes, attrs) = get_inputs(node, kwargs)
# Converting to float32
mean = float(attrs.get('loc', 0))
scale = float(attrs.get... |
def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) | def function[total_timer, parameter[msg]]:
constant[ A context which add the time spent inside to TotalTimer. ]
variable[start] assign[=] call[name[timer], parameter[]]
<ast.Yield object at 0x7da18f09dfc0>
variable[t] assign[=] binary_operation[call[name[timer], parameter[]] - name[start... | keyword[def] identifier[total_timer] ( identifier[msg] ):
literal[string]
identifier[start] = identifier[timer] ()
keyword[yield]
identifier[t] = identifier[timer] ()- identifier[start]
identifier[_TOTAL_TIMER_DATA] [ identifier[msg] ]. identifier[feed] ( identifier[t] ) | def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) |
def extra(self, value, extra_name, default=None):
"""
Get the additional enumeration value for ``extra_name``.
:param unicode value: Enumeration value.
:param str extra_name: Extra name.
:param default: Default value in the case ``extra_name`` doesn't exist.
"""
... | def function[extra, parameter[self, value, extra_name, default]]:
constant[
Get the additional enumeration value for ``extra_name``.
:param unicode value: Enumeration value.
:param str extra_name: Extra name.
:param default: Default value in the case ``extra_name`` doesn't exist... | keyword[def] identifier[extra] ( identifier[self] , identifier[value] , identifier[extra_name] , identifier[default] = keyword[None] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[get] ( identifier[value] ). identifier[get] ( identifier[extra_name] , i... | def extra(self, value, extra_name, default=None):
"""
Get the additional enumeration value for ``extra_name``.
:param unicode value: Enumeration value.
:param str extra_name: Extra name.
:param default: Default value in the case ``extra_name`` doesn't exist.
"""
try:
... |
def start(self):
"""Starts the advertise loop.
Returns the result of the first ad request.
"""
if self.running:
raise Exception('Advertiser is already running')
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
self.running ... | def function[start, parameter[self]]:
constant[Starts the advertise loop.
Returns the result of the first ad request.
]
if name[self].running begin[:]
<ast.Raise object at 0x7da18dc99990>
if compare[name[self].io_loop is constant[None]] begin[:]
name[self... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[running] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[if] identifier[self] . identifier[io_loop] keyword[is] keyword[None] :
i... | def start(self):
"""Starts the advertise loop.
Returns the result of the first ad request.
"""
if self.running:
raise Exception('Advertiser is already running') # depends on [control=['if'], data=[]]
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current() #... |
def _calculate(world, seed, elevation, mountain_level):
width = world.width
height = world.height
rng = numpy.random.RandomState(seed) # create our own random generator
base = rng.randint(0, 4096)
temp = numpy.zeros((height, width), dtype=float)
'''
Set up vari... | def function[_calculate, parameter[world, seed, elevation, mountain_level]]:
variable[width] assign[=] name[world].width
variable[height] assign[=] name[world].height
variable[rng] assign[=] call[name[numpy].random.RandomState, parameter[name[seed]]]
variable[base] assign[=] call[name[rn... | keyword[def] identifier[_calculate] ( identifier[world] , identifier[seed] , identifier[elevation] , identifier[mountain_level] ):
identifier[width] = identifier[world] . identifier[width]
identifier[height] = identifier[world] . identifier[height]
identifier[rng] = identifier[numpy] . i... | def _calculate(world, seed, elevation, mountain_level):
width = world.width
height = world.height
rng = numpy.random.RandomState(seed) # create our own random generator
base = rng.randint(0, 4096)
temp = numpy.zeros((height, width), dtype=float)
'\n Set up variables to take care of some ... |
def lsst_doc_shortlink_titlecase_display_role(
name, rawtext, text, lineno, inliner, options=None, content=None):
"""Link to LSST documents given their handle using LSST's ls.st link
shortener with the document handle displayed in title case.
This role is useful for Document, Report, Minutes, and C... | def function[lsst_doc_shortlink_titlecase_display_role, parameter[name, rawtext, text, lineno, inliner, options, content]]:
constant[Link to LSST documents given their handle using LSST's ls.st link
shortener with the document handle displayed in title case.
This role is useful for Document, Report, Mi... | keyword[def] identifier[lsst_doc_shortlink_titlecase_display_role] (
identifier[name] , identifier[rawtext] , identifier[text] , identifier[lineno] , identifier[inliner] , identifier[options] = keyword[None] , identifier[content] = keyword[None] ):
literal[string]
identifier[options] = identifier[options]... | def lsst_doc_shortlink_titlecase_display_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Link to LSST documents given their handle using LSST's ls.st link
shortener with the document handle displayed in title case.
This role is useful for Document, Report, Minutes, and Collection... |
def get_input_list(self):
"""
Description:
Get input list
Returns an ordered list of all available input keys and names
"""
inputs = [' '] * len(self.command['input'])
for key in self.command['input']:
inputs[self.command['input'][key]['order... | def function[get_input_list, parameter[self]]:
constant[
Description:
Get input list
Returns an ordered list of all available input keys and names
]
variable[inputs] assign[=] binary_operation[list[[<ast.Constant object at 0x7da20e960c40>]] * call[name[len], par... | keyword[def] identifier[get_input_list] ( identifier[self] ):
literal[string]
identifier[inputs] =[ literal[string] ]* identifier[len] ( identifier[self] . identifier[command] [ literal[string] ])
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[command] [ literal[... | def get_input_list(self):
"""
Description:
Get input list
Returns an ordered list of all available input keys and names
"""
inputs = [' '] * len(self.command['input'])
for key in self.command['input']:
inputs[self.command['input'][key]['order']] = {'key': ke... |
def _get_synsets(synset_offsets):
"""Given synset offsets in the WordNet file, parses synset object for every offset.
Notes
-----
Internal function. Do not call directly.
Stores every parsed synset into global synset dictionary under two keys:
synset's name lemma.pos.sense_no and synset's id ... | def function[_get_synsets, parameter[synset_offsets]]:
constant[Given synset offsets in the WordNet file, parses synset object for every offset.
Notes
-----
Internal function. Do not call directly.
Stores every parsed synset into global synset dictionary under two keys:
synset's name lemm... | keyword[def] identifier[_get_synsets] ( identifier[synset_offsets] ):
literal[string]
keyword[global] identifier[parser]
keyword[if] identifier[parser] keyword[is] keyword[None] :
identifier[parser] = identifier[Parser] ( identifier[_WN_FILE] )
identifier[synsets] =[]
keyword[... | def _get_synsets(synset_offsets):
"""Given synset offsets in the WordNet file, parses synset object for every offset.
Notes
-----
Internal function. Do not call directly.
Stores every parsed synset into global synset dictionary under two keys:
synset's name lemma.pos.sense_no and synset's id ... |
def wait_for_import(self, connection_id, wait_interval):
"""
Wait until connection state is no longer ``IMPORT_CONFIGURATION``.
Args:
connection_id (str): Heroku Connect connection to monitor.
wait_interval (int): How frequently to poll in seconds.
Raises:
... | def function[wait_for_import, parameter[self, connection_id, wait_interval]]:
constant[
Wait until connection state is no longer ``IMPORT_CONFIGURATION``.
Args:
connection_id (str): Heroku Connect connection to monitor.
wait_interval (int): How frequently to poll in seco... | keyword[def] identifier[wait_for_import] ( identifier[self] , identifier[connection_id] , identifier[wait_interval] ):
literal[string]
identifier[self] . identifier[stdout] . identifier[write] ( identifier[self] . identifier[style] . identifier[NOTICE] ( literal[string] ), identifier[ending] = lite... | def wait_for_import(self, connection_id, wait_interval):
"""
Wait until connection state is no longer ``IMPORT_CONFIGURATION``.
Args:
connection_id (str): Heroku Connect connection to monitor.
wait_interval (int): How frequently to poll in seconds.
Raises:
... |
def create_gh_pr(self, base_branch, head_branch, *, commit_message, gh_auth):
"""
Create PR in GitHub
"""
request_headers = sansio.create_headers(self.username, oauth_token=gh_auth)
title, body = normalize_commit_message(commit_message)
if not self.prefix_commit:
... | def function[create_gh_pr, parameter[self, base_branch, head_branch]]:
constant[
Create PR in GitHub
]
variable[request_headers] assign[=] call[name[sansio].create_headers, parameter[name[self].username]]
<ast.Tuple object at 0x7da1b230b2e0> assign[=] call[name[normalize_commit_m... | keyword[def] identifier[create_gh_pr] ( identifier[self] , identifier[base_branch] , identifier[head_branch] ,*, identifier[commit_message] , identifier[gh_auth] ):
literal[string]
identifier[request_headers] = identifier[sansio] . identifier[create_headers] ( identifier[self] . identifier[username... | def create_gh_pr(self, base_branch, head_branch, *, commit_message, gh_auth):
"""
Create PR in GitHub
"""
request_headers = sansio.create_headers(self.username, oauth_token=gh_auth)
(title, body) = normalize_commit_message(commit_message)
if not self.prefix_commit:
title = f'[{ba... |
def get_parameters_by_path(self, path, with_decryption, recursive, filters=None):
"""Implement the get-parameters-by-path-API in the backend."""
result = []
# path could be with or without a trailing /. we handle this
# difference here.
path = path.rstrip('/') + '/'
for p... | def function[get_parameters_by_path, parameter[self, path, with_decryption, recursive, filters]]:
constant[Implement the get-parameters-by-path-API in the backend.]
variable[result] assign[=] list[[]]
variable[path] assign[=] binary_operation[call[name[path].rstrip, parameter[constant[/]]] + con... | keyword[def] identifier[get_parameters_by_path] ( identifier[self] , identifier[path] , identifier[with_decryption] , identifier[recursive] , identifier[filters] = keyword[None] ):
literal[string]
identifier[result] =[]
identifier[path] = identifier[path] . identifier[rst... | def get_parameters_by_path(self, path, with_decryption, recursive, filters=None):
"""Implement the get-parameters-by-path-API in the backend."""
result = []
# path could be with or without a trailing /. we handle this
# difference here.
path = path.rstrip('/') + '/'
for param in self._parameters... |
def installedUniqueRequirements(self, target):
"""
Return an iterable of things installed on the target that this item
requires and are not required by anything else.
"""
myDepends = dependentsOf(self.__class__)
#XXX optimize?
for dc in self.store.query(_DependencyConnector,
... | def function[installedUniqueRequirements, parameter[self, target]]:
constant[
Return an iterable of things installed on the target that this item
requires and are not required by anything else.
]
variable[myDepends] assign[=] call[name[dependentsOf], parameter[name[self].__class__]]
... | keyword[def] identifier[installedUniqueRequirements] ( identifier[self] , identifier[target] ):
literal[string]
identifier[myDepends] = identifier[dependentsOf] ( identifier[self] . identifier[__class__] )
keyword[for] identifier[dc] keyword[in] identifier[self] . identifier[store] . identifi... | def installedUniqueRequirements(self, target):
"""
Return an iterable of things installed on the target that this item
requires and are not required by anything else.
"""
myDepends = dependentsOf(self.__class__)
#XXX optimize?
for dc in self.store.query(_DependencyConnector, _DependencyConne... |
def dicom_to_nifti(dicom_input, output_file):
"""
This function will convert an anatomical dicom series to a nifti
Examples: See unit test
:param output_file: filepath to the output nifti
:param dicom_input: directory with the dicom files for a single scan, or list of read in dicoms
"""
if... | def function[dicom_to_nifti, parameter[dicom_input, output_file]]:
constant[
This function will convert an anatomical dicom series to a nifti
Examples: See unit test
:param output_file: filepath to the output nifti
:param dicom_input: directory with the dicom files for a single scan, or list o... | keyword[def] identifier[dicom_to_nifti] ( identifier[dicom_input] , identifier[output_file] ):
literal[string]
keyword[if] identifier[len] ( identifier[dicom_input] )<= literal[int] :
keyword[raise] identifier[ConversionError] ( literal[string] )
identifier[dicom_input] = identifi... | def dicom_to_nifti(dicom_input, output_file):
"""
This function will convert an anatomical dicom series to a nifti
Examples: See unit test
:param output_file: filepath to the output nifti
:param dicom_input: directory with the dicom files for a single scan, or list of read in dicoms
"""
if... |
async def _handle_bad_notification(self, message):
"""
Adjusts the current state to be correct based on the
received bad message notification whenever possible:
bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int
error_code:int = BadMsgNotification;
"... | <ast.AsyncFunctionDef object at 0x7da1b21db5b0> | keyword[async] keyword[def] identifier[_handle_bad_notification] ( identifier[self] , identifier[message] ):
literal[string]
identifier[bad_msg] = identifier[message] . identifier[obj]
identifier[states] = identifier[self] . identifier[_pop_states] ( identifier[bad_msg] . identifier[bad_... | async def _handle_bad_notification(self, message):
"""
Adjusts the current state to be correct based on the
received bad message notification whenever possible:
bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int
error_code:int = BadMsgNotification;
"""
... |
def context_changed(self, context):
""" :type context: dict """
self._image.set_cmap(context['colormap'])
self._image.set_clim(context['min'], context['max'])
self._image.set_interpolation(context['interpolation'])
self._update_indicators(context)
self._set_view_limits()... | def function[context_changed, parameter[self, context]]:
constant[ :type context: dict ]
call[name[self]._image.set_cmap, parameter[call[name[context]][constant[colormap]]]]
call[name[self]._image.set_clim, parameter[call[name[context]][constant[min]], call[name[context]][constant[max]]]]
... | keyword[def] identifier[context_changed] ( identifier[self] , identifier[context] ):
literal[string]
identifier[self] . identifier[_image] . identifier[set_cmap] ( identifier[context] [ literal[string] ])
identifier[self] . identifier[_image] . identifier[set_clim] ( identifier[context] [ ... | def context_changed(self, context):
""" :type context: dict """
self._image.set_cmap(context['colormap'])
self._image.set_clim(context['min'], context['max'])
self._image.set_interpolation(context['interpolation'])
self._update_indicators(context)
self._set_view_limits()
if self._model.index... |
def _retrieve_resources(self, url, class_, full):
'''Retrieve HTTP resources, return related objects (with pagination)'''
objects_to_return = []
response = self.session.get(url)
if response.status_code == 200:
result = response.json()
resources = result['results']... | def function[_retrieve_resources, parameter[self, url, class_, full]]:
constant[Retrieve HTTP resources, return related objects (with pagination)]
variable[objects_to_return] assign[=] list[[]]
variable[response] assign[=] call[name[self].session.get, parameter[name[url]]]
if compare[nam... | keyword[def] identifier[_retrieve_resources] ( identifier[self] , identifier[url] , identifier[class_] , identifier[full] ):
literal[string]
identifier[objects_to_return] =[]
identifier[response] = identifier[self] . identifier[session] . identifier[get] ( identifier[url] )
keywor... | def _retrieve_resources(self, url, class_, full):
"""Retrieve HTTP resources, return related objects (with pagination)"""
objects_to_return = []
response = self.session.get(url)
if response.status_code == 200:
result = response.json()
resources = result['results']
objects_to_retu... |
def get_revoked(self):
"""
Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tup... | def function[get_revoked, parameter[self]]:
constant[
Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
... | keyword[def] identifier[get_revoked] ( identifier[self] ):
literal[string]
identifier[results] =[]
identifier[revoked_stack] = identifier[_lib] . identifier[X509_CRL_get_REVOKED] ( identifier[self] . identifier[_crl] )
keyword[for] identifier[i] keyword[in] identifier[range] ( ... | def get_revoked(self):
"""
Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tuple` ... |
def clear_first_angle_projection(self):
"""stub"""
if (self.get_first_angle_projection_metadata().is_read_only() or
self.get_first_angle_projection_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['firstAngle'] = \
self._first_a... | def function[clear_first_angle_projection, parameter[self]]:
constant[stub]
if <ast.BoolOp object at 0x7da20c6a9b10> begin[:]
<ast.Raise object at 0x7da20e955bd0>
call[name[self].my_osid_object_form._my_map][constant[firstAngle]] assign[=] call[call[name[self]._first_angle_metadata][cons... | keyword[def] identifier[clear_first_angle_projection] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[get_first_angle_projection_metadata] (). identifier[is_read_only] () keyword[or]
identifier[self] . identifier[get_first_angle_projection_metadata] (). i... | def clear_first_angle_projection(self):
"""stub"""
if self.get_first_angle_projection_metadata().is_read_only() or self.get_first_angle_projection_metadata().is_required():
raise NoAccess() # depends on [control=['if'], data=[]]
self.my_osid_object_form._my_map['firstAngle'] = self._first_angle_met... |
def userinfo_claims_only_specified_when_access_token_is_issued(authentication_request):
"""
According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter">
"OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST
also use a response_typ... | def function[userinfo_claims_only_specified_when_access_token_is_issued, parameter[authentication_request]]:
constant[
According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter">
"OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request M... | keyword[def] identifier[userinfo_claims_only_specified_when_access_token_is_issued] ( identifier[authentication_request] ):
literal[string]
identifier[will_issue_access_token] = identifier[authentication_request] [ literal[string] ]!=[ literal[string] ]
identifier[contains_userinfo_claims_request] = l... | def userinfo_claims_only_specified_when_access_token_is_issued(authentication_request):
"""
According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter">
"OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST
also use a response_typ... |
def _get_session(self):
"""
S3 Boto3 Session.
Returns:
boto3.session.Session: session
"""
if self._session is None:
self._session = _boto3.session.Session(
**self._storage_parameters.get('session', dict()))
return self._session | def function[_get_session, parameter[self]]:
constant[
S3 Boto3 Session.
Returns:
boto3.session.Session: session
]
if compare[name[self]._session is constant[None]] begin[:]
name[self]._session assign[=] call[name[_boto3].session.Session, parameter[]]... | keyword[def] identifier[_get_session] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_session] keyword[is] keyword[None] :
identifier[self] . identifier[_session] = identifier[_boto3] . identifier[session] . identifier[Session] (
** ident... | def _get_session(self):
"""
S3 Boto3 Session.
Returns:
boto3.session.Session: session
"""
if self._session is None:
self._session = _boto3.session.Session(**self._storage_parameters.get('session', dict())) # depends on [control=['if'], data=[]]
return self._sess... |
def decrypt(self, data):
"""
Decrypt the data. Also, update the cipher iv. This is needed for SSLv3
and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.pre_dissect().
If we lack the key, we raise a CipherError which contains the input.
"""
if False in six.itervalues(se... | def function[decrypt, parameter[self, data]]:
constant[
Decrypt the data. Also, update the cipher iv. This is needed for SSLv3
and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.pre_dissect().
If we lack the key, we raise a CipherError which contains the input.
]
if c... | keyword[def] identifier[decrypt] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[False] keyword[in] identifier[six] . identifier[itervalues] ( identifier[self] . identifier[ready] ):
keyword[raise] identifier[CipherError] ( identifier[data] )
i... | def decrypt(self, data):
"""
Decrypt the data. Also, update the cipher iv. This is needed for SSLv3
and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.pre_dissect().
If we lack the key, we raise a CipherError which contains the input.
"""
if False in six.itervalues(self.ready... |
def _custom_rdd_reduce(self, reduce_func):
"""Provides a custom RDD reduce which preserves ordering if the RDD has
been sorted. This is useful for us because we need this functionality
as many pandas operations support sorting the results. The standard
reduce in PySpark does not have thi... | def function[_custom_rdd_reduce, parameter[self, reduce_func]]:
constant[Provides a custom RDD reduce which preserves ordering if the RDD has
been sorted. This is useful for us because we need this functionality
as many pandas operations support sorting the results. The standard
reduce i... | keyword[def] identifier[_custom_rdd_reduce] ( identifier[self] , identifier[reduce_func] ):
literal[string]
keyword[def] identifier[accumulating_iter] ( identifier[iterator] ):
identifier[acc] = keyword[None]
keyword[for] identifier[obj] keyword[in] identifier[iterato... | def _custom_rdd_reduce(self, reduce_func):
"""Provides a custom RDD reduce which preserves ordering if the RDD has
been sorted. This is useful for us because we need this functionality
as many pandas operations support sorting the results. The standard
reduce in PySpark does not have this pr... |
def _compute_linear_weights_edge(idcs, ndist):
"""Helper for linear interpolation."""
# Get out-of-bounds indices from the norm_distances. Negative
# means "too low", larger than or equal to 1 means "too high"
lo = np.where(ndist < 0)
hi = np.where(ndist > 1)
# For "too low" nodes, the lower ne... | def function[_compute_linear_weights_edge, parameter[idcs, ndist]]:
constant[Helper for linear interpolation.]
variable[lo] assign[=] call[name[np].where, parameter[compare[name[ndist] less[<] constant[0]]]]
variable[hi] assign[=] call[name[np].where, parameter[compare[name[ndist] greater[>] con... | keyword[def] identifier[_compute_linear_weights_edge] ( identifier[idcs] , identifier[ndist] ):
literal[string]
identifier[lo] = identifier[np] . identifier[where] ( identifier[ndist] < literal[int] )
identifier[hi] = identifier[np] . identifier[where] ( identifier[ndist] > literal[int] )
... | def _compute_linear_weights_edge(idcs, ndist):
"""Helper for linear interpolation."""
# Get out-of-bounds indices from the norm_distances. Negative
# means "too low", larger than or equal to 1 means "too high"
lo = np.where(ndist < 0)
hi = np.where(ndist > 1)
# For "too low" nodes, the lower nei... |
def positiveints(value):
"""
>>> positiveints('1, -1')
Traceback (most recent call last):
...
ValueError: -1 is negative in '1, -1'
"""
ints = integers(value)
for val in ints:
if val < 0:
raise ValueError('%d is negative in %r' % (val, value))
return ints | def function[positiveints, parameter[value]]:
constant[
>>> positiveints('1, -1')
Traceback (most recent call last):
...
ValueError: -1 is negative in '1, -1'
]
variable[ints] assign[=] call[name[integers], parameter[name[value]]]
for taget[name[val]] in starred[name[ints]... | keyword[def] identifier[positiveints] ( identifier[value] ):
literal[string]
identifier[ints] = identifier[integers] ( identifier[value] )
keyword[for] identifier[val] keyword[in] identifier[ints] :
keyword[if] identifier[val] < literal[int] :
keyword[raise] identifier[Value... | def positiveints(value):
"""
>>> positiveints('1, -1')
Traceback (most recent call last):
...
ValueError: -1 is negative in '1, -1'
"""
ints = integers(value)
for val in ints:
if val < 0:
raise ValueError('%d is negative in %r' % (val, value)) # depends on [contro... |
def activate_crontab(self):
"""Activate polling function and register first crontab
"""
self._crontab = []
if hasattr(self, 'CRONTAB'):
for crontab_spec in self.CRONTAB:
args = cronjob.parse_crontab(crontab_spec)
job = cronjob.CronJob()
... | def function[activate_crontab, parameter[self]]:
constant[Activate polling function and register first crontab
]
name[self]._crontab assign[=] list[[]]
if call[name[hasattr], parameter[name[self], constant[CRONTAB]]] begin[:]
for taget[name[crontab_spec]] in starred[name[... | keyword[def] identifier[activate_crontab] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_crontab] =[]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[for] identifier[crontab_spec] keyword[in] identifier[self] . identifi... | def activate_crontab(self):
"""Activate polling function and register first crontab
"""
self._crontab = []
if hasattr(self, 'CRONTAB'):
for crontab_spec in self.CRONTAB:
args = cronjob.parse_crontab(crontab_spec)
job = cronjob.CronJob()
if args['_timer'] =... |
def until_not_synced(self, timeout=None):
"""Return a tornado Future; resolves when any subordinate client is not synced"""
yield until_any(*[r.until_not_synced() for r in dict.values(self.children)],
timeout=timeout) | def function[until_not_synced, parameter[self, timeout]]:
constant[Return a tornado Future; resolves when any subordinate client is not synced]
<ast.Yield object at 0x7da1b05db3a0> | keyword[def] identifier[until_not_synced] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[yield] identifier[until_any] (*[ identifier[r] . identifier[until_not_synced] () keyword[for] identifier[r] keyword[in] identifier[dict] . identifier[values] ( identifie... | def until_not_synced(self, timeout=None):
"""Return a tornado Future; resolves when any subordinate client is not synced"""
yield until_any(*[r.until_not_synced() for r in dict.values(self.children)], timeout=timeout) |
def gfdist(target, abcorr, obsrvr, relate, refval, adjust, step, nintvls,
cnfine, result=None):
"""
Return the time window over which a specified constraint on
observer-target distance is met.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfdist_c.html
:param target: Name of t... | def function[gfdist, parameter[target, abcorr, obsrvr, relate, refval, adjust, step, nintvls, cnfine, result]]:
constant[
Return the time window over which a specified constraint on
observer-target distance is met.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfdist_c.html
:param ta... | keyword[def] identifier[gfdist] ( identifier[target] , identifier[abcorr] , identifier[obsrvr] , identifier[relate] , identifier[refval] , identifier[adjust] , identifier[step] , identifier[nintvls] ,
identifier[cnfine] , identifier[result] = keyword[None] ):
literal[string]
keyword[assert] identifier[is... | def gfdist(target, abcorr, obsrvr, relate, refval, adjust, step, nintvls, cnfine, result=None):
"""
Return the time window over which a specified constraint on
observer-target distance is met.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfdist_c.html
:param target: Name of the target b... |
def get_map(self):
"""
Collects all the points coordinates from this ``pyny.Space``
instance.
In order to keep the reference, it returns an index with the
following key:
* The first column is the Place.
* The second column is the... | def function[get_map, parameter[self]]:
constant[
Collects all the points coordinates from this ``pyny.Space``
instance.
In order to keep the reference, it returns an index with the
following key:
* The first column is the Place.
* The se... | keyword[def] identifier[get_map] ( identifier[self] ):
literal[string]
identifier[seed] = identifier[self] . identifier[get_seed] ()[ literal[string] ]
identifier[points] =[]
identifier[index] =[]
keyword[for] identifier[i] , identifier[place] keyword[in] identi... | def get_map(self):
"""
Collects all the points coordinates from this ``pyny.Space``
instance.
In order to keep the reference, it returns an index with the
following key:
* The first column is the Place.
* The second column is the body (-1: po... |
def _add_signal_history(self, df, symbol):
""" Initilize signal history """
if symbol not in self.signals.keys() or len(self.signals[symbol]) == 0:
self.signals[symbol] = [nan] * len(df.index)
else:
self.signals[symbol].append(nan)
self.signals[symbol] = self.sig... | def function[_add_signal_history, parameter[self, df, symbol]]:
constant[ Initilize signal history ]
if <ast.BoolOp object at 0x7da204622230> begin[:]
call[name[self].signals][name[symbol]] assign[=] binary_operation[list[[<ast.Name object at 0x7da20c7c9a50>]] * call[name[len], parameter... | keyword[def] identifier[_add_signal_history] ( identifier[self] , identifier[df] , identifier[symbol] ):
literal[string]
keyword[if] identifier[symbol] keyword[not] keyword[in] identifier[self] . identifier[signals] . identifier[keys] () keyword[or] identifier[len] ( identifier[self] . identif... | def _add_signal_history(self, df, symbol):
""" Initilize signal history """
if symbol not in self.signals.keys() or len(self.signals[symbol]) == 0:
self.signals[symbol] = [nan] * len(df.index) # depends on [control=['if'], data=[]]
else:
self.signals[symbol].append(nan)
self.signals[sym... |
def check_file_size(file_size, path):
"""
Raise an error if we didn't get all of the file.
:param file_size: int: size of this file
:param path: str path where we downloaded the file to
"""
stat_info = os.stat(path)
if stat_info.st_size != file_size:
f... | def function[check_file_size, parameter[file_size, path]]:
constant[
Raise an error if we didn't get all of the file.
:param file_size: int: size of this file
:param path: str path where we downloaded the file to
]
variable[stat_info] assign[=] call[name[os].stat, paramet... | keyword[def] identifier[check_file_size] ( identifier[file_size] , identifier[path] ):
literal[string]
identifier[stat_info] = identifier[os] . identifier[stat] ( identifier[path] )
keyword[if] identifier[stat_info] . identifier[st_size] != identifier[file_size] :
identifier[... | def check_file_size(file_size, path):
"""
Raise an error if we didn't get all of the file.
:param file_size: int: size of this file
:param path: str path where we downloaded the file to
"""
stat_info = os.stat(path)
if stat_info.st_size != file_size:
format_str = 'Err... |
def get_environments():
"""
:return: all knows environments
"""
LOGGER.debug("EnvironmentService.get_environments")
args = {'http_operation': 'GET', 'operation_path': ''}
response = EnvironmentService.requester.call(args)
ret = None
if response.rc == 0:
... | def function[get_environments, parameter[]]:
constant[
:return: all knows environments
]
call[name[LOGGER].debug, parameter[constant[EnvironmentService.get_environments]]]
variable[args] assign[=] dictionary[[<ast.Constant object at 0x7da1b1450b80>, <ast.Constant object at 0x7da1... | keyword[def] identifier[get_environments] ():
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
identifier[args] ={ literal[string] : literal[string] , literal[string] : literal[string] }
identifier[response] = identifier[EnvironmentService] . identifier[r... | def get_environments():
"""
:return: all knows environments
"""
LOGGER.debug('EnvironmentService.get_environments')
args = {'http_operation': 'GET', 'operation_path': ''}
response = EnvironmentService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
f... |
def _handle_end_node(self):
"""
Handle closing node element
"""
self._result.append(Node(result=self._result, **self._curr))
self._curr = {} | def function[_handle_end_node, parameter[self]]:
constant[
Handle closing node element
]
call[name[self]._result.append, parameter[call[name[Node], parameter[]]]]
name[self]._curr assign[=] dictionary[[], []] | keyword[def] identifier[_handle_end_node] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_result] . identifier[append] ( identifier[Node] ( identifier[result] = identifier[self] . identifier[_result] ,** identifier[self] . identifier[_curr] ))
identifier[self] . identi... | def _handle_end_node(self):
"""
Handle closing node element
"""
self._result.append(Node(result=self._result, **self._curr))
self._curr = {} |
def _gen_identity(self, key, param=None):
"""generate identity according to key and param given"""
if self.identity_generator and param is not None:
if self.serializer:
param = self.serializer.serialize(param)
if self.compressor:
param = self.compr... | def function[_gen_identity, parameter[self, key, param]]:
constant[generate identity according to key and param given]
if <ast.BoolOp object at 0x7da1b07cee00> begin[:]
if name[self].serializer begin[:]
variable[param] assign[=] call[name[self].serializer.serializ... | keyword[def] identifier[_gen_identity] ( identifier[self] , identifier[key] , identifier[param] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[identity_generator] keyword[and] identifier[param] keyword[is] keyword[not] keyword[None] :
keyword[if] id... | def _gen_identity(self, key, param=None):
"""generate identity according to key and param given"""
if self.identity_generator and param is not None:
if self.serializer:
param = self.serializer.serialize(param) # depends on [control=['if'], data=[]]
if self.compressor:
pa... |
def attach_hardware(self, ticket_id=None, hardware_id=None):
"""Attach hardware to a ticket.
:param integer ticket_id: the id of the ticket to attach to
:param integer hardware_id: the id of the hardware to attach
:returns: dict -- The new ticket attachment
"""
return s... | def function[attach_hardware, parameter[self, ticket_id, hardware_id]]:
constant[Attach hardware to a ticket.
:param integer ticket_id: the id of the ticket to attach to
:param integer hardware_id: the id of the hardware to attach
:returns: dict -- The new ticket attachment
]
... | keyword[def] identifier[attach_hardware] ( identifier[self] , identifier[ticket_id] = keyword[None] , identifier[hardware_id] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[ticket] . identifier[addAttachedHardware] ( identifier[hardware_id] , identifier[id] = iden... | def attach_hardware(self, ticket_id=None, hardware_id=None):
"""Attach hardware to a ticket.
:param integer ticket_id: the id of the ticket to attach to
:param integer hardware_id: the id of the hardware to attach
:returns: dict -- The new ticket attachment
"""
return self.tick... |
def update_instance(InstanceId=None, LayerIds=None, InstanceType=None, AutoScalingType=None, Hostname=None, Os=None, AmiId=None, SshKeyName=None, Architecture=None, InstallUpdatesOnBoot=None, EbsOptimized=None, AgentVersion=None):
"""
Updates a specified instance.
See also: AWS API Documentation
... | def function[update_instance, parameter[InstanceId, LayerIds, InstanceType, AutoScalingType, Hostname, Os, AmiId, SshKeyName, Architecture, InstallUpdatesOnBoot, EbsOptimized, AgentVersion]]:
constant[
Updates a specified instance.
See also: AWS API Documentation
:example: response = clien... | keyword[def] identifier[update_instance] ( identifier[InstanceId] = keyword[None] , identifier[LayerIds] = keyword[None] , identifier[InstanceType] = keyword[None] , identifier[AutoScalingType] = keyword[None] , identifier[Hostname] = keyword[None] , identifier[Os] = keyword[None] , identifier[AmiId] = keyword[None] ... | def update_instance(InstanceId=None, LayerIds=None, InstanceType=None, AutoScalingType=None, Hostname=None, Os=None, AmiId=None, SshKeyName=None, Architecture=None, InstallUpdatesOnBoot=None, EbsOptimized=None, AgentVersion=None):
"""
Updates a specified instance.
See also: AWS API Documentation
... |
def report_exception(self, filename, exc):
"""
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception.
"""
# Build fake event.
event = AbinitError(src_file="Unknown", src_line=0, mess... | def function[report_exception, parameter[self, filename, exc]]:
constant[
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception.
]
variable[event] assign[=] call[name[AbinitError], parameter... | keyword[def] identifier[report_exception] ( identifier[self] , identifier[filename] , identifier[exc] ):
literal[string]
identifier[event] = identifier[AbinitError] ( identifier[src_file] = literal[string] , identifier[src_line] = literal[int] , identifier[message] = identifier[str] ( iden... | def report_exception(self, filename, exc):
"""
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception.
"""
# Build fake event.
event = AbinitError(src_file='Unknown', src_line=0, message=str(exc)... |
def get_goone2ntletter(self, go2dcnt, depth2goobjs):
"""Assign letters to depth-01 GO terms ordered using descendants cnt."""
# 1. Group level-01/depth-01 GO terms by namespace
ns2dcntgoobj = cx.defaultdict(list)
for goobj in depth2goobjs[1]:
dcnt = go2dcnt[goobj.id]
... | def function[get_goone2ntletter, parameter[self, go2dcnt, depth2goobjs]]:
constant[Assign letters to depth-01 GO terms ordered using descendants cnt.]
variable[ns2dcntgoobj] assign[=] call[name[cx].defaultdict, parameter[name[list]]]
for taget[name[goobj]] in starred[call[name[depth2goobjs]][con... | keyword[def] identifier[get_goone2ntletter] ( identifier[self] , identifier[go2dcnt] , identifier[depth2goobjs] ):
literal[string]
identifier[ns2dcntgoobj] = identifier[cx] . identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[goobj] keyword[in] identifier[dept... | def get_goone2ntletter(self, go2dcnt, depth2goobjs):
"""Assign letters to depth-01 GO terms ordered using descendants cnt."""
# 1. Group level-01/depth-01 GO terms by namespace
ns2dcntgoobj = cx.defaultdict(list)
for goobj in depth2goobjs[1]:
dcnt = go2dcnt[goobj.id]
ns2dcntgoobj[goobj.n... |
def config_value_changed(option):
"""
Determine if config value changed since last call to this function.
"""
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved ... | def function[config_value_changed, parameter[option]]:
constant[
Determine if config value changed since last call to this function.
]
variable[hook_data] assign[=] call[name[unitdata].HookData, parameter[]]
with call[name[hook_data], parameter[]] begin[:]
variable[db] as... | keyword[def] identifier[config_value_changed] ( identifier[option] ):
literal[string]
identifier[hook_data] = identifier[unitdata] . identifier[HookData] ()
keyword[with] identifier[hook_data] ():
identifier[db] = identifier[unitdata] . identifier[kv] ()
identifier[current] = identi... | def config_value_changed(option):
"""
Determine if config value changed since last call to this function.
"""
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved ... |
def site_info(request):
'''Expose the site's info to templates'''
site = get_current_site(request)
context = {
'WAFER_CONFERENCE_NAME': site.name,
'WAFER_CONFERENCE_DOMAIN': site.domain,
}
return context | def function[site_info, parameter[request]]:
constant[Expose the site's info to templates]
variable[site] assign[=] call[name[get_current_site], parameter[name[request]]]
variable[context] assign[=] dictionary[[<ast.Constant object at 0x7da1b0ebee90>, <ast.Constant object at 0x7da1b0ebdea0>], [<... | keyword[def] identifier[site_info] ( identifier[request] ):
literal[string]
identifier[site] = identifier[get_current_site] ( identifier[request] )
identifier[context] ={
literal[string] : identifier[site] . identifier[name] ,
literal[string] : identifier[site] . identifier[domain] ,
}
... | def site_info(request):
"""Expose the site's info to templates"""
site = get_current_site(request)
context = {'WAFER_CONFERENCE_NAME': site.name, 'WAFER_CONFERENCE_DOMAIN': site.domain}
return context |
def _enforce_space(self, item):
"""Enforce a space in certain situations.
There are cases where we will want a space where normally we
wouldn't put one. This just enforces the addition of a space.
"""
if isinstance(self._lines[-1],
(self._Space, self._Line... | def function[_enforce_space, parameter[self, item]]:
constant[Enforce a space in certain situations.
There are cases where we will want a space where normally we
wouldn't put one. This just enforces the addition of a space.
]
if call[name[isinstance], parameter[call[name[self].... | keyword[def] identifier[_enforce_space] ( identifier[self] , identifier[item] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[_lines] [- literal[int] ],
( identifier[self] . identifier[_Space] , identifier[self] . identifier[_LineBreak] , identifier[se... | def _enforce_space(self, item):
"""Enforce a space in certain situations.
There are cases where we will want a space where normally we
wouldn't put one. This just enforces the addition of a space.
"""
if isinstance(self._lines[-1], (self._Space, self._LineBreak, self._Indent)):
... |
def get_template(template_name,fields=None):
'''get_template will return a template in the template folder,
with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"}
'''
template = None
if not template_name.endswith('.html'):
template_name = "%s.html" %(template_name)
here = "%... | def function[get_template, parameter[template_name, fields]]:
constant[get_template will return a template in the template folder,
with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"}
]
variable[template] assign[=] constant[None]
if <ast.UnaryOp object at 0x7da1b2344850> b... | keyword[def] identifier[get_template] ( identifier[template_name] , identifier[fields] = keyword[None] ):
literal[string]
identifier[template] = keyword[None]
keyword[if] keyword[not] identifier[template_name] . identifier[endswith] ( literal[string] ):
identifier[template_name] = literal[... | def get_template(template_name, fields=None):
"""get_template will return a template in the template folder,
with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"}
"""
template = None
if not template_name.endswith('.html'):
template_name = '%s.html' % template_name # depends on... |
def instantiate(self, params, auth=None):
"""
Allows you to fetch the map tiles of a created map
:param params: The json with the styling info for the named map
:param auth: The auth client
:type params: dict
:type auth: :class:`carto.auth.APIKeyAuthClient`
:ret... | def function[instantiate, parameter[self, params, auth]]:
constant[
Allows you to fetch the map tiles of a created map
:param params: The json with the styling info for the named map
:param auth: The auth client
:type params: dict
:type auth: :class:`carto.auth.APIKeyAut... | keyword[def] identifier[instantiate] ( identifier[self] , identifier[params] , identifier[auth] = keyword[None] ):
literal[string]
keyword[try] :
identifier[endpoint] =( identifier[self] . identifier[Meta] . identifier[collection_endpoint]
+ literal[string] ). identifier[f... | def instantiate(self, params, auth=None):
"""
Allows you to fetch the map tiles of a created map
:param params: The json with the styling info for the named map
:param auth: The auth client
:type params: dict
:type auth: :class:`carto.auth.APIKeyAuthClient`
:return:... |
def recv_match(self, condition=None, type=None, blocking=False):
'''recv the next message that matches the given condition
type can be a string or a list of strings'''
if type is not None and not isinstance(type, list):
type = [type]
while True:
m = self.recv_msg(... | def function[recv_match, parameter[self, condition, type, blocking]]:
constant[recv the next message that matches the given condition
type can be a string or a list of strings]
if <ast.BoolOp object at 0x7da1b2345720> begin[:]
variable[type] assign[=] list[[<ast.Name object at 0x... | keyword[def] identifier[recv_match] ( identifier[self] , identifier[condition] = keyword[None] , identifier[type] = keyword[None] , identifier[blocking] = keyword[False] ):
literal[string]
keyword[if] identifier[type] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifie... | def recv_match(self, condition=None, type=None, blocking=False):
"""recv the next message that matches the given condition
type can be a string or a list of strings"""
if type is not None and (not isinstance(type, list)):
type = [type] # depends on [control=['if'], data=[]]
while True:
... |
def _getOutputElegant(self, **kws):
""" get results from elegant output according to the given keywords,
input parameter format: key = sdds field name tuple, e.g.:
available keywords are:
- 'file': sdds fielname, file = test.sig
- 'data': data array, data = (... | def function[_getOutputElegant, parameter[self]]:
constant[ get results from elegant output according to the given keywords,
input parameter format: key = sdds field name tuple, e.g.:
available keywords are:
- 'file': sdds fielname, file = test.sig
- 'data': dat... | keyword[def] identifier[_getOutputElegant] ( identifier[self] ,** identifier[kws] ):
literal[string]
identifier[datascript] = literal[string]
identifier[datapath] = identifier[self] . identifier[sim_path]
identifier[trajparam_list] = identifier[kws] [ literal[string] ]
... | def _getOutputElegant(self, **kws):
""" get results from elegant output according to the given keywords,
input parameter format: key = sdds field name tuple, e.g.:
available keywords are:
- 'file': sdds fielname, file = test.sig
- 'data': data array, data = ('s',... |
def hash(self, *args, **kwargs):
"""
:param args:
:param kwargs:
joiner - string to join values (args)
as_bytes - bool to return hash bytes instead of default int
:rtype: int|bytes
"""
joiner = kwargs.get('joiner', '').encode('utf-8')
as_by... | def function[hash, parameter[self]]:
constant[
:param args:
:param kwargs:
joiner - string to join values (args)
as_bytes - bool to return hash bytes instead of default int
:rtype: int|bytes
]
variable[joiner] assign[=] call[call[name[kwargs].get, ... | keyword[def] identifier[hash] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[joiner] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] ). identifier[encode] ( literal[string] )
identifier[as_bytes] = identifier[kwargs] .... | def hash(self, *args, **kwargs):
"""
:param args:
:param kwargs:
joiner - string to join values (args)
as_bytes - bool to return hash bytes instead of default int
:rtype: int|bytes
"""
joiner = kwargs.get('joiner', '').encode('utf-8')
as_bytes = kwargs... |
def show_event_analysis_dialog(self):
"""Create the event analysis dialog."""
self.event_analysis_dialog.update_types()
self.event_analysis_dialog.update_groups()
self.event_analysis_dialog.update_cycles()
self.event_analysis_dialog.show() | def function[show_event_analysis_dialog, parameter[self]]:
constant[Create the event analysis dialog.]
call[name[self].event_analysis_dialog.update_types, parameter[]]
call[name[self].event_analysis_dialog.update_groups, parameter[]]
call[name[self].event_analysis_dialog.update_cycles, p... | keyword[def] identifier[show_event_analysis_dialog] ( identifier[self] ):
literal[string]
identifier[self] . identifier[event_analysis_dialog] . identifier[update_types] ()
identifier[self] . identifier[event_analysis_dialog] . identifier[update_groups] ()
identifier[self] . ident... | def show_event_analysis_dialog(self):
"""Create the event analysis dialog."""
self.event_analysis_dialog.update_types()
self.event_analysis_dialog.update_groups()
self.event_analysis_dialog.update_cycles()
self.event_analysis_dialog.show() |
def address(cls, address, bits = None):
"""
@type address: int
@param address: Memory address.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@r... | def function[address, parameter[cls, address, bits]]:
constant[
@type address: int
@param address: Memory address.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.addre... | keyword[def] identifier[address] ( identifier[cls] , identifier[address] , identifier[bits] = keyword[None] ):
literal[string]
keyword[if] identifier[bits] keyword[is] keyword[None] :
identifier[address_size] = identifier[cls] . identifier[address_size]
identifier[bits... | def address(cls, address, bits=None):
"""
@type address: int
@param address: Memory address.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: ... |
def HEAD(self, *args, **kwargs):
""" HEAD request """
return self._handle_api(self.API_HEAD, args, kwargs) | def function[HEAD, parameter[self]]:
constant[ HEAD request ]
return[call[name[self]._handle_api, parameter[name[self].API_HEAD, name[args], name[kwargs]]]] | keyword[def] identifier[HEAD] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_handle_api] ( identifier[self] . identifier[API_HEAD] , identifier[args] , identifier[kwargs] ) | def HEAD(self, *args, **kwargs):
""" HEAD request """
return self._handle_api(self.API_HEAD, args, kwargs) |
def wr_txt_section_hdrgos(self, fout_txt, sortby=None, prt_section=True):
"""Write high GO IDs that are actually used to group current set of GO IDs."""
sec2d_go = self.grprobj.get_sections_2d() # lists of GO IDs
sec2d_nt = self.get_sections_2dnt(sec2d_go) # lists of GO Grouper namedtuples
... | def function[wr_txt_section_hdrgos, parameter[self, fout_txt, sortby, prt_section]]:
constant[Write high GO IDs that are actually used to group current set of GO IDs.]
variable[sec2d_go] assign[=] call[name[self].grprobj.get_sections_2d, parameter[]]
variable[sec2d_nt] assign[=] call[name[self].... | keyword[def] identifier[wr_txt_section_hdrgos] ( identifier[self] , identifier[fout_txt] , identifier[sortby] = keyword[None] , identifier[prt_section] = keyword[True] ):
literal[string]
identifier[sec2d_go] = identifier[self] . identifier[grprobj] . identifier[get_sections_2d] ()
identifi... | def wr_txt_section_hdrgos(self, fout_txt, sortby=None, prt_section=True):
"""Write high GO IDs that are actually used to group current set of GO IDs."""
sec2d_go = self.grprobj.get_sections_2d() # lists of GO IDs
sec2d_nt = self.get_sections_2dnt(sec2d_go) # lists of GO Grouper namedtuples
if sortby i... |
def parse(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
... | def function[parse, parameter[text, encoding, handler]]:
constant[
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
... | keyword[def] identifier[parse] ( identifier[text] , identifier[encoding] = literal[string] , identifier[handler] = keyword[None] ,** identifier[defaults] ):
literal[string]
identifier[text] = identifier[u] ( identifier[text] , identifier[encoding] ). identifier[strip] ()
identifier[metadata... | def parse(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
... |
def get(api_code=None):
"""Get network statistics.
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Stats` class
"""
resource = 'stats?format=json'
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(... | def function[get, parameter[api_code]]:
constant[Get network statistics.
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Stats` class
]
variable[resource] assign[=] constant[stats?format=json]
if compare[name[api_code] is_not constant[Non... | keyword[def] identifier[get] ( identifier[api_code] = keyword[None] ):
literal[string]
identifier[resource] = literal[string]
keyword[if] identifier[api_code] keyword[is] keyword[not] keyword[None] :
identifier[resource] += literal[string] + identifier[api_code]
identifier[respons... | def get(api_code=None):
"""Get network statistics.
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Stats` class
"""
resource = 'stats?format=json'
if api_code is not None:
resource += '&api_code=' + api_code # depends on [control=['if'], dat... |
def observed(obj=None, **kwds):
"""
Decorator function to instantiate data objects.
If given a Stochastic, sets a the observed flag to True.
Can be used as
@observed
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
or as
@stochastic(observed=True)
... | def function[observed, parameter[obj]]:
constant[
Decorator function to instantiate data objects.
If given a Stochastic, sets a the observed flag to True.
Can be used as
@observed
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
or as
@stochast... | keyword[def] identifier[observed] ( identifier[obj] = keyword[None] ,** identifier[kwds] ):
literal[string]
keyword[if] identifier[obj] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[Stochastic] ):
identifier[obj] . ide... | def observed(obj=None, **kwds):
"""
Decorator function to instantiate data objects.
If given a Stochastic, sets a the observed flag to True.
Can be used as
@observed
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
or as
@stochastic(observed=True)
... |
def _event_func_names(self, event: str) -> List[str]:
""" Returns string name of each function subscribed to an event.
:param event: Name of the event.
:type event: str
:return: Names of functions subscribed to a specific event.
:rtype: list
"""
return [func.__n... | def function[_event_func_names, parameter[self, event]]:
constant[ Returns string name of each function subscribed to an event.
:param event: Name of the event.
:type event: str
:return: Names of functions subscribed to a specific event.
:rtype: list
]
return[<ast.L... | keyword[def] identifier[_event_func_names] ( identifier[self] , identifier[event] : identifier[str] )-> identifier[List] [ identifier[str] ]:
literal[string]
keyword[return] [ identifier[func] . identifier[__name__] keyword[for] identifier[func] keyword[in] identifier[self] . identifier[_events... | def _event_func_names(self, event: str) -> List[str]:
""" Returns string name of each function subscribed to an event.
:param event: Name of the event.
:type event: str
:return: Names of functions subscribed to a specific event.
:rtype: list
"""
return [func.__name__ fo... |
def generate_zip_data(M, L, n_cells, cluster_probs=None):
"""
Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parameters
n_cells (int)... | def function[generate_zip_data, parameter[M, L, n_cells, cluster_probs]]:
constant[
Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parame... | keyword[def] identifier[generate_zip_data] ( identifier[M] , identifier[L] , identifier[n_cells] , identifier[cluster_probs] = keyword[None] ):
literal[string]
identifier[genes] , identifier[clusters] = identifier[M] . identifier[shape]
identifier[output] = identifier[np] . identifier[zeros] (( ident... | def generate_zip_data(M, L, n_cells, cluster_probs=None):
"""
Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parameters
n_cells (int)... |
def get_free_voice(self, item):
""" Free voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
view = True
if item.get('perms', None):
view = self.check_user_permission(item.get('perms', []))
elif item.get('... | def function[get_free_voice, parameter[self, item]]:
constant[ Free voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
]
variable[view] assign[=] constant[True]
if call[name[item].get, parameter[constant[perms], constant[None]]]... | keyword[def] identifier[get_free_voice] ( identifier[self] , identifier[item] ):
literal[string]
identifier[view] = keyword[True]
keyword[if] identifier[item] . identifier[get] ( literal[string] , keyword[None] ):
identifier[view] = identifier[self] . identifier[check_user_p... | def get_free_voice(self, item):
""" Free voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
view = True
if item.get('perms', None):
view = self.check_user_permission(item.get('perms', [])) # depends on [control=['if'], data=[]]... |
def extract_log(rpath,extract=simple_attributes):
"""
Extracts Git commit test_data from a local repository.
:param rpath: The path to a local Git repo.
:param extract: A list of attribute name strings.
:return: A Pandas dataframe containing Git commit test_data.
"""
# Get repo
m_repo = ... | def function[extract_log, parameter[rpath, extract]]:
constant[
Extracts Git commit test_data from a local repository.
:param rpath: The path to a local Git repo.
:param extract: A list of attribute name strings.
:return: A Pandas dataframe containing Git commit test_data.
]
variable... | keyword[def] identifier[extract_log] ( identifier[rpath] , identifier[extract] = identifier[simple_attributes] ):
literal[string]
identifier[m_repo] = identifier[git] . identifier[Repo] ( identifier[rpath] )
identifier[count] = literal[int]
identifier[m_commits] = identifier[m_repo] .... | def extract_log(rpath, extract=simple_attributes):
"""
Extracts Git commit test_data from a local repository.
:param rpath: The path to a local Git repo.
:param extract: A list of attribute name strings.
:return: A Pandas dataframe containing Git commit test_data.
"""
# Get repo
m_repo =... |
def aggregate_hazard_summary(impact, aggregate_hazard):
"""Compute the summary from the source layer to the aggregate_hazard layer.
Source layer :
|exp_id|exp_class|haz_id|haz_class|aggr_id|aggr_name|affected|extra*|
Target layer :
| aggr_id | aggr_name | haz_id | haz_class | extra* |
Output ... | def function[aggregate_hazard_summary, parameter[impact, aggregate_hazard]]:
constant[Compute the summary from the source layer to the aggregate_hazard layer.
Source layer :
|exp_id|exp_class|haz_id|haz_class|aggr_id|aggr_name|affected|extra*|
Target layer :
| aggr_id | aggr_name | haz_id | ha... | keyword[def] identifier[aggregate_hazard_summary] ( identifier[impact] , identifier[aggregate_hazard] ):
literal[string]
identifier[source_fields] = identifier[impact] . identifier[keywords] [ literal[string] ]
identifier[target_fields] = identifier[aggregate_hazard] . identifier[keywords] [ literal[s... | def aggregate_hazard_summary(impact, aggregate_hazard):
"""Compute the summary from the source layer to the aggregate_hazard layer.
Source layer :
|exp_id|exp_class|haz_id|haz_class|aggr_id|aggr_name|affected|extra*|
Target layer :
| aggr_id | aggr_name | haz_id | haz_class | extra* |
Output ... |
def refresh_menu(self):
"""Refresh context menu"""
index = self.currentIndex()
condition = index.isValid()
self.edit_action.setEnabled( condition )
self.remove_action.setEnabled( condition )
self.refresh_plot_entries(index) | def function[refresh_menu, parameter[self]]:
constant[Refresh context menu]
variable[index] assign[=] call[name[self].currentIndex, parameter[]]
variable[condition] assign[=] call[name[index].isValid, parameter[]]
call[name[self].edit_action.setEnabled, parameter[name[condition]]]
... | keyword[def] identifier[refresh_menu] ( identifier[self] ):
literal[string]
identifier[index] = identifier[self] . identifier[currentIndex] ()
identifier[condition] = identifier[index] . identifier[isValid] ()
identifier[self] . identifier[edit_action] . identifier[setEnabled]... | def refresh_menu(self):
"""Refresh context menu"""
index = self.currentIndex()
condition = index.isValid()
self.edit_action.setEnabled(condition)
self.remove_action.setEnabled(condition)
self.refresh_plot_entries(index) |
def wtFromUTCpy(pyUTC, leapSecs=14):
"""convenience function:
allows to use python UTC times and
returns only week and tow"""
ymdhms = ymdhmsFromPyUTC(pyUTC)
wSowDSoD = apply(gpsFromUTC, ymdhms + (leapSecs,))
return wSowDSoD[0:2] | def function[wtFromUTCpy, parameter[pyUTC, leapSecs]]:
constant[convenience function:
allows to use python UTC times and
returns only week and tow]
variable[ymdhms] assign[=] call[name[ymdhmsFromPyUTC], parameter[name[pyUTC]]]
variable[wSowDSoD] assign[=] call[name[apply], para... | keyword[def] identifier[wtFromUTCpy] ( identifier[pyUTC] , identifier[leapSecs] = literal[int] ):
literal[string]
identifier[ymdhms] = identifier[ymdhmsFromPyUTC] ( identifier[pyUTC] )
identifier[wSowDSoD] = identifier[apply] ( identifier[gpsFromUTC] , identifier[ymdhms] +( identifier[leapSecs] ,))
... | def wtFromUTCpy(pyUTC, leapSecs=14):
"""convenience function:
allows to use python UTC times and
returns only week and tow"""
ymdhms = ymdhmsFromPyUTC(pyUTC)
wSowDSoD = apply(gpsFromUTC, ymdhms + (leapSecs,))
return wSowDSoD[0:2] |
def get_formatted_path(self, **kwargs):
"""
Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str
"""
self._validate_path_placeholders(self.path_placeholders, kwargs)
return self.pat... | def function[get_formatted_path, parameter[self]]:
constant[
Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str
]
call[name[self]._validate_path_placeholders, parameter[name[self].path_pla... | keyword[def] identifier[get_formatted_path] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_validate_path_placeholders] ( identifier[self] . identifier[path_placeholders] , identifier[kwargs] )
keyword[return] identifier[self] . identifier[path... | def get_formatted_path(self, **kwargs):
"""
Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str
"""
self._validate_path_placeholders(self.path_placeholders, kwargs)
return self.path.format(**kw... |
def _examine_key(self, key_name, key_val, p, i, option_parsing):
""" Examine the current matching key
Extracts information, such as function to execute and command
options, from the current key (passed to function as 'key_name' and
'key_val').
"""
# if the e... | def function[_examine_key, parameter[self, key_name, key_val, p, i, option_parsing]]:
constant[ Examine the current matching key
Extracts information, such as function to execute and command
options, from the current key (passed to function as 'key_name' and
'key_val').
... | keyword[def] identifier[_examine_key] ( identifier[self] , identifier[key_name] , identifier[key_val] , identifier[p] , identifier[i] , identifier[option_parsing] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[key_val] :
identifier[self] . identifier... | def _examine_key(self, key_name, key_val, p, i, option_parsing):
""" Examine the current matching key
Extracts information, such as function to execute and command
options, from the current key (passed to function as 'key_name' and
'key_val').
"""
# if the element we... |
def get_field_by_name(self, name):
"""
the field member matching name, or None if no such field is found
"""
for f in self.fields:
if f.get_name() == name:
return f
return None | def function[get_field_by_name, parameter[self, name]]:
constant[
the field member matching name, or None if no such field is found
]
for taget[name[f]] in starred[name[self].fields] begin[:]
if compare[call[name[f].get_name, parameter[]] equal[==] name[name]] begin[:]
... | keyword[def] identifier[get_field_by_name] ( identifier[self] , identifier[name] ):
literal[string]
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[fields] :
keyword[if] identifier[f] . identifier[get_name] ()== identifier[name] :
keyword[retu... | def get_field_by_name(self, name):
"""
the field member matching name, or None if no such field is found
"""
for f in self.fields:
if f.get_name() == name:
return f # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['f']]
return None |
def get_ptr(data, offset=None, ptr_type=ctypes.c_void_p):
"""Returns a void pointer to the data"""
ptr = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p)
if offset:
ptr = ctypes.c_void_p(ptr.value + offset)
if ptr_type != ctypes.c_void_p:
ptr = ctypes.cast(ptr, ptr_type)
return ... | def function[get_ptr, parameter[data, offset, ptr_type]]:
constant[Returns a void pointer to the data]
variable[ptr] assign[=] call[name[ctypes].cast, parameter[call[name[ctypes].pointer, parameter[name[data]]], name[ctypes].c_void_p]]
if name[offset] begin[:]
variable[ptr] assig... | keyword[def] identifier[get_ptr] ( identifier[data] , identifier[offset] = keyword[None] , identifier[ptr_type] = identifier[ctypes] . identifier[c_void_p] ):
literal[string]
identifier[ptr] = identifier[ctypes] . identifier[cast] ( identifier[ctypes] . identifier[pointer] ( identifier[data] ), identifier[... | def get_ptr(data, offset=None, ptr_type=ctypes.c_void_p):
"""Returns a void pointer to the data"""
ptr = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p)
if offset:
ptr = ctypes.c_void_p(ptr.value + offset) # depends on [control=['if'], data=[]]
if ptr_type != ctypes.c_void_p:
ptr = c... |
def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full | def function[is_full, parameter[cls, pid]]:
constant[Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
]
with name[cls]._lock begin[:]
call[name[cls]._ensure_pool_exists, parameter[name[pid]]]
return[call[nam... | keyword[def] identifier[is_full] ( identifier[cls] , identifier[pid] ):
literal[string]
keyword[with] identifier[cls] . identifier[_lock] :
identifier[cls] . identifier[_ensure_pool_exists] ( identifier[pid] )
keyword[return] identifier[cls] . identifier[_pools] [ identi... | def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full # depends on [control=['with'], data=[]] |
def select_extended_word(self, continuation_chars=('.',)):
"""
Performs extended word selection. Extended selection consists in
selecting the word under cursor and any other words that are linked
by a ``continuation_chars``.
:param continuation_chars: the list of characters that... | def function[select_extended_word, parameter[self, continuation_chars]]:
constant[
Performs extended word selection. Extended selection consists in
selecting the word under cursor and any other words that are linked
by a ``continuation_chars``.
:param continuation_chars: the lis... | keyword[def] identifier[select_extended_word] ( identifier[self] , identifier[continuation_chars] =( literal[string] ,)):
literal[string]
identifier[cursor] = identifier[self] . identifier[_editor] . identifier[textCursor] ()
identifier[original_pos] = identifier[cursor] . identifier[posit... | def select_extended_word(self, continuation_chars=('.',)):
"""
Performs extended word selection. Extended selection consists in
selecting the word under cursor and any other words that are linked
by a ``continuation_chars``.
:param continuation_chars: the list of characters that may... |
def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Outbound message
"""
# Look up subscriber
subscription_id = kwargs["subscription_id"]
if Subscription.objects.filter(id=subscription_id).exists():
status = 202
accept... | def function[post, parameter[self, request]]:
constant[ Validates subscription data before creating Outbound message
]
variable[subscription_id] assign[=] call[name[kwargs]][constant[subscription_id]]
if call[call[name[Subscription].objects.filter, parameter[]].exists, parameter[]] begin... | keyword[def] identifier[post] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[subscription_id] = identifier[kwargs] [ literal[string] ]
keyword[if] identifier[Subscription] . identifier[objects] . identifier[filter... | def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Outbound message
"""
# Look up subscriber
subscription_id = kwargs['subscription_id']
if Subscription.objects.filter(id=subscription_id).exists():
status = 202
accepted = {'accepted': True}
... |
def remove_duplicates(apps, schema_editor):
"""
Remove any duplicates from the entity relationship table
:param apps:
:param schema_editor:
:return:
"""
# Get the model
EntityRelationship = apps.get_model('entity', 'EntityRelationship')
# Find the duplicates
duplicates = Entity... | def function[remove_duplicates, parameter[apps, schema_editor]]:
constant[
Remove any duplicates from the entity relationship table
:param apps:
:param schema_editor:
:return:
]
variable[EntityRelationship] assign[=] call[name[apps].get_model, parameter[constant[entity], constant[Ent... | keyword[def] identifier[remove_duplicates] ( identifier[apps] , identifier[schema_editor] ):
literal[string]
identifier[EntityRelationship] = identifier[apps] . identifier[get_model] ( literal[string] , literal[string] )
identifier[duplicates] = identifier[EntityRelationship] . identifier[... | def remove_duplicates(apps, schema_editor):
"""
Remove any duplicates from the entity relationship table
:param apps:
:param schema_editor:
:return:
"""
# Get the model
EntityRelationship = apps.get_model('entity', 'EntityRelationship')
# Find the duplicates
duplicates = EntityRe... |
def register_device(ctx, device, model, nickname, client_type):
"""Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
hyphen (-), underscore (_), a... | def function[register_device, parameter[ctx, device, model, nickname, client_type]]:
constant[Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
... | keyword[def] identifier[register_device] ( identifier[ctx] , identifier[device] , identifier[model] , identifier[nickname] , identifier[client_type] ):
literal[string]
identifier[session] , identifier[api_url] , identifier[project_id] = identifier[build_client_from_context] ( identifier[ctx] )
identif... | def register_device(ctx, device, model, nickname, client_type):
"""Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
hyphen (-), underscore (_), a... |
def _find_devices_mac(self):
"""Find devices on Mac."""
self.keyboards.append(Keyboard(self))
self.mice.append(MightyMouse(self))
self.mice.append(Mouse(self)) | def function[_find_devices_mac, parameter[self]]:
constant[Find devices on Mac.]
call[name[self].keyboards.append, parameter[call[name[Keyboard], parameter[name[self]]]]]
call[name[self].mice.append, parameter[call[name[MightyMouse], parameter[name[self]]]]]
call[name[self].mice.append, ... | keyword[def] identifier[_find_devices_mac] ( identifier[self] ):
literal[string]
identifier[self] . identifier[keyboards] . identifier[append] ( identifier[Keyboard] ( identifier[self] ))
identifier[self] . identifier[mice] . identifier[append] ( identifier[MightyMouse] ( identifier[self] ... | def _find_devices_mac(self):
"""Find devices on Mac."""
self.keyboards.append(Keyboard(self))
self.mice.append(MightyMouse(self))
self.mice.append(Mouse(self)) |
def loglevel(level):
"""
Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
...
ValueError: None is no... | def function[loglevel, parameter[level]]:
constant[
Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
... | keyword[def] identifier[loglevel] ( identifier[level] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[level] , identifier[str] ):
identifier[level] = identifier[getattr] ( identifier[logging] , identifier[level] . identifier[upper] ())
keyword[elif] identifier[isinstance]... | def loglevel(level):
"""
Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
...
ValueError: None is no... |
async def verify_worker_impls(chain):
"""Verify the task type (e.g. decision, build) of each link in the chain.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure
"""
valid_worker_impls = get_valid_worker_impls()
for obj in chain.get_all_link... | <ast.AsyncFunctionDef object at 0x7da204565ff0> | keyword[async] keyword[def] identifier[verify_worker_impls] ( identifier[chain] ):
literal[string]
identifier[valid_worker_impls] = identifier[get_valid_worker_impls] ()
keyword[for] identifier[obj] keyword[in] identifier[chain] . identifier[get_all_links_in_chain] ():
identifier[worker_i... | async def verify_worker_impls(chain):
"""Verify the task type (e.g. decision, build) of each link in the chain.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure
"""
valid_worker_impls = get_valid_worker_impls()
for obj in chain.get_all_link... |
def get_child_directories(path):
"""Return names of immediate child directories"""
if not _is_valid_directory(path):
raise exceptions.InvalidDirectory
entries = os.listdir(path)
directory_names = []
for entry in entries:
abs_entry_path = os.path.join(path, entry)
if _is_val... | def function[get_child_directories, parameter[path]]:
constant[Return names of immediate child directories]
if <ast.UnaryOp object at 0x7da1b1643970> begin[:]
<ast.Raise object at 0x7da1b1641510>
variable[entries] assign[=] call[name[os].listdir, parameter[name[path]]]
variable[d... | keyword[def] identifier[get_child_directories] ( identifier[path] ):
literal[string]
keyword[if] keyword[not] identifier[_is_valid_directory] ( identifier[path] ):
keyword[raise] identifier[exceptions] . identifier[InvalidDirectory]
identifier[entries] = identifier[os] . identifier[listd... | def get_child_directories(path):
"""Return names of immediate child directories"""
if not _is_valid_directory(path):
raise exceptions.InvalidDirectory # depends on [control=['if'], data=[]]
entries = os.listdir(path)
directory_names = []
for entry in entries:
abs_entry_path = os.pat... |
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more tha... | <ast.AsyncFunctionDef object at 0x7da18f58c760> | keyword[async] keyword[def] identifier[close] ( identifier[self] ,* identifier[args] , identifier[_conn] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[start] = identifier[time] . identifier[monotonic] ()
identifier[ret] = keyword[await] identifier[self] . identifie... | async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than se... |
def process_npdu(self, npdu):
"""encode NPDUs from the service access point and send them downstream."""
if _debug: DeviceToDeviceClientService._debug("process_npdu %r", npdu)
# broadcast messages go to everyone
if npdu.pduDestination.addrType == Address.localBroadcastAddr:
... | def function[process_npdu, parameter[self, npdu]]:
constant[encode NPDUs from the service access point and send them downstream.]
if name[_debug] begin[:]
call[name[DeviceToDeviceClientService]._debug, parameter[constant[process_npdu %r], name[npdu]]]
if compare[name[npdu].pduDes... | keyword[def] identifier[process_npdu] ( identifier[self] , identifier[npdu] ):
literal[string]
keyword[if] identifier[_debug] : identifier[DeviceToDeviceClientService] . identifier[_debug] ( literal[string] , identifier[npdu] )
keyword[if] identifier[npdu] . identifier[pduDesti... | def process_npdu(self, npdu):
"""encode NPDUs from the service access point and send them downstream."""
if _debug:
DeviceToDeviceClientService._debug('process_npdu %r', npdu) # depends on [control=['if'], data=[]]
# broadcast messages go to everyone
if npdu.pduDestination.addrType == Address.l... |
def with_global_options(method):
"""Apply the global options that we desire on every method within
tower-cli to the given click command.
"""
# Create global options for the Tower host, username, and password.
#
# These are runtime options that will override the configuration file
# settings.... | def function[with_global_options, parameter[method]]:
constant[Apply the global options that we desire on every method within
tower-cli to the given click command.
]
variable[method] assign[=] call[call[name[click].option, parameter[constant[-h], constant[--tower-host]]], parameter[name[method]]... | keyword[def] identifier[with_global_options] ( identifier[method] ):
literal[string]
identifier[method] = identifier[click] . identifier[option] (
literal[string] , literal[string] ,
identifier[help] = literal[string]
literal[string]
literal[string]
literal[s... | def with_global_options(method):
"""Apply the global options that we desire on every method within
tower-cli to the given click command.
"""
# Create global options for the Tower host, username, and password.
#
# These are runtime options that will override the configuration file
# settings.... |
def safe_exit(output):
"""exit without breaking pipes."""
try:
sys.stdout.write(output)
sys.stdout.flush()
except IOError:
pass | def function[safe_exit, parameter[output]]:
constant[exit without breaking pipes.]
<ast.Try object at 0x7da1b27e33d0> | keyword[def] identifier[safe_exit] ( identifier[output] ):
literal[string]
keyword[try] :
identifier[sys] . identifier[stdout] . identifier[write] ( identifier[output] )
identifier[sys] . identifier[stdout] . identifier[flush] ()
keyword[except] identifier[IOError] :
keywor... | def safe_exit(output):
"""exit without breaking pipes."""
try:
sys.stdout.write(output)
sys.stdout.flush() # depends on [control=['try'], data=[]]
except IOError:
pass # depends on [control=['except'], data=[]] |
async def create_ffmpeg_player(self, filepath):
"""Creates a streamer that plays from a file"""
self.current_download_elapsed = 0
self.streamer = self.vclient.create_ffmpeg_player(filepath, after=self.vafter_ts)
self.state = "ready"
await self.setup_streamer()
try:
... | <ast.AsyncFunctionDef object at 0x7da1b1914e50> | keyword[async] keyword[def] identifier[create_ffmpeg_player] ( identifier[self] , identifier[filepath] ):
literal[string]
identifier[self] . identifier[current_download_elapsed] = literal[int]
identifier[self] . identifier[streamer] = identifier[self] . identifier[vclient] . identifier[... | async def create_ffmpeg_player(self, filepath):
"""Creates a streamer that plays from a file"""
self.current_download_elapsed = 0
self.streamer = self.vclient.create_ffmpeg_player(filepath, after=self.vafter_ts)
self.state = 'ready'
await self.setup_streamer()
try:
# Read from the info j... |
def set_mode_broodlord_params(
self, zerg_count=None,
vassal_overload_sos_interval=None, vassal_queue_items_sos=None):
"""This mode is a way for a vassal to ask for reinforcements to the Emperor.
Reinforcements are new vassals spawned on demand generally bound on the same socket... | def function[set_mode_broodlord_params, parameter[self, zerg_count, vassal_overload_sos_interval, vassal_queue_items_sos]]:
constant[This mode is a way for a vassal to ask for reinforcements to the Emperor.
Reinforcements are new vassals spawned on demand generally bound on the same socket.
..... | keyword[def] identifier[set_mode_broodlord_params] (
identifier[self] , identifier[zerg_count] = keyword[None] ,
identifier[vassal_overload_sos_interval] = keyword[None] , identifier[vassal_queue_items_sos] = keyword[None] ):
literal[string]
identifier[self] . identifier[_set] ( literal[string] ,... | def set_mode_broodlord_params(self, zerg_count=None, vassal_overload_sos_interval=None, vassal_queue_items_sos=None):
"""This mode is a way for a vassal to ask for reinforcements to the Emperor.
Reinforcements are new vassals spawned on demand generally bound on the same socket.
.. warning:: If yo... |
def pool(n=None, dummy=False):
"""
create a multiprocessing pool that responds to interrupts.
"""
if dummy:
from multiprocessing.dummy import Pool
else:
from multiprocessing import Pool
if n is None:
import multiprocessing
n = multiprocessing.cpu_count() - 1
... | def function[pool, parameter[n, dummy]]:
constant[
create a multiprocessing pool that responds to interrupts.
]
if name[dummy] begin[:]
from relative_module[multiprocessing.dummy] import module[Pool]
if compare[name[n] is constant[None]] begin[:]
import module[multiproces... | keyword[def] identifier[pool] ( identifier[n] = keyword[None] , identifier[dummy] = keyword[False] ):
literal[string]
keyword[if] identifier[dummy] :
keyword[from] identifier[multiprocessing] . identifier[dummy] keyword[import] identifier[Pool]
keyword[else] :
keyword[from] id... | def pool(n=None, dummy=False):
"""
create a multiprocessing pool that responds to interrupts.
"""
if dummy:
from multiprocessing.dummy import Pool # depends on [control=['if'], data=[]]
else:
from multiprocessing import Pool
if n is None:
import multiprocessing
n... |
def keysym_to_keycodes(self, keysym):
"""Look up all the keycodes that is bound to keysym. A list of
tuples (keycode, index) is returned, sorted primarily on the
lowest index and secondarily on the lowest keycode."""
try:
# Copy the map list, reversing the arguments
... | def function[keysym_to_keycodes, parameter[self, keysym]]:
constant[Look up all the keycodes that is bound to keysym. A list of
tuples (keycode, index) is returned, sorted primarily on the
lowest index and secondarily on the lowest keycode.]
<ast.Try object at 0x7da1b26ae320> | keyword[def] identifier[keysym_to_keycodes] ( identifier[self] , identifier[keysym] ):
literal[string]
keyword[try] :
keyword[return] identifier[map] ( keyword[lambda] identifier[x] :( identifier[x] [ literal[int] ], identifier[x] [ literal[int] ]), identifier[self] . identi... | def keysym_to_keycodes(self, keysym):
"""Look up all the keycodes that is bound to keysym. A list of
tuples (keycode, index) is returned, sorted primarily on the
lowest index and secondarily on the lowest keycode."""
try:
# Copy the map list, reversing the arguments
return map(la... |
def nonoverlap(item_a, time_a, item_b, time_b, max_value):
"""
Percentage of pixels in each object that do not overlap with the other object
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in Object... | def function[nonoverlap, parameter[item_a, time_a, item_b, time_b, max_value]]:
constant[
Percentage of pixels in each object that do not overlap with the other object
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObjec... | keyword[def] identifier[nonoverlap] ( identifier[item_a] , identifier[time_a] , identifier[item_b] , identifier[time_b] , identifier[max_value] ):
literal[string]
keyword[return] identifier[np] . identifier[minimum] ( literal[int] - identifier[item_a] . identifier[count_overlap] ( identifier[time_a] , ide... | def nonoverlap(item_a, time_a, item_b, time_b, max_value):
"""
Percentage of pixels in each object that do not overlap with the other object
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in Object... |
def index_by(self, column_or_label):
"""Return a dict keyed by values in a column that contains lists of
rows corresponding to each value.
"""
column = self._get_column(column_or_label)
index = {}
for key, row in zip(column, self.rows):
index.setdefault(key, [... | def function[index_by, parameter[self, column_or_label]]:
constant[Return a dict keyed by values in a column that contains lists of
rows corresponding to each value.
]
variable[column] assign[=] call[name[self]._get_column, parameter[name[column_or_label]]]
variable[index] assign... | keyword[def] identifier[index_by] ( identifier[self] , identifier[column_or_label] ):
literal[string]
identifier[column] = identifier[self] . identifier[_get_column] ( identifier[column_or_label] )
identifier[index] ={}
keyword[for] identifier[key] , identifier[row] keyword[in] ... | def index_by(self, column_or_label):
"""Return a dict keyed by values in a column that contains lists of
rows corresponding to each value.
"""
column = self._get_column(column_or_label)
index = {}
for (key, row) in zip(column, self.rows):
index.setdefault(key, []).append(row) # ... |
def set_positions(self, positions=None, position_mapper='name', ids=None):
'''
checks for position validity & collisions,
but not that all measurements are assigned.
Parameters
-----------
positions : is dict-like of measurement_key:(row,col)
parser :
... | def function[set_positions, parameter[self, positions, position_mapper, ids]]:
constant[
checks for position validity & collisions,
but not that all measurements are assigned.
Parameters
-----------
positions : is dict-like of measurement_key:(row,col)
parser :
... | keyword[def] identifier[set_positions] ( identifier[self] , identifier[positions] = keyword[None] , identifier[position_mapper] = literal[string] , identifier[ids] = keyword[None] ):
literal[string]
keyword[if] identifier[positions] keyword[is] keyword[None] :
keyword[if] identifie... | def set_positions(self, positions=None, position_mapper='name', ids=None):
"""
checks for position validity & collisions,
but not that all measurements are assigned.
Parameters
-----------
positions : is dict-like of measurement_key:(row,col)
parser :
cal... |
def assign_objective_requisite(self, objective_id, requisite_objective_id):
"""Creates a requirement dependency between two ``Objectives``.
arg: objective_id (osid.id.Id): the ``Id`` of the dependent
``Objective``
arg: requisite_objective_id (osid.id.Id): the ``Id`` of the... | def function[assign_objective_requisite, parameter[self, objective_id, requisite_objective_id]]:
constant[Creates a requirement dependency between two ``Objectives``.
arg: objective_id (osid.id.Id): the ``Id`` of the dependent
``Objective``
arg: requisite_objective_id (osi... | keyword[def] identifier[assign_objective_requisite] ( identifier[self] , identifier[objective_id] , identifier[requisite_objective_id] ):
literal[string]
identifier[requisite_type] = identifier[Type] (** identifier[Relationship] (). identifier[get_type_data] ( literal[string] ))
identifie... | def assign_objective_requisite(self, objective_id, requisite_objective_id):
"""Creates a requirement dependency between two ``Objectives``.
arg: objective_id (osid.id.Id): the ``Id`` of the dependent
``Objective``
arg: requisite_objective_id (osid.id.Id): the ``Id`` of the
... |
async def trigger_callback(self, sid, namespace, id, data):
"""Invoke an application callback.
Note: this method is a coroutine.
"""
callback = None
try:
callback = self.callbacks[sid][namespace][id]
except KeyError:
# if we get an unknown callbac... | <ast.AsyncFunctionDef object at 0x7da1b1cb09d0> | keyword[async] keyword[def] identifier[trigger_callback] ( identifier[self] , identifier[sid] , identifier[namespace] , identifier[id] , identifier[data] ):
literal[string]
identifier[callback] = keyword[None]
keyword[try] :
identifier[callback] = identifier[self] . identifi... | async def trigger_callback(self, sid, namespace, id, data):
"""Invoke an application callback.
Note: this method is a coroutine.
"""
callback = None
try:
callback = self.callbacks[sid][namespace][id] # depends on [control=['try'], data=[]]
except KeyError:
# if we get a... |
def port_bindings(val, **kwargs):
'''
On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python dictionary mapping ports to their bindings. The format the API
expects is complicated depending on whether o... | def function[port_bindings, parameter[val]]:
constant[
On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python dictionary mapping ports to their bindings. The format the API
expects is complicated d... | keyword[def] identifier[port_bindings] ( identifier[val] ,** identifier[kwargs] ):
literal[string]
identifier[validate_ip_addrs] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[True] )
keyword[if] keyword[not] identifier[isinstance] ( identifier[val] , identifier[dict] ):
... | def port_bindings(val, **kwargs):
"""
On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python dictionary mapping ports to their bindings. The format the API
expects is complicated depending on whether o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.