code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_json_history(self, item=None, nb=0):
"""Return the history (JSON format).
- the stats history (dict of list) if item is None
- the stats history for the given item (list) instead
- None if item did not exist in the history
Limit to lasts nb items (all if nb=0)
""... | def function[get_json_history, parameter[self, item, nb]]:
constant[Return the history (JSON format).
- the stats history (dict of list) if item is None
- the stats history for the given item (list) instead
- None if item did not exist in the history
Limit to lasts nb items (all... | keyword[def] identifier[get_json_history] ( identifier[self] , identifier[item] = keyword[None] , identifier[nb] = literal[int] ):
literal[string]
identifier[s] = identifier[self] . identifier[stats_history] . identifier[get_json] ( identifier[nb] = identifier[nb] )
keyword[if] identifier... | def get_json_history(self, item=None, nb=0):
"""Return the history (JSON format).
- the stats history (dict of list) if item is None
- the stats history for the given item (list) instead
- None if item did not exist in the history
Limit to lasts nb items (all if nb=0)
"""
... |
def push_notification_devices_destroy_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/push_notification_devices#bulk-unregister-push-notification-devices"
api_path = "/api/v2/push_notification_devices/destroy_many.json"
return self.call(api_path, method="POST", data... | def function[push_notification_devices_destroy_many, parameter[self, data]]:
constant[https://developer.zendesk.com/rest_api/docs/core/push_notification_devices#bulk-unregister-push-notification-devices]
variable[api_path] assign[=] constant[/api/v2/push_notification_devices/destroy_many.json]
retur... | keyword[def] identifier[push_notification_devices_destroy_many] ( identifier[self] , identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
keyword[return] identifier[self] . identifier[call] ( identifier[api_path] , identifier[method] = literal... | def push_notification_devices_destroy_many(self, data, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/push_notification_devices#bulk-unregister-push-notification-devices"""
api_path = '/api/v2/push_notification_devices/destroy_many.json'
return self.call(api_path, method='POST', data=data, *... |
async def status(self, *args, **kwargs):
"""
Get task status
Get task status structure from `taskId`
This method gives output: ``v1/task-status-response.json#``
This method is ``stable``
"""
return await self._makeApiCall(self.funcinfo["status"], *args, **kwar... | <ast.AsyncFunctionDef object at 0x7da20c991fc0> | keyword[async] keyword[def] identifier[status] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] keyword[await] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,** identif... | async def status(self, *args, **kwargs):
"""
Get task status
Get task status structure from `taskId`
This method gives output: ``v1/task-status-response.json#``
This method is ``stable``
"""
return await self._makeApiCall(self.funcinfo['status'], *args, **kwargs) |
def add_attribute(self, name, value):
"""
:param name: Name of the attribute
:type name: string
:param value: Value of the attribute
:type value: string
"""
self.attributes.append(Attribute(name, value)) | def function[add_attribute, parameter[self, name, value]]:
constant[
:param name: Name of the attribute
:type name: string
:param value: Value of the attribute
:type value: string
]
call[name[self].attributes.append, parameter[call[name[Attribute],... | keyword[def] identifier[add_attribute] ( identifier[self] , identifier[name] , identifier[value] ):
literal[string]
identifier[self] . identifier[attributes] . identifier[append] ( identifier[Attribute] ( identifier[name] , identifier[value] )) | def add_attribute(self, name, value):
"""
:param name: Name of the attribute
:type name: string
:param value: Value of the attribute
:type value: string
"""
self.attributes.append(Attribute(name, value)) |
def plot_hpd(
x,
y,
credible_interval=0.94,
color="C1",
circular=False,
smooth=True,
smooth_kwargs=None,
fill_kwargs=None,
plot_kwargs=None,
ax=None,
):
"""
Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
... | def function[plot_hpd, parameter[x, y, credible_interval, color, circular, smooth, smooth_kwargs, fill_kwargs, plot_kwargs, ax]]:
constant[
Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
y : array-like
values from which to compu... | keyword[def] identifier[plot_hpd] (
identifier[x] ,
identifier[y] ,
identifier[credible_interval] = literal[int] ,
identifier[color] = literal[string] ,
identifier[circular] = keyword[False] ,
identifier[smooth] = keyword[True] ,
identifier[smooth_kwargs] = keyword[None] ,
identifier[fill_kwargs] = keyword[No... | def plot_hpd(x, y, credible_interval=0.94, color='C1', circular=False, smooth=True, smooth_kwargs=None, fill_kwargs=None, plot_kwargs=None, ax=None):
"""
Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
y : array-like
values \u200b\u200... |
def sport_update(self, sport_id, names=[], account=None, **kwargs):
""" Update a sport. This needs to be **proposed**.
:param str sport_id: The id of the sport to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:para... | def function[sport_update, parameter[self, sport_id, names, account]]:
constant[ Update a sport. This needs to be **proposed**.
:param str sport_id: The id of the sport to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
... | keyword[def] identifier[sport_update] ( identifier[self] , identifier[sport_id] , identifier[names] =[], identifier[account] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[names] , identifier[list] )
keyword[if] keyword[not] ... | def sport_update(self, sport_id, names=[], account=None, **kwargs):
""" Update a sport. This needs to be **proposed**.
:param str sport_id: The id of the sport to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:param st... |
def _clip_gradient_op(dtype):
"""Create an op that clips gradients using a Defun.
The tensorflow Defun decorator creates an op and tensorflow caches these op
automatically according to `func_name`. Using a Defun decorator twice with the
same `func_name` does not create a new op, instead the cached op is used.
... | def function[_clip_gradient_op, parameter[dtype]]:
constant[Create an op that clips gradients using a Defun.
The tensorflow Defun decorator creates an op and tensorflow caches these op
automatically according to `func_name`. Using a Defun decorator twice with the
same `func_name` does not create a new op... | keyword[def] identifier[_clip_gradient_op] ( identifier[dtype] ):
literal[string]
keyword[def] identifier[clip_gradient_backward] ( identifier[op] , identifier[grad] ):
identifier[clip_value_min] = identifier[op] . identifier[inputs] [ literal[int] ]
identifier[clip_value_max] = identifier[op] . id... | def _clip_gradient_op(dtype):
"""Create an op that clips gradients using a Defun.
The tensorflow Defun decorator creates an op and tensorflow caches these op
automatically according to `func_name`. Using a Defun decorator twice with the
same `func_name` does not create a new op, instead the cached op is used... |
def _reverse(self):
""" reverse patch direction (this doesn't touch filenames) """
for p in self.items:
for h in p.hunks:
h.startsrc, h.starttgt = h.starttgt, h.startsrc
h.linessrc, h.linestgt = h.linestgt, h.linessrc
for i,line in enumerate(h.text):
# need to use line[0:... | def function[_reverse, parameter[self]]:
constant[ reverse patch direction (this doesn't touch filenames) ]
for taget[name[p]] in starred[name[self].items] begin[:]
for taget[name[h]] in starred[name[p].hunks] begin[:]
<ast.Tuple object at 0x7da1b2207cd0> assign[=... | keyword[def] identifier[_reverse] ( identifier[self] ):
literal[string]
keyword[for] identifier[p] keyword[in] identifier[self] . identifier[items] :
keyword[for] identifier[h] keyword[in] identifier[p] . identifier[hunks] :
identifier[h] . identifier[startsrc] , identifier[h] . ident... | def _reverse(self):
""" reverse patch direction (this doesn't touch filenames) """
for p in self.items:
for h in p.hunks:
(h.startsrc, h.starttgt) = (h.starttgt, h.startsrc)
(h.linessrc, h.linestgt) = (h.linestgt, h.linessrc)
for (i, line) in enumerate(h.text):
... |
def copy_tier(self, eaf_obj, tier_name):
"""Copies a tier to another :class:`pympi.Elan.Eaf` object.
:param pympi.Elan.Eaf eaf_obj: Target Eaf object.
:param str tier_name: Name of the tier.
:raises KeyError: If the tier doesn't exist.
"""
if tier_name in eaf_obj.get_tie... | def function[copy_tier, parameter[self, eaf_obj, tier_name]]:
constant[Copies a tier to another :class:`pympi.Elan.Eaf` object.
:param pympi.Elan.Eaf eaf_obj: Target Eaf object.
:param str tier_name: Name of the tier.
:raises KeyError: If the tier doesn't exist.
]
if com... | keyword[def] identifier[copy_tier] ( identifier[self] , identifier[eaf_obj] , identifier[tier_name] ):
literal[string]
keyword[if] identifier[tier_name] keyword[in] identifier[eaf_obj] . identifier[get_tier_names] ():
identifier[eaf_obj] . identifier[remove_tier] ( identifier[tier_n... | def copy_tier(self, eaf_obj, tier_name):
"""Copies a tier to another :class:`pympi.Elan.Eaf` object.
:param pympi.Elan.Eaf eaf_obj: Target Eaf object.
:param str tier_name: Name of the tier.
:raises KeyError: If the tier doesn't exist.
"""
if tier_name in eaf_obj.get_tier_names(... |
def _data2rec(schema, rec_data):
'''
schema = OrderedDict({
'prio': int,
'weight': int,
'port': to_port,
'name': str,
})
rec_data = '10 20 25 myawesome.nl'
res = {'prio': 10, 'weight': 20, 'port': 25 'name': 'myawesome.nl'}
'''
try:
rec_fields = rec_d... | def function[_data2rec, parameter[schema, rec_data]]:
constant[
schema = OrderedDict({
'prio': int,
'weight': int,
'port': to_port,
'name': str,
})
rec_data = '10 20 25 myawesome.nl'
res = {'prio': 10, 'weight': 20, 'port': 25 'name': 'myawesome.nl'}
]
<a... | keyword[def] identifier[_data2rec] ( identifier[schema] , identifier[rec_data] ):
literal[string]
keyword[try] :
identifier[rec_fields] = identifier[rec_data] . identifier[split] ( literal[string] )
keyword[assert] identifier[len] ( identifier[rec_fields] )>= identifier[len] ( i... | def _data2rec(schema, rec_data):
"""
schema = OrderedDict({
'prio': int,
'weight': int,
'port': to_port,
'name': str,
})
rec_data = '10 20 25 myawesome.nl'
res = {'prio': 10, 'weight': 20, 'port': 25 'name': 'myawesome.nl'}
"""
try:
rec_fields = rec_d... |
def _default_docx_path():
"""
Return the path to the built-in default .docx package.
"""
_thisdir = os.path.split(__file__)[0]
return os.path.join(_thisdir, 'templates', 'default-docx-template') | def function[_default_docx_path, parameter[]]:
constant[
Return the path to the built-in default .docx package.
]
variable[_thisdir] assign[=] call[call[name[os].path.split, parameter[name[__file__]]]][constant[0]]
return[call[name[os].path.join, parameter[name[_thisdir], constant[templates]... | keyword[def] identifier[_default_docx_path] ():
literal[string]
identifier[_thisdir] = identifier[os] . identifier[path] . identifier[split] ( identifier[__file__] )[ literal[int] ]
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[_thisdir] , literal[string] , literal... | def _default_docx_path():
"""
Return the path to the built-in default .docx package.
"""
_thisdir = os.path.split(__file__)[0]
return os.path.join(_thisdir, 'templates', 'default-docx-template') |
def get_module_by_name(self, modName):
"""
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
Y... | def function[get_module_by_name, parameter[self, modName]]:
constant[
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules ... | keyword[def] identifier[get_module_by_name] ( identifier[self] , identifier[modName] ):
literal[string]
identifier[modName] = identifier[modName] . identifier[lower] ()
keyword[if] identifier[PathOperations] . identifier[path_is_absolute] ( identifier[modName]... | def get_module_by_name(self, modName):
"""
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
You c... |
def text_changed(self):
"""Text has changed"""
# Save text as bytes, if it was initially bytes
if self.is_binary:
self.text = to_binary_string(self.edit.toPlainText(), 'utf8')
else:
self.text = to_text_string(self.edit.toPlainText())
if self.btn_sav... | def function[text_changed, parameter[self]]:
constant[Text has changed]
if name[self].is_binary begin[:]
name[self].text assign[=] call[name[to_binary_string], parameter[call[name[self].edit.toPlainText, parameter[]], constant[utf8]]]
if name[self].btn_save_and_close begin[:]
... | keyword[def] identifier[text_changed] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_binary] :
identifier[self] . identifier[text] = identifier[to_binary_string] ( identifier[self] . identifier[edit] . identifier[toPlainText] (), litera... | def text_changed(self):
"""Text has changed""" # Save text as bytes, if it was initially bytes
if self.is_binary:
self.text = to_binary_string(self.edit.toPlainText(), 'utf8') # depends on [control=['if'], data=[]]
else:
self.text = to_text_string(self.edit.toPlainText())
if self.btn_s... |
def delete_keyvault(access_token, subscription_id, rgname, vault_name):
'''Deletes a key vault in the named resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_... | def function[delete_keyvault, parameter[access_token, subscription_id, rgname, vault_name]]:
constant[Deletes a key vault in the named resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure reso... | keyword[def] identifier[delete_keyvault] ( identifier[access_token] , identifier[subscription_id] , identifier[rgname] , identifier[vault_name] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ identifier[get_rm_endpoint] (),
literal[string] , identifier[subscription_id] ... | def delete_keyvault(access_token, subscription_id, rgname, vault_name):
"""Deletes a key vault in the named resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_... |
def delete(self, **kwargs):
"""
Performs a DELETE statement on the model's table in the master database.
:param where: The WHERE clause. This can be a plain string, a dict or an array.
:type where: string, dict, array
"""
kwargs['stack'] = self.stack_mark(inspect.stack()... | def function[delete, parameter[self]]:
constant[
Performs a DELETE statement on the model's table in the master database.
:param where: The WHERE clause. This can be a plain string, a dict or an array.
:type where: string, dict, array
]
call[name[kwargs]][constant[stack]... | keyword[def] identifier[delete] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[stack_mark] ( identifier[inspect] . identifier[stack] ())
keyword[return] identifier[self] . identifier[db_adapter] ( identif... | def delete(self, **kwargs):
"""
Performs a DELETE statement on the model's table in the master database.
:param where: The WHERE clause. This can be a plain string, a dict or an array.
:type where: string, dict, array
"""
kwargs['stack'] = self.stack_mark(inspect.stack())
re... |
def as_uni_errors(form):
"""
Renders only form errors like django-uni-form::
{% load uni_form_tags %}
{{ form|as_uni_errors }}
"""
if isinstance(form, BaseFormSet):
template = get_template('uni_form/errors_formset.html')
c = Context({'formset': form})
else:
t... | def function[as_uni_errors, parameter[form]]:
constant[
Renders only form errors like django-uni-form::
{% load uni_form_tags %}
{{ form|as_uni_errors }}
]
if call[name[isinstance], parameter[name[form], name[BaseFormSet]]] begin[:]
variable[template] assign[=] c... | keyword[def] identifier[as_uni_errors] ( identifier[form] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[form] , identifier[BaseFormSet] ):
identifier[template] = identifier[get_template] ( literal[string] )
identifier[c] = identifier[Context] ({ literal[string] : ide... | def as_uni_errors(form):
"""
Renders only form errors like django-uni-form::
{% load uni_form_tags %}
{{ form|as_uni_errors }}
"""
if isinstance(form, BaseFormSet):
template = get_template('uni_form/errors_formset.html')
c = Context({'formset': form}) # depends on [cont... |
def getArc(self, prom, sig):
""" Returns the arcs between a promissor and
a significator. Should uses the object creation
functions to build the objects.
"""
res = self._arc(prom, sig)
res.update({
'prom': prom['id'],
'sig': sig['id']
... | def function[getArc, parameter[self, prom, sig]]:
constant[ Returns the arcs between a promissor and
a significator. Should uses the object creation
functions to build the objects.
]
variable[res] assign[=] call[name[self]._arc, parameter[name[prom], name[sig]]]
... | keyword[def] identifier[getArc] ( identifier[self] , identifier[prom] , identifier[sig] ):
literal[string]
identifier[res] = identifier[self] . identifier[_arc] ( identifier[prom] , identifier[sig] )
identifier[res] . identifier[update] ({
literal[string] : identifier[prom] [ lite... | def getArc(self, prom, sig):
""" Returns the arcs between a promissor and
a significator. Should uses the object creation
functions to build the objects.
"""
res = self._arc(prom, sig)
res.update({'prom': prom['id'], 'sig': sig['id']})
return res |
def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw):
""" Updates the progress. Will update progress bars or other progress output.
Parameters
----------
numerator : int
numerator of partial work done already in current stage
stage : int, non... | def function[_progress_update, parameter[self, numerator_increment, stage, show_eta]]:
constant[ Updates the progress. Will update progress bars or other progress output.
Parameters
----------
numerator : int
numerator of partial work done already in current stage
st... | keyword[def] identifier[_progress_update] ( identifier[self] , identifier[numerator_increment] , identifier[stage] = literal[int] , identifier[show_eta] = keyword[True] ,** identifier[kw] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[show_progress] :
keywo... | def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw):
""" Updates the progress. Will update progress bars or other progress output.
Parameters
----------
numerator : int
numerator of partial work done already in current stage
stage : int, nonnega... |
def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]):
"""Accumulates single qubit phase gates into the scratch shards."""
index = args['indices'][0]
shard_num = args['shard_num']
half_turns = args['half_turns']
num_shard_qubits = args['num_shard_qubits']
scratch = _scratch_shard(args)... | def function[_single_qubit_accumulate_into_scratch, parameter[args]]:
constant[Accumulates single qubit phase gates into the scratch shards.]
variable[index] assign[=] call[call[name[args]][constant[indices]]][constant[0]]
variable[shard_num] assign[=] call[name[args]][constant[shard_num]]
... | keyword[def] identifier[_single_qubit_accumulate_into_scratch] ( identifier[args] : identifier[Dict] [ identifier[str] , identifier[Any] ]):
literal[string]
identifier[index] = identifier[args] [ literal[string] ][ literal[int] ]
identifier[shard_num] = identifier[args] [ literal[string] ]
identi... | def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]):
"""Accumulates single qubit phase gates into the scratch shards."""
index = args['indices'][0]
shard_num = args['shard_num']
half_turns = args['half_turns']
num_shard_qubits = args['num_shard_qubits']
scratch = _scratch_shard(args)... |
def _unassembled_reads2_out_file_name(self):
"""Checks if file name is set for reads2 output.
Returns absolute path."""
if self.Parameters['-2'].isOn():
unassembled_reads2 = self._absolute(
str(self.Parameters['-2'].Value))
else:
raise ValueErro... | def function[_unassembled_reads2_out_file_name, parameter[self]]:
constant[Checks if file name is set for reads2 output.
Returns absolute path.]
if call[call[name[self].Parameters][constant[-2]].isOn, parameter[]] begin[:]
variable[unassembled_reads2] assign[=] call[name[self]... | keyword[def] identifier[_unassembled_reads2_out_file_name] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[Parameters] [ literal[string] ]. identifier[isOn] ():
identifier[unassembled_reads2] = identifier[self] . identifier[_absolute] (
ide... | def _unassembled_reads2_out_file_name(self):
"""Checks if file name is set for reads2 output.
Returns absolute path."""
if self.Parameters['-2'].isOn():
unassembled_reads2 = self._absolute(str(self.Parameters['-2'].Value)) # depends on [control=['if'], data=[]]
else:
raise ValueE... |
def point_in_multipolygon(point, multipoly):
"""
valid whether the point is located in a mulitpolygon (donut polygon is not supported)
Keyword arguments:
point -- point geojson object
multipoly -- multipolygon geojson object
if(point inside multipoly) return true else false
"""
c... | def function[point_in_multipolygon, parameter[point, multipoly]]:
constant[
valid whether the point is located in a mulitpolygon (donut polygon is not supported)
Keyword arguments:
point -- point geojson object
multipoly -- multipolygon geojson object
if(point inside multipoly) retur... | keyword[def] identifier[point_in_multipolygon] ( identifier[point] , identifier[multipoly] ):
literal[string]
identifier[coords_array] =[ identifier[multipoly] [ literal[string] ]] keyword[if] identifier[multipoly] [
literal[string] ]== literal[string] keyword[else] identifier[multipoly] [ literal[... | def point_in_multipolygon(point, multipoly):
"""
valid whether the point is located in a mulitpolygon (donut polygon is not supported)
Keyword arguments:
point -- point geojson object
multipoly -- multipolygon geojson object
if(point inside multipoly) return true else false
"""
c... |
def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
... | def function[add, parameter[envelope]]:
constant[ Take a dict-like fedmsg envelope and store the headers and message
in the table.
]
variable[message] assign[=] call[name[envelope]][constant[body]]
variable[timestamp] assign[=] call[name[message].get, parameter[constant[timestamp], c... | keyword[def] identifier[add] ( identifier[envelope] ):
literal[string]
identifier[message] = identifier[envelope] [ literal[string] ]
identifier[timestamp] = identifier[message] . identifier[get] ( literal[string] , keyword[None] )
keyword[try] :
keyword[if] identifier[timestamp] :
... | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp) # depends on [co... |
def to_ipa(s, delimiter=' ', all_readings=False, container='[]'):
"""Convert a string's Chinese characters to IPA.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a m... | def function[to_ipa, parameter[s, delimiter, all_readings, container]]:
constant[Convert a string's Chinese characters to IPA.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and charac... | keyword[def] identifier[to_ipa] ( identifier[s] , identifier[delimiter] = literal[string] , identifier[all_readings] = keyword[False] , identifier[container] = literal[string] ):
literal[string]
identifier[numbered_pinyin] = identifier[to_pinyin] ( identifier[s] , identifier[delimiter] , identifier[all_rea... | def to_ipa(s, delimiter=' ', all_readings=False, container='[]'):
"""Convert a string's Chinese characters to IPA.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a m... |
def parse_request(self, request, parameters, fake_method=None):
'''
Parse Django request
'''
return (fake_method or request.method,
request.build_absolute_uri(),
request.META,
(dict(request.POST.iteritems())
if request.m... | def function[parse_request, parameter[self, request, parameters, fake_method]]:
constant[
Parse Django request
]
return[tuple[[<ast.BoolOp object at 0x7da1b1b342b0>, <ast.Call object at 0x7da1b1b351e0>, <ast.Attribute object at 0x7da1b1b34160>, <ast.IfExp object at 0x7da1b1b34e50>]]] | keyword[def] identifier[parse_request] ( identifier[self] , identifier[request] , identifier[parameters] , identifier[fake_method] = keyword[None] ):
literal[string]
keyword[return] ( identifier[fake_method] keyword[or] identifier[request] . identifier[method] ,
identifier[request] . ide... | def parse_request(self, request, parameters, fake_method=None):
"""
Parse Django request
"""
return (fake_method or request.method, request.build_absolute_uri(), request.META, dict(request.POST.iteritems()) if request.method == 'POST' else parameters) |
def _init_client(self, from_archive=False):
"""Init client"""
return ConfluenceClient(self.url, archive=self.archive, from_archive=from_archive) | def function[_init_client, parameter[self, from_archive]]:
constant[Init client]
return[call[name[ConfluenceClient], parameter[name[self].url]]] | keyword[def] identifier[_init_client] ( identifier[self] , identifier[from_archive] = keyword[False] ):
literal[string]
keyword[return] identifier[ConfluenceClient] ( identifier[self] . identifier[url] , identifier[archive] = identifier[self] . identifier[archive] , identifier[from_archive] = ide... | def _init_client(self, from_archive=False):
"""Init client"""
return ConfluenceClient(self.url, archive=self.archive, from_archive=from_archive) |
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data) | def function[on_command_control, parameter[self, val_id]]:
constant[
Parameters
----------
val_id : str
Returns
-------
requests.Response
]
variable[data] assign[=] binary_operation[constant[control,controlId=1|] + name[val_id]]
return[call[na... | keyword[def] identifier[on_command_control] ( identifier[self] , identifier[val_id] ):
literal[string]
identifier[data] = literal[string] + identifier[val_id]
keyword[return] identifier[self] . identifier[_basic_post] ( identifier[url] = literal[string] , identifier[data] = identifier[da... | def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = 'control,controlId=1|' + val_id
return self._basic_post(url='commandControlPublic', data=data) |
def get_date(datetime, time_format=None):
"""
Return a datetime oject from a string, with optional time format.
Parameters
----------
datetime : str
Date-time as string in any sensible format.
time_format : datetime str (optional)
String describing the datetime format. If missin... | def function[get_date, parameter[datetime, time_format]]:
constant[
Return a datetime oject from a string, with optional time format.
Parameters
----------
datetime : str
Date-time as string in any sensible format.
time_format : datetime str (optional)
String describing the ... | keyword[def] identifier[get_date] ( identifier[datetime] , identifier[time_format] = keyword[None] ):
literal[string]
keyword[if] identifier[time_format] keyword[is] keyword[None] :
identifier[t] = identifier[du] . identifier[parser] . identifier[parse] ( identifier[datetime] )
keyword[els... | def get_date(datetime, time_format=None):
"""
Return a datetime oject from a string, with optional time format.
Parameters
----------
datetime : str
Date-time as string in any sensible format.
time_format : datetime str (optional)
String describing the datetime format. If missin... |
def get_capabilities(cls):
"""List the model's capabilities."""
capabilities = []
for _cls in cls.mro():
if issubclass(_cls, Capability) and _cls is not Capability \
and not issubclass(_cls, Model):
capabilities.append(_cls)
return capabilities | def function[get_capabilities, parameter[cls]]:
constant[List the model's capabilities.]
variable[capabilities] assign[=] list[[]]
for taget[name[_cls]] in starred[call[name[cls].mro, parameter[]]] begin[:]
if <ast.BoolOp object at 0x7da1b0e646a0> begin[:]
... | keyword[def] identifier[get_capabilities] ( identifier[cls] ):
literal[string]
identifier[capabilities] =[]
keyword[for] identifier[_cls] keyword[in] identifier[cls] . identifier[mro] ():
keyword[if] identifier[issubclass] ( identifier[_cls] , identifier[Capability] ) keyw... | def get_capabilities(cls):
"""List the model's capabilities."""
capabilities = []
for _cls in cls.mro():
if issubclass(_cls, Capability) and _cls is not Capability and (not issubclass(_cls, Model)):
capabilities.append(_cls) # depends on [control=['if'], data=[]] # depends on [control=... |
def cmdify(self, extra_args=None):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes be... | def function[cmdify, parameter[self, extra_args]]:
constant[Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* E... | keyword[def] identifier[cmdify] ( identifier[self] , identifier[extra_args] = keyword[None] ):
literal[string]
identifier[parts] = identifier[list] ( identifier[self] . identifier[_parts] )
keyword[if] identifier[extra_args] :
identifier[parts] . identifier[extend] ( identifi... | def cmdify(self, extra_args=None):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before... |
def add_kv_store(self, key, value):
"""Add a key-value store entry.
:param key: string
:param value: string
"""
data = {
'operation': 'STORE',
'key': key,
'value': value
}
return self.post(self.make_url("/useragent-kv"), data=t... | def function[add_kv_store, parameter[self, key, value]]:
constant[Add a key-value store entry.
:param key: string
:param value: string
]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da18fe93fa0>, <ast.Constant object at 0x7da18fe91cc0>, <ast.Constant object at... | keyword[def] identifier[add_kv_store] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[data] ={
literal[string] : literal[string] ,
literal[string] : identifier[key] ,
literal[string] : identifier[value]
}
keyword[re... | def add_kv_store(self, key, value):
"""Add a key-value store entry.
:param key: string
:param value: string
"""
data = {'operation': 'STORE', 'key': key, 'value': value}
return self.post(self.make_url('/useragent-kv'), data=to_json(data), headers=self.default_headers).text |
def update(self, name, html_url, zip_url):
"""Updates this email template."""
body = {
"Name": name,
"HtmlPageURL": html_url,
"ZipFileURL": zip_url}
response = self._put("/templates/%s.json" %
self.template_id, json.dumps(body)) | def function[update, parameter[self, name, html_url, zip_url]]:
constant[Updates this email template.]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da20c7ca980>, <ast.Constant object at 0x7da20c7ca8f0>, <ast.Constant object at 0x7da20c7c9fc0>], [<ast.Name object at 0x7da20c7c8430>, <a... | keyword[def] identifier[update] ( identifier[self] , identifier[name] , identifier[html_url] , identifier[zip_url] ):
literal[string]
identifier[body] ={
literal[string] : identifier[name] ,
literal[string] : identifier[html_url] ,
literal[string] : identifier[zip_url] }
... | def update(self, name, html_url, zip_url):
"""Updates this email template."""
body = {'Name': name, 'HtmlPageURL': html_url, 'ZipFileURL': zip_url}
response = self._put('/templates/%s.json' % self.template_id, json.dumps(body)) |
def _get(self, api_call, params, method='GET', file_=None):
"""Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (dict): API function parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
file_ (fil... | def function[_get, parameter[self, api_call, params, method, file_]]:
constant[Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (dict): API function parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
... | keyword[def] identifier[_get] ( identifier[self] , identifier[api_call] , identifier[params] , identifier[method] = literal[string] , identifier[file_] = keyword[None] ):
literal[string]
identifier[url] = identifier[self] . identifier[_build_url] ( identifier[api_call] )
keyword[if] iden... | def _get(self, api_call, params, method='GET', file_=None):
"""Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (dict): API function parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
file_ (file): ... |
def get_actor(self, actor, aid, check_monitor=True):
'''Given an actor unique id return the actor proxy.'''
a = super().get_actor(actor, aid)
if a is None:
if aid in self.monitors: # Check in monitors aid
return self.monitors[aid]
elif aid in self.managed... | def function[get_actor, parameter[self, actor, aid, check_monitor]]:
constant[Given an actor unique id return the actor proxy.]
variable[a] assign[=] call[call[name[super], parameter[]].get_actor, parameter[name[actor], name[aid]]]
if compare[name[a] is constant[None]] begin[:]
i... | keyword[def] identifier[get_actor] ( identifier[self] , identifier[actor] , identifier[aid] , identifier[check_monitor] = keyword[True] ):
literal[string]
identifier[a] = identifier[super] (). identifier[get_actor] ( identifier[actor] , identifier[aid] )
keyword[if] identifier[a] keyword... | def get_actor(self, actor, aid, check_monitor=True):
"""Given an actor unique id return the actor proxy."""
a = super().get_actor(actor, aid)
if a is None:
if aid in self.monitors: # Check in monitors aid
return self.monitors[aid] # depends on [control=['if'], data=['aid']]
eli... |
def set(self, key, value):
"""Sets the value for the key in the override register.
Will be used instead of values obtained via
args, config file, env, defaults or key/value store.
"""
k = self._real_key(key.lower())
self._override[k] = value | def function[set, parameter[self, key, value]]:
constant[Sets the value for the key in the override register.
Will be used instead of values obtained via
args, config file, env, defaults or key/value store.
]
variable[k] assign[=] call[name[self]._real_key, parameter[call[name[ke... | keyword[def] identifier[set] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[k] = identifier[self] . identifier[_real_key] ( identifier[key] . identifier[lower] ())
identifier[self] . identifier[_override] [ identifier[k] ]= identifier[value] | def set(self, key, value):
"""Sets the value for the key in the override register.
Will be used instead of values obtained via
args, config file, env, defaults or key/value store.
"""
k = self._real_key(key.lower())
self._override[k] = value |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
type = msg.get_type()
master = self.master
# add some status fields
if type in [ 'RC_CHANNELS_RAW' ]:
rc6 = msg.chan6_raw
if rc6 > 1500:
ign_colour = 'green'
... | def function[mavlink_packet, parameter[self, msg]]:
constant[handle an incoming mavlink packet]
variable[type] assign[=] call[name[msg].get_type, parameter[]]
variable[master] assign[=] name[self].master
if compare[name[type] in list[[<ast.Constant object at 0x7da204345ba0>]]] begin[:]
... | keyword[def] identifier[mavlink_packet] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[type] = identifier[msg] . identifier[get_type] ()
identifier[master] = identifier[self] . identifier[master]
keyword[if] identifier[type] keyword[in] [ literal[... | def mavlink_packet(self, msg):
"""handle an incoming mavlink packet"""
type = msg.get_type()
master = self.master
# add some status fields
if type in ['RC_CHANNELS_RAW']:
rc6 = msg.chan6_raw
if rc6 > 1500:
ign_colour = 'green' # depends on [control=['if'], data=[]]
... |
def renew_step_dir(step_dir: str):
"""Delete step directory if exists and create, reporting actions."""
if os.path.exists(step_dir):
logging.info("Remove unfinished step %s", step_dir)
shutil.rmtree(step_dir)
logging.info("Create: %s", step_dir)
os.makedirs(step_dir) | def function[renew_step_dir, parameter[step_dir]]:
constant[Delete step directory if exists and create, reporting actions.]
if call[name[os].path.exists, parameter[name[step_dir]]] begin[:]
call[name[logging].info, parameter[constant[Remove unfinished step %s], name[step_dir]]]
... | keyword[def] identifier[renew_step_dir] ( identifier[step_dir] : identifier[str] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[step_dir] ):
identifier[logging] . identifier[info] ( literal[string] , identifier[step_dir] )
identifier[sh... | def renew_step_dir(step_dir: str):
"""Delete step directory if exists and create, reporting actions."""
if os.path.exists(step_dir):
logging.info('Remove unfinished step %s', step_dir)
shutil.rmtree(step_dir) # depends on [control=['if'], data=[]]
logging.info('Create: %s', step_dir)
os... |
def optimal_parameters(reconstruction, fom, phantoms, data,
initial=None, univariate=False):
r"""Find the optimal parameters for a reconstruction method.
Notes
-----
For a forward operator :math:`A : X \to Y`, a reconstruction operator
parametrized by :math:`\theta` is some o... | def function[optimal_parameters, parameter[reconstruction, fom, phantoms, data, initial, univariate]]:
constant[Find the optimal parameters for a reconstruction method.
Notes
-----
For a forward operator :math:`A : X \to Y`, a reconstruction operator
parametrized by :math:`\theta` is some opera... | keyword[def] identifier[optimal_parameters] ( identifier[reconstruction] , identifier[fom] , identifier[phantoms] , identifier[data] ,
identifier[initial] = keyword[None] , identifier[univariate] = keyword[False] ):
literal[string]
keyword[def] identifier[func] ( identifier[lam] ):
keyword... | def optimal_parameters(reconstruction, fom, phantoms, data, initial=None, univariate=False):
"""Find the optimal parameters for a reconstruction method.
Notes
-----
For a forward operator :math:`A : X \\to Y`, a reconstruction operator
parametrized by :math:`\\theta` is some operator
:math:`R_\... |
def add_put(self, *args, **kwargs):
"""
Shortcut for add_route with method PUT
"""
return self.add_route(hdrs.METH_PUT, *args, **kwargs) | def function[add_put, parameter[self]]:
constant[
Shortcut for add_route with method PUT
]
return[call[name[self].add_route, parameter[name[hdrs].METH_PUT, <ast.Starred object at 0x7da1b0e24ee0>]]] | keyword[def] identifier[add_put] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[add_route] ( identifier[hdrs] . identifier[METH_PUT] ,* identifier[args] ,** identifier[kwargs] ) | def add_put(self, *args, **kwargs):
"""
Shortcut for add_route with method PUT
"""
return self.add_route(hdrs.METH_PUT, *args, **kwargs) |
def _update_trace_info(self, fields, hm):
"""Parses a trace line and updates the :attr:`status_info` attribute.
Parameters
----------
fields : list
List of the tab-seperated elements of the trace line
hm : dict
Maps the column IDs to their position in the... | def function[_update_trace_info, parameter[self, fields, hm]]:
constant[Parses a trace line and updates the :attr:`status_info` attribute.
Parameters
----------
fields : list
List of the tab-seperated elements of the trace line
hm : dict
Maps the column I... | keyword[def] identifier[_update_trace_info] ( identifier[self] , identifier[fields] , identifier[hm] ):
literal[string]
identifier[process] = identifier[fields] [ identifier[hm] [ literal[string] ]]
keyword[if] identifier[process] keyword[not] keyword[in] identifier[self] . identifie... | def _update_trace_info(self, fields, hm):
"""Parses a trace line and updates the :attr:`status_info` attribute.
Parameters
----------
fields : list
List of the tab-seperated elements of the trace line
hm : dict
Maps the column IDs to their position in the fie... |
def _split_section_and_key(key):
"""Return a tuple with config section and key."""
parts = key.split('.')
if len(parts) > 1:
return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
return 'renku', key | def function[_split_section_and_key, parameter[key]]:
constant[Return a tuple with config section and key.]
variable[parts] assign[=] call[name[key].split, parameter[constant[.]]]
if compare[call[name[len], parameter[name[parts]]] greater[>] constant[1]] begin[:]
return[tuple[[<ast.Call ... | keyword[def] identifier[_split_section_and_key] ( identifier[key] ):
literal[string]
identifier[parts] = identifier[key] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[parts] )> literal[int] :
keyword[return] literal[string] . identifier[format] ( identifie... | def _split_section_and_key(key):
"""Return a tuple with config section and key."""
parts = key.split('.')
if len(parts) > 1:
return ('renku "{0}"'.format(parts[0]), '.'.join(parts[1:])) # depends on [control=['if'], data=[]]
return ('renku', key) |
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing inp... | def function[accuracy, parameter[sess, model, x, y, batch_size, devices, feed, attack, attack_params]]:
constant[
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input ex... | keyword[def] identifier[accuracy] ( identifier[sess] , identifier[model] , identifier[x] , identifier[y] , identifier[batch_size] = keyword[None] , identifier[devices] = keyword[None] , identifier[feed] = keyword[None] ,
identifier[attack] = keyword[None] , identifier[attack_params] = keyword[None] ):
literal[str... | def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None, attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples... |
def _next_code_point_handler(whence, ctx):
"""Retrieves the next code point from within a quoted string or symbol."""
data_event, self = yield
queue = ctx.queue
unicode_escapes_allowed = ctx.ion_type is not IonType.CLOB
escaped_newline = False
escape_sequence = b''
low_surrogate_required = F... | def function[_next_code_point_handler, parameter[whence, ctx]]:
constant[Retrieves the next code point from within a quoted string or symbol.]
<ast.Tuple object at 0x7da1b13c3190> assign[=] <ast.Yield object at 0x7da1b13c2350>
variable[queue] assign[=] name[ctx].queue
variable[unicode_es... | keyword[def] identifier[_next_code_point_handler] ( identifier[whence] , identifier[ctx] ):
literal[string]
identifier[data_event] , identifier[self] = keyword[yield]
identifier[queue] = identifier[ctx] . identifier[queue]
identifier[unicode_escapes_allowed] = identifier[ctx] . identifier[ion_t... | def _next_code_point_handler(whence, ctx):
"""Retrieves the next code point from within a quoted string or symbol."""
(data_event, self) = (yield)
queue = ctx.queue
unicode_escapes_allowed = ctx.ion_type is not IonType.CLOB
escaped_newline = False
escape_sequence = b''
low_surrogate_required... |
def cookies(self):
"""A :class:`dict` with the contents of all cookies transmitted with
the request."""
return parse_cookie(
self.environ,
self.charset,
self.encoding_errors,
cls=self.dict_storage_class,
) | def function[cookies, parameter[self]]:
constant[A :class:`dict` with the contents of all cookies transmitted with
the request.]
return[call[name[parse_cookie], parameter[name[self].environ, name[self].charset, name[self].encoding_errors]]] | keyword[def] identifier[cookies] ( identifier[self] ):
literal[string]
keyword[return] identifier[parse_cookie] (
identifier[self] . identifier[environ] ,
identifier[self] . identifier[charset] ,
identifier[self] . identifier[encoding_errors] ,
identifier[cls] =... | def cookies(self):
"""A :class:`dict` with the contents of all cookies transmitted with
the request."""
return parse_cookie(self.environ, self.charset, self.encoding_errors, cls=self.dict_storage_class) |
def dfs_get_all_childs(self, root):
"""Recursively get all sons of this node
:param root: node to get sons
:type root:
:return: sons
:rtype: list
"""
self.nodes[root]['dfs_loop_status'] = 'DFS_CHECKED'
ret = set()
# Me
ret.add(root)
... | def function[dfs_get_all_childs, parameter[self, root]]:
constant[Recursively get all sons of this node
:param root: node to get sons
:type root:
:return: sons
:rtype: list
]
call[call[name[self].nodes][name[root]]][constant[dfs_loop_status]] assign[=] constant[D... | keyword[def] identifier[dfs_get_all_childs] ( identifier[self] , identifier[root] ):
literal[string]
identifier[self] . identifier[nodes] [ identifier[root] ][ literal[string] ]= literal[string]
identifier[ret] = identifier[set] ()
identifier[ret] . identifier[add] ( id... | def dfs_get_all_childs(self, root):
"""Recursively get all sons of this node
:param root: node to get sons
:type root:
:return: sons
:rtype: list
"""
self.nodes[root]['dfs_loop_status'] = 'DFS_CHECKED'
ret = set()
# Me
ret.add(root)
# And my sons
ret.... |
def _add_container(props_node, tag, container):
"""
Walks through the given container and fills the node
:param props_node: A property node
:param tag: Name of the container tag
:param container: The container
"""
values_node = ElementTree.SubElement(props_node, ... | def function[_add_container, parameter[props_node, tag, container]]:
constant[
Walks through the given container and fills the node
:param props_node: A property node
:param tag: Name of the container tag
:param container: The container
]
variable[values_node] as... | keyword[def] identifier[_add_container] ( identifier[props_node] , identifier[tag] , identifier[container] ):
literal[string]
identifier[values_node] = identifier[ElementTree] . identifier[SubElement] ( identifier[props_node] , identifier[tag] )
keyword[for] identifier[value] keyword[in]... | def _add_container(props_node, tag, container):
"""
Walks through the given container and fills the node
:param props_node: A property node
:param tag: Name of the container tag
:param container: The container
"""
values_node = ElementTree.SubElement(props_node, tag)
... |
def _merge_data(self, data: AnyMapping, *additional: AnyMapping) -> dict:
r"""Merge base data and additional dicts.
:param data: Base data.
:param \*additional: Additional data dicts to be merged into base dict.
"""
return defaults(
dict(data) if not isinstance(data,... | def function[_merge_data, parameter[self, data]]:
constant[Merge base data and additional dicts.
:param data: Base data.
:param \*additional: Additional data dicts to be merged into base dict.
]
return[call[name[defaults], parameter[<ast.IfExp object at 0x7da1b1a3e830>, <ast.Starred... | keyword[def] identifier[_merge_data] ( identifier[self] , identifier[data] : identifier[AnyMapping] ,* identifier[additional] : identifier[AnyMapping] )-> identifier[dict] :
literal[string]
keyword[return] identifier[defaults] (
identifier[dict] ( identifier[data] ) keyword[if] keyword[n... | def _merge_data(self, data: AnyMapping, *additional: AnyMapping) -> dict:
"""Merge base data and additional dicts.
:param data: Base data.
:param \\*additional: Additional data dicts to be merged into base dict.
"""
return defaults(dict(data) if not isinstance(data, dict) else data, *(d... |
def tuple_len(self):
"""
Length of tuples produced by this generator.
"""
try:
return self._tuple_len
except AttributeError:
raise NotImplementedError("Class {} does not implement attribute 'tuple_len'.".format(self.__class__.__name__)) | def function[tuple_len, parameter[self]]:
constant[
Length of tuples produced by this generator.
]
<ast.Try object at 0x7da1b10a4640> | keyword[def] identifier[tuple_len] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_tuple_len]
keyword[except] identifier[AttributeError] :
keyword[raise] identifier[NotImplementedError] ( literal[string] . id... | def tuple_len(self):
"""
Length of tuples produced by this generator.
"""
try:
return self._tuple_len # depends on [control=['try'], data=[]]
except AttributeError:
raise NotImplementedError("Class {} does not implement attribute 'tuple_len'.".format(self.__class__.__name__)... |
def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("a... | def function[args_repr, parameter[]]:
constant[
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_k... | keyword[def] identifier[args_repr] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[items] =[ identifier[repr] ( identifier[a] ) keyword[for] identifier[a] keyword[in] identifier[args] ]
identifier[items] +=[ literal[string] %( identifier[k] , identifier[v] ) keyword[for] i... | def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("a... |
def averageSequenceAccuracy(self, minOverlap, maxOverlap,
firstStat=0, lastStat=None):
"""
For each object, decide whether the TM uniquely classified it by checking
that the number of predictedActive cells are in an acceptable range.
"""
numCorrectSparsity = 0.0
num... | def function[averageSequenceAccuracy, parameter[self, minOverlap, maxOverlap, firstStat, lastStat]]:
constant[
For each object, decide whether the TM uniquely classified it by checking
that the number of predictedActive cells are in an acceptable range.
]
variable[numCorrectSparsity] assign[... | keyword[def] identifier[averageSequenceAccuracy] ( identifier[self] , identifier[minOverlap] , identifier[maxOverlap] ,
identifier[firstStat] = literal[int] , identifier[lastStat] = keyword[None] ):
literal[string]
identifier[numCorrectSparsity] = literal[int]
identifier[numCorrectClassifications] =... | def averageSequenceAccuracy(self, minOverlap, maxOverlap, firstStat=0, lastStat=None):
"""
For each object, decide whether the TM uniquely classified it by checking
that the number of predictedActive cells are in an acceptable range.
"""
numCorrectSparsity = 0.0
numCorrectClassifications = 0.0
... |
def replace_runtime_class(self, name, body, **kwargs):
"""
replace the specified RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_runtime_class(name, body, async_req=Tru... | def function[replace_runtime_class, parameter[self, name, body]]:
constant[
replace the specified RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_runtime_class(name, bo... | keyword[def] identifier[replace_runtime_class] ( identifier[self] , identifier[name] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keywo... | def replace_runtime_class(self, name, body, **kwargs):
"""
replace the specified RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_runtime_class(name, body, async_req=True)
... |
def FromBinary(cls, record_data, record_count=1):
"""Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a ResetDeviceRecord.
Args:
record_data (bytearray)... | def function[FromBinary, parameter[cls, record_data, record_count]]:
constant[Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a ResetDeviceRecord.
Args:
... | keyword[def] identifier[FromBinary] ( identifier[cls] , identifier[record_data] , identifier[record_count] = literal[int] ):
literal[string]
keyword[if] identifier[len] ( identifier[record_data] )!= literal[int] :
keyword[raise] identifier[ArgumentError] ( literal[string] , identifi... | def FromBinary(cls, record_data, record_count=1):
"""Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a ResetDeviceRecord.
Args:
record_data (bytearray): Th... |
def fader(self, value: int):
"""Move the fader to a new position in the range 0 to 1023."""
self._fader = int(value) if 0 < value < 1024 else 0
self.outport.send(mido.Message('control_change', control=0,
value=self._fader >> 7))
self.outport.send(mi... | def function[fader, parameter[self, value]]:
constant[Move the fader to a new position in the range 0 to 1023.]
name[self]._fader assign[=] <ast.IfExp object at 0x7da2054a6d40>
call[name[self].outport.send, parameter[call[name[mido].Message, parameter[constant[control_change]]]]]
call[na... | keyword[def] identifier[fader] ( identifier[self] , identifier[value] : identifier[int] ):
literal[string]
identifier[self] . identifier[_fader] = identifier[int] ( identifier[value] ) keyword[if] literal[int] < identifier[value] < literal[int] keyword[else] literal[int]
identifier[sel... | def fader(self, value: int):
"""Move the fader to a new position in the range 0 to 1023."""
self._fader = int(value) if 0 < value < 1024 else 0
self.outport.send(mido.Message('control_change', control=0, value=self._fader >> 7))
self.outport.send(mido.Message('control_change', control=32, value=self._fa... |
def _set_af_ipv4_uc_and_vrf_cmds_call_point_holder(self, v, load=False):
"""
Setter method for af_ipv4_uc_and_vrf_cmds_call_point_holder, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/af_ipv4_uc_and_vrf_cmds_call_point_holder (container)
If this variabl... | def function[_set_af_ipv4_uc_and_vrf_cmds_call_point_holder, parameter[self, v, load]]:
constant[
Setter method for af_ipv4_uc_and_vrf_cmds_call_point_holder, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/af_ipv4_uc_and_vrf_cmds_call_point_holder (conta... | keyword[def] identifier[_set_af_ipv4_uc_and_vrf_cmds_call_point_holder] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )... | def _set_af_ipv4_uc_and_vrf_cmds_call_point_holder(self, v, load=False):
"""
Setter method for af_ipv4_uc_and_vrf_cmds_call_point_holder, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/af_ipv4_uc_and_vrf_cmds_call_point_holder (container)
If this variabl... |
def get_now_datetime_filestamp(longTime=False):
"""
*A datetime stamp to be appended to the end of filenames: ``YYYYMMDDtHHMMSS``*
**Key Arguments:**
- ``longTime`` -- make time string longer (more change of filenames being unique)
**Return:**
- ``now`` -- current time and date in file... | def function[get_now_datetime_filestamp, parameter[longTime]]:
constant[
*A datetime stamp to be appended to the end of filenames: ``YYYYMMDDtHHMMSS``*
**Key Arguments:**
- ``longTime`` -- make time string longer (more change of filenames being unique)
**Return:**
- ``now`` -- curr... | keyword[def] identifier[get_now_datetime_filestamp] ( identifier[longTime] = keyword[False] ):
literal[string]
keyword[from] identifier[datetime] keyword[import] identifier[datetime] , identifier[date] , identifier[time]
identifier[now] = identifier[datetime] . identifier[now] ()
keyword... | def get_now_datetime_filestamp(longTime=False):
"""
*A datetime stamp to be appended to the end of filenames: ``YYYYMMDDtHHMMSS``*
**Key Arguments:**
- ``longTime`` -- make time string longer (more change of filenames being unique)
**Return:**
- ``now`` -- current time and date in file... |
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout=... | def function[get_response, parameter[url, plugins, timeout]]:
constant[
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
]
variable[lua_script] assign[=] call[name[create_lua_script], parameter[name[plugins]]]
variable[lua] assign[=] call[... | keyword[def] identifier[get_response] ( identifier[url] , identifier[plugins] , identifier[timeout] = identifier[SPLASH_TIMEOUT] ):
literal[string]
identifier[lua_script] = identifier[create_lua_script] ( identifier[plugins] )
identifier[lua] = identifier[urllib] . identifier[parse] . identifier[quote... | def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout=... |
def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
languag... | def function[get_children_graph, parameter[self, item_ids, language, forbidden_item_ids]]:
constant[
Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
... | keyword[def] identifier[get_children_graph] ( identifier[self] , identifier[item_ids] = keyword[None] , identifier[language] = keyword[None] , identifier[forbidden_item_ids] = keyword[None] ):
literal[string]
keyword[if] identifier[forbidden_item_ids] keyword[is] keyword[None] :
ide... | def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (s... |
def dataset(self):
"""A Tablib Dataset containing the row."""
data = tablib.Dataset()
data.headers = self.keys()
row = _reduce_datetimes(self.values())
data.append(row)
return data | def function[dataset, parameter[self]]:
constant[A Tablib Dataset containing the row.]
variable[data] assign[=] call[name[tablib].Dataset, parameter[]]
name[data].headers assign[=] call[name[self].keys, parameter[]]
variable[row] assign[=] call[name[_reduce_datetimes], parameter[call[nam... | keyword[def] identifier[dataset] ( identifier[self] ):
literal[string]
identifier[data] = identifier[tablib] . identifier[Dataset] ()
identifier[data] . identifier[headers] = identifier[self] . identifier[keys] ()
identifier[row] = identifier[_reduce_datetimes] ( identifier[self]... | def dataset(self):
"""A Tablib Dataset containing the row."""
data = tablib.Dataset()
data.headers = self.keys()
row = _reduce_datetimes(self.values())
data.append(row)
return data |
def close(self, filehandle):
"""Close openend file if no longer used."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
while size >... | def function[close, parameter[self, filehandle]]:
constant[Close openend file if no longer used.]
with name[self].lock begin[:]
if compare[name[filehandle] in name[self].files] begin[:]
<ast.AugAssign object at 0x7da1b18c2c20>
variable[index] assign[=]... | keyword[def] identifier[close] ( identifier[self] , identifier[filehandle] ):
literal[string]
keyword[with] identifier[self] . identifier[lock] :
keyword[if] identifier[filehandle] keyword[in] identifier[self] . identifier[files] :
identifier[self] . identifier[fil... | def close(self, filehandle):
"""Close openend file if no longer used."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
while size > self.size and index < size:
... |
def _matchOther(self, obj, **kwargs):
"""Perform _match but on another object, not self."""
if obj is not None:
# Need to check that the returned UI element wasn't destroyed first:
if self._findFirstR(**kwargs):
return obj._match(**kwargs)
return False | def function[_matchOther, parameter[self, obj]]:
constant[Perform _match but on another object, not self.]
if compare[name[obj] is_not constant[None]] begin[:]
if call[name[self]._findFirstR, parameter[]] begin[:]
return[call[name[obj]._match, parameter[]]]
return[constan... | keyword[def] identifier[_matchOther] ( identifier[self] , identifier[obj] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[obj] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[self] . identifier[_findFirstR] (** identifier[kwargs] ):
... | def _matchOther(self, obj, **kwargs):
"""Perform _match but on another object, not self."""
if obj is not None:
# Need to check that the returned UI element wasn't destroyed first:
if self._findFirstR(**kwargs):
return obj._match(**kwargs) # depends on [control=['if'], data=[]] # d... |
def homer_stats_table_tagInfo(self):
""" Add core HOMER stats to the general stats table from tagInfo file"""
if len(self.tagdir_data['header']) == 0:
return None
headers = OrderedDict()
headers['UniqPositions'] = {
'title': 'Uniq Pos',
'description'... | def function[homer_stats_table_tagInfo, parameter[self]]:
constant[ Add core HOMER stats to the general stats table from tagInfo file]
if compare[call[name[len], parameter[call[name[self].tagdir_data][constant[header]]]] equal[==] constant[0]] begin[:]
return[constant[None]]
variable[hea... | keyword[def] identifier[homer_stats_table_tagInfo] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[tagdir_data] [ literal[string] ])== literal[int] :
keyword[return] keyword[None]
identifier[headers] = identifier[OrderedDi... | def homer_stats_table_tagInfo(self):
""" Add core HOMER stats to the general stats table from tagInfo file"""
if len(self.tagdir_data['header']) == 0:
return None # depends on [control=['if'], data=[]]
headers = OrderedDict()
headers['UniqPositions'] = {'title': 'Uniq Pos', 'description': 'Nume... |
def get_config(self):
"""Return configurations of BoltzmannQPolicy
# Returns
Dict of config
"""
config = super(BoltzmannQPolicy, self).get_config()
config['tau'] = self.tau
config['clip'] = self.clip
return config | def function[get_config, parameter[self]]:
constant[Return configurations of BoltzmannQPolicy
# Returns
Dict of config
]
variable[config] assign[=] call[call[name[super], parameter[name[BoltzmannQPolicy], name[self]]].get_config, parameter[]]
call[name[config]][const... | keyword[def] identifier[get_config] ( identifier[self] ):
literal[string]
identifier[config] = identifier[super] ( identifier[BoltzmannQPolicy] , identifier[self] ). identifier[get_config] ()
identifier[config] [ literal[string] ]= identifier[self] . identifier[tau]
identifier[co... | def get_config(self):
"""Return configurations of BoltzmannQPolicy
# Returns
Dict of config
"""
config = super(BoltzmannQPolicy, self).get_config()
config['tau'] = self.tau
config['clip'] = self.clip
return config |
def _on_server_disconnect(self, exception):
"""Handle server disconnection."""
self._protocol = None
if self._on_disconnect_callback_func and callable(self._on_disconnect_callback_func):
self._on_disconnect_callback_func(exception)
if self._reconnect:
self._reconn... | def function[_on_server_disconnect, parameter[self, exception]]:
constant[Handle server disconnection.]
name[self]._protocol assign[=] constant[None]
if <ast.BoolOp object at 0x7da1b02e5a20> begin[:]
call[name[self]._on_disconnect_callback_func, parameter[name[exception]]]
... | keyword[def] identifier[_on_server_disconnect] ( identifier[self] , identifier[exception] ):
literal[string]
identifier[self] . identifier[_protocol] = keyword[None]
keyword[if] identifier[self] . identifier[_on_disconnect_callback_func] keyword[and] identifier[callable] ( identifier[s... | def _on_server_disconnect(self, exception):
"""Handle server disconnection."""
self._protocol = None
if self._on_disconnect_callback_func and callable(self._on_disconnect_callback_func):
self._on_disconnect_callback_func(exception) # depends on [control=['if'], data=[]]
if self._reconnect:
... |
def load(fname: str) -> 'Config':
"""
Returns a Config object loaded from a file. The loaded object is not frozen.
:param fname: Name of file to load the Config from.
:return: Configuration.
"""
with open(fname) as inp:
obj = yaml.load(inp)
obj.__... | def function[load, parameter[fname]]:
constant[
Returns a Config object loaded from a file. The loaded object is not frozen.
:param fname: Name of file to load the Config from.
:return: Configuration.
]
with call[name[open], parameter[name[fname]]] begin[:]
... | keyword[def] identifier[load] ( identifier[fname] : identifier[str] )-> literal[string] :
literal[string]
keyword[with] identifier[open] ( identifier[fname] ) keyword[as] identifier[inp] :
identifier[obj] = identifier[yaml] . identifier[load] ( identifier[inp] )
identifi... | def load(fname: str) -> 'Config':
"""
Returns a Config object loaded from a file. The loaded object is not frozen.
:param fname: Name of file to load the Config from.
:return: Configuration.
"""
with open(fname) as inp:
obj = yaml.load(inp)
obj.__add_frozen()
... |
def validate_duration(self, field, duration):
'''
2h
2h5m
5m
180
1h4m3
:param duration:
:return:
'''
DURATION_RE = r'^(\d+d)?(\d+h)?(\d+m)?(\d+s?)?$'
if not re.match(DURATION_RE, duration):
self._error(field, 'Load durat... | def function[validate_duration, parameter[self, field, duration]]:
constant[
2h
2h5m
5m
180
1h4m3
:param duration:
:return:
]
variable[DURATION_RE] assign[=] constant[^(\d+d)?(\d+h)?(\d+m)?(\d+s?)?$]
if <ast.UnaryOp object at 0x7da1... | keyword[def] identifier[validate_duration] ( identifier[self] , identifier[field] , identifier[duration] ):
literal[string]
identifier[DURATION_RE] = literal[string]
keyword[if] keyword[not] identifier[re] . identifier[match] ( identifier[DURATION_RE] , identifier[duration] ):
... | def validate_duration(self, field, duration):
"""
2h
2h5m
5m
180
1h4m3
:param duration:
:return:
"""
DURATION_RE = '^(\\d+d)?(\\d+h)?(\\d+m)?(\\d+s?)?$'
if not re.match(DURATION_RE, duration):
self._error(field, 'Load duration examples:... |
def horizontal_infrared_radiation_intensity(self, value=9999.0):
"""Corresponds to IDD Field `horizontal_infrared_radiation_intensity`
Args:
value (float): value for IDD Field `horizontal_infrared_radiation_intensity`
Unit: Wh/m2
value >= 0.0
... | def function[horizontal_infrared_radiation_intensity, parameter[self, value]]:
constant[Corresponds to IDD Field `horizontal_infrared_radiation_intensity`
Args:
value (float): value for IDD Field `horizontal_infrared_radiation_intensity`
Unit: Wh/m2
value >= ... | keyword[def] identifier[horizontal_infrared_radiation_intensity] ( identifier[self] , identifier[value] = literal[int] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[value] = identifier[float] ( i... | def horizontal_infrared_radiation_intensity(self, value=9999.0):
"""Corresponds to IDD Field `horizontal_infrared_radiation_intensity`
Args:
value (float): value for IDD Field `horizontal_infrared_radiation_intensity`
Unit: Wh/m2
value >= 0.0
Miss... |
def connect(self, ip_address, tsap_snap7, tsap_logo, tcpport=102):
"""
Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 =... | def function[connect, parameter[self, ip_address, tsap_snap7, tsap_logo, tcpport]]:
constant[
Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNA... | keyword[def] identifier[connect] ( identifier[self] , identifier[ip_address] , identifier[tsap_snap7] , identifier[tsap_logo] , identifier[tcpport] = literal[int] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] %( identifier[ip_address] , identifier[tcpport] ,
id... | def connect(self, ip_address, tsap_snap7, tsap_logo, tcpport=102):
"""
Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1... |
def receive_ack_requesting(self, pkt):
"""Receive ACK in REQUESTING state."""
logger.debug("C3. Received ACK?, in REQUESTING state.")
if self.process_received_ack(pkt):
logger.debug("C3: T. Received ACK, in REQUESTING state, "
"raise BOUND.")
rais... | def function[receive_ack_requesting, parameter[self, pkt]]:
constant[Receive ACK in REQUESTING state.]
call[name[logger].debug, parameter[constant[C3. Received ACK?, in REQUESTING state.]]]
if call[name[self].process_received_ack, parameter[name[pkt]]] begin[:]
call[name[logger].... | keyword[def] identifier[receive_ack_requesting] ( identifier[self] , identifier[pkt] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identifier[self] . identifier[process_received_ack] ( identifier[pkt] ):
identifier[logger] . identif... | def receive_ack_requesting(self, pkt):
"""Receive ACK in REQUESTING state."""
logger.debug('C3. Received ACK?, in REQUESTING state.')
if self.process_received_ack(pkt):
logger.debug('C3: T. Received ACK, in REQUESTING state, raise BOUND.')
raise self.BOUND() # depends on [control=['if'], da... |
def from_data( name, coors, ngroups, conns, mat_ids, descs, igs = None ):
"""
Create a mesh from mesh data.
"""
if igs is None:
igs = range( len( conns ) )
mesh = Mesh(name)
mesh._set_data(coors = coors,
ngroups = ngroups,
... | def function[from_data, parameter[name, coors, ngroups, conns, mat_ids, descs, igs]]:
constant[
Create a mesh from mesh data.
]
if compare[name[igs] is constant[None]] begin[:]
variable[igs] assign[=] call[name[range], parameter[call[name[len], parameter[name[conns]]]]]
... | keyword[def] identifier[from_data] ( identifier[name] , identifier[coors] , identifier[ngroups] , identifier[conns] , identifier[mat_ids] , identifier[descs] , identifier[igs] = keyword[None] ):
literal[string]
keyword[if] identifier[igs] keyword[is] keyword[None] :
identifier[igs] ... | def from_data(name, coors, ngroups, conns, mat_ids, descs, igs=None):
"""
Create a mesh from mesh data.
"""
if igs is None:
igs = range(len(conns)) # depends on [control=['if'], data=['igs']]
mesh = Mesh(name)
mesh._set_data(coors=coors, ngroups=ngroups, conns=[conns[ig] for ig ... |
def run_command_under_r_root(self, cmd, catched=True):
"""
subprocess run on here
"""
RPATH = self.path
with self.cd(newdir=RPATH):
if catched:
process = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
else:
process = sp.run(cmd... | def function[run_command_under_r_root, parameter[self, cmd, catched]]:
constant[
subprocess run on here
]
variable[RPATH] assign[=] name[self].path
with call[name[self].cd, parameter[]] begin[:]
if name[catched] begin[:]
variable[process] a... | keyword[def] identifier[run_command_under_r_root] ( identifier[self] , identifier[cmd] , identifier[catched] = keyword[True] ):
literal[string]
identifier[RPATH] = identifier[self] . identifier[path]
keyword[with] identifier[self] . identifier[cd] ( identifier[newdir] = identifier[RPATH]... | def run_command_under_r_root(self, cmd, catched=True):
"""
subprocess run on here
"""
RPATH = self.path
with self.cd(newdir=RPATH):
if catched:
process = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE) # depends on [control=['if'], data=[]]
else:
process ... |
def browse(self, cat=None, subCat=None):
"""Browse categories. If neither cat nor subcat are specified,
return a list of categories, otherwise it return a list of apps
using cat (category ID) and subCat (subcategory ID) as filters."""
path = BROWSE_URL + "?c=3"
if cat is not None... | def function[browse, parameter[self, cat, subCat]]:
constant[Browse categories. If neither cat nor subcat are specified,
return a list of categories, otherwise it return a list of apps
using cat (category ID) and subCat (subcategory ID) as filters.]
variable[path] assign[=] binary_operat... | keyword[def] identifier[browse] ( identifier[self] , identifier[cat] = keyword[None] , identifier[subCat] = keyword[None] ):
literal[string]
identifier[path] = identifier[BROWSE_URL] + literal[string]
keyword[if] identifier[cat] keyword[is] keyword[not] keyword[None] :
id... | def browse(self, cat=None, subCat=None):
"""Browse categories. If neither cat nor subcat are specified,
return a list of categories, otherwise it return a list of apps
using cat (category ID) and subCat (subcategory ID) as filters."""
path = BROWSE_URL + '?c=3'
if cat is not None:
pa... |
def wrap_function(func):
"""
RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH
"""
if is_text(func):
return compile_expression(func)
numarg = func.__code__.co_argcount
if numarg == 0:
def temp(row, rownum, rows):
return func()
return temp
elif numarg ==... | def function[wrap_function, parameter[func]]:
constant[
RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH
]
if call[name[is_text], parameter[name[func]]] begin[:]
return[call[name[compile_expression], parameter[name[func]]]]
variable[numarg] assign[=] name[func].__code__.co_argco... | keyword[def] identifier[wrap_function] ( identifier[func] ):
literal[string]
keyword[if] identifier[is_text] ( identifier[func] ):
keyword[return] identifier[compile_expression] ( identifier[func] )
identifier[numarg] = identifier[func] . identifier[__code__] . identifier[co_argcount]
... | def wrap_function(func):
"""
RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH
"""
if is_text(func):
return compile_expression(func) # depends on [control=['if'], data=[]]
numarg = func.__code__.co_argcount
if numarg == 0:
def temp(row, rownum, rows):
return func()
... |
def seconds_to_DHMS(seconds, as_str=True):
"""converts seconds to Days, Hours, Minutes, Seconds
:param int seconds: number of seconds
:param bool as_string: to return a formated string defaults to True
:returns: a formated string if as_str else a dictionary
:Example:
>>> seconds_to_DHMS(60*... | def function[seconds_to_DHMS, parameter[seconds, as_str]]:
constant[converts seconds to Days, Hours, Minutes, Seconds
:param int seconds: number of seconds
:param bool as_string: to return a formated string defaults to True
:returns: a formated string if as_str else a dictionary
:Example:
... | keyword[def] identifier[seconds_to_DHMS] ( identifier[seconds] , identifier[as_str] = keyword[True] ):
literal[string]
identifier[d] = identifier[DotDot] ()
identifier[d] . identifier[days] = identifier[int] ( identifier[seconds] //( literal[int] * literal[int] ))
identifier[d] . identifier[hours... | def seconds_to_DHMS(seconds, as_str=True):
"""converts seconds to Days, Hours, Minutes, Seconds
:param int seconds: number of seconds
:param bool as_string: to return a formated string defaults to True
:returns: a formated string if as_str else a dictionary
:Example:
>>> seconds_to_DHMS(60*... |
def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.... | def function[evaluate_binop_logical, parameter[self, operation, left, right]]:
constant[
Evaluate given logical binary operation with given operands.
]
if <ast.UnaryOp object at 0x7da20c6aa350> begin[:]
<ast.Raise object at 0x7da20c6a9bd0>
variable[result] assign[=] call[... | keyword[def] identifier[evaluate_binop_logical] ( identifier[self] , identifier[operation] , identifier[left] , identifier[right] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[operation] keyword[in] identifier[self] . identifier[binops_logical] :
key... | def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation)) # depends on [control=['if'], dat... |
def define_laser_variables(Nl, real_amplitudes=False, variables=None):
r"""Return the amplitudes and frequencies of Nl fields.
>>> E0, omega_laser = define_laser_variables(2)
>>> E0, omega_laser
([E_0^1, E_0^2], [varpi_1, varpi_2])
The amplitudes are complex by default:
>>> conjugate(E0[0])
... | def function[define_laser_variables, parameter[Nl, real_amplitudes, variables]]:
constant[Return the amplitudes and frequencies of Nl fields.
>>> E0, omega_laser = define_laser_variables(2)
>>> E0, omega_laser
([E_0^1, E_0^2], [varpi_1, varpi_2])
The amplitudes are complex by default:
>>> ... | keyword[def] identifier[define_laser_variables] ( identifier[Nl] , identifier[real_amplitudes] = keyword[False] , identifier[variables] = keyword[None] ):
literal[string]
keyword[if] identifier[variables] keyword[is] keyword[None] :
identifier[E0] =[ identifier[Symbol] ( literal[string] + ident... | def define_laser_variables(Nl, real_amplitudes=False, variables=None):
"""Return the amplitudes and frequencies of Nl fields.
>>> E0, omega_laser = define_laser_variables(2)
>>> E0, omega_laser
([E_0^1, E_0^2], [varpi_1, varpi_2])
The amplitudes are complex by default:
>>> conjugate(E0[0])
... |
def squad_v2_exact_match(y_true: List[List[str]], y_predicted: List[str]) -> float:
""" Calculates Exact Match score between y_true and y_predicted
EM score uses the best matching y_true answer:
if y_pred equal at least to one answer in y_true then EM = 1, else EM = 0
The same as in SQuAD-v... | def function[squad_v2_exact_match, parameter[y_true, y_predicted]]:
constant[ Calculates Exact Match score between y_true and y_predicted
EM score uses the best matching y_true answer:
if y_pred equal at least to one answer in y_true then EM = 1, else EM = 0
The same as in SQuAD-v2.0
... | keyword[def] identifier[squad_v2_exact_match] ( identifier[y_true] : identifier[List] [ identifier[List] [ identifier[str] ]], identifier[y_predicted] : identifier[List] [ identifier[str] ])-> identifier[float] :
literal[string]
identifier[EM_total] = identifier[sum] ( identifier[normalize_answer] ( identi... | def squad_v2_exact_match(y_true: List[List[str]], y_predicted: List[str]) -> float:
""" Calculates Exact Match score between y_true and y_predicted
EM score uses the best matching y_true answer:
if y_pred equal at least to one answer in y_true then EM = 1, else EM = 0
The same as in SQuAD-v... |
def run_segment_operation(outdoc, filenames, segments, use_segment_table, operation, result_name = 'RESULT', preserve = True):
"""
Performs an operation (intersect or union) across a set of segments.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc and a list of segments... | def function[run_segment_operation, parameter[outdoc, filenames, segments, use_segment_table, operation, result_name, preserve]]:
constant[
Performs an operation (intersect or union) across a set of segments.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc and a lis... | keyword[def] identifier[run_segment_operation] ( identifier[outdoc] , identifier[filenames] , identifier[segments] , identifier[use_segment_table] , identifier[operation] , identifier[result_name] = literal[string] , identifier[preserve] = keyword[True] ):
literal[string]
identifier[proc_id] = identifier[... | def run_segment_operation(outdoc, filenames, segments, use_segment_table, operation, result_name='RESULT', preserve=True):
"""
Performs an operation (intersect or union) across a set of segments.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc and a list of segments DMT... |
def invocation_environment_dict(self):
"""A dict to use as this _Executable's execution environment.
This isn't made into an "algebraic" field because its contents (the keys of the dict) are
generally known to the specific class which is overriding this property. Implementations of this
property can th... | def function[invocation_environment_dict, parameter[self]]:
constant[A dict to use as this _Executable's execution environment.
This isn't made into an "algebraic" field because its contents (the keys of the dict) are
generally known to the specific class which is overriding this property. Implementati... | keyword[def] identifier[invocation_environment_dict] ( identifier[self] ):
literal[string]
identifier[lib_env_var] = identifier[self] . identifier[_platform] . identifier[resolve_for_enum_variant] ({
literal[string] : literal[string] ,
literal[string] : literal[string] ,
})
keyword[retur... | def invocation_environment_dict(self):
"""A dict to use as this _Executable's execution environment.
This isn't made into an "algebraic" field because its contents (the keys of the dict) are
generally known to the specific class which is overriding this property. Implementations of this
property can th... |
def parse_www_authenticate_header(value, on_update=None):
"""Parse an HTTP WWW-Authenticate header into a
:class:`~werkzeug.datastructures.WWWAuthenticate` object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a value
... | def function[parse_www_authenticate_header, parameter[value, on_update]]:
constant[Parse an HTTP WWW-Authenticate header into a
:class:`~werkzeug.datastructures.WWWAuthenticate` object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every tim... | keyword[def] identifier[parse_www_authenticate_header] ( identifier[value] , identifier[on_update] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[value] :
keyword[return] identifier[WWWAuthenticate] ( identifier[on_update] = identifier[on_update] )
keyword[try] :
... | def parse_www_authenticate_header(value, on_update=None):
"""Parse an HTTP WWW-Authenticate header into a
:class:`~werkzeug.datastructures.WWWAuthenticate` object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a value
... |
def make_agent() -> EcommerceAgent:
"""Make an agent
Returns:
agent: created Ecommerce agent
"""
config_path = find_config('tfidf_retrieve')
skill = build_model(config_path)
agent = EcommerceAgent(skills=[skill])
return agent | def function[make_agent, parameter[]]:
constant[Make an agent
Returns:
agent: created Ecommerce agent
]
variable[config_path] assign[=] call[name[find_config], parameter[constant[tfidf_retrieve]]]
variable[skill] assign[=] call[name[build_model], parameter[name[config_path]]]
... | keyword[def] identifier[make_agent] ()-> identifier[EcommerceAgent] :
literal[string]
identifier[config_path] = identifier[find_config] ( literal[string] )
identifier[skill] = identifier[build_model] ( identifier[config_path] )
identifier[agent] = identifier[EcommerceAgent] ( identifier[skills] ... | def make_agent() -> EcommerceAgent:
"""Make an agent
Returns:
agent: created Ecommerce agent
"""
config_path = find_config('tfidf_retrieve')
skill = build_model(config_path)
agent = EcommerceAgent(skills=[skill])
return agent |
def config_filename(filename):
"""
Obtains the first filename found that is included in one of the configuration folders.
This function returs the full path for the file.
* It is useful for files that are not config-formatted (e.g. hosts files, json, etc.)
that will be rea... | def function[config_filename, parameter[filename]]:
constant[
Obtains the first filename found that is included in one of the configuration folders.
This function returs the full path for the file.
* It is useful for files that are not config-formatted (e.g. hosts files, json, e... | keyword[def] identifier[config_filename] ( identifier[filename] ):
literal[string]
keyword[global] identifier[_ETC_PATHS]
keyword[if] identifier[filename] . identifier[startswith] ( literal[string] ):
identifier[_LOGGER] . identifier[info] ( literal[string] % identifier[filename] )
... | def config_filename(filename):
"""
Obtains the first filename found that is included in one of the configuration folders.
This function returs the full path for the file.
* It is useful for files that are not config-formatted (e.g. hosts files, json, etc.)
that will be rea... |
def set_regionfiles(self, filenames):
"""
This method directly sets the region files for this instance to use.
It assumes the filenames are in the form r.<x-digit>.<z-digit>.<extension>
"""
for filename in filenames:
# Assume that filenames have the name r.<x-digit>.<... | def function[set_regionfiles, parameter[self, filenames]]:
constant[
This method directly sets the region files for this instance to use.
It assumes the filenames are in the form r.<x-digit>.<z-digit>.<extension>
]
for taget[name[filename]] in starred[name[filenames]] begin[:]
... | keyword[def] identifier[set_regionfiles] ( identifier[self] , identifier[filenames] ):
literal[string]
keyword[for] identifier[filename] keyword[in] identifier[filenames] :
identifier[m] = identifier[re] . identifier[match] ( literal[string] + identifier[self] . identifier[... | def set_regionfiles(self, filenames):
"""
This method directly sets the region files for this instance to use.
It assumes the filenames are in the form r.<x-digit>.<z-digit>.<extension>
"""
for filename in filenames:
# Assume that filenames have the name r.<x-digit>.<z-digit>.<ex... |
def write(self, b):
'''write some bytes'''
from . import mavutil
self.debug("sending '%s' (0x%02x) of len %u\n" % (b, ord(b[0]), len(b)), 2)
while len(b) > 0:
n = len(b)
if n > 70:
... | def function[write, parameter[self, b]]:
constant[write some bytes]
from relative_module[None] import module[mavutil]
call[name[self].debug, parameter[binary_operation[constant[sending '%s' (0x%02x) of len %u
] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da20e9b2d40>, <ast.Call ... | keyword[def] identifier[write] ( identifier[self] , identifier[b] ):
literal[string]
keyword[from] . keyword[import] identifier[mavutil]
identifier[self] . identifier[debug] ( literal[string] %( identifier[b] , identifier[ord] ( identifier[b] [ literal[int] ]), id... | def write(self, b):
"""write some bytes"""
from . import mavutil
self.debug("sending '%s' (0x%02x) of len %u\n" % (b, ord(b[0]), len(b)), 2)
while len(b) > 0:
n = len(b)
if n > 70:
n = 70 # depends on [control=['if'], data=['n']]
buf = [ord(x) for x in b[:n]]
... |
def begin(self):
""" Begin a transaction """
if self.journal != None:
raise Exception('Storage is already active, nested begin not supported')
# under normal operation journal is deleted at end of transaction
# if it does exist we need to roll back
if os.path.isfile... | def function[begin, parameter[self]]:
constant[ Begin a transaction ]
if compare[name[self].journal not_equal[!=] constant[None]] begin[:]
<ast.Raise object at 0x7da18eb55b40>
if call[name[os].path.isfile, parameter[name[self].j_file]] begin[:]
call[name[self].rollback, p... | keyword[def] identifier[begin] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[journal] != keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[if] identifier[os] . identifier[path] . id... | def begin(self):
""" Begin a transaction """
if self.journal != None:
raise Exception('Storage is already active, nested begin not supported') # depends on [control=['if'], data=[]]
# under normal operation journal is deleted at end of transaction
# if it does exist we need to roll back
if ... |
def setLayout(self, value):
"""
Sets the worksheet layout, keeping it sorted by position
:param value: the layout to set
"""
new_layout = sorted(value, key=lambda k: k['position'])
self.getField('Layout').set(self, new_layout) | def function[setLayout, parameter[self, value]]:
constant[
Sets the worksheet layout, keeping it sorted by position
:param value: the layout to set
]
variable[new_layout] assign[=] call[name[sorted], parameter[name[value]]]
call[call[name[self].getField, parameter[constan... | keyword[def] identifier[setLayout] ( identifier[self] , identifier[value] ):
literal[string]
identifier[new_layout] = identifier[sorted] ( identifier[value] , identifier[key] = keyword[lambda] identifier[k] : identifier[k] [ literal[string] ])
identifier[self] . identifier[getField] ( lit... | def setLayout(self, value):
"""
Sets the worksheet layout, keeping it sorted by position
:param value: the layout to set
"""
new_layout = sorted(value, key=lambda k: k['position'])
self.getField('Layout').set(self, new_layout) |
def add_raw(self, raw):
"""
Adds row aggregation state at the query
:param raw: list of raw stages or a dict of raw stage
:return: The current object
"""
if type(raw) == list:
self._q += raw
if type(raw) == dict:
self._q.append(raw)
... | def function[add_raw, parameter[self, raw]]:
constant[
Adds row aggregation state at the query
:param raw: list of raw stages or a dict of raw stage
:return: The current object
]
if compare[call[name[type], parameter[name[raw]]] equal[==] name[list]] begin[:]
<ast... | keyword[def] identifier[add_raw] ( identifier[self] , identifier[raw] ):
literal[string]
keyword[if] identifier[type] ( identifier[raw] )== identifier[list] :
identifier[self] . identifier[_q] += identifier[raw]
keyword[if] identifier[type] ( identifier[raw] )== identifier[... | def add_raw(self, raw):
"""
Adds row aggregation state at the query
:param raw: list of raw stages or a dict of raw stage
:return: The current object
"""
if type(raw) == list:
self._q += raw # depends on [control=['if'], data=[]]
if type(raw) == dict:
self._q... |
def image2working(self,i):
"""Transform images i provided into the specified working
color space."""
return self.colorspace.convert(self.image_space,
self.working_space, i) | def function[image2working, parameter[self, i]]:
constant[Transform images i provided into the specified working
color space.]
return[call[name[self].colorspace.convert, parameter[name[self].image_space, name[self].working_space, name[i]]]] | keyword[def] identifier[image2working] ( identifier[self] , identifier[i] ):
literal[string]
keyword[return] identifier[self] . identifier[colorspace] . identifier[convert] ( identifier[self] . identifier[image_space] ,
identifier[self] . identifier[working_space] , identifier[i] ) | def image2working(self, i):
"""Transform images i provided into the specified working
color space."""
return self.colorspace.convert(self.image_space, self.working_space, i) |
def change_password(self, new_password, email):
"""
Changes the login password
:param new_password: The new login password to set for the account
:param email: The current email of the account
"""
log.info("[+] Changing the password of the account")
return self._... | def function[change_password, parameter[self, new_password, email]]:
constant[
Changes the login password
:param new_password: The new login password to set for the account
:param email: The current email of the account
]
call[name[log].info, parameter[constant[[+] Chang... | keyword[def] identifier[change_password] ( identifier[self] , identifier[new_password] , identifier[email] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] )
keyword[return] identifier[self] . identifier[_send_xmpp_element] ( identifier[account] . identifier[ChangeP... | def change_password(self, new_password, email):
"""
Changes the login password
:param new_password: The new login password to set for the account
:param email: The current email of the account
"""
log.info('[+] Changing the password of the account')
return self._send_xmpp_el... |
def list_servers(self, nicknames=None):
"""
Iterate through the servers of the server group with the specified
nicknames, or the single server with the specified nickname, and yield
a `ServerDefinition` object for each server.
nicknames may be: None, string defining a nickname o... | def function[list_servers, parameter[self, nicknames]]:
constant[
Iterate through the servers of the server group with the specified
nicknames, or the single server with the specified nickname, and yield
a `ServerDefinition` object for each server.
nicknames may be: None, string... | keyword[def] identifier[list_servers] ( identifier[self] , identifier[nicknames] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[nicknames] :
keyword[return] identifier[self] . identifier[list_all_servers] ()
keyword[if] identifier[isinstance] ( ide... | def list_servers(self, nicknames=None):
"""
Iterate through the servers of the server group with the specified
nicknames, or the single server with the specified nickname, and yield
a `ServerDefinition` object for each server.
nicknames may be: None, string defining a nickname or li... |
def _from_dict(cls, _dict):
"""Initialize a MessageOutputDebug object from a json dictionary."""
args = {}
if 'nodes_visited' in _dict:
args['nodes_visited'] = [
DialogNodesVisited._from_dict(x)
for x in (_dict.get('nodes_visited'))
]
... | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a MessageOutputDebug object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
if compare[constant[nodes_visited] in name[_dict]] begin[:]
call[name[args]][constant[nodes_visited]] assign[=] <a... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[string] ]=[
identifier[DialogNodesVisited] . identifier[_fro... | def _from_dict(cls, _dict):
"""Initialize a MessageOutputDebug object from a json dictionary."""
args = {}
if 'nodes_visited' in _dict:
args['nodes_visited'] = [DialogNodesVisited._from_dict(x) for x in _dict.get('nodes_visited')] # depends on [control=['if'], data=['_dict']]
if 'log_messages' ... |
def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs):
"""
Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifier: either t... | def function[query_more, parameter[self, next_records_identifier, identifier_is_url]]:
constant[
Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifie... | keyword[def] identifier[query_more] ( identifier[self] , identifier[next_records_identifier] , identifier[identifier_is_url] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[identifier_is_url] :
identifier[url] =( literal[string]
... | def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs):
"""
Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifier: either the I... |
def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list:
"""Find a list of files with the given classification"""
return [
filename
for output, target, filename in zip(self.outputs, self.targets, self.filenames)
if ((output > threshold) ... | def function[calc_filenames, parameter[self, is_correct, actual_output, threshold]]:
constant[Find a list of files with the given classification]
return[<ast.ListComp object at 0x7da18ede5000>] | keyword[def] identifier[calc_filenames] ( identifier[self] , identifier[is_correct] : identifier[bool] , identifier[actual_output] : identifier[bool] , identifier[threshold] = literal[int] )-> identifier[list] :
literal[string]
keyword[return] [
identifier[filename]
keyword[for] ... | def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list:
"""Find a list of files with the given classification"""
return [filename for (output, target, filename) in zip(self.outputs, self.targets, self.filenames) if ((output > threshold) == bool(target)) == is_correct and actual_o... |
def cherry_pick(self):
""" git cherry-pick -x <commit_sha1> """
cmd = ["git", "cherry-pick", "-x", self.commit_sha1]
try:
self.run_cmd(cmd)
except subprocess.CalledProcessError as err:
click.echo(f"Error cherry-pick {self.commit_sha1}.")
click.echo(err... | def function[cherry_pick, parameter[self]]:
constant[ git cherry-pick -x <commit_sha1> ]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da18eb55990>, <ast.Constant object at 0x7da18eb54520>, <ast.Constant object at 0x7da18eb55030>, <ast.Attribute object at 0x7da18eb541f0>]]
<ast.Try object... | keyword[def] identifier[cherry_pick] ( identifier[self] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , identifier[self] . identifier[commit_sha1] ]
keyword[try] :
identifier[self] . identifier[run_cmd] ( identifier[cmd] )
k... | def cherry_pick(self):
""" git cherry-pick -x <commit_sha1> """
cmd = ['git', 'cherry-pick', '-x', self.commit_sha1]
try:
self.run_cmd(cmd) # depends on [control=['try'], data=[]]
except subprocess.CalledProcessError as err:
click.echo(f'Error cherry-pick {self.commit_sha1}.')
c... |
def get_arg_dict(argv=None, prefix_list=['--'], type_hints={}):
r"""
Yet another way for parsing args
CommandLine:
python -m utool.util_arg --exec-get_arg_dict
python -m utool.util_arg --test-get_arg_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * #... | def function[get_arg_dict, parameter[argv, prefix_list, type_hints]]:
constant[
Yet another way for parsing args
CommandLine:
python -m utool.util_arg --exec-get_arg_dict
python -m utool.util_arg --test-get_arg_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_... | keyword[def] identifier[get_arg_dict] ( identifier[argv] = keyword[None] , identifier[prefix_list] =[ literal[string] ], identifier[type_hints] ={}):
literal[string]
keyword[if] identifier[argv] keyword[is] keyword[None] :
identifier[argv] = identifier[sys] . identifier[argv]
identifier[a... | def get_arg_dict(argv=None, prefix_list=['--'], type_hints={}):
"""
Yet another way for parsing args
CommandLine:
python -m utool.util_arg --exec-get_arg_dict
python -m utool.util_arg --test-get_arg_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # ... |
def stacksize(self):
"""The maximum amount of stack space used by this code object.
"""
return max(scanl(
op.add,
0,
map(op.attrgetter('stack_effect'), self.instrs),
)) | def function[stacksize, parameter[self]]:
constant[The maximum amount of stack space used by this code object.
]
return[call[name[max], parameter[call[name[scanl], parameter[name[op].add, constant[0], call[name[map], parameter[call[name[op].attrgetter, parameter[constant[stack_effect]]], name[self].... | keyword[def] identifier[stacksize] ( identifier[self] ):
literal[string]
keyword[return] identifier[max] ( identifier[scanl] (
identifier[op] . identifier[add] ,
literal[int] ,
identifier[map] ( identifier[op] . identifier[attrgetter] ( literal[string] ), identifier[self... | def stacksize(self):
"""The maximum amount of stack space used by this code object.
"""
return max(scanl(op.add, 0, map(op.attrgetter('stack_effect'), self.instrs))) |
def _get_ref_alt(self, var, boundary):
"""Get reference allele and alternative allele of the variant
"""
# Get reference allele
if var.posedit.edit.type == "ins" or var.posedit.edit.type == "dup":
ref = ""
else:
# For NARefAlt and Inv
if var.p... | def function[_get_ref_alt, parameter[self, var, boundary]]:
constant[Get reference allele and alternative allele of the variant
]
if <ast.BoolOp object at 0x7da207f993f0> begin[:]
variable[ref] assign[=] constant[]
if <ast.BoolOp object at 0x7da207f9b700> begin[:]
... | keyword[def] identifier[_get_ref_alt] ( identifier[self] , identifier[var] , identifier[boundary] ):
literal[string]
keyword[if] identifier[var] . identifier[posedit] . identifier[edit] . identifier[type] == literal[string] keyword[or] identifier[var] . identifier[posedit] . identifier... | def _get_ref_alt(self, var, boundary):
"""Get reference allele and alternative allele of the variant
"""
# Get reference allele
if var.posedit.edit.type == 'ins' or var.posedit.edit.type == 'dup':
ref = '' # depends on [control=['if'], data=[]]
# For NARefAlt and Inv
elif var.posedi... |
def __create_author_investigator_str(self):
"""
When investigators is empty, try to get authors from the first publication instead.
:return str author: Author names
"""
_author = ""
try:
for pub in self.noaa_data_sorted["Publication"]:
if "auth... | def function[__create_author_investigator_str, parameter[self]]:
constant[
When investigators is empty, try to get authors from the first publication instead.
:return str author: Author names
]
variable[_author] assign[=] constant[]
<ast.Try object at 0x7da18f723640>
retu... | keyword[def] identifier[__create_author_investigator_str] ( identifier[self] ):
literal[string]
identifier[_author] = literal[string]
keyword[try] :
keyword[for] identifier[pub] keyword[in] identifier[self] . identifier[noaa_data_sorted] [ literal[string] ]:
... | def __create_author_investigator_str(self):
"""
When investigators is empty, try to get authors from the first publication instead.
:return str author: Author names
"""
_author = ''
try:
for pub in self.noaa_data_sorted['Publication']:
if 'author' in pub:
... |
def dump(self, filename=None, compressed=True, pretty=True):
'''dump device window and pull to local file.'''
content = self.server.jsonrpc.dumpWindowHierarchy(compressed, None)
if filename:
with open(filename, "wb") as f:
f.write(content.encode("utf-8"))
if p... | def function[dump, parameter[self, filename, compressed, pretty]]:
constant[dump device window and pull to local file.]
variable[content] assign[=] call[name[self].server.jsonrpc.dumpWindowHierarchy, parameter[name[compressed], constant[None]]]
if name[filename] begin[:]
with cal... | keyword[def] identifier[dump] ( identifier[self] , identifier[filename] = keyword[None] , identifier[compressed] = keyword[True] , identifier[pretty] = keyword[True] ):
literal[string]
identifier[content] = identifier[self] . identifier[server] . identifier[jsonrpc] . identifier[dumpWindowHierarchy... | def dump(self, filename=None, compressed=True, pretty=True):
"""dump device window and pull to local file."""
content = self.server.jsonrpc.dumpWindowHierarchy(compressed, None)
if filename:
with open(filename, 'wb') as f:
f.write(content.encode('utf-8')) # depends on [control=['with'],... |
def run(self):
"""Build the Fortran library, all python extensions and the docs."""
print('---- CUSTOM DEVELOP ----')
_develop.run(self)
# build documentation
print('---- BUILDING DOCS ----')
docdir = os.path.join(self.setup_path, 'pyshtools', 'doc')
self.mkpath(... | def function[run, parameter[self]]:
constant[Build the Fortran library, all python extensions and the docs.]
call[name[print], parameter[constant[---- CUSTOM DEVELOP ----]]]
call[name[_develop].run, parameter[name[self]]]
call[name[print], parameter[constant[---- BUILDING DOCS ----]]]
... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[print] ( literal[string] )
identifier[_develop] . identifier[run] ( identifier[self] )
identifier[print] ( literal[string] )
identifier[docdir] = identifier[os] . identifier[path] . id... | def run(self):
"""Build the Fortran library, all python extensions and the docs."""
print('---- CUSTOM DEVELOP ----')
_develop.run(self)
# build documentation
print('---- BUILDING DOCS ----')
docdir = os.path.join(self.setup_path, 'pyshtools', 'doc')
self.mkpath(docdir)
doc_builder = os.... |
def compile_all(self):
"""Compiles all of the contracts in the self.contracts_dir directory
Creates {contract name}.json files in self.output_dir that contain
the build output for each contract.
"""
# Solidity input JSON
solc_input = self.get_solc_input()
# Com... | def function[compile_all, parameter[self]]:
constant[Compiles all of the contracts in the self.contracts_dir directory
Creates {contract name}.json files in self.output_dir that contain
the build output for each contract.
]
variable[solc_input] assign[=] call[name[self].get_solc... | keyword[def] identifier[compile_all] ( identifier[self] ):
literal[string]
identifier[solc_input] = identifier[self] . identifier[get_solc_input] ()
identifier[real_path] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[self] . identifier[contract... | def compile_all(self):
"""Compiles all of the contracts in the self.contracts_dir directory
Creates {contract name}.json files in self.output_dir that contain
the build output for each contract.
"""
# Solidity input JSON
solc_input = self.get_solc_input()
# Compile the contracts... |
def update_customer(self, customer_id, customer_deets):
"""Updates an existing customer."""
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request) | def function[update_customer, parameter[self, customer_id, customer_deets]]:
constant[Updates an existing customer.]
variable[request] assign[=] call[name[self]._put, parameter[binary_operation[constant[customers/] + call[name[str], parameter[name[customer_id]]]], name[customer_deets]]]
return[call[... | keyword[def] identifier[update_customer] ( identifier[self] , identifier[customer_id] , identifier[customer_deets] ):
literal[string]
identifier[request] = identifier[self] . identifier[_put] ( literal[string] + identifier[str] ( identifier[customer_id] ), identifier[customer_deets] )
keyw... | def update_customer(self, customer_id, customer_deets):
"""Updates an existing customer."""
request = self._put('customers/' + str(customer_id), customer_deets)
return self.responder(request) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.