code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def do_some_work(
self,
work_dict):
"""do_some_work
:param work_dict: dictionary for key/values
"""
label = "do_some_work"
log.info(("task - {} - start "
"work_dict={}")
.format(label,
work_dict))
ret_data = {
"job_resul... | def function[do_some_work, parameter[self, work_dict]]:
constant[do_some_work
:param work_dict: dictionary for key/values
]
variable[label] assign[=] constant[do_some_work]
call[name[log].info, parameter[call[constant[task - {} - start work_dict={}].format, parameter[name[label], name[w... | keyword[def] identifier[do_some_work] (
identifier[self] ,
identifier[work_dict] ):
literal[string]
identifier[label] = literal[string]
identifier[log] . identifier[info] (( literal[string]
literal[string] )
. identifier[format] ( identifier[label] ,
identifier[work_dict] ))
... | def do_some_work(self, work_dict):
"""do_some_work
:param work_dict: dictionary for key/values
"""
label = 'do_some_work'
log.info('task - {} - start work_dict={}'.format(label, work_dict))
ret_data = {'job_results': 'some response key={}'.format(str(uuid.uuid4()))}
log.info('task - {} - re... |
def get_object(table, id=None, condition=None, cache=False, fields=None, use_local=False,
engine_name=None, session=None):
"""
Get obj in Local.object_caches first and also use get(cache=True) function if
not found in object_caches
"""
from uliweb import functions, settings
... | def function[get_object, parameter[table, id, condition, cache, fields, use_local, engine_name, session]]:
constant[
Get obj in Local.object_caches first and also use get(cache=True) function if
not found in object_caches
]
from relative_module[uliweb] import module[functions], module[settings]... | keyword[def] identifier[get_object] ( identifier[table] , identifier[id] = keyword[None] , identifier[condition] = keyword[None] , identifier[cache] = keyword[False] , identifier[fields] = keyword[None] , identifier[use_local] = keyword[False] ,
identifier[engine_name] = keyword[None] , identifier[session] = keyword... | def get_object(table, id=None, condition=None, cache=False, fields=None, use_local=False, engine_name=None, session=None):
"""
Get obj in Local.object_caches first and also use get(cache=True) function if
not found in object_caches
"""
from uliweb import functions, settings
model = get_model(ta... |
def roles_accepted(*accepted_rolenames):
"""
This decorator ensures that any uses accessing the decorated route have one
of the needed roles to access it. If an @auth_required decorator is not
supplied already, this decorator will implicitly check @auth_required first
"""
def decorator(method):
... | def function[roles_accepted, parameter[]]:
constant[
This decorator ensures that any uses accessing the decorated route have one
of the needed roles to access it. If an @auth_required decorator is not
supplied already, this decorator will implicitly check @auth_required first
]
def funct... | keyword[def] identifier[roles_accepted] (* identifier[accepted_rolenames] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[method] ):
@ identifier[functools] . identifier[wraps] ( identifier[method] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[k... | def roles_accepted(*accepted_rolenames):
"""
This decorator ensures that any uses accessing the decorated route have one
of the needed roles to access it. If an @auth_required decorator is not
supplied already, this decorator will implicitly check @auth_required first
"""
def decorator(method):... |
def copy(self,
fitness_function=None,
decode_function=None,
fitness_args=None,
decode_args=None,
fitness_kwargs=None,
decode_kwargs=None):
"""Return a copy of this problem.
Optionally replace this problems arguments with thos... | def function[copy, parameter[self, fitness_function, decode_function, fitness_args, decode_args, fitness_kwargs, decode_kwargs]]:
constant[Return a copy of this problem.
Optionally replace this problems arguments with those passed in.
]
if compare[name[fitness_function] is constant[None... | keyword[def] identifier[copy] ( identifier[self] ,
identifier[fitness_function] = keyword[None] ,
identifier[decode_function] = keyword[None] ,
identifier[fitness_args] = keyword[None] ,
identifier[decode_args] = keyword[None] ,
identifier[fitness_kwargs] = keyword[None] ,
identifier[decode_kwargs] = keyword[No... | def copy(self, fitness_function=None, decode_function=None, fitness_args=None, decode_args=None, fitness_kwargs=None, decode_kwargs=None):
"""Return a copy of this problem.
Optionally replace this problems arguments with those passed in.
"""
if fitness_function is None:
fitness_function... |
def from_envvar(self, variable_name):
"""Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
config_file = os.e... | def function[from_envvar, parameter[self, variable_name]]:
constant[Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
]
... | keyword[def] identifier[from_envvar] ( identifier[self] , identifier[variable_name] ):
literal[string]
identifier[config_file] = identifier[os] . identifier[environ] . identifier[get] ( identifier[variable_name] )
keyword[if] keyword[not] identifier[config_file] :
keyword[ra... | def from_envvar(self, variable_name):
"""Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
config_file = os.environ.g... |
def add_value(
self, secret_resource_name, secret_value_resource_name, name, value=None, custom_headers=None, raw=False, **operation_config):
"""Adds the specified value as a new version of the specified secret
resource.
Creates a new value of the specified secret resource. The name... | def function[add_value, parameter[self, secret_resource_name, secret_value_resource_name, name, value, custom_headers, raw]]:
constant[Adds the specified value as a new version of the specified secret
resource.
Creates a new value of the specified secret resource. The name of the
value ... | keyword[def] identifier[add_value] (
identifier[self] , identifier[secret_resource_name] , identifier[secret_value_resource_name] , identifier[name] , identifier[value] = keyword[None] , identifier[custom_headers] = keyword[None] , identifier[raw] = keyword[False] ,** identifier[operation_config] ):
literal... | def add_value(self, secret_resource_name, secret_value_resource_name, name, value=None, custom_headers=None, raw=False, **operation_config):
"""Adds the specified value as a new version of the specified secret
resource.
Creates a new value of the specified secret resource. The name of the
v... |
def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None):
"""Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping ... | def function[calc_osc_accels, parameter[self, osc_freqs, osc_damping, tf]]:
constant[Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
... | keyword[def] identifier[calc_osc_accels] ( identifier[self] , identifier[osc_freqs] , identifier[osc_damping] = literal[int] , identifier[tf] = keyword[None] ):
literal[string]
keyword[if] identifier[tf] keyword[is] keyword[None] :
identifier[tf] = identifier[np] . identifier[ones_l... | def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None):
"""Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping : fl... |
def S2L(dd, mm, yy, timeZone=7):
'''def S2L(dd, mm, yy, timeZone = 7): Convert solar date dd/mm/yyyy to
the corresponding lunar date.'''
dayNumber = jdFromDate(dd, mm, yy)
k = int((dayNumber - 2415021.076998695) / 29.530588853)
monthStart = getNewMoonDay(k + 1, timeZone)
if (monthStart > dayNumb... | def function[S2L, parameter[dd, mm, yy, timeZone]]:
constant[def S2L(dd, mm, yy, timeZone = 7): Convert solar date dd/mm/yyyy to
the corresponding lunar date.]
variable[dayNumber] assign[=] call[name[jdFromDate], parameter[name[dd], name[mm], name[yy]]]
variable[k] assign[=] call[name[int], ... | keyword[def] identifier[S2L] ( identifier[dd] , identifier[mm] , identifier[yy] , identifier[timeZone] = literal[int] ):
literal[string]
identifier[dayNumber] = identifier[jdFromDate] ( identifier[dd] , identifier[mm] , identifier[yy] )
identifier[k] = identifier[int] (( identifier[dayNumber] - litera... | def S2L(dd, mm, yy, timeZone=7):
"""def S2L(dd, mm, yy, timeZone = 7): Convert solar date dd/mm/yyyy to
the corresponding lunar date."""
dayNumber = jdFromDate(dd, mm, yy)
k = int((dayNumber - 2415021.076998695) / 29.530588853)
monthStart = getNewMoonDay(k + 1, timeZone)
if monthStart > dayNumbe... |
def _contains_yieldpoint(children):
"""Returns True if ``children`` contains any YieldPoints.
``children`` may be a dict or a list, as used by `MultiYieldPoint`
and `multi_future`.
"""
if isinstance(children, dict):
return any(isinstance(i, YieldPoint) for i in children.values())
if isi... | def function[_contains_yieldpoint, parameter[children]]:
constant[Returns True if ``children`` contains any YieldPoints.
``children`` may be a dict or a list, as used by `MultiYieldPoint`
and `multi_future`.
]
if call[name[isinstance], parameter[name[children], name[dict]]] begin[:]
... | keyword[def] identifier[_contains_yieldpoint] ( identifier[children] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[children] , identifier[dict] ):
keyword[return] identifier[any] ( identifier[isinstance] ( identifier[i] , identifier[YieldPoint] ) keyword[for] identifier[i] ... | def _contains_yieldpoint(children):
"""Returns True if ``children`` contains any YieldPoints.
``children`` may be a dict or a list, as used by `MultiYieldPoint`
and `multi_future`.
"""
if isinstance(children, dict):
return any((isinstance(i, YieldPoint) for i in children.values())) # depen... |
def crawl(self, *args, **kwargs):
'''
执行爬取操作,并阻塞直到爬取完成,返回结果数据。
此处考虑到 Scrapy 本身的并发特性,故通过临时文件方式做数据传递,
将临时路径传递到爬虫业务中,并在爬取结束后对文件进行读取、 JSON 反序列化,返回
:return: 返回符合接口定义的字典对象
:rtype: dict
'''
temp = tempfile.NamedTemporaryFile(mode='w+t')
try:
... | def function[crawl, parameter[self]]:
constant[
执行爬取操作,并阻塞直到爬取完成,返回结果数据。
此处考虑到 Scrapy 本身的并发特性,故通过临时文件方式做数据传递,
将临时路径传递到爬虫业务中,并在爬取结束后对文件进行读取、 JSON 反序列化,返回
:return: 返回符合接口定义的字典对象
:rtype: dict
]
variable[temp] assign[=] call[name[tempfile].NamedTemporaryFile,... | keyword[def] identifier[crawl] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[temp] = identifier[tempfile] . identifier[NamedTemporaryFile] ( identifier[mode] = literal[string] )
keyword[try] :
identifier[crawler] = identifier[Craw... | def crawl(self, *args, **kwargs):
"""
执行爬取操作,并阻塞直到爬取完成,返回结果数据。
此处考虑到 Scrapy 本身的并发特性,故通过临时文件方式做数据传递,
将临时路径传递到爬虫业务中,并在爬取结束后对文件进行读取、 JSON 反序列化,返回
:return: 返回符合接口定义的字典对象
:rtype: dict
"""
temp = tempfile.NamedTemporaryFile(mode='w+t')
try:
crawler = Crawle... |
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 ReflashControllerRecord.
Args:
record_data (byte... | 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 ReflashControllerRecord.
Args:
... | keyword[def] identifier[FromBinary] ( identifier[cls] , identifier[record_data] , identifier[record_count] = literal[int] ):
literal[string]
keyword[if] identifier[len] ( identifier[record_data] )< identifier[ReflashControllerRecord] . identifier[RecordHeaderLength] :
keyword[raise] ... | 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 ReflashControllerRecord.
Args:
record_data (bytearra... |
def func_call_as_str(name, *args, **kwds):
"""
Return arguments and keyword arguments as formatted string
>>> func_call_as_str('f', 1, 2, a=1)
'f(1, 2, a=1)'
"""
return '{0}({1})'.format(
name,
', '.join(itertools.chain(
map('{0!r}'.format, args),
map('{... | def function[func_call_as_str, parameter[name]]:
constant[
Return arguments and keyword arguments as formatted string
>>> func_call_as_str('f', 1, 2, a=1)
'f(1, 2, a=1)'
]
return[call[constant[{0}({1})].format, parameter[name[name], call[constant[, ].join, parameter[call[name[itertools].ch... | keyword[def] identifier[func_call_as_str] ( identifier[name] ,* identifier[args] ,** identifier[kwds] ):
literal[string]
keyword[return] literal[string] . identifier[format] (
identifier[name] ,
literal[string] . identifier[join] ( identifier[itertools] . identifier[chain] (
identifier[map]... | def func_call_as_str(name, *args, **kwds):
"""
Return arguments and keyword arguments as formatted string
>>> func_call_as_str('f', 1, 2, a=1)
'f(1, 2, a=1)'
"""
return '{0}({1})'.format(name, ', '.join(itertools.chain(map('{0!r}'.format, args), map('{0[0]!s}={0[1]!r}'.format, sorted(kwds.item... |
def show_relations(self):
''' display every relation in the database as (src, relation, dst) '''
for src_node in self.iter_nodes():
for relation in src_node.outgoing:
for dst_node in src_node.outgoing[relation]:
print(repr(src_node.obj), '-', relation, '-'... | def function[show_relations, parameter[self]]:
constant[ display every relation in the database as (src, relation, dst) ]
for taget[name[src_node]] in starred[call[name[self].iter_nodes, parameter[]]] begin[:]
for taget[name[relation]] in starred[name[src_node].outgoing] begin[:]
... | keyword[def] identifier[show_relations] ( identifier[self] ):
literal[string]
keyword[for] identifier[src_node] keyword[in] identifier[self] . identifier[iter_nodes] ():
keyword[for] identifier[relation] keyword[in] identifier[src_node] . identifier[outgoing] :
k... | def show_relations(self):
""" display every relation in the database as (src, relation, dst) """
for src_node in self.iter_nodes():
for relation in src_node.outgoing:
for dst_node in src_node.outgoing[relation]:
print(repr(src_node.obj), '-', relation, '-', repr(dst_node.obj)... |
def get_users_of_group(self, group_id, **kwargs): # noqa: E501
"""Get users of a group. # noqa: E501
An endpoint for listing the users of a group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id}/users -H 'Authorization: Bearer API_KEY'` # noqa:... | def function[get_users_of_group, parameter[self, group_id]]:
constant[Get users of a group. # noqa: E501
An endpoint for listing the users of a group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id}/users -H 'Authorization: Bearer API_KEY'` # no... | keyword[def] identifier[get_users_of_group] ( identifier[self] , identifier[group_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identi... | def get_users_of_group(self, group_id, **kwargs): # noqa: E501
"Get users of a group. # noqa: E501\n\n An endpoint for listing the users of a group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id}/users -H 'Authorization: Bearer API_KEY'` # noqa: E50... |
def _encode(self, obj):
"""Returns a JSON representation of a Python object - see dumps.
Accepts objects of any type, calls the appropriate type-specific encoder.
"""
if self._use_hook:
obj = self.encode_hook(obj)
# first try simple strict checks
_objtype =... | def function[_encode, parameter[self, obj]]:
constant[Returns a JSON representation of a Python object - see dumps.
Accepts objects of any type, calls the appropriate type-specific encoder.
]
if name[self]._use_hook begin[:]
variable[obj] assign[=] call[name[self].encode_... | keyword[def] identifier[_encode] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[self] . identifier[_use_hook] :
identifier[obj] = identifier[self] . identifier[encode_hook] ( identifier[obj] )
identifier[_objtype] = identifier[o... | def _encode(self, obj):
"""Returns a JSON representation of a Python object - see dumps.
Accepts objects of any type, calls the appropriate type-specific encoder.
"""
if self._use_hook:
obj = self.encode_hook(obj) # depends on [control=['if'], data=[]]
# first try simple strict chec... |
def has_readable_server(self, read_preference=ReadPreference.PRIMARY):
"""Does this topology have any readable servers available matching the
given read preference?
:Parameters:
- `read_preference`: an instance of a read preference from
:mod:`~pymongo.read_preferences`. De... | def function[has_readable_server, parameter[self, read_preference]]:
constant[Does this topology have any readable servers available matching the
given read preference?
:Parameters:
- `read_preference`: an instance of a read preference from
:mod:`~pymongo.read_preferences`... | keyword[def] identifier[has_readable_server] ( identifier[self] , identifier[read_preference] = identifier[ReadPreference] . identifier[PRIMARY] ):
literal[string]
identifier[common] . identifier[validate_read_preference] ( literal[string] , identifier[read_preference] )
keyword[return] i... | def has_readable_server(self, read_preference=ReadPreference.PRIMARY):
"""Does this topology have any readable servers available matching the
given read preference?
:Parameters:
- `read_preference`: an instance of a read preference from
:mod:`~pymongo.read_preferences`. Defaul... |
def getLeapSecondLastUpdated(): # @NoSelf
"""
Shows the latest date a leap second was added to the leap second table.
"""
print('Leap second last updated:', str(CDFepoch.LTS[-1][0]) + '-' +
str(CDFepoch.LTS[-1][1]) + '-' + str(CDFepoch.LTS[-1][2])) | def function[getLeapSecondLastUpdated, parameter[]]:
constant[
Shows the latest date a leap second was added to the leap second table.
]
call[name[print], parameter[constant[Leap second last updated:], binary_operation[binary_operation[binary_operation[binary_operation[call[name[str], pa... | keyword[def] identifier[getLeapSecondLastUpdated] ():
literal[string]
identifier[print] ( literal[string] , identifier[str] ( identifier[CDFepoch] . identifier[LTS] [- literal[int] ][ literal[int] ])+ literal[string] +
identifier[str] ( identifier[CDFepoch] . identifier[LTS] [- literal[int... | def getLeapSecondLastUpdated(): # @NoSelf
'\n Shows the latest date a leap second was added to the leap second table.\n '
print('Leap second last updated:', str(CDFepoch.LTS[-1][0]) + '-' + str(CDFepoch.LTS[-1][1]) + '-' + str(CDFepoch.LTS[-1][2])) |
def qname(self, uri: str) -> str:
''' Returns qname of uri in rdflib graph while also saving it '''
try:
prefix, namespace, name = self.g.compute_qname(uri)
qname = prefix + ':' + name
return qname
except:
try:
print('prefix:', pref... | def function[qname, parameter[self, uri]]:
constant[ Returns qname of uri in rdflib graph while also saving it ]
<ast.Try object at 0x7da1b1aa49d0> | keyword[def] identifier[qname] ( identifier[self] , identifier[uri] : identifier[str] )-> identifier[str] :
literal[string]
keyword[try] :
identifier[prefix] , identifier[namespace] , identifier[name] = identifier[self] . identifier[g] . identifier[compute_qname] ( identifier[uri] )
... | def qname(self, uri: str) -> str:
""" Returns qname of uri in rdflib graph while also saving it """
try:
(prefix, namespace, name) = self.g.compute_qname(uri)
qname = prefix + ':' + name
return qname # depends on [control=['try'], data=[]]
except:
try:
print('pre... |
def _fill(self):
"""Advance the iterator without returning the old head."""
try:
self._head = self._iterable.next()
except StopIteration:
self._head = None | def function[_fill, parameter[self]]:
constant[Advance the iterator without returning the old head.]
<ast.Try object at 0x7da18f09ffa0> | keyword[def] identifier[_fill] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[_head] = identifier[self] . identifier[_iterable] . identifier[next] ()
keyword[except] identifier[StopIteration] :
identifier[self] . identifier[_head] = keyword[None] | def _fill(self):
"""Advance the iterator without returning the old head."""
try:
self._head = self._iterable.next() # depends on [control=['try'], data=[]]
except StopIteration:
self._head = None # depends on [control=['except'], data=[]] |
def friendly_type_name(raw_type: typing.Type) -> str:
"""
Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string
"""
try:
return _TRANSLATE_TYPE[raw_type]
except KeyError:
LOGGER.error('unmanaged value type: %s', raw... | def function[friendly_type_name, parameter[raw_type]]:
constant[
Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string
]
<ast.Try object at 0x7da18bc729b0> | keyword[def] identifier[friendly_type_name] ( identifier[raw_type] : identifier[typing] . identifier[Type] )-> identifier[str] :
literal[string]
keyword[try] :
keyword[return] identifier[_TRANSLATE_TYPE] [ identifier[raw_type] ]
keyword[except] identifier[KeyError] :
identifier[LOG... | def friendly_type_name(raw_type: typing.Type) -> str:
"""
Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string
"""
try:
return _TRANSLATE_TYPE[raw_type] # depends on [control=['try'], data=[]]
except KeyError:
LOG... |
def copy_file_tree(src: str,
dest: str,
ctx: Optional[Dict[str, Any]] = None,
option_locations: Optional[List[Tuple[str, List[str]]]] = None):
"""
Copy the file tree under the :param:`src` directory to the :param:`dest`
directory. Pass :param:`ctx` to... | def function[copy_file_tree, parameter[src, dest, ctx, option_locations]]:
constant[
Copy the file tree under the :param:`src` directory to the :param:`dest`
directory. Pass :param:`ctx` to support rendering the files, and pass
:param:`option_locations` to support deleting optional files/folders.
... | keyword[def] identifier[copy_file_tree] ( identifier[src] : identifier[str] ,
identifier[dest] : identifier[str] ,
identifier[ctx] : identifier[Optional] [ identifier[Dict] [ identifier[str] , identifier[Any] ]]= keyword[None] ,
identifier[option_locations] : identifier[Optional] [ identifier[List] [ identifier[Tu... | def copy_file_tree(src: str, dest: str, ctx: Optional[Dict[str, Any]]=None, option_locations: Optional[List[Tuple[str, List[str]]]]=None):
"""
Copy the file tree under the :param:`src` directory to the :param:`dest`
directory. Pass :param:`ctx` to support rendering the files, and pass
:param:`option_loc... |
def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated times for the segment boundaries in frame indeces.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# Structural Features params
... | def function[processFlat, parameter[self]]:
constant[Main process.
Returns
-------
est_idxs : np.array(N)
Estimated times for the segment boundaries in frame indeces.
est_labels : np.array(N-1)
Estimated labels for the segments.
]
variable[... | keyword[def] identifier[processFlat] ( identifier[self] ):
literal[string]
identifier[Mp] = identifier[self] . identifier[config] [ literal[string] ]
identifier[od] = identifier[self] . identifier[config] [ literal[string] ]
identifier[M] = identifier[s... | def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated times for the segment boundaries in frame indeces.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# Structural Features params
Mp = self... |
def _get_representative(self, obj):
"""Finds and returns the root of the set containing `obj`."""
if obj not in self._parents:
self._parents[obj] = obj
self._weights[obj] = 1
self._prev_next[obj] = [obj, obj]
self._min_values[obj] = obj
return... | def function[_get_representative, parameter[self, obj]]:
constant[Finds and returns the root of the set containing `obj`.]
if compare[name[obj] <ast.NotIn object at 0x7da2590d7190> name[self]._parents] begin[:]
call[name[self]._parents][name[obj]] assign[=] name[obj]
call... | keyword[def] identifier[_get_representative] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[obj] keyword[not] keyword[in] identifier[self] . identifier[_parents] :
identifier[self] . identifier[_parents] [ identifier[obj] ]= identifier[obj]
... | def _get_representative(self, obj):
"""Finds and returns the root of the set containing `obj`."""
if obj not in self._parents:
self._parents[obj] = obj
self._weights[obj] = 1
self._prev_next[obj] = [obj, obj]
self._min_values[obj] = obj
return obj # depends on [control=[... |
def generate(self, data, *args, **kwargs):
"""
根据传入的数据结构生成最终用于推送的文件字节字符串( :func:`bytes` ),
MoEar会将其持久化并用于之后的推送任务
:param dict data: 待打包的数据结构
:return: 返回生成的书籍打包输出字节
:rtype: bytes
"""
with tempfile.TemporaryDirectory() as tmpdirname:
self.options... | def function[generate, parameter[self, data]]:
constant[
根据传入的数据结构生成最终用于推送的文件字节字符串( :func:`bytes` ),
MoEar会将其持久化并用于之后的推送任务
:param dict data: 待打包的数据结构
:return: 返回生成的书籍打包输出字节
:rtype: bytes
]
with call[name[tempfile].TemporaryDirectory, parameter[]] begin[:]... | keyword[def] identifier[generate] ( identifier[self] , identifier[data] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[tempfile] . identifier[TemporaryDirectory] () keyword[as] identifier[tmpdirname] :
identifier[self] . identifier[options] . i... | def generate(self, data, *args, **kwargs):
"""
根据传入的数据结构生成最终用于推送的文件字节字符串( :func:`bytes` ),
MoEar会将其持久化并用于之后的推送任务
:param dict data: 待打包的数据结构
:return: 返回生成的书籍打包输出字节
:rtype: bytes
"""
with tempfile.TemporaryDirectory() as tmpdirname:
self.options.setdefault(... |
def command(self, cmd_code, cmd_data, timeout):
"""Send a host command and return the chip response.
"""
log.log(logging.DEBUG-1, self.CMD[cmd_code]+" "+hexlify(cmd_data))
frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(f... | def function[command, parameter[self, cmd_code, cmd_data, timeout]]:
constant[Send a host command and return the chip response.
]
call[name[log].log, parameter[binary_operation[name[logging].DEBUG - constant[1]], binary_operation[binary_operation[call[name[self].CMD][name[cmd_code]] + constant[... | keyword[def] identifier[command] ( identifier[self] , identifier[cmd_code] , identifier[cmd_data] , identifier[timeout] ):
literal[string]
identifier[log] . identifier[log] ( identifier[logging] . identifier[DEBUG] - literal[int] , identifier[self] . identifier[CMD] [ identifier[cmd_code] ]+ litera... | def command(self, cmd_code, cmd_data, timeout):
"""Send a host command and return the chip response.
"""
log.log(logging.DEBUG - 1, self.CMD[cmd_code] + ' ' + hexlify(cmd_data))
frame = bytearray([212, cmd_code]) + bytearray(cmd_data)
frame = bytearray([255, 0, 0, 0, len(frame)]) + frame
fr... |
def fmthours (radians, norm='wrap', precision=3, seps='::'):
"""Format an angle as sexagesimal hours in a string.
Arguments are:
radians
The angle, in radians.
norm (default "wrap")
The normalization mode, used for angles outside of the standard range
of 0 to 2π. If "none", the value... | def function[fmthours, parameter[radians, norm, precision, seps]]:
constant[Format an angle as sexagesimal hours in a string.
Arguments are:
radians
The angle, in radians.
norm (default "wrap")
The normalization mode, used for angles outside of the standard range
of 0 to 2π. If "... | keyword[def] identifier[fmthours] ( identifier[radians] , identifier[norm] = literal[string] , identifier[precision] = literal[int] , identifier[seps] = literal[string] ):
literal[string]
keyword[return] identifier[_fmtsexagesimal] ( identifier[radians] * identifier[R2H] , identifier[norm] , literal[int] ... | def fmthours(radians, norm='wrap', precision=3, seps='::'):
"""Format an angle as sexagesimal hours in a string.
Arguments are:
radians
The angle, in radians.
norm (default "wrap")
The normalization mode, used for angles outside of the standard range
of 0 to 2π. If "none", the value ... |
def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
"""Generate a transcript file from a given history of commands."""
import io
# Validate the transcript file path to make sure directory exists and write access is available
transcript_pa... | def function[_generate_transcript, parameter[self, history, transcript_file]]:
constant[Generate a transcript file from a given history of commands.]
import module[io]
variable[transcript_path] assign[=] call[name[os].path.abspath, parameter[call[name[os].path.expanduser, parameter[name[transcript_f... | keyword[def] identifier[_generate_transcript] ( identifier[self] , identifier[history] : identifier[List] [ identifier[Union] [ identifier[HistoryItem] , identifier[str] ]], identifier[transcript_file] : identifier[str] )-> keyword[None] :
literal[string]
keyword[import] identifier[io]
... | def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
"""Generate a transcript file from a given history of commands."""
import io
# Validate the transcript file path to make sure directory exists and write access is available
transcript_path = os.path.abs... |
def _add_base_info(self, event_dict):
"""
Instead of using a processor, adding basic information like caller, filename etc
here.
"""
f = sys._getframe()
level_method_frame = f.f_back
caller_frame = level_method_frame.f_back
return event_dict | def function[_add_base_info, parameter[self, event_dict]]:
constant[
Instead of using a processor, adding basic information like caller, filename etc
here.
]
variable[f] assign[=] call[name[sys]._getframe, parameter[]]
variable[level_method_frame] assign[=] name[f].f_back... | keyword[def] identifier[_add_base_info] ( identifier[self] , identifier[event_dict] ):
literal[string]
identifier[f] = identifier[sys] . identifier[_getframe] ()
identifier[level_method_frame] = identifier[f] . identifier[f_back]
identifier[caller_frame] = identifier[level_method... | def _add_base_info(self, event_dict):
"""
Instead of using a processor, adding basic information like caller, filename etc
here.
"""
f = sys._getframe()
level_method_frame = f.f_back
caller_frame = level_method_frame.f_back
return event_dict |
def parse_command_line():
""" Parse CLI args."""
## create the parser
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
* Example command-line usage:
## push test branch to conda --label=conda-test for travis CI
./versioner.py -p toyt... | def function[parse_command_line, parameter[]]:
constant[ Parse CLI args.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[-v], constant[--version]]]
call[name[parser].add_argument, parameter[constant[-p]]]
... | keyword[def] identifier[parse_command_line] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[formatter_class] = identifier[argparse] . identifier[RawDescriptionHelpFormatter] ,
identifier[epilog] = literal[string] )
identifie... | def parse_command_line():
""" Parse CLI args."""
## create the parser
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, epilog='\n * Example command-line usage: \n\n ## push test branch to conda --label=conda-test for travis CI\n ./versioner.py -p toytree -b test -t 0... |
def main():
"""Main function"""
# **** For Pytest ****
# We need to create MainWindow **here** to avoid passing pytest
# options to Spyder
if running_under_pytest():
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock # Pyth... | def function[main, parameter[]]:
constant[Main function]
if call[name[running_under_pytest], parameter[]] begin[:]
<ast.Try object at 0x7da207f03cd0>
variable[options] assign[=] call[name[Mock], parameter[]]
name[options].working_directory assign[=] constant[None]... | keyword[def] identifier[main] ():
literal[string]
keyword[if] identifier[running_under_pytest] ():
keyword[try] :
keyword[from] identifier[unittest] . identifier[mock] keyword[import] identifier[Mock]
keyword[except] identifier[ImportError] :
... | def main():
"""Main function""" # **** For Pytest ****
# We need to create MainWindow **here** to avoid passing pytest
# options to Spyder
if running_under_pytest():
try:
from unittest.mock import Mock # depends on [control=['try'], data=[]]
except ImportError:
... |
def cond_entropy(x, y, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'):
'''
compute the conditional entropy H(X|Y).
method: 'nearest-neighbors', 'gaussian', or 'bin'
if 'bin' need to provide bins_y, and bins_xy
units: 'bits' or 'nats'
'''
HXY = entr... | def function[cond_entropy, parameter[x, y, bins_y, bins_xy, method, units]]:
constant[
compute the conditional entropy H(X|Y).
method: 'nearest-neighbors', 'gaussian', or 'bin'
if 'bin' need to provide bins_y, and bins_xy
units: 'bits' or 'nats'
]
variable[HXY] ... | keyword[def] identifier[cond_entropy] ( identifier[x] , identifier[y] , identifier[bins_y] = keyword[None] , identifier[bins_xy] = keyword[None] , identifier[method] = literal[string] , identifier[units] = literal[string] ):
literal[string]
identifier[HXY] = identifier[entropy] ( identifier[data] = identif... | def cond_entropy(x, y, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'):
"""
compute the conditional entropy H(X|Y).
method: 'nearest-neighbors', 'gaussian', or 'bin'
if 'bin' need to provide bins_y, and bins_xy
units: 'bits' or 'nats'
"""
HXY = entr... |
def list_file(self, commit, path, recursive=False):
"""
Lists the files in a directory.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the directory.
* recursive: If True, continue listing the files for sub-directories.
... | def function[list_file, parameter[self, commit, path, recursive]]:
constant[
Lists the files in a directory.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the directory.
* recursive: If True, continue listing the files f... | keyword[def] identifier[list_file] ( identifier[self] , identifier[commit] , identifier[path] , identifier[recursive] = keyword[False] ):
literal[string]
identifier[req] = identifier[proto] . identifier[ListFileRequest] (
identifier[file] = identifier[proto] . identifier[File] ( identifier... | def list_file(self, commit, path, recursive=False):
"""
Lists the files in a directory.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the directory.
* recursive: If True, continue listing the files for sub-directories.
... |
def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) | def function[set_exception, parameter[self, exception]]:
constant[Sets the exception on the future.]
if <ast.UnaryOp object at 0x7da2041dae60> begin[:]
<ast.Raise object at 0x7da2041dbee0>
call[name[self]._coordinator.set_exception, parameter[name[exception]]] | keyword[def] identifier[set_exception] ( identifier[self] , identifier[exception] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[done] ():
keyword[raise] identifier[TransferNotDoneError] (
literal[string]
literal[string] )
... | def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.done():
raise TransferNotDoneError('set_exception can only be called once the transfer is complete.') # depends on [control=['if'], data=[]]
self._coordinator.set_exception(exception, override=True) |
def _generate_feed(self, feed_data):
""" render feed file with data
"""
atom_feed = self._render_html('atom.xml', feed_data)
feed_path = os.path.join(os.getcwd(), 'public', 'atom.xml')
with codecs.open(feed_path, 'wb', 'utf-8') as f:
f.write(atom_feed) | def function[_generate_feed, parameter[self, feed_data]]:
constant[ render feed file with data
]
variable[atom_feed] assign[=] call[name[self]._render_html, parameter[constant[atom.xml], name[feed_data]]]
variable[feed_path] assign[=] call[name[os].path.join, parameter[call[name[os].getc... | keyword[def] identifier[_generate_feed] ( identifier[self] , identifier[feed_data] ):
literal[string]
identifier[atom_feed] = identifier[self] . identifier[_render_html] ( literal[string] , identifier[feed_data] )
identifier[feed_path] = identifier[os] . identifier[path] . identifier[join... | def _generate_feed(self, feed_data):
""" render feed file with data
"""
atom_feed = self._render_html('atom.xml', feed_data)
feed_path = os.path.join(os.getcwd(), 'public', 'atom.xml')
with codecs.open(feed_path, 'wb', 'utf-8') as f:
f.write(atom_feed) # depends on [control=['with'], da... |
def cmd(send, msg, args):
"""Converts text into NATO form.
Syntax: {command} <text>
"""
if not msg:
send("NATO what?")
return
nato = gen_nato(msg)
if len(nato) > 100:
send("Your NATO is too long. Have you considered letters?")
else:
send(nato) | def function[cmd, parameter[send, msg, args]]:
constant[Converts text into NATO form.
Syntax: {command} <text>
]
if <ast.UnaryOp object at 0x7da1b20d4550> begin[:]
call[name[send], parameter[constant[NATO what?]]]
return[None]
variable[nato] assign[=] call[name[... | keyword[def] identifier[cmd] ( identifier[send] , identifier[msg] , identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[msg] :
identifier[send] ( literal[string] )
keyword[return]
identifier[nato] = identifier[gen_nato] ( identifier[msg] )
keyword[if] ide... | def cmd(send, msg, args):
"""Converts text into NATO form.
Syntax: {command} <text>
"""
if not msg:
send('NATO what?')
return # depends on [control=['if'], data=[]]
nato = gen_nato(msg)
if len(nato) > 100:
send('Your NATO is too long. Have you considered letters?') # ... |
def domain(host, port, username, password, avail_timeout=240.):
"""
Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in se... | def function[domain, parameter[host, port, username, password, avail_timeout]]:
constant[
Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Avail... | keyword[def] identifier[domain] ( identifier[host] , identifier[port] , identifier[username] , identifier[password] , identifier[avail_timeout] = literal[int] ):
literal[string]
keyword[return] identifier[Domain] ( identifier[Endpoint] ( identifier[host] , identifier[port] , identifier[username] , identifier[... | def domain(host, port, username, password, avail_timeout=240.0):
"""
Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in ... |
def update_empty_fields(self, **kwargs):
"""Updates the field of info about an OTU that might not be filled in by a match_names or taxon call."""
if self._is_deprecated is None:
self._is_deprecated = kwargs.get('is_deprecated')
if self._is_dubious is None:
self._is_dubiou... | def function[update_empty_fields, parameter[self]]:
constant[Updates the field of info about an OTU that might not be filled in by a match_names or taxon call.]
if compare[name[self]._is_deprecated is constant[None]] begin[:]
name[self]._is_deprecated assign[=] call[name[kwargs].get, par... | keyword[def] identifier[update_empty_fields] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[_is_deprecated] keyword[is] keyword[None] :
identifier[self] . identifier[_is_deprecated] = identifier[kwargs] . identifier[get] ( lite... | def update_empty_fields(self, **kwargs):
"""Updates the field of info about an OTU that might not be filled in by a match_names or taxon call."""
if self._is_deprecated is None:
self._is_deprecated = kwargs.get('is_deprecated') # depends on [control=['if'], data=[]]
if self._is_dubious is None:
... |
def get_series_episode(series_id, season, episode):
"""Get an episode of a series.
:param int series_id: id of the series.
:param int season: season number of the episode.
:param int episode: episode number of the episode.
:return: the episode data.
:rtype: dict
"""
result = tvdb_clien... | def function[get_series_episode, parameter[series_id, season, episode]]:
constant[Get an episode of a series.
:param int series_id: id of the series.
:param int season: season number of the episode.
:param int episode: episode number of the episode.
:return: the episode data.
:rtype: dict
... | keyword[def] identifier[get_series_episode] ( identifier[series_id] , identifier[season] , identifier[episode] ):
literal[string]
identifier[result] = identifier[tvdb_client] . identifier[query_series_episodes] ( identifier[series_id] , identifier[aired_season] = identifier[season] , identifier[aired_episo... | def get_series_episode(series_id, season, episode):
"""Get an episode of a series.
:param int series_id: id of the series.
:param int season: season number of the episode.
:param int episode: episode number of the episode.
:return: the episode data.
:rtype: dict
"""
result = tvdb_clien... |
def _run_raw(self, cmd: str, ignore_errors=False) -> Tuple[str, str]:
"""Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during in... | def function[_run_raw, parameter[self, cmd, ignore_errors]]:
constant[Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during i... | keyword[def] identifier[_run_raw] ( identifier[self] , identifier[cmd] : identifier[str] , identifier[ignore_errors] = keyword[False] )-> identifier[Tuple] [ identifier[str] , identifier[str] ]:
literal[string]
identifier[stdin] , identifier[stdout] , identifier[stderr] = identifier[u] . identifier[c... | def _run_raw(self, cmd: str, ignore_errors=False) -> Tuple[str, str]:
"""Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during in... |
def _iter_response(self, url, params=None):
"""Return an enumerable that iterates through a multi-page API request"""
if params is None:
params = {}
params['page_number'] = 1
# Last page lists itself as next page
while True:
response = self._request(url, ... | def function[_iter_response, parameter[self, url, params]]:
constant[Return an enumerable that iterates through a multi-page API request]
if compare[name[params] is constant[None]] begin[:]
variable[params] assign[=] dictionary[[], []]
call[name[params]][constant[page_number]] as... | keyword[def] identifier[_iter_response] ( identifier[self] , identifier[url] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] identifier[params] keyword[is] keyword[None] :
identifier[params] ={}
identifier[params] [ literal[string] ]= literal[int]
... | def _iter_response(self, url, params=None):
"""Return an enumerable that iterates through a multi-page API request"""
if params is None:
params = {} # depends on [control=['if'], data=['params']]
params['page_number'] = 1
# Last page lists itself as next page
while True:
response = ... |
def DeleteJob(self, job_id, token=None):
"""Deletes cron job with the given URN."""
job_urn = self.CRON_JOBS_PATH.Add(job_id)
aff4.FACTORY.Delete(job_urn, token=token) | def function[DeleteJob, parameter[self, job_id, token]]:
constant[Deletes cron job with the given URN.]
variable[job_urn] assign[=] call[name[self].CRON_JOBS_PATH.Add, parameter[name[job_id]]]
call[name[aff4].FACTORY.Delete, parameter[name[job_urn]]] | keyword[def] identifier[DeleteJob] ( identifier[self] , identifier[job_id] , identifier[token] = keyword[None] ):
literal[string]
identifier[job_urn] = identifier[self] . identifier[CRON_JOBS_PATH] . identifier[Add] ( identifier[job_id] )
identifier[aff4] . identifier[FACTORY] . identifier[Delete] ( i... | def DeleteJob(self, job_id, token=None):
"""Deletes cron job with the given URN."""
job_urn = self.CRON_JOBS_PATH.Add(job_id)
aff4.FACTORY.Delete(job_urn, token=token) |
def set_gcc():
"""
Try to find and use GCC on OSX for OpenMP support.
"""
# For macports and homebrew
patterns = ['/opt/local/bin/gcc-mp-[0-9].[0-9]',
'/opt/local/bin/gcc-mp-[0-9]',
'/usr/local/bin/gcc-[0-9].[0-9]',
'/usr/local/bin/gcc-[0-9]']
if... | def function[set_gcc, parameter[]]:
constant[
Try to find and use GCC on OSX for OpenMP support.
]
variable[patterns] assign[=] list[[<ast.Constant object at 0x7da1b1d5e230>, <ast.Constant object at 0x7da1b1d5d090>, <ast.Constant object at 0x7da1b1d5d870>, <ast.Constant object at 0x7da1b1d5cc10>... | keyword[def] identifier[set_gcc] ():
literal[string]
identifier[patterns] =[ literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ]
keyword[if] literal[string] keyword[in] identifier[platform] . identifier[platform] (). identifier[lower] ():
identifi... | def set_gcc():
"""
Try to find and use GCC on OSX for OpenMP support.
"""
# For macports and homebrew
patterns = ['/opt/local/bin/gcc-mp-[0-9].[0-9]', '/opt/local/bin/gcc-mp-[0-9]', '/usr/local/bin/gcc-[0-9].[0-9]', '/usr/local/bin/gcc-[0-9]']
if 'darwin' in platform.platform().lower():
... |
def parse_band_log(self, message):
"""Process incoming logging messages from the service."""
if "payload" in message and hasattr(message["payload"], "name"):
record = message["payload"]
for k in dir(record):
if k.startswith("workflows_exc_"):
s... | def function[parse_band_log, parameter[self, message]]:
constant[Process incoming logging messages from the service.]
if <ast.BoolOp object at 0x7da18c4cc850> begin[:]
variable[record] assign[=] call[name[message]][constant[payload]]
for taget[name[k]] in starred[call[nam... | keyword[def] identifier[parse_band_log] ( identifier[self] , identifier[message] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[message] keyword[and] identifier[hasattr] ( identifier[message] [ literal[string] ], literal[string] ):
identifier[record] = ident... | def parse_band_log(self, message):
"""Process incoming logging messages from the service."""
if 'payload' in message and hasattr(message['payload'], 'name'):
record = message['payload']
for k in dir(record):
if k.startswith('workflows_exc_'):
setattr(record, k[14:], g... |
def random_leaf(self):
"Returns a random variable with the associated weight"
for i in range(self._number_tries_feasible_ind):
var = np.random.randint(self.nvar)
v = self._random_leaf(var)
if v is None:
continue
return v
raise Runti... | def function[random_leaf, parameter[self]]:
constant[Returns a random variable with the associated weight]
for taget[name[i]] in starred[call[name[range], parameter[name[self]._number_tries_feasible_ind]]] begin[:]
variable[var] assign[=] call[name[np].random.randint, parameter[name[self... | keyword[def] identifier[random_leaf] ( identifier[self] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[_number_tries_feasible_ind] ):
identifier[var] = identifier[np] . identifier[random] . identifier[randint] ( identifier... | def random_leaf(self):
"""Returns a random variable with the associated weight"""
for i in range(self._number_tries_feasible_ind):
var = np.random.randint(self.nvar)
v = self._random_leaf(var)
if v is None:
continue # depends on [control=['if'], data=[]]
return v # ... |
def emit_var_assign(self, var, t):
""" Emits code for storing a value into a variable
:param var: variable (node) to be updated
:param t: the value to emmit (e.g. a _label, a const, a tN...)
"""
p = '*' if var.byref else '' # Indirection prefix
if self.O_LEVEL > 1 and no... | def function[emit_var_assign, parameter[self, var, t]]:
constant[ Emits code for storing a value into a variable
:param var: variable (node) to be updated
:param t: the value to emmit (e.g. a _label, a const, a tN...)
]
variable[p] assign[=] <ast.IfExp object at 0x7da18fe93c40>
... | keyword[def] identifier[emit_var_assign] ( identifier[self] , identifier[var] , identifier[t] ):
literal[string]
identifier[p] = literal[string] keyword[if] identifier[var] . identifier[byref] keyword[else] literal[string]
keyword[if] identifier[self] . identifier[O_LEVEL] > literal[... | def emit_var_assign(self, var, t):
""" Emits code for storing a value into a variable
:param var: variable (node) to be updated
:param t: the value to emmit (e.g. a _label, a const, a tN...)
"""
p = '*' if var.byref else '' # Indirection prefix
if self.O_LEVEL > 1 and (not var.acces... |
def strip_suffix(s, suffix, strict=False):
"""Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present"""
if s.endswith(suffix):
return s[: len(s) - len(suffix)]
elif strict:
raise WimpyError("string doesn't end w... | def function[strip_suffix, parameter[s, suffix, strict]]:
constant[Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present]
if call[name[s].endswith, parameter[name[suffix]]] begin[:]
return[call[name[s]][<ast.Slice ... | keyword[def] identifier[strip_suffix] ( identifier[s] , identifier[suffix] , identifier[strict] = keyword[False] ):
literal[string]
keyword[if] identifier[s] . identifier[endswith] ( identifier[suffix] ):
keyword[return] identifier[s] [: identifier[len] ( identifier[s] )- identifier[len] ( ident... | def strip_suffix(s, suffix, strict=False):
"""Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present"""
if s.endswith(suffix):
return s[:len(s) - len(suffix)] # depends on [control=['if'], data=[]]
elif strict:
... |
def delete_loadbalancer(self, datacenter_id, loadbalancer_id):
"""
Removes the load balancer from the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param loadbalancer_id: The unique ID of the load balancer.
... | def function[delete_loadbalancer, parameter[self, datacenter_id, loadbalancer_id]]:
constant[
Removes the load balancer from the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param loadbalancer_id: The unique ... | keyword[def] identifier[delete_loadbalancer] ( identifier[self] , identifier[datacenter_id] , identifier[loadbalancer_id] ):
literal[string]
identifier[response] = identifier[self] . identifier[_perform_request] (
identifier[url] = literal[string] %(
identifier[datacenter_id] , id... | def delete_loadbalancer(self, datacenter_id, loadbalancer_id):
"""
Removes the load balancer from the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param loadbalancer_id: The unique ID of the load balancer.
... |
def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
"""
nonzero_px = np.where(np.sum(self.raw_data, axis=2) > 0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
... | def function[nonzero_pixels, parameter[self]]:
constant[ Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
]
variable[nonzero_px] assign[=] call[name[np].where, parameter[compare[call[name[np].sum, pa... | keyword[def] identifier[nonzero_pixels] ( identifier[self] ):
literal[string]
identifier[nonzero_px] = identifier[np] . identifier[where] ( identifier[np] . identifier[sum] ( identifier[self] . identifier[raw_data] , identifier[axis] = literal[int] )> literal[int] )
identifier[nonzero_px] ... | def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
"""
nonzero_px = np.where(np.sum(self.raw_data, axis=2) > 0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
return non... |
def _parse_tag(self, tag):
"""
Given a tag string (characters enclosed by []), this function will
parse any options and return a tuple of the form:
(valid, tag_name, closer, options)
"""
if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or ('... | def function[_parse_tag, parameter[self, tag]]:
constant[
Given a tag string (characters enclosed by []), this function will
parse any options and return a tuple of the form:
(valid, tag_name, closer, options)
]
if <ast.BoolOp object at 0x7da1b05ef970> begin[:]
... | keyword[def] identifier[_parse_tag] ( identifier[self] , identifier[tag] ):
literal[string]
keyword[if] keyword[not] identifier[tag] . identifier[startswith] ( identifier[self] . identifier[tag_opener] ) keyword[or] keyword[not] identifier[tag] . identifier[endswith] ( identifier[self] . identi... | def _parse_tag(self, tag):
"""
Given a tag string (characters enclosed by []), this function will
parse any options and return a tuple of the form:
(valid, tag_name, closer, options)
"""
if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or '\n' in ta... |
def get_name_from_abbrev(abbrev, case_sensitive=False):
"""
Given a country code abbreviation, get the full name from the table.
abbrev: (str) Country code to retrieve the full name of.
case_sensitive: (bool) When True, enforce case sensitivity.
"""
if case_sensitive:
country_code = abb... | def function[get_name_from_abbrev, parameter[abbrev, case_sensitive]]:
constant[
Given a country code abbreviation, get the full name from the table.
abbrev: (str) Country code to retrieve the full name of.
case_sensitive: (bool) When True, enforce case sensitivity.
]
if name[case_sensi... | keyword[def] identifier[get_name_from_abbrev] ( identifier[abbrev] , identifier[case_sensitive] = keyword[False] ):
literal[string]
keyword[if] identifier[case_sensitive] :
identifier[country_code] = identifier[abbrev]
keyword[else] :
identifier[country_code] = identifier[abbrev] .... | def get_name_from_abbrev(abbrev, case_sensitive=False):
"""
Given a country code abbreviation, get the full name from the table.
abbrev: (str) Country code to retrieve the full name of.
case_sensitive: (bool) When True, enforce case sensitivity.
"""
if case_sensitive:
country_code = abb... |
def lvresize(size=None, lvpath=None, extents=None):
'''
Return information about the logical volume(s)
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvresize +12M /dev/mapper/vg1-test
salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE
'''
if size and exten... | def function[lvresize, parameter[size, lvpath, extents]]:
constant[
Return information about the logical volume(s)
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvresize +12M /dev/mapper/vg1-test
salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE
]
... | keyword[def] identifier[lvresize] ( identifier[size] = keyword[None] , identifier[lvpath] = keyword[None] , identifier[extents] = keyword[None] ):
literal[string]
keyword[if] identifier[size] keyword[and] identifier[extents] :
identifier[log] . identifier[error] ( literal[string] )
key... | def lvresize(size=None, lvpath=None, extents=None):
"""
Return information about the logical volume(s)
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvresize +12M /dev/mapper/vg1-test
salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE
"""
if size and exten... |
def filesByType(fileList):
"""
given a list of files, return them as a dict sorted by type:
* plot, tif, data, other
"""
features=["plot","tif","data","other","experiment"]
files={}
for feature in features:
files[feature]=[]
for fname in fileList:
other=True
f... | def function[filesByType, parameter[fileList]]:
constant[
given a list of files, return them as a dict sorted by type:
* plot, tif, data, other
]
variable[features] assign[=] list[[<ast.Constant object at 0x7da1afe8efe0>, <ast.Constant object at 0x7da1afe07b80>, <ast.Constant object at 0... | keyword[def] identifier[filesByType] ( identifier[fileList] ):
literal[string]
identifier[features] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[files] ={}
keyword[for] identifier[feature] keyword[in] identifier[features] :
id... | def filesByType(fileList):
"""
given a list of files, return them as a dict sorted by type:
* plot, tif, data, other
"""
features = ['plot', 'tif', 'data', 'other', 'experiment']
files = {}
for feature in features:
files[feature] = [] # depends on [control=['for'], data=['featur... |
def main(symbol_yml_file, raw_pickle_file, pickle_dest_path):
"""
Parameters
----------
symbol_yml_file : str
Path to a YAML file which contains recordings.
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
pickle_dest_path : str
Path where the fi... | def function[main, parameter[symbol_yml_file, raw_pickle_file, pickle_dest_path]]:
constant[
Parameters
----------
symbol_yml_file : str
Path to a YAML file which contains recordings.
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
pickle_dest_path ... | keyword[def] identifier[main] ( identifier[symbol_yml_file] , identifier[raw_pickle_file] , identifier[pickle_dest_path] ):
literal[string]
identifier[metadata] = identifier[get_metadata] ()
identifier[symbol_ids] = identifier[get_symbol_ids] ( identifier[symbol_yml_file] , identifier[metadata] )
... | def main(symbol_yml_file, raw_pickle_file, pickle_dest_path):
"""
Parameters
----------
symbol_yml_file : str
Path to a YAML file which contains recordings.
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
pickle_dest_path : str
Path where the fi... |
def horizon_dashboard_nav(context):
"""Generates sub-navigation entries for the current dashboard."""
if 'request' not in context:
return {}
dashboard = context['request'].horizon['dashboard']
panel_groups = dashboard.get_panel_groups()
non_empty_groups = []
for group in panel_groups.va... | def function[horizon_dashboard_nav, parameter[context]]:
constant[Generates sub-navigation entries for the current dashboard.]
if compare[constant[request] <ast.NotIn object at 0x7da2590d7190> name[context]] begin[:]
return[dictionary[[], []]]
variable[dashboard] assign[=] call[call[name... | keyword[def] identifier[horizon_dashboard_nav] ( identifier[context] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[context] :
keyword[return] {}
identifier[dashboard] = identifier[context] [ literal[string] ]. identifier[horizon] [ literal[string] ]
... | def horizon_dashboard_nav(context):
"""Generates sub-navigation entries for the current dashboard."""
if 'request' not in context:
return {} # depends on [control=['if'], data=[]]
dashboard = context['request'].horizon['dashboard']
panel_groups = dashboard.get_panel_groups()
non_empty_group... |
def format_vk(vk):
"""Format vk before using it"""
# Force extension require to be a list
for ext in get_extensions_filtered(vk):
req = ext['require']
if not isinstance(req, list):
ext['require'] = [req] | def function[format_vk, parameter[vk]]:
constant[Format vk before using it]
for taget[name[ext]] in starred[call[name[get_extensions_filtered], parameter[name[vk]]]] begin[:]
variable[req] assign[=] call[name[ext]][constant[require]]
if <ast.UnaryOp object at 0x7da1b07927... | keyword[def] identifier[format_vk] ( identifier[vk] ):
literal[string]
keyword[for] identifier[ext] keyword[in] identifier[get_extensions_filtered] ( identifier[vk] ):
identifier[req] = identifier[ext] [ literal[string] ]
keyword[if] keyword[not] identifier[isinstance] ( identi... | def format_vk(vk):
"""Format vk before using it"""
# Force extension require to be a list
for ext in get_extensions_filtered(vk):
req = ext['require']
if not isinstance(req, list):
ext['require'] = [req] # depends on [control=['if'], data=[]] # depends on [control=['for'], data... |
def get_positions(self, copy=True):
'''
Get a dictionary of measurement positions.
'''
if copy:
return self._positions.copy()
else:
return self._positions | def function[get_positions, parameter[self, copy]]:
constant[
Get a dictionary of measurement positions.
]
if name[copy] begin[:]
return[call[name[self]._positions.copy, parameter[]]] | keyword[def] identifier[get_positions] ( identifier[self] , identifier[copy] = keyword[True] ):
literal[string]
keyword[if] identifier[copy] :
keyword[return] identifier[self] . identifier[_positions] . identifier[copy] ()
keyword[else] :
keyword[return] identi... | def get_positions(self, copy=True):
"""
Get a dictionary of measurement positions.
"""
if copy:
return self._positions.copy() # depends on [control=['if'], data=[]]
else:
return self._positions |
def _set_if_role(self, v, load=False):
"""
Setter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_mst_detail/output/cist/port/if_role (stp-port-role)
If this variable is read-only (config: false) in the
source YANG file, then _set_if_role is considered as a private
method... | def function[_set_if_role, parameter[self, v, load]]:
constant[
Setter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_mst_detail/output/cist/port/if_role (stp-port-role)
If this variable is read-only (config: false) in the
source YANG file, then _set_if_role is considere... | keyword[def] identifier[_set_if_role] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identi... | def _set_if_role(self, v, load=False):
"""
Setter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_mst_detail/output/cist/port/if_role (stp-port-role)
If this variable is read-only (config: false) in the
source YANG file, then _set_if_role is considered as a private
method... |
def Pepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Adds pepper noise to an image, i.e. black-ish pixels.
This is similar to dropout, but slower and the black pixels are not uniformly black.
dtype support::
See ``imgaug.augmenters.arithmetic.ReplaceEleme... | def function[Pepper, parameter[p, per_channel, name, deterministic, random_state]]:
constant[
Adds pepper noise to an image, i.e. black-ish pixels.
This is similar to dropout, but slower and the black pixels are not uniformly black.
dtype support::
See ``imgaug.augmenters.arithmetic.Repla... | keyword[def] identifier[Pepper] ( identifier[p] = literal[int] , identifier[per_channel] = keyword[False] , identifier[name] = keyword[None] , identifier[deterministic] = keyword[False] , identifier[random_state] = keyword[None] ):
literal[string]
identifier[replacement01] = identifier[iap] . identifier[F... | def Pepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Adds pepper noise to an image, i.e. black-ish pixels.
This is similar to dropout, but slower and the black pixels are not uniformly black.
dtype support::
See ``imgaug.augmenters.arithmetic.ReplaceEleme... |
def fetchone(self, query, *args):
"""
Returns the first result of the given query.
:param query: The query to be executed as a `str`.
:param params: A `tuple` of parameters that will be replaced for
placeholders in the query.
:return: The retrieved row wit... | def function[fetchone, parameter[self, query]]:
constant[
Returns the first result of the given query.
:param query: The query to be executed as a `str`.
:param params: A `tuple` of parameters that will be replaced for
placeholders in the query.
:return: T... | keyword[def] identifier[fetchone] ( identifier[self] , identifier[query] ,* identifier[args] ):
literal[string]
identifier[cursor] = identifier[self] . identifier[connection] . identifier[cursor] ()
keyword[try] :
identifier[cursor] . identifier[execute] ( identifier[query] ,... | def fetchone(self, query, *args):
"""
Returns the first result of the given query.
:param query: The query to be executed as a `str`.
:param params: A `tuple` of parameters that will be replaced for
placeholders in the query.
:return: The retrieved row with ea... |
def persist(self, **kwargs):
""" Trigger computation in constituent dask arrays
This keeps them as dask arrays but encourages them to keep data in
memory. This is particularly useful when on a distributed machine.
When on a single machine consider using ``.compute()`` instead.
... | def function[persist, parameter[self]]:
constant[ Trigger computation in constituent dask arrays
This keeps them as dask arrays but encourages them to keep data in
memory. This is particularly useful when on a distributed machine.
When on a single machine consider using ``.compute()`` ... | keyword[def] identifier[persist] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[ds] = identifier[self] . identifier[_to_temp_dataset] (). identifier[persist] (** identifier[kwargs] )
keyword[return] identifier[self] . identifier[_from_temp_dataset] ( identifier[ds... | def persist(self, **kwargs):
""" Trigger computation in constituent dask arrays
This keeps them as dask arrays but encourages them to keep data in
memory. This is particularly useful when on a distributed machine.
When on a single machine consider using ``.compute()`` instead.
Par... |
def get_cachedir_csig(self):
"""
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
Any files that don't ex... | def function[get_cachedir_csig, parameter[self]]:
constant[
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
... | keyword[def] identifier[get_cachedir_csig] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[cachedir_csig]
keyword[except] identifier[AttributeError] :
keyword[pass]
identifier[cachedir] , identifier[... | def get_cachedir_csig(self):
"""
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
Any files that don't exist ... |
def list_resourcepools(kwargs=None, call=None):
'''
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_resourcep... | def function[list_resourcepools, parameter[kwargs, call]]:
constant[
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config
]
if compare[name[call] not_equal[!=] constant[function]] begin[:]
... | keyword[def] identifier[list_resourcepools] ( identifier[kwargs] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
)
... | def list_resourcepools(kwargs=None, call=None):
"""
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config
"""
if call != 'function':
raise SaltCloudSystemExit('The list_resourcepools function... |
def save_patches(self, out_dir):
"""Save the current state of this repository to one or more patches.
Makes one patch against HEAD and another one against the most recent
commit that occurs in an upstream branch. This way we can be robust
to history editing as long as the user never doe... | def function[save_patches, parameter[self, out_dir]]:
constant[Save the current state of this repository to one or more patches.
Makes one patch against HEAD and another one against the most recent
commit that occurs in an upstream branch. This way we can be robust
to history editing as... | keyword[def] identifier[save_patches] ( identifier[self] , identifier[out_dir] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[git] . identifier[enabled] :
keyword[return] keyword[False]
keyword[try] :
identifier[root] = identifier[s... | def save_patches(self, out_dir):
"""Save the current state of this repository to one or more patches.
Makes one patch against HEAD and another one against the most recent
commit that occurs in an upstream branch. This way we can be robust
to history editing as long as the user never does "p... |
def _stringify_path(filepath_or_buffer):
"""Attempt to convert a path-like object to a string.
Parameters
----------
filepath_or_buffer : object to be converted
Returns
-------
str_filepath_or_buffer : maybe a string version of the object
Notes
-----
Objects supporting the fsp... | def function[_stringify_path, parameter[filepath_or_buffer]]:
constant[Attempt to convert a path-like object to a string.
Parameters
----------
filepath_or_buffer : object to be converted
Returns
-------
str_filepath_or_buffer : maybe a string version of the object
Notes
-----... | keyword[def] identifier[_stringify_path] ( identifier[filepath_or_buffer] ):
literal[string]
keyword[try] :
keyword[import] identifier[pathlib]
identifier[_PATHLIB_INSTALLED] = keyword[True]
keyword[except] identifier[ImportError] :
identifier[_PATHLIB_INSTALLED] = keywo... | def _stringify_path(filepath_or_buffer):
"""Attempt to convert a path-like object to a string.
Parameters
----------
filepath_or_buffer : object to be converted
Returns
-------
str_filepath_or_buffer : maybe a string version of the object
Notes
-----
Objects supporting the fsp... |
def get_arcs(analysis):
"""
Hit stats for each branch.
Returns a flat list where every four values represent a branch:
1. line-number
2. block-number (not used)
3. branch-number
4. hits (we only get 1/0 from coverage.py)
"""
if not analysis.has_ar... | def function[get_arcs, parameter[analysis]]:
constant[
Hit stats for each branch.
Returns a flat list where every four values represent a branch:
1. line-number
2. block-number (not used)
3. branch-number
4. hits (we only get 1/0 from coverage.py)
]
... | keyword[def] identifier[get_arcs] ( identifier[analysis] ):
literal[string]
keyword[if] keyword[not] identifier[analysis] . identifier[has_arcs] ():
keyword[return] keyword[None]
identifier[branch_lines] = identifier[analysis] . identifier[branch_lines] ()
identi... | def get_arcs(analysis):
"""
Hit stats for each branch.
Returns a flat list where every four values represent a branch:
1. line-number
2. block-number (not used)
3. branch-number
4. hits (we only get 1/0 from coverage.py)
"""
if not analysis.has_arcs():
... |
def handle_class(signature_node, module, object_name, cache):
"""
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
"""
class_ = getattr(module, object_name, None)
if class_ is None:
return
if class_ not in cache:
cache[class_] = {}
attribut... | def function[handle_class, parameter[signature_node, module, object_name, cache]]:
constant[
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
]
variable[class_] assign[=] call[name[getattr], parameter[name[module], name[object_name], constant[None]]]
if co... | keyword[def] identifier[handle_class] ( identifier[signature_node] , identifier[module] , identifier[object_name] , identifier[cache] ):
literal[string]
identifier[class_] = identifier[getattr] ( identifier[module] , identifier[object_name] , keyword[None] )
keyword[if] identifier[class_] keyword[is... | def handle_class(signature_node, module, object_name, cache):
"""
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
"""
class_ = getattr(module, object_name, None)
if class_ is None:
return # depends on [control=['if'], data=[]]
if class_ not in cache:
... |
def create_free_shipping(cls, free_shipping, **kwargs):
"""Create FreeShipping
Create a new FreeShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shipping(free_shipping, asy... | def function[create_free_shipping, parameter[cls, free_shipping]]:
constant[Create FreeShipping
Create a new FreeShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shipping(f... | keyword[def] identifier[create_free_shipping] ( identifier[cls] , identifier[free_shipping] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] ... | def create_free_shipping(cls, free_shipping, **kwargs):
"""Create FreeShipping
Create a new FreeShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shipping(free_shipping, async=T... |
def _set_serializer_by_mime_type(self, mime_type):
"""
:param mime_type:
:return:
used by content_type_set to set get a reference to the appropriate serializer
"""
# ignore if binary response
if isinstance(self._app_iter, BinaryResponse):
self.logger... | def function[_set_serializer_by_mime_type, parameter[self, mime_type]]:
constant[
:param mime_type:
:return:
used by content_type_set to set get a reference to the appropriate serializer
]
if call[name[isinstance], parameter[name[self]._app_iter, name[BinaryResponse]]] b... | keyword[def] identifier[_set_serializer_by_mime_type] ( identifier[self] , identifier[mime_type] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[_app_iter] , identifier[BinaryResponse] ):
identifier[self] . identifier[logger] . identifie... | def _set_serializer_by_mime_type(self, mime_type):
"""
:param mime_type:
:return:
used by content_type_set to set get a reference to the appropriate serializer
"""
# ignore if binary response
if isinstance(self._app_iter, BinaryResponse):
self.logger.info('ignoring s... |
def _set_version(self, v, load=False):
"""
Setter method for version, mapped from YANG variable /interface/port_channel/hide_vrrp_holer/vrrp/version (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_version is considered as a private
method. Backends looking to... | def function[_set_version, parameter[self, v, load]]:
constant[
Setter method for version, mapped from YANG variable /interface/port_channel/hide_vrrp_holer/vrrp/version (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_version is considered as a private
me... | keyword[def] identifier[_set_version] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
identifier[parent] = identifier[getattr] ( identifier[self] , literal[string] , keyword[None] )
keyword[if] identifier[parent] keyword[is] keyword[not] keyword[None] key... | def _set_version(self, v, load=False):
"""
Setter method for version, mapped from YANG variable /interface/port_channel/hide_vrrp_holer/vrrp/version (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_version is considered as a private
method. Backends looking to... |
def bulk_insert(self, resource, docs, **kwargs):
"""Bulk insert documents."""
kwargs.update(self._es_args(resource))
parent_type = self._get_parent_type(resource)
if parent_type:
for doc in docs:
if doc.get(parent_type.get('field')):
doc['_... | def function[bulk_insert, parameter[self, resource, docs]]:
constant[Bulk insert documents.]
call[name[kwargs].update, parameter[call[name[self]._es_args, parameter[name[resource]]]]]
variable[parent_type] assign[=] call[name[self]._get_parent_type, parameter[name[resource]]]
if name[par... | keyword[def] identifier[bulk_insert] ( identifier[self] , identifier[resource] , identifier[docs] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] . identifier[update] ( identifier[self] . identifier[_es_args] ( identifier[resource] ))
identifier[parent_type] = identifier[self]... | def bulk_insert(self, resource, docs, **kwargs):
"""Bulk insert documents."""
kwargs.update(self._es_args(resource))
parent_type = self._get_parent_type(resource)
if parent_type:
for doc in docs:
if doc.get(parent_type.get('field')):
doc['_parent'] = doc.get(parent_ty... |
def _udf_get_file_from_iso_fp(self, outfp, blocksize, udf_path):
# type: (BinaryIO, int, bytes) -> None
'''
An internal method to fetch a single UDF file from the ISO and write it
out to the file object.
Parameters:
outfp - The file object to write data to.
blo... | def function[_udf_get_file_from_iso_fp, parameter[self, outfp, blocksize, udf_path]]:
constant[
An internal method to fetch a single UDF file from the ISO and write it
out to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number ... | keyword[def] identifier[_udf_get_file_from_iso_fp] ( identifier[self] , identifier[outfp] , identifier[blocksize] , identifier[udf_path] ):
literal[string]
keyword[if] identifier[self] . identifier[udf_root] keyword[is] keyword[None] :
keyword[raise] identifier[pycdlibexception] .... | def _udf_get_file_from_iso_fp(self, outfp, blocksize, udf_path):
# type: (BinaryIO, int, bytes) -> None
'\n An internal method to fetch a single UDF file from the ISO and write it\n out to the file object.\n\n Parameters:\n outfp - The file object to write data to.\n blocksi... |
def set_min_priority(self, infohash_list):
"""
Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/bottomPrio', data=data) | def function[set_min_priority, parameter[self, infohash_list]]:
constant[
Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes.
]
variable[data] assign[=] call[name[self]._process_infohash_list, parameter[name[infohash_list]]]
return[c... | keyword[def] identifier[set_min_priority] ( identifier[self] , identifier[infohash_list] ):
literal[string]
identifier[data] = identifier[self] . identifier[_process_infohash_list] ( identifier[infohash_list] )
keyword[return] identifier[self] . identifier[_post] ( literal[string] , ident... | def set_min_priority(self, infohash_list):
"""
Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/bottomPrio', data=data) |
def check_complicance(self):
"""Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error.
"""
# check Media RSS requirement: one of the following elements is
# required: media_group | media_content... | def function[check_complicance, parameter[self]]:
constant[Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error.
]
if <ast.BoolOp object at 0x7da20e955c00> begin[:]
<ast.Raise object at 0x7da20... | keyword[def] identifier[check_complicance] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[any] ([ identifier[ma] keyword[for] identifier[ma] keyword[in] identifier[vars] ( identifier[self] )
keyword[if] identifier[ma] . identifier[st... | def check_complicance(self):
"""Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error.
"""
# check Media RSS requirement: one of the following elements is
# required: media_group | media_content | media_pla... |
def cond_remove_all(ol,**kwargs):
'''
from elist.elist import *
ol = [1,'X',3,'b',5,'c',6,'A',7,'b',8,'B',9]
id(ol)
def afterCH(ele,ch):
cond = (ord(str(ele)) > ord(ch))
return(cond)
new = cond_remove_all(ol,cond_func=afterCH,cond_func_args=['B'])
... | def function[cond_remove_all, parameter[ol]]:
constant[
from elist.elist import *
ol = [1,'X',3,'b',5,'c',6,'A',7,'b',8,'B',9]
id(ol)
def afterCH(ele,ch):
cond = (ord(str(ele)) > ord(ch))
return(cond)
new = cond_remove_all(ol,cond_func=afterCH,con... | keyword[def] identifier[cond_remove_all] ( identifier[ol] ,** identifier[kwargs] ):
literal[string]
identifier[cond_func] = identifier[kwargs] [ literal[string] ]
keyword[if] ( literal[string] keyword[in] identifier[kwargs] ):
identifier[cond_func_args] = identifier[kwargs] [ literal[string... | def cond_remove_all(ol, **kwargs):
"""
from elist.elist import *
ol = [1,'X',3,'b',5,'c',6,'A',7,'b',8,'B',9]
id(ol)
def afterCH(ele,ch):
cond = (ord(str(ele)) > ord(ch))
return(cond)
new = cond_remove_all(ol,cond_func=afterCH,cond_func_args=['B'])
... |
def replace(text, old, new, count=None, strip=False):
'''
Replace an ``old`` subset of ``text`` with ``new``.
``old`` type may be either a string or regular expression.
If ``strip``, remove all leading/trailing whitespace.
If ``count``, replace the specified number of occurence, other... | def function[replace, parameter[text, old, new, count, strip]]:
constant[
Replace an ``old`` subset of ``text`` with ``new``.
``old`` type may be either a string or regular expression.
If ``strip``, remove all leading/trailing whitespace.
If ``count``, replace the specified number... | keyword[def] identifier[replace] ( identifier[text] , identifier[old] , identifier[new] , identifier[count] = keyword[None] , identifier[strip] = keyword[False] ):
literal[string]
keyword[if] identifier[is_string] ( identifier[old] ):
identifier[text] = identifier[text] . identifier[replace] ( id... | def replace(text, old, new, count=None, strip=False):
"""
Replace an ``old`` subset of ``text`` with ``new``.
``old`` type may be either a string or regular expression.
If ``strip``, remove all leading/trailing whitespace.
If ``count``, replace the specified number of occurence, other... |
def utc_datetime(dt=None, local_value=True):
""" Convert local datetime and/or datetime without timezone information to UTC datetime with timezone
information.
:param dt: local datetime to convert. If is None, then system datetime value is used
:param local_value: whether dt is a datetime in system timezone or UTC... | def function[utc_datetime, parameter[dt, local_value]]:
constant[ Convert local datetime and/or datetime without timezone information to UTC datetime with timezone
information.
:param dt: local datetime to convert. If is None, then system datetime value is used
:param local_value: whether dt is a datetime i... | keyword[def] identifier[utc_datetime] ( identifier[dt] = keyword[None] , identifier[local_value] = keyword[True] ):
literal[string]
keyword[if] identifier[dt] keyword[is] keyword[None] :
keyword[return] identifier[datetime] . identifier[now] ( identifier[tz] = identifier[timezone] . identifier[utc] )
... | def utc_datetime(dt=None, local_value=True):
""" Convert local datetime and/or datetime without timezone information to UTC datetime with timezone
information.
:param dt: local datetime to convert. If is None, then system datetime value is used
:param local_value: whether dt is a datetime in system timezone or ... |
def pipe_item_split(tokens, loc):
"""Process a pipe item, which could be a partial, an attribute access, a method call, or an expression.
Return (type, split) where split is
- (expr,) for expression,
- (func, pos_args, kwd_args) for partial,
- (name, args) for attr/method, and
- ... | def function[pipe_item_split, parameter[tokens, loc]]:
constant[Process a pipe item, which could be a partial, an attribute access, a method call, or an expression.
Return (type, split) where split is
- (expr,) for expression,
- (func, pos_args, kwd_args) for partial,
- (name, args) ... | keyword[def] identifier[pipe_item_split] ( identifier[tokens] , identifier[loc] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[tokens] , identifier[list] ) keyword[or] literal[string] keyword[in] identifier[tokens] :
identifier[internal_assert] ( identifier[len] ( iden... | def pipe_item_split(tokens, loc):
"""Process a pipe item, which could be a partial, an attribute access, a method call, or an expression.
Return (type, split) where split is
- (expr,) for expression,
- (func, pos_args, kwd_args) for partial,
- (name, args) for attr/method, and
- ... |
def on_release_key(key, callback, suppress=False):
"""
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
"""
return hook_key(key, lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress) | def function[on_release_key, parameter[key, callback, suppress]]:
constant[
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
]
return[call[name[hook_key], parameter[name[key], <ast.Lambda object at 0x7da1b1bf98a0>]]] | keyword[def] identifier[on_release_key] ( identifier[key] , identifier[callback] , identifier[suppress] = keyword[False] ):
literal[string]
keyword[return] identifier[hook_key] ( identifier[key] , keyword[lambda] identifier[e] : identifier[e] . identifier[event_type] == identifier[KEY_DOWN] keyword[or] ... | def on_release_key(key, callback, suppress=False):
"""
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
"""
return hook_key(key, lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress) |
def get_url_from (base_url, recursion_level, aggregate,
parent_url=None, base_ref=None, line=0, column=0, page=0,
name=u"", parent_content_type=None, extern=None):
"""
Get url data from given base data.
@param base_url: base url from a link tag
@type base_url: string... | def function[get_url_from, parameter[base_url, recursion_level, aggregate, parent_url, base_ref, line, column, page, name, parent_content_type, extern]]:
constant[
Get url data from given base data.
@param base_url: base url from a link tag
@type base_url: string or None
@param recursion_level:... | keyword[def] identifier[get_url_from] ( identifier[base_url] , identifier[recursion_level] , identifier[aggregate] ,
identifier[parent_url] = keyword[None] , identifier[base_ref] = keyword[None] , identifier[line] = literal[int] , identifier[column] = literal[int] , identifier[page] = literal[int] ,
identifier[name... | def get_url_from(base_url, recursion_level, aggregate, parent_url=None, base_ref=None, line=0, column=0, page=0, name=u'', parent_content_type=None, extern=None):
"""
Get url data from given base data.
@param base_url: base url from a link tag
@type base_url: string or None
@param recursion_level: ... |
def list_downloads():
'''
Return a list of all updates that have been downloaded locally.
:return: A list of updates that have been downloaded
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_downloads
'''
outfiles = []
for root, subFolder, files... | def function[list_downloads, parameter[]]:
constant[
Return a list of all updates that have been downloaded locally.
:return: A list of updates that have been downloaded
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_downloads
]
variable[ou... | keyword[def] identifier[list_downloads] ():
literal[string]
identifier[outfiles] =[]
keyword[for] identifier[root] , identifier[subFolder] , identifier[files] keyword[in] identifier[salt] . identifier[utils] . identifier[path] . identifier[os_walk] ( literal[string] ):
keyword[for] identi... | def list_downloads():
"""
Return a list of all updates that have been downloaded locally.
:return: A list of updates that have been downloaded
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_downloads
"""
outfiles = []
for (root, subFolder, file... |
def from_pygments_lexer_cls(cls, lexer_cls):
"""
Create a :class:`.RegexSync` instance for this Pygments lexer class.
"""
patterns = {
# For Python, start highlighting at any class/def block.
'Python': r'^\s*(class|def)\s+',
'Python 3': r'^\s*(class|... | def function[from_pygments_lexer_cls, parameter[cls, lexer_cls]]:
constant[
Create a :class:`.RegexSync` instance for this Pygments lexer class.
]
variable[patterns] assign[=] dictionary[[<ast.Constant object at 0x7da204347eb0>, <ast.Constant object at 0x7da204344dc0>, <ast.Constant obje... | keyword[def] identifier[from_pygments_lexer_cls] ( identifier[cls] , identifier[lexer_cls] ):
literal[string]
identifier[patterns] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
... | def from_pygments_lexer_cls(cls, lexer_cls):
"""
Create a :class:`.RegexSync` instance for this Pygments lexer class.
"""
# For Python, start highlighting at any class/def block.
# For HTML, start at any open/close tag definition.
# For javascript, start at a function.
# TODO: Add de... |
def get_auth_params_from_request(request):
"""Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient.
"""
return (
request.user.username,
request.user.token.id,
request.user.tenant_id,
request.user.tok... | def function[get_auth_params_from_request, parameter[request]]:
constant[Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient.
]
return[tuple[[<ast.Attribute object at 0x7da1b1985780>, <ast.Attribute object at 0x7da1b1985510>, ... | keyword[def] identifier[get_auth_params_from_request] ( identifier[request] ):
literal[string]
keyword[return] (
identifier[request] . identifier[user] . identifier[username] ,
identifier[request] . identifier[user] . identifier[token] . identifier[id] ,
identifier[request] . identifier[user... | def get_auth_params_from_request(request):
"""Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient.
"""
return (request.user.username, request.user.token.id, request.user.tenant_id, request.user.token.project.get('domain_id'), base... |
def _set_bpdu_drop(self, v, load=False):
"""
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
method. Backends looking t... | def function[_set_bpdu_drop, parameter[self, v, load]]:
constant[
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
m... | keyword[def] identifier[_set_bpdu_drop] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
iden... | def _set_bpdu_drop(self, v, load=False):
"""
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
method. Backends looking t... |
def files(self):
"""
Returns the list of file names for all documents.
"""
return [
os.path.join(self.root, label, name)
for label in self.labels
for name in os.listdir(os.path.join(self.root, label))
] | def function[files, parameter[self]]:
constant[
Returns the list of file names for all documents.
]
return[<ast.ListComp object at 0x7da18f00cfa0>] | keyword[def] identifier[files] ( identifier[self] ):
literal[string]
keyword[return] [
identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[root] , identifier[label] , identifier[name] )
keyword[for] identifier[label] keyword[in] identifier[self]... | def files(self):
"""
Returns the list of file names for all documents.
"""
return [os.path.join(self.root, label, name) for label in self.labels for name in os.listdir(os.path.join(self.root, label))] |
def cache(self, name, cache_class=Cache,
identity_generator_class=IdentityGenerator,
compressor_class=Compressor,
serializer_class=Serializer, *args, **kwargs):
"""
Return a cache object using default identity generator,
serializer and compressor.
... | def function[cache, parameter[self, name, cache_class, identity_generator_class, compressor_class, serializer_class]]:
constant[
Return a cache object using default identity generator,
serializer and compressor.
``name`` is used to identify the series of your cache
``cache_class... | keyword[def] identifier[cache] ( identifier[self] , identifier[name] , identifier[cache_class] = identifier[Cache] ,
identifier[identity_generator_class] = identifier[IdentityGenerator] ,
identifier[compressor_class] = identifier[Compressor] ,
identifier[serializer_class] = identifier[Serializer] ,* identifier[arg... | def cache(self, name, cache_class=Cache, identity_generator_class=IdentityGenerator, compressor_class=Compressor, serializer_class=Serializer, *args, **kwargs):
"""
Return a cache object using default identity generator,
serializer and compressor.
``name`` is used to identify the series of ... |
def _imagpart(self, f):
"""Function returning the imaginary part of the result from ``f``."""
def f_im(x, **kwargs):
result = np.asarray(f(x, **kwargs),
dtype=self.scalar_out_dtype)
return result.imag
if is_real_dtype(self.out_dtype):
... | def function[_imagpart, parameter[self, f]]:
constant[Function returning the imaginary part of the result from ``f``.]
def function[f_im, parameter[x]]:
variable[result] assign[=] call[name[np].asarray, parameter[call[name[f], parameter[name[x]]]]]
return[name[result].imag]
... | keyword[def] identifier[_imagpart] ( identifier[self] , identifier[f] ):
literal[string]
keyword[def] identifier[f_im] ( identifier[x] ,** identifier[kwargs] ):
identifier[result] = identifier[np] . identifier[asarray] ( identifier[f] ( identifier[x] ,** identifier[kwargs] ),
... | def _imagpart(self, f):
"""Function returning the imaginary part of the result from ``f``."""
def f_im(x, **kwargs):
result = np.asarray(f(x, **kwargs), dtype=self.scalar_out_dtype)
return result.imag
if is_real_dtype(self.out_dtype):
return self.zero() # depends on [control=['if']... |
def JTg(self):
r'''Joule Thomson coefficient of the chemical in the gas phase at
its current temperature and pressure, in units of [K/Pa].
.. math::
\mu_{JT} = \left(\frac{\partial T}{\partial P}\right)_H = \frac{1}{C_p}
\left[T \left(\frac{\partial V}{\partial T}\right)... | def function[JTg, parameter[self]]:
constant[Joule Thomson coefficient of the chemical in the gas phase at
its current temperature and pressure, in units of [K/Pa].
.. math::
\mu_{JT} = \left(\frac{\partial T}{\partial P}\right)_H = \frac{1}{C_p}
\left[T \left(\frac{\par... | keyword[def] identifier[JTg] ( identifier[self] ):
literal[string]
identifier[Vmg] , identifier[Cpgm] , identifier[isobaric_expansion_g] = identifier[self] . identifier[Vmg] , identifier[self] . identifier[Cpgm] , identifier[self] . identifier[isobaric_expansion_g]
keyword[if] identifier... | def JTg(self):
"""Joule Thomson coefficient of the chemical in the gas phase at
its current temperature and pressure, in units of [K/Pa].
.. math::
\\mu_{JT} = \\left(\\frac{\\partial T}{\\partial P}\\right)_H = \\frac{1}{C_p}
\\left[T \\left(\\frac{\\partial V}{\\partial T}... |
def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
text = format_heading(1, '%s' % makename(master_package, subroot))
if opts.modulefirst:
text += format_directive(subroot, master_package)
text += '\n'
# bu... | def function[create_package_file, parameter[root, master_package, subroot, py_files, opts, subs]]:
constant[Build the text of the file and write the file.]
variable[text] assign[=] call[name[format_heading], parameter[constant[1], binary_operation[constant[%s] <ast.Mod object at 0x7da2590d6920> call[nam... | keyword[def] identifier[create_package_file] ( identifier[root] , identifier[master_package] , identifier[subroot] , identifier[py_files] , identifier[opts] , identifier[subs] ):
literal[string]
identifier[text] = identifier[format_heading] ( literal[int] , literal[string] % identifier[makename] ( identifi... | def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
text = format_heading(1, '%s' % makename(master_package, subroot))
if opts.modulefirst:
text += format_directive(subroot, master_package)
text += '\n' # depends... |
def calculate_ef_var(tpf, fpf):
"""
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param fpf: float fpf @ which the enr... | def function[calculate_ef_var, parameter[tpf, fpf]]:
constant[
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param... | keyword[def] identifier[calculate_ef_var] ( identifier[tpf] , identifier[fpf] ):
literal[string]
identifier[efvara] =( identifier[tpf] *( literal[int] - identifier[tpf] ))
identifier[efvard] =( identifier[fpf] *( literal[int] - identifier[fpf] ))
identifier[ef] = identifier[tpf] / identifier[fp... | def calculate_ef_var(tpf, fpf):
"""
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param fpf: float fpf @ which the enr... |
def response_body(self):
'''
Gets response body as a SAFEARRAY and converts the SAFEARRAY to str.
'''
var_respbody = VARIANT()
_WinHttpRequest._ResponseBody(self, byref(var_respbody))
if var_respbody.is_safearray_of_bytes():
respbody = var_respbody.str_from_sa... | def function[response_body, parameter[self]]:
constant[
Gets response body as a SAFEARRAY and converts the SAFEARRAY to str.
]
variable[var_respbody] assign[=] call[name[VARIANT], parameter[]]
call[name[_WinHttpRequest]._ResponseBody, parameter[name[self], call[name[byref], param... | keyword[def] identifier[response_body] ( identifier[self] ):
literal[string]
identifier[var_respbody] = identifier[VARIANT] ()
identifier[_WinHttpRequest] . identifier[_ResponseBody] ( identifier[self] , identifier[byref] ( identifier[var_respbody] ))
keyword[if] identifier[var_r... | def response_body(self):
"""
Gets response body as a SAFEARRAY and converts the SAFEARRAY to str.
"""
var_respbody = VARIANT()
_WinHttpRequest._ResponseBody(self, byref(var_respbody))
if var_respbody.is_safearray_of_bytes():
respbody = var_respbody.str_from_safearray()
re... |
def printTriples(self):
""" display triples """
printDebug(Fore.RED + self.uri + Style.RESET_ALL)
for x in self.triples:
printDebug(Fore.BLACK + "=> " + unicode(x[1]))
printDebug(Style.DIM + ".... " + unicode(x[2]) + Fore.RESET)
print("") | def function[printTriples, parameter[self]]:
constant[ display triples ]
call[name[printDebug], parameter[binary_operation[binary_operation[name[Fore].RED + name[self].uri] + name[Style].RESET_ALL]]]
for taget[name[x]] in starred[name[self].triples] begin[:]
call[name[printDebug]... | keyword[def] identifier[printTriples] ( identifier[self] ):
literal[string]
identifier[printDebug] ( identifier[Fore] . identifier[RED] + identifier[self] . identifier[uri] + identifier[Style] . identifier[RESET_ALL] )
keyword[for] identifier[x] keyword[in] identifier[self] . identifier... | def printTriples(self):
""" display triples """
printDebug(Fore.RED + self.uri + Style.RESET_ALL)
for x in self.triples:
printDebug(Fore.BLACK + '=> ' + unicode(x[1]))
printDebug(Style.DIM + '.... ' + unicode(x[2]) + Fore.RESET) # depends on [control=['for'], data=['x']]
print('') |
def _get_recursive_iterator(self, recursive=False):
"""
Basic recursive iterator whose only purpose is to yield all items
and sections in order, with their full paths as keys.
Main challenge is to de-duplicate items and sections which
have aliases.
Do not add any new fe... | def function[_get_recursive_iterator, parameter[self, recursive]]:
constant[
Basic recursive iterator whose only purpose is to yield all items
and sections in order, with their full paths as keys.
Main challenge is to de-duplicate items and sections which
have aliases.
... | keyword[def] identifier[_get_recursive_iterator] ( identifier[self] , identifier[recursive] = keyword[False] ):
literal[string]
identifier[names_yielded] = identifier[set] ()
keyword[for] identifier[obj_alias] , identifier[obj] keyword[in] identifier[self] . identifier[_tree] . identi... | def _get_recursive_iterator(self, recursive=False):
"""
Basic recursive iterator whose only purpose is to yield all items
and sections in order, with their full paths as keys.
Main challenge is to de-duplicate items and sections which
have aliases.
Do not add any new featur... |
def append_partition_with_environment_context(self, db_name, tbl_name, part_vals, environment_context):
"""
Parameters:
- db_name
- tbl_name
- part_vals
- environment_context
"""
self.send_append_partition_with_environment_context(db_name, tbl_name, part_vals, environment_context)
... | def function[append_partition_with_environment_context, parameter[self, db_name, tbl_name, part_vals, environment_context]]:
constant[
Parameters:
- db_name
- tbl_name
- part_vals
- environment_context
]
call[name[self].send_append_partition_with_environment_context, paramete... | keyword[def] identifier[append_partition_with_environment_context] ( identifier[self] , identifier[db_name] , identifier[tbl_name] , identifier[part_vals] , identifier[environment_context] ):
literal[string]
identifier[self] . identifier[send_append_partition_with_environment_context] ( identifier[db_name]... | def append_partition_with_environment_context(self, db_name, tbl_name, part_vals, environment_context):
"""
Parameters:
- db_name
- tbl_name
- part_vals
- environment_context
"""
self.send_append_partition_with_environment_context(db_name, tbl_name, part_vals, environment_context)
... |
def list(cls, invoice_id, custom_headers=None):
"""
:type user_id: int
:type invoice_id: int
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseBytes
"""
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient... | def function[list, parameter[cls, invoice_id, custom_headers]]:
constant[
:type user_id: int
:type invoice_id: int
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseBytes
]
if compare[name[custom_headers] is constant[None]] begin[:]
va... | keyword[def] identifier[list] ( identifier[cls] , identifier[invoice_id] , identifier[custom_headers] = keyword[None] ):
literal[string]
keyword[if] identifier[custom_headers] keyword[is] keyword[None] :
identifier[custom_headers] ={}
identifier[api_client] = identifier[c... | def list(cls, invoice_id, custom_headers=None):
"""
:type user_id: int
:type invoice_id: int
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseBytes
"""
if custom_headers is None:
custom_headers = {} # depends on [control=['if'], data=['custom_header... |
def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://gi... | def function[pythons, parameter[]]:
constant[Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
]
if <ast.UnaryOp object at 0x7da18bccb4f0> begin[:]
call[name[print], paramete... | keyword[def] identifier[pythons] ():
literal[string]
keyword[if] keyword[not] identifier[_pyenv_exists] ():
identifier[print] ( literal[string]
literal[string] +
identifier[cyan] ( literal[string]
literal[string]
literal[string] ))
keyword[return] ... | def pythons():
"""Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
"""
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup (https://github.com/theno/fa... |
async def send_heartbeat(self, name):
"""Send a heartbeat for a service.
Args:
name (string): The name of the service to send a heartbeat for
"""
await self.send_command(OPERATIONS.CMD_HEARTBEAT, {'name': name},
MESSAGES.HeartbeatResponse, ti... | <ast.AsyncFunctionDef object at 0x7da18fe918a0> | keyword[async] keyword[def] identifier[send_heartbeat] ( identifier[self] , identifier[name] ):
literal[string]
keyword[await] identifier[self] . identifier[send_command] ( identifier[OPERATIONS] . identifier[CMD_HEARTBEAT] ,{ literal[string] : identifier[name] },
identifier[MESSAGES] .... | async def send_heartbeat(self, name):
"""Send a heartbeat for a service.
Args:
name (string): The name of the service to send a heartbeat for
"""
await self.send_command(OPERATIONS.CMD_HEARTBEAT, {'name': name}, MESSAGES.HeartbeatResponse, timeout=5.0) |
def apply(self, matrix):
"""
Slices the supplied matrix and applies any transform bound to this window
"""
view = matrix[ self.indices() ]
return self.transform(view) if self.transform != None else view | def function[apply, parameter[self, matrix]]:
constant[
Slices the supplied matrix and applies any transform bound to this window
]
variable[view] assign[=] call[name[matrix]][call[name[self].indices, parameter[]]]
return[<ast.IfExp object at 0x7da1b12f30d0>] | keyword[def] identifier[apply] ( identifier[self] , identifier[matrix] ):
literal[string]
identifier[view] = identifier[matrix] [ identifier[self] . identifier[indices] ()]
keyword[return] identifier[self] . identifier[transform] ( identifier[view] ) keyword[if] identifier[self] . identifier[transform] !=... | def apply(self, matrix):
"""
Slices the supplied matrix and applies any transform bound to this window
"""
view = matrix[self.indices()]
return self.transform(view) if self.transform != None else view |
def visit_complex_value(self, node):
"""Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes."""
if node.value.startswith(ComplexValue.EXACT_VALUE_TOKEN):
value = node.value.strip(ComplexValue.EXACT_VALUE_TOKEN)
return ExactMatchValue(value)
... | def function[visit_complex_value, parameter[self, node]]:
constant[Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes.]
if call[name[node].value.startswith, parameter[name[ComplexValue].EXACT_VALUE_TOKEN]] begin[:]
variable[value] assign[=] call[name[n... | keyword[def] identifier[visit_complex_value] ( identifier[self] , identifier[node] ):
literal[string]
keyword[if] identifier[node] . identifier[value] . identifier[startswith] ( identifier[ComplexValue] . identifier[EXACT_VALUE_TOKEN] ):
identifier[value] = identifier[node] . identifi... | def visit_complex_value(self, node):
"""Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes."""
if node.value.startswith(ComplexValue.EXACT_VALUE_TOKEN):
value = node.value.strip(ComplexValue.EXACT_VALUE_TOKEN)
return ExactMatchValue(value) # depends on [contr... |
def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, status=None):
"""Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of t... | def function[edit, parameter[self, name, description, start_date, due_date, assignees, status]]:
constant[Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of the ... | keyword[def] identifier[edit] ( identifier[self] , identifier[name] = keyword[None] , identifier[description] = keyword[None] , identifier[start_date] = keyword[None] , identifier[due_date] = keyword[None] , identifier[assignees] = keyword[None] , identifier[status] = keyword[None] ):
literal[string]
... | def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, status=None):
"""Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of the a... |
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | def function[_send, parameter[self, packet]]:
constant[Add packet to send queue.]
variable[fut] assign[=] call[name[self].loop.create_future, parameter[]]
call[name[self].waiters.append, parameter[tuple[[<ast.Name object at 0x7da1b27824a0>, <ast.Name object at 0x7da1b2780190>]]]]
if <ast... | keyword[def] identifier[_send] ( identifier[self] , identifier[packet] ):
literal[string]
identifier[fut] = identifier[self] . identifier[loop] . identifier[create_future] ()
identifier[self] . identifier[waiters] . identifier[append] (( identifier[fut] , identifier[packet] ))
key... | def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet() # depends on [control=['if'], data=[]]
return fut |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.