code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _add_dependency(self, p, template, inlane, outlane, pid):
"""Automatically Adds a dependency of a process.
This method adds a template to the process list attribute as a
dependency. It will adapt the input lane, output lane and process
id of the process that depends on it.
... | def function[_add_dependency, parameter[self, p, template, inlane, outlane, pid]]:
constant[Automatically Adds a dependency of a process.
This method adds a template to the process list attribute as a
dependency. It will adapt the input lane, output lane and process
id of the process th... | keyword[def] identifier[_add_dependency] ( identifier[self] , identifier[p] , identifier[template] , identifier[inlane] , identifier[outlane] , identifier[pid] ):
literal[string]
identifier[dependency_proc] = identifier[self] . identifier[process_map] [ identifier[template] ]( identifier[template]... | def _add_dependency(self, p, template, inlane, outlane, pid):
"""Automatically Adds a dependency of a process.
This method adds a template to the process list attribute as a
dependency. It will adapt the input lane, output lane and process
id of the process that depends on it.
Para... |
def SendUnicodeChar(char: str) -> int:
"""
Type a single unicode char.
char: str, len(char) must equal to 1.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
If the function returns zero, the input was already blocked by another thre... | def function[SendUnicodeChar, parameter[char]]:
constant[
Type a single unicode char.
char: str, len(char) must equal to 1.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
If the function returns zero, the input was already bloc... | keyword[def] identifier[SendUnicodeChar] ( identifier[char] : identifier[str] )-> identifier[int] :
literal[string]
keyword[return] identifier[SendInput] ( identifier[KeyboardInput] ( literal[int] , identifier[ord] ( identifier[char] ), identifier[KeyboardEventFlag] . identifier[KeyUnicode] | identifier[K... | def SendUnicodeChar(char: str) -> int:
"""
Type a single unicode char.
char: str, len(char) must equal to 1.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
If the function returns zero, the input was already blocked by another thre... |
def put(self, pid, record, **kwargs):
"""Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updat... | def function[put, parameter[self, pid, record]]:
constant[Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. Th... | keyword[def] identifier[put] ( identifier[self] , identifier[pid] , identifier[record] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[request] . identifier[mimetype] keyword[not] keyword[in] identifier[self] . identifier[loaders] :
keyword[raise] identifier[Unsup... | def put(self, pid, record, **kwargs):
"""Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updated b... |
def load(self, dbfile, password=None, keyfile=None, readonly=False):
"""
Load the database from file/stream.
:param dbfile: The database file path/stream.
:type dbfile: str or file-like object
:param password: The password for the database.
:type password: str
... | def function[load, parameter[self, dbfile, password, keyfile, readonly]]:
constant[
Load the database from file/stream.
:param dbfile: The database file path/stream.
:type dbfile: str or file-like object
:param password: The password for the database.
:type passw... | keyword[def] identifier[load] ( identifier[self] , identifier[dbfile] , identifier[password] = keyword[None] , identifier[keyfile] = keyword[None] , identifier[readonly] = keyword[False] ):
literal[string]
identifier[self] . identifier[_clear] ()
identifier[buf] = keyword[None]
... | def load(self, dbfile, password=None, keyfile=None, readonly=False):
"""
Load the database from file/stream.
:param dbfile: The database file path/stream.
:type dbfile: str or file-like object
:param password: The password for the database.
:type password: str
... |
def neutron(*arg):
"""
Neutron annotation for adding function to process neutron notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notification
"""
check_eve... | def function[neutron, parameter[]]:
constant[
Neutron annotation for adding function to process neutron notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notific... | keyword[def] identifier[neutron] (* identifier[arg] ):
literal[string]
identifier[check_event_type] ( identifier[Openstack] . identifier[Neutron] ,* identifier[arg] )
identifier[event_type] = identifier[arg] [ literal[int] ]
keyword[def] identifier[decorator] ( identifier[func] ):
keyw... | def neutron(*arg):
"""
Neutron annotation for adding function to process neutron notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notification
"""
check_eve... |
def marginalize(self, variables, inplace=True):
u"""
Modifies the factor with marginalized values.
Let C(X,Y ; K, h, g) be some canonical form over X,Y where,
k = [[K_XX, K_XY], ; h = [[h_X],
[K_YX, K_YY]] [h_Y]]
In this case, the ... | def function[marginalize, parameter[self, variables, inplace]]:
constant[
Modifies the factor with marginalized values.
Let C(X,Y ; K, h, g) be some canonical form over X,Y where,
k = [[K_XX, K_XY], ; h = [[h_X],
[K_YX, K_YY]] [h_Y]]
... | keyword[def] identifier[marginalize] ( identifier[self] , identifier[variables] , identifier[inplace] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[variables] ,( identifier[list] , identifier[tuple] , identifier[np] . identifier[ndarray] )):
... | def marginalize(self, variables, inplace=True):
u"""
Modifies the factor with marginalized values.
Let C(X,Y ; K, h, g) be some canonical form over X,Y where,
k = [[K_XX, K_XY], ; h = [[h_X],
[K_YX, K_YY]] [h_Y]]
In this case, the resu... |
def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
# Items should be an array of type CoinState, not of ints!
corrected_items = list(map(lambda i: CoinState(i), self.Items))
return super(UnspentCoinState, self).Size... | def function[Size, parameter[self]]:
constant[
Get the total size in bytes of the object.
Returns:
int: size.
]
variable[corrected_items] assign[=] call[name[list], parameter[call[name[map], parameter[<ast.Lambda object at 0x7da20e9b0220>, name[self].Items]]]]
re... | keyword[def] identifier[Size] ( identifier[self] ):
literal[string]
identifier[corrected_items] = identifier[list] ( identifier[map] ( keyword[lambda] identifier[i] : identifier[CoinState] ( identifier[i] ), identifier[self] . identifier[Items] ))
keyword[return] identifier[supe... | def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
# Items should be an array of type CoinState, not of ints!
corrected_items = list(map(lambda i: CoinState(i), self.Items))
return super(UnspentCoinState, self).Size() + GetVarSize(... |
def enable_autozoom(self, option):
"""Set ``autozoom`` behavior.
Parameters
----------
option : {'on', 'override', 'once', 'off'}
Option for zoom behavior. A list of acceptable options can
also be obtained by :meth:`get_autozoom_options`.
Raises
... | def function[enable_autozoom, parameter[self, option]]:
constant[Set ``autozoom`` behavior.
Parameters
----------
option : {'on', 'override', 'once', 'off'}
Option for zoom behavior. A list of acceptable options can
also be obtained by :meth:`get_autozoom_options... | keyword[def] identifier[enable_autozoom] ( identifier[self] , identifier[option] ):
literal[string]
identifier[option] = identifier[option] . identifier[lower] ()
keyword[assert] ( identifier[option] keyword[in] identifier[self] . identifier[autozoom_options] ), identifier[ImageViewError... | def enable_autozoom(self, option):
"""Set ``autozoom`` behavior.
Parameters
----------
option : {'on', 'override', 'once', 'off'}
Option for zoom behavior. A list of acceptable options can
also be obtained by :meth:`get_autozoom_options`.
Raises
----... |
def extract_module(self, path: str, freeze: bool = True) -> Module:
"""
This method can be used to load a module from the pretrained model archive.
It is also used implicitly in FromParams based construction. So instead of using standard
params to construct a module, you can instead loa... | def function[extract_module, parameter[self, path, freeze]]:
constant[
This method can be used to load a module from the pretrained model archive.
It is also used implicitly in FromParams based construction. So instead of using standard
params to construct a module, you can instead load... | keyword[def] identifier[extract_module] ( identifier[self] , identifier[path] : identifier[str] , identifier[freeze] : identifier[bool] = keyword[True] )-> identifier[Module] :
literal[string]
identifier[modules_dict] ={ identifier[path] : identifier[module] keyword[for] identifier[path] , identi... | def extract_module(self, path: str, freeze: bool=True) -> Module:
"""
This method can be used to load a module from the pretrained model archive.
It is also used implicitly in FromParams based construction. So instead of using standard
params to construct a module, you can instead load a pr... |
def token_from_fragment(self, authorization_response):
"""Parse token from the URI fragment, used by MobileApplicationClients.
:param authorization_response: The full URL of the redirect back to you
:return: A token dict
"""
self._client.parse_request_uri_response(
a... | def function[token_from_fragment, parameter[self, authorization_response]]:
constant[Parse token from the URI fragment, used by MobileApplicationClients.
:param authorization_response: The full URL of the redirect back to you
:return: A token dict
]
call[name[self]._client.parse... | keyword[def] identifier[token_from_fragment] ( identifier[self] , identifier[authorization_response] ):
literal[string]
identifier[self] . identifier[_client] . identifier[parse_request_uri_response] (
identifier[authorization_response] , identifier[state] = identifier[self] . identifier[_... | def token_from_fragment(self, authorization_response):
"""Parse token from the URI fragment, used by MobileApplicationClients.
:param authorization_response: The full URL of the redirect back to you
:return: A token dict
"""
self._client.parse_request_uri_response(authorization_response... |
def get_static_url():
"""Return a base static url, always ending with a /"""
path = getattr(settings, 'STATIC_URL', None)
if not path:
path = getattr(settings, 'MEDIA_URL', None)
if not path:
path = '/'
return path | def function[get_static_url, parameter[]]:
constant[Return a base static url, always ending with a /]
variable[path] assign[=] call[name[getattr], parameter[name[settings], constant[STATIC_URL], constant[None]]]
if <ast.UnaryOp object at 0x7da1b20b4310> begin[:]
variable[path] as... | keyword[def] identifier[get_static_url] ():
literal[string]
identifier[path] = identifier[getattr] ( identifier[settings] , literal[string] , keyword[None] )
keyword[if] keyword[not] identifier[path] :
identifier[path] = identifier[getattr] ( identifier[settings] , literal[string] , keyword... | def get_static_url():
"""Return a base static url, always ending with a /"""
path = getattr(settings, 'STATIC_URL', None)
if not path:
path = getattr(settings, 'MEDIA_URL', None) # depends on [control=['if'], data=[]]
if not path:
path = '/' # depends on [control=['if'], data=[]]
r... |
def _gam(self):
""" Lorentz factor array
"""
log10gmin = np.log10(self.Eemin / mec2).value
log10gmax = np.log10(self.Eemax / mec2).value
return np.logspace(
log10gmin, log10gmax, int(self.nEed * (log10gmax - log10gmin))
) | def function[_gam, parameter[self]]:
constant[ Lorentz factor array
]
variable[log10gmin] assign[=] call[name[np].log10, parameter[binary_operation[name[self].Eemin / name[mec2]]]].value
variable[log10gmax] assign[=] call[name[np].log10, parameter[binary_operation[name[self].Eemax / name... | keyword[def] identifier[_gam] ( identifier[self] ):
literal[string]
identifier[log10gmin] = identifier[np] . identifier[log10] ( identifier[self] . identifier[Eemin] / identifier[mec2] ). identifier[value]
identifier[log10gmax] = identifier[np] . identifier[log10] ( identifier[self] . ide... | def _gam(self):
""" Lorentz factor array
"""
log10gmin = np.log10(self.Eemin / mec2).value
log10gmax = np.log10(self.Eemax / mec2).value
return np.logspace(log10gmin, log10gmax, int(self.nEed * (log10gmax - log10gmin))) |
def _synthesize_multiple_c_extension(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple text fragments, using the cew extension.
Return a tuple (anchors, total_time, num_chars).
:rtype: (bool, (list, :class:`~aeneas.exacttiming.TimeValue`, int... | def function[_synthesize_multiple_c_extension, parameter[self, text_file, output_file_path, quit_after, backwards]]:
constant[
Synthesize multiple text fragments, using the cew extension.
Return a tuple (anchors, total_time, num_chars).
:rtype: (bool, (list, :class:`~aeneas.exacttiming... | keyword[def] identifier[_synthesize_multiple_c_extension] ( identifier[self] , identifier[text_file] , identifier[output_file_path] , identifier[quit_after] = keyword[None] , identifier[backwards] = keyword[False] ):
literal[string]
identifier[self] . identifier[log] ( literal[string] )
... | def _synthesize_multiple_c_extension(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple text fragments, using the cew extension.
Return a tuple (anchors, total_time, num_chars).
:rtype: (bool, (list, :class:`~aeneas.exacttiming.TimeValue`, int))
... |
def _get_pandasindex():
"""
>>> from hydpy import pub
>>> pub.timegrids = '2004.01.01', '2005.01.01', '1d'
>>> from hydpy.core.devicetools import _get_pandasindex
>>> _get_pandasindex() # doctest: +ELLIPSIS
DatetimeIndex(['2004-01-01 12:00:00', '2004-01-02 12:00:00',
...
... | def function[_get_pandasindex, parameter[]]:
constant[
>>> from hydpy import pub
>>> pub.timegrids = '2004.01.01', '2005.01.01', '1d'
>>> from hydpy.core.devicetools import _get_pandasindex
>>> _get_pandasindex() # doctest: +ELLIPSIS
DatetimeIndex(['2004-01-01 12:00:00', '2004-01-02 12:00:... | keyword[def] identifier[_get_pandasindex] ():
literal[string]
identifier[tg] = identifier[hydpy] . identifier[pub] . identifier[timegrids] . identifier[init]
identifier[shift] = identifier[tg] . identifier[stepsize] / literal[int]
identifier[index] = identifier[pandas] . identifier[date_range] ... | def _get_pandasindex():
"""
>>> from hydpy import pub
>>> pub.timegrids = '2004.01.01', '2005.01.01', '1d'
>>> from hydpy.core.devicetools import _get_pandasindex
>>> _get_pandasindex() # doctest: +ELLIPSIS
DatetimeIndex(['2004-01-01 12:00:00', '2004-01-02 12:00:00',
...
... |
def memoize_methodcalls(func, pickle=False, dumps=pickle.dumps):
'''Cache the results of the function for each input it gets called with.
'''
cache = func._memoize_cache = {}
@functools.wraps(func)
def memoizer(self, *args, **kwargs):
if pickle:
key = dumps((args, kwargs))
... | def function[memoize_methodcalls, parameter[func, pickle, dumps]]:
constant[Cache the results of the function for each input it gets called with.
]
variable[cache] assign[=] dictionary[[], []]
def function[memoizer, parameter[self]]:
if name[pickle] begin[:]
... | keyword[def] identifier[memoize_methodcalls] ( identifier[func] , identifier[pickle] = keyword[False] , identifier[dumps] = identifier[pickle] . identifier[dumps] ):
literal[string]
identifier[cache] = identifier[func] . identifier[_memoize_cache] ={}
@ identifier[functools] . identifier[wraps] ( ident... | def memoize_methodcalls(func, pickle=False, dumps=pickle.dumps):
"""Cache the results of the function for each input it gets called with.
"""
cache = func._memoize_cache = {}
@functools.wraps(func)
def memoizer(self, *args, **kwargs):
if pickle:
key = dumps((args, kwargs)) # de... |
def nodes(self, type=None, failed=False):
"""Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True``, for all nodes... | def function[nodes, parameter[self, type, failed]]:
constant[Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True`... | keyword[def] identifier[nodes] ( identifier[self] , identifier[type] = keyword[None] , identifier[failed] = keyword[False] ):
literal[string]
keyword[if] identifier[type] keyword[is] keyword[None] :
identifier[type] = identifier[Node]
keyword[if] keyword[not] identifier... | def nodes(self, type=None, failed=False):
"""Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True``, for all nodes use... |
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cr... | def function[_get_cron_info, parameter[]]:
constant[
Returns the proper group owner and path to the cron directory
]
variable[owner] assign[=] constant[root]
if compare[call[name[__grains__]][constant[os]] equal[==] constant[FreeBSD]] begin[:]
variable[group] assign[=] co... | keyword[def] identifier[_get_cron_info] ():
literal[string]
identifier[owner] = literal[string]
keyword[if] identifier[__grains__] [ literal[string] ]== literal[string] :
identifier[group] = literal[string]
identifier[crontab_dir] = literal[string]
keyword[elif] identifier[... | def _get_cron_info():
"""
Returns the proper group owner and path to the cron directory
"""
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs' # depends on [control=['if'], data=[]]
elif __grains__['os'] == 'OpenBSD':
group = ... |
def set_stim(self, signal, fs, attenuation=0):
"""Sets any vector as the next stimulus to be output. Does not call write to hardware"""
self.tone_lock.acquire()
self.stim = signal
self.fs = fs
self.atten = attenuation
self.stim_changed = True
self.tone_lock.rele... | def function[set_stim, parameter[self, signal, fs, attenuation]]:
constant[Sets any vector as the next stimulus to be output. Does not call write to hardware]
call[name[self].tone_lock.acquire, parameter[]]
name[self].stim assign[=] name[signal]
name[self].fs assign[=] name[fs]
n... | keyword[def] identifier[set_stim] ( identifier[self] , identifier[signal] , identifier[fs] , identifier[attenuation] = literal[int] ):
literal[string]
identifier[self] . identifier[tone_lock] . identifier[acquire] ()
identifier[self] . identifier[stim] = identifier[signal]
ident... | def set_stim(self, signal, fs, attenuation=0):
"""Sets any vector as the next stimulus to be output. Does not call write to hardware"""
self.tone_lock.acquire()
self.stim = signal
self.fs = fs
self.atten = attenuation
self.stim_changed = True
self.tone_lock.release() |
def read_backup(self, p_todolist=None, p_timestamp=None):
"""
Retrieves a backup for p_timestamp or p_todolist (if p_timestamp is not
specified) from backup file and sets timestamp, todolist, archive and
label attributes to appropriate data from it.
"""
if not p_timestamp... | def function[read_backup, parameter[self, p_todolist, p_timestamp]]:
constant[
Retrieves a backup for p_timestamp or p_todolist (if p_timestamp is not
specified) from backup file and sets timestamp, todolist, archive and
label attributes to appropriate data from it.
]
if ... | keyword[def] identifier[read_backup] ( identifier[self] , identifier[p_todolist] = keyword[None] , identifier[p_timestamp] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[p_timestamp] :
identifier[change_hash] = identifier[hash_todolist] ( identifier[p_todolist... | def read_backup(self, p_todolist=None, p_timestamp=None):
"""
Retrieves a backup for p_timestamp or p_todolist (if p_timestamp is not
specified) from backup file and sets timestamp, todolist, archive and
label attributes to appropriate data from it.
"""
if not p_timestamp:
... |
def _get_xml(self, metric):
"""Returns the channel element of the RSS feed"""
self._opener = urllib2.build_opener()
self._opener.addheaders = [('User-agent', self.user_agent)]
if metric:
url = self.base_url + '?w={0}&u=c'.format(self.woeid)
else:
url = se... | def function[_get_xml, parameter[self, metric]]:
constant[Returns the channel element of the RSS feed]
name[self]._opener assign[=] call[name[urllib2].build_opener, parameter[]]
name[self]._opener.addheaders assign[=] list[[<ast.Tuple object at 0x7da207f00f10>]]
if name[metric] begin[:]
... | keyword[def] identifier[_get_xml] ( identifier[self] , identifier[metric] ):
literal[string]
identifier[self] . identifier[_opener] = identifier[urllib2] . identifier[build_opener] ()
identifier[self] . identifier[_opener] . identifier[addheaders] =[( literal[string] , identifier[self] . i... | def _get_xml(self, metric):
"""Returns the channel element of the RSS feed"""
self._opener = urllib2.build_opener()
self._opener.addheaders = [('User-agent', self.user_agent)]
if metric:
url = self.base_url + '?w={0}&u=c'.format(self.woeid) # depends on [control=['if'], data=[]]
else:
... |
def reverse_formats(format_string, resolved_strings):
"""
Reverse the string method format for a list of strings.
Given format_string and resolved_strings, for each resolved string
find arguments that would give
``format_string.format(**arguments) == resolved_string``.
Each item in the output ... | def function[reverse_formats, parameter[format_string, resolved_strings]]:
constant[
Reverse the string method format for a list of strings.
Given format_string and resolved_strings, for each resolved string
find arguments that would give
``format_string.format(**arguments) == resolved_string``... | keyword[def] identifier[reverse_formats] ( identifier[format_string] , identifier[resolved_strings] ):
literal[string]
keyword[from] identifier[string] keyword[import] identifier[Formatter]
identifier[fmt] = identifier[Formatter] ()
identifier[field_names] =[ identifier[i] [ literal[in... | def reverse_formats(format_string, resolved_strings):
"""
Reverse the string method format for a list of strings.
Given format_string and resolved_strings, for each resolved string
find arguments that would give
``format_string.format(**arguments) == resolved_string``.
Each item in the output ... |
def number_of_changes(slots, events, original_schedule, X, **kwargs):
"""
A function that counts the number of changes between a given schedule
and an array (either numpy array of lp array).
"""
changes = 0
original_array = schedule_to_array(original_schedule, events=events,
... | def function[number_of_changes, parameter[slots, events, original_schedule, X]]:
constant[
A function that counts the number of changes between a given schedule
and an array (either numpy array of lp array).
]
variable[changes] assign[=] constant[0]
variable[original_array] assign[=]... | keyword[def] identifier[number_of_changes] ( identifier[slots] , identifier[events] , identifier[original_schedule] , identifier[X] ,** identifier[kwargs] ):
literal[string]
identifier[changes] = literal[int]
identifier[original_array] = identifier[schedule_to_array] ( identifier[original_schedule] ,... | def number_of_changes(slots, events, original_schedule, X, **kwargs):
"""
A function that counts the number of changes between a given schedule
and an array (either numpy array of lp array).
"""
changes = 0
original_array = schedule_to_array(original_schedule, events=events, slots=slots)
for... |
def _get_suggestions(self, filter_word=None):
"""
This only gets caled internally from the get_suggestion method.
"""
keys = self.manifest.keys()
words = []
for key in keys:
if isinstance(self.manifest[key], Manifest):
# if this key... | def function[_get_suggestions, parameter[self, filter_word]]:
constant[
This only gets caled internally from the get_suggestion method.
]
variable[keys] assign[=] call[name[self].manifest.keys, parameter[]]
variable[words] assign[=] list[[]]
for taget[name[key]] in starre... | keyword[def] identifier[_get_suggestions] ( identifier[self] , identifier[filter_word] = keyword[None] ):
literal[string]
identifier[keys] = identifier[self] . identifier[manifest] . identifier[keys] ()
identifier[words] =[]
keyword[for] identifier[key] keyword[in] identifier[k... | def _get_suggestions(self, filter_word=None):
"""
This only gets caled internally from the get_suggestion method.
"""
keys = self.manifest.keys()
words = []
for key in keys:
if isinstance(self.manifest[key], Manifest): # if this key is another manifest, append a slash to the
... |
def MessageToJson(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitiv... | def function[MessageToJson, parameter[message, including_default_value_fields, preserving_proto_field_name]]:
constant[Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
... | keyword[def] identifier[MessageToJson] ( identifier[message] ,
identifier[including_default_value_fields] = keyword[False] ,
identifier[preserving_proto_field_name] = keyword[False] ):
literal[string]
identifier[printer] = identifier[_Printer] ( identifier[including_default_value_fields] ,
identifier[pres... | def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields,... |
def _createFromObject(obj, *args, **kwargs):
""" Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
constructor (with exce... | def function[_createFromObject, parameter[obj]]:
constant[ Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
construc... | keyword[def] identifier[_createFromObject] ( identifier[obj] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[is_a_sequence] ( identifier[obj] ):
keyword[return] identifier[SequenceRti] ( identifier[obj] ,* identifier[args] ,** identifier[kwargs] )
keywor... | def _createFromObject(obj, *args, **kwargs):
""" Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
constructor (with exce... |
def cache_func(prefix, method=False):
"""
Cache result of function execution into the django cache backend.
Calculate cache key based on `prefix`, `args` and `kwargs` of the function.
For using like object method set `method=True`.
"""
def decorator(func):
@wraps(func)
def wrappe... | def function[cache_func, parameter[prefix, method]]:
constant[
Cache result of function execution into the django cache backend.
Calculate cache key based on `prefix`, `args` and `kwargs` of the function.
For using like object method set `method=True`.
]
def function[decorator, parameter... | keyword[def] identifier[cache_func] ( identifier[prefix] , identifier[method] = keyword[False] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ... | def cache_func(prefix, method=False):
"""
Cache result of function execution into the django cache backend.
Calculate cache key based on `prefix`, `args` and `kwargs` of the function.
For using like object method set `method=True`.
"""
def decorator(func):
@wraps(func)
def wrap... |
def send(self, message_type, task_id, message):
""" Sends a message to the UDP receiver
Parameter
---------
message_type: monitoring.MessageType (enum)
In this case message type is RESOURCE_INFO most often
task_id: int
Task identifier of the task for whi... | def function[send, parameter[self, message_type, task_id, message]]:
constant[ Sends a message to the UDP receiver
Parameter
---------
message_type: monitoring.MessageType (enum)
In this case message type is RESOURCE_INFO most often
task_id: int
Task ide... | keyword[def] identifier[send] ( identifier[self] , identifier[message_type] , identifier[task_id] , identifier[message] ):
literal[string]
identifier[x] = literal[int]
keyword[try] :
identifier[buffer] = identifier[pickle] . identifier[dumps] (( identifier[self] . identifier[... | def send(self, message_type, task_id, message):
""" Sends a message to the UDP receiver
Parameter
---------
message_type: monitoring.MessageType (enum)
In this case message type is RESOURCE_INFO most often
task_id: int
Task identifier of the task for which r... |
def fit(self, data, debug=False):
"""
Fit each of the models in the group.
Parameters
----------
data : pandas.DataFrame
Must have a column with the same name as `segmentation_col`.
debug : bool
If set to true (default false) will pass the debug p... | def function[fit, parameter[self, data, debug]]:
constant[
Fit each of the models in the group.
Parameters
----------
data : pandas.DataFrame
Must have a column with the same name as `segmentation_col`.
debug : bool
If set to true (default false) ... | keyword[def] identifier[fit] ( identifier[self] , identifier[data] , identifier[debug] = keyword[False] ):
literal[string]
keyword[with] identifier[log_start_finish] (
literal[string] . identifier[format] ( identifier[self] . identifier[name] ), identifier[logger] ):
keyword[... | def fit(self, data, debug=False):
"""
Fit each of the models in the group.
Parameters
----------
data : pandas.DataFrame
Must have a column with the same name as `segmentation_col`.
debug : bool
If set to true (default false) will pass the debug param... |
def pull(self):
"""
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
"""
sock = self.__sock(zmq.PULL)
return self.... | def function[pull, parameter[self]]:
constant[
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
]
variable[sock] assign[=]... | keyword[def] identifier[pull] ( identifier[self] ):
literal[string]
identifier[sock] = identifier[self] . identifier[__sock] ( identifier[zmq] . identifier[PULL] )
keyword[return] identifier[self] . identifier[__recv_generator] ( identifier[sock] ) | def pull(self):
"""
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
"""
sock = self.__sock(zmq.PULL)
return self.__recv_gener... |
def SetPosition(self, track_id, position):
"""Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If ... | def function[SetPosition, parameter[self, track_id, position]]:
constant[Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <... | keyword[def] identifier[SetPosition] ( identifier[self] , identifier[track_id] , identifier[position] ):
literal[string]
identifier[self] . identifier[iface] . identifier[SetPosition] ( identifier[convert2dbus] ( identifier[track_id] , literal[string] ),
identifier[convert2dbus] ( identifi... | def SetPosition(self, track_id, position):
"""Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If the ... |
def BitVecVal(
value: int, size: int, annotations: Annotations = None
) -> z3.BitVecRef:
"""Creates a new bit vector with a concrete value."""
return z3.BitVecVal(value, size) | def function[BitVecVal, parameter[value, size, annotations]]:
constant[Creates a new bit vector with a concrete value.]
return[call[name[z3].BitVecVal, parameter[name[value], name[size]]]] | keyword[def] identifier[BitVecVal] (
identifier[value] : identifier[int] , identifier[size] : identifier[int] , identifier[annotations] : identifier[Annotations] = keyword[None]
)-> identifier[z3] . identifier[BitVecRef] :
literal[string]
keyword[return] identifier[z3] . identifier[BitVecVal] ( ... | def BitVecVal(value: int, size: int, annotations: Annotations=None) -> z3.BitVecRef:
"""Creates a new bit vector with a concrete value."""
return z3.BitVecVal(value, size) |
def cmd_tracker_position(self, args):
'''tracker manual positioning commands'''
connection = self.find_connection()
if not connection:
print("No antenna tracker found")
return
positions = [0, 0, 0, 0, 0] # x, y, z, r, buttons. only position[0] (yaw) and position[1... | def function[cmd_tracker_position, parameter[self, args]]:
constant[tracker manual positioning commands]
variable[connection] assign[=] call[name[self].find_connection, parameter[]]
if <ast.UnaryOp object at 0x7da1b1720430> begin[:]
call[name[print], parameter[constant[No antenna... | keyword[def] identifier[cmd_tracker_position] ( identifier[self] , identifier[args] ):
literal[string]
identifier[connection] = identifier[self] . identifier[find_connection] ()
keyword[if] keyword[not] identifier[connection] :
identifier[print] ( literal[string] )
... | def cmd_tracker_position(self, args):
"""tracker manual positioning commands"""
connection = self.find_connection()
if not connection:
print('No antenna tracker found')
return # depends on [control=['if'], data=[]]
positions = [0, 0, 0, 0, 0] # x, y, z, r, buttons. only position[0] (ya... |
def delete_hook(self, id):
"""
:calls: `DELETE /orgs/:owner/hooks/:id <http://developer.github.com/v3/orgs/hooks>`_
:param id: integer
:rtype: None`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"DELETE... | def function[delete_hook, parameter[self, id]]:
constant[
:calls: `DELETE /orgs/:owner/hooks/:id <http://developer.github.com/v3/orgs/hooks>`_
:param id: integer
:rtype: None`
]
assert[call[name[isinstance], parameter[name[id], tuple[[<ast.Name object at 0x7da1b21ec0d0>, <ast... | keyword[def] identifier[delete_hook] ( identifier[self] , identifier[id] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[id] ,( identifier[int] , identifier[long] )), identifier[id]
identifier[headers] , identifier[data] = identifier[self] . identifier[_requester] ... | def delete_hook(self, id):
"""
:calls: `DELETE /orgs/:owner/hooks/:id <http://developer.github.com/v3/orgs/hooks>`_
:param id: integer
:rtype: None`
"""
assert isinstance(id, (int, long)), id
(headers, data) = self._requester.requestJsonAndCheck('DELETE', self.url + '/hooks/'... |
def __filter_past_mappings(self,
past_mappings,
long_inclusion_array):
"""
Parameters
----------
past_mappings : dict.
All elements should be None or compressed sparse row matrices from
scipy.sparse. Th... | def function[__filter_past_mappings, parameter[self, past_mappings, long_inclusion_array]]:
constant[
Parameters
----------
past_mappings : dict.
All elements should be None or compressed sparse row matrices from
scipy.sparse. The following keys should be in past_... | keyword[def] identifier[__filter_past_mappings] ( identifier[self] ,
identifier[past_mappings] ,
identifier[long_inclusion_array] ):
literal[string]
identifier[new_mappings] ={}
keyword[for] identifier[key] keyword[in] identifier[past_mappings] :
keyword[if] identifier[p... | def __filter_past_mappings(self, past_mappings, long_inclusion_array):
"""
Parameters
----------
past_mappings : dict.
All elements should be None or compressed sparse row matrices from
scipy.sparse. The following keys should be in past_mappings:
- "rows_... |
def handle_cursor(cls, cursor, query, session):
"""Updates progress information"""
from pyhive import hive # pylint: disable=no-name-in-module
unfinished_states = (
hive.ttypes.TOperationState.INITIALIZED_STATE,
hive.ttypes.TOperationState.RUNNING_STATE,
)
... | def function[handle_cursor, parameter[cls, cursor, query, session]]:
constant[Updates progress information]
from relative_module[pyhive] import module[hive]
variable[unfinished_states] assign[=] tuple[[<ast.Attribute object at 0x7da1b209b9d0>, <ast.Attribute object at 0x7da1b2098850>]]
varia... | keyword[def] identifier[handle_cursor] ( identifier[cls] , identifier[cursor] , identifier[query] , identifier[session] ):
literal[string]
keyword[from] identifier[pyhive] keyword[import] identifier[hive]
identifier[unfinished_states] =(
identifier[hive] . identifier[ttypes] .... | def handle_cursor(cls, cursor, query, session):
"""Updates progress information"""
from pyhive import hive # pylint: disable=no-name-in-module
unfinished_states = (hive.ttypes.TOperationState.INITIALIZED_STATE, hive.ttypes.TOperationState.RUNNING_STATE)
polled = cursor.poll()
last_log_line = 0
... |
def wcxf2arrays(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values. This is needed for the parsing
of input in WCxf format."""
... | def function[wcxf2arrays, parameter[d]]:
constant[Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values. This is needed for the parsing
... | keyword[def] identifier[wcxf2arrays] ( identifier[d] ):
literal[string]
identifier[C] ={}
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[d] . identifier[items] ():
identifier[name] = identifier[k] . identifier[split] ( literal[string] )[ literal[int] ]
identifie... | def wcxf2arrays(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values. This is needed for the parsing
of input in WCxf format."""
... |
def hmget(self, name, keys, *args):
"Returns a list of values ordered identically to ``keys``"
args = list_or_args(keys, args)
return self.execute_command('HMGET', name, *args) | def function[hmget, parameter[self, name, keys]]:
constant[Returns a list of values ordered identically to ``keys``]
variable[args] assign[=] call[name[list_or_args], parameter[name[keys], name[args]]]
return[call[name[self].execute_command, parameter[constant[HMGET], name[name], <ast.Starred object... | keyword[def] identifier[hmget] ( identifier[self] , identifier[name] , identifier[keys] ,* identifier[args] ):
literal[string]
identifier[args] = identifier[list_or_args] ( identifier[keys] , identifier[args] )
keyword[return] identifier[self] . identifier[execute_command] ( literal[strin... | def hmget(self, name, keys, *args):
"""Returns a list of values ordered identically to ``keys``"""
args = list_or_args(keys, args)
return self.execute_command('HMGET', name, *args) |
def polyfit2dGrid(arr, mask=None, order=3, replace_all=False,
copy=True, outgrid=None):
'''
replace all masked values with polynomial fitted ones
'''
s0,s1 = arr.shape
if mask is None:
if outgrid is None:
y,x = np.mgrid[:float(s0),:float(s1)]
... | def function[polyfit2dGrid, parameter[arr, mask, order, replace_all, copy, outgrid]]:
constant[
replace all masked values with polynomial fitted ones
]
<ast.Tuple object at 0x7da1b11d1570> assign[=] name[arr].shape
if compare[name[mask] is constant[None]] begin[:]
if comp... | keyword[def] identifier[polyfit2dGrid] ( identifier[arr] , identifier[mask] = keyword[None] , identifier[order] = literal[int] , identifier[replace_all] = keyword[False] ,
identifier[copy] = keyword[True] , identifier[outgrid] = keyword[None] ):
literal[string]
identifier[s0] , identifier[s1] = identif... | def polyfit2dGrid(arr, mask=None, order=3, replace_all=False, copy=True, outgrid=None):
"""
replace all masked values with polynomial fitted ones
"""
(s0, s1) = arr.shape
if mask is None:
if outgrid is None:
(y, x) = np.mgrid[:float(s0), :float(s1)]
p = polyfit2d(x.fl... |
def srm_id_auto(self, srms_used=['NIST610', 'NIST612', 'NIST614'], n_min=10, reload_srm_database=False):
"""
Function for automarically identifying SRMs
Parameters
----------
srms_used : iterable
Which SRMs have been used. Must match SRM names
in SRM ... | def function[srm_id_auto, parameter[self, srms_used, n_min, reload_srm_database]]:
constant[
Function for automarically identifying SRMs
Parameters
----------
srms_used : iterable
Which SRMs have been used. Must match SRM names
in SRM database *exactl... | keyword[def] identifier[srm_id_auto] ( identifier[self] , identifier[srms_used] =[ literal[string] , literal[string] , literal[string] ], identifier[n_min] = literal[int] , identifier[reload_srm_database] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[srms_used... | def srm_id_auto(self, srms_used=['NIST610', 'NIST612', 'NIST614'], n_min=10, reload_srm_database=False):
"""
Function for automarically identifying SRMs
Parameters
----------
srms_used : iterable
Which SRMs have been used. Must match SRM names
in SRM data... |
def _score(self, state, score_movement=True):
"""Score a state based on how balanced it is. A higher score represents
a more balanced state.
:param state: The state to score.
"""
score = 0
max_score = 0
if state.total_weight:
# Coefficient of variance... | def function[_score, parameter[self, state, score_movement]]:
constant[Score a state based on how balanced it is. A higher score represents
a more balanced state.
:param state: The state to score.
]
variable[score] assign[=] constant[0]
variable[max_score] assign[=] cons... | keyword[def] identifier[_score] ( identifier[self] , identifier[state] , identifier[score_movement] = keyword[True] ):
literal[string]
identifier[score] = literal[int]
identifier[max_score] = literal[int]
keyword[if] identifier[state] . identifier[total_weight] :
... | def _score(self, state, score_movement=True):
"""Score a state based on how balanced it is. A higher score represents
a more balanced state.
:param state: The state to score.
"""
score = 0
max_score = 0
if state.total_weight:
# Coefficient of variance is a value between ... |
def GetName(self, number):
"""Retrieves the name of an enumeration value by number.
Args:
number (int): number.
Returns:
str: name of the enumeration value or None if no corresponding
enumeration value was found.
"""
value = self._data_type_definition.values_per_number.get(nu... | def function[GetName, parameter[self, number]]:
constant[Retrieves the name of an enumeration value by number.
Args:
number (int): number.
Returns:
str: name of the enumeration value or None if no corresponding
enumeration value was found.
]
variable[value] assign[=] ... | keyword[def] identifier[GetName] ( identifier[self] , identifier[number] ):
literal[string]
identifier[value] = identifier[self] . identifier[_data_type_definition] . identifier[values_per_number] . identifier[get] ( identifier[number] , keyword[None] )
keyword[if] keyword[not] identifier[value] :
... | def GetName(self, number):
"""Retrieves the name of an enumeration value by number.
Args:
number (int): number.
Returns:
str: name of the enumeration value or None if no corresponding
enumeration value was found.
"""
value = self._data_type_definition.values_per_number.get(nu... |
def recall_score(gold, pred, pos_label=1, ignore_in_gold=[], ignore_in_pred=[]):
"""
Calculate recall for a single class.
Args:
gold: A 1d array-like of gold labels
pred: A 1d array-like of predicted labels (assuming abstain = 0)
ignore_in_gold: A list of labels for which elements ha... | def function[recall_score, parameter[gold, pred, pos_label, ignore_in_gold, ignore_in_pred]]:
constant[
Calculate recall for a single class.
Args:
gold: A 1d array-like of gold labels
pred: A 1d array-like of predicted labels (assuming abstain = 0)
ignore_in_gold: A list of label... | keyword[def] identifier[recall_score] ( identifier[gold] , identifier[pred] , identifier[pos_label] = literal[int] , identifier[ignore_in_gold] =[], identifier[ignore_in_pred] =[]):
literal[string]
identifier[gold] , identifier[pred] = identifier[_preprocess] ( identifier[gold] , identifier[pred] , identif... | def recall_score(gold, pred, pos_label=1, ignore_in_gold=[], ignore_in_pred=[]):
"""
Calculate recall for a single class.
Args:
gold: A 1d array-like of gold labels
pred: A 1d array-like of predicted labels (assuming abstain = 0)
ignore_in_gold: A list of labels for which elements ha... |
def update_last_wm_layers(self, service_id, num_layers=10):
"""
Update and index the last added and deleted layers (num_layers) in WorldMap service.
"""
from hypermap.aggregator.models import Service
LOGGER.debug(
'Updating the index the last %s added and %s deleted layers in WorldMap servi... | def function[update_last_wm_layers, parameter[self, service_id, num_layers]]:
constant[
Update and index the last added and deleted layers (num_layers) in WorldMap service.
]
from relative_module[hypermap.aggregator.models] import module[Service]
call[name[LOGGER].debug, parameter[binary_ope... | keyword[def] identifier[update_last_wm_layers] ( identifier[self] , identifier[service_id] , identifier[num_layers] = literal[int] ):
literal[string]
keyword[from] identifier[hypermap] . identifier[aggregator] . identifier[models] keyword[import] identifier[Service]
identifier[LOGGER] . identifie... | def update_last_wm_layers(self, service_id, num_layers=10):
"""
Update and index the last added and deleted layers (num_layers) in WorldMap service.
"""
from hypermap.aggregator.models import Service
LOGGER.debug('Updating the index the last %s added and %s deleted layers in WorldMap service' % (num... |
def get_right_geo_fhs(self, dsid, fhs):
"""Find the right geographical file handlers for given dataset ID *dsid*."""
ds_info = self.ids[dsid]
req_geo, rem_geo = self._get_req_rem_geo(ds_info)
desired, other = split_desired_other(fhs, req_geo, rem_geo)
if desired:
try:... | def function[get_right_geo_fhs, parameter[self, dsid, fhs]]:
constant[Find the right geographical file handlers for given dataset ID *dsid*.]
variable[ds_info] assign[=] call[name[self].ids][name[dsid]]
<ast.Tuple object at 0x7da1b22ae1d0> assign[=] call[name[self]._get_req_rem_geo, parameter[na... | keyword[def] identifier[get_right_geo_fhs] ( identifier[self] , identifier[dsid] , identifier[fhs] ):
literal[string]
identifier[ds_info] = identifier[self] . identifier[ids] [ identifier[dsid] ]
identifier[req_geo] , identifier[rem_geo] = identifier[self] . identifier[_get_req_rem_geo] ( ... | def get_right_geo_fhs(self, dsid, fhs):
"""Find the right geographical file handlers for given dataset ID *dsid*."""
ds_info = self.ids[dsid]
(req_geo, rem_geo) = self._get_req_rem_geo(ds_info)
(desired, other) = split_desired_other(fhs, req_geo, rem_geo)
if desired:
try:
ds_info... |
def report(self, obj, message, linenum, char_offset=0):
"""Report an error or warning"""
self.controller.report(linenumber=linenum, filename=obj.path,
severity=self.severity, message=message,
rulename = self.__class__.__name__,
... | def function[report, parameter[self, obj, message, linenum, char_offset]]:
constant[Report an error or warning]
call[name[self].controller.report, parameter[]] | keyword[def] identifier[report] ( identifier[self] , identifier[obj] , identifier[message] , identifier[linenum] , identifier[char_offset] = literal[int] ):
literal[string]
identifier[self] . identifier[controller] . identifier[report] ( identifier[linenumber] = identifier[linenum] , identifier[fil... | def report(self, obj, message, linenum, char_offset=0):
"""Report an error or warning"""
self.controller.report(linenumber=linenum, filename=obj.path, severity=self.severity, message=message, rulename=self.__class__.__name__, char=char_offset) |
def _smooth_the_residuals(self):
"""
Apply the MID_SPAN to the residuals of the primary smooths.
"For stability reasons, it turns out to be a little better to smooth
|r_{i}(J)| against xi" - [1]
"""
for primary_smooth in self._primary_smooths:
smooth = smooth... | def function[_smooth_the_residuals, parameter[self]]:
constant[
Apply the MID_SPAN to the residuals of the primary smooths.
"For stability reasons, it turns out to be a little better to smooth
|r_{i}(J)| against xi" - [1]
]
for taget[name[primary_smooth]] in starred[name... | keyword[def] identifier[_smooth_the_residuals] ( identifier[self] ):
literal[string]
keyword[for] identifier[primary_smooth] keyword[in] identifier[self] . identifier[_primary_smooths] :
identifier[smooth] = identifier[smoother] . identifier[perform_smooth] ( identifier[self] . iden... | def _smooth_the_residuals(self):
"""
Apply the MID_SPAN to the residuals of the primary smooths.
"For stability reasons, it turns out to be a little better to smooth
|r_{i}(J)| against xi" - [1]
"""
for primary_smooth in self._primary_smooths:
smooth = smoother.perform_s... |
def read_exactly(self, num_bytes):
"""
Reads exactly the specified number of bytes from the socket
:param num_bytes:
An integer - the exact number of bytes to read
:return:
A byte string of the data that was read
"""
output = b''
remaini... | def function[read_exactly, parameter[self, num_bytes]]:
constant[
Reads exactly the specified number of bytes from the socket
:param num_bytes:
An integer - the exact number of bytes to read
:return:
A byte string of the data that was read
]
vari... | keyword[def] identifier[read_exactly] ( identifier[self] , identifier[num_bytes] ):
literal[string]
identifier[output] = literal[string]
identifier[remaining] = identifier[num_bytes]
keyword[while] identifier[remaining] > literal[int] :
identifier[output] += ident... | def read_exactly(self, num_bytes):
"""
Reads exactly the specified number of bytes from the socket
:param num_bytes:
An integer - the exact number of bytes to read
:return:
A byte string of the data that was read
"""
output = b''
remaining = num_byte... |
def pre_populate_buyer_email(self, pre_populate_buyer_email):
"""
Sets the pre_populate_buyer_email of this CreateCheckoutRequest.
If provided, the buyer's email is pre-populated on the checkout page as an editable text field. Default: none; only exists if explicitly set.
:param pre_po... | def function[pre_populate_buyer_email, parameter[self, pre_populate_buyer_email]]:
constant[
Sets the pre_populate_buyer_email of this CreateCheckoutRequest.
If provided, the buyer's email is pre-populated on the checkout page as an editable text field. Default: none; only exists if explicitly ... | keyword[def] identifier[pre_populate_buyer_email] ( identifier[self] , identifier[pre_populate_buyer_email] ):
literal[string]
keyword[if] identifier[pre_populate_buyer_email] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if... | def pre_populate_buyer_email(self, pre_populate_buyer_email):
"""
Sets the pre_populate_buyer_email of this CreateCheckoutRequest.
If provided, the buyer's email is pre-populated on the checkout page as an editable text field. Default: none; only exists if explicitly set.
:param pre_popula... |
def runGetReadGroupSet(self, id_):
"""
Returns a readGroupSet with the given id_
"""
compoundId = datamodel.ReadGroupSetCompoundId.parse(id_)
dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
readGroupSet = dataset.getReadGroupSet(id_)
return se... | def function[runGetReadGroupSet, parameter[self, id_]]:
constant[
Returns a readGroupSet with the given id_
]
variable[compoundId] assign[=] call[name[datamodel].ReadGroupSetCompoundId.parse, parameter[name[id_]]]
variable[dataset] assign[=] call[call[name[self].getDataRepository... | keyword[def] identifier[runGetReadGroupSet] ( identifier[self] , identifier[id_] ):
literal[string]
identifier[compoundId] = identifier[datamodel] . identifier[ReadGroupSetCompoundId] . identifier[parse] ( identifier[id_] )
identifier[dataset] = identifier[self] . identifier[getDataReposit... | def runGetReadGroupSet(self, id_):
"""
Returns a readGroupSet with the given id_
"""
compoundId = datamodel.ReadGroupSetCompoundId.parse(id_)
dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
readGroupSet = dataset.getReadGroupSet(id_)
return self.runGetRequest(rea... |
def trim_nonpercolating_paths(im, inlet_axis=0, outlet_axis=0):
r"""
Removes all nonpercolating paths between specified edges
This function is essential when performing transport simulations on an
image, since image regions that do not span between the desired inlet and
outlet do not contribute to ... | def function[trim_nonpercolating_paths, parameter[im, inlet_axis, outlet_axis]]:
constant[
Removes all nonpercolating paths between specified edges
This function is essential when performing transport simulations on an
image, since image regions that do not span between the desired inlet and
ou... | keyword[def] identifier[trim_nonpercolating_paths] ( identifier[im] , identifier[inlet_axis] = literal[int] , identifier[outlet_axis] = literal[int] ):
literal[string]
keyword[if] identifier[im] . identifier[ndim] != identifier[im] . identifier[squeeze] (). identifier[ndim] :
identifier[warnings]... | def trim_nonpercolating_paths(im, inlet_axis=0, outlet_axis=0):
"""
Removes all nonpercolating paths between specified edges
This function is essential when performing transport simulations on an
image, since image regions that do not span between the desired inlet and
outlet do not contribute to t... |
def pmll(self,*args,**kwargs):
"""
NAME:
pmll
PURPOSE:
return proper motion in Galactic longitude (in mas/yr)
INPUT:
t - (optional) time at which to get pmll
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
... | def function[pmll, parameter[self]]:
constant[
NAME:
pmll
PURPOSE:
return proper motion in Galactic longitude (in mas/yr)
INPUT:
t - (optional) time at which to get pmll
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
... | keyword[def] identifier[pmll] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[_check_roSet] ( identifier[self] , identifier[kwargs] , literal[string] )
identifier[_check_voSet] ( identifier[self] , identifier[kwargs] , literal[string] )
... | def pmll(self, *args, **kwargs):
"""
NAME:
pmll
PURPOSE:
return proper motion in Galactic longitude (in mas/yr)
INPUT:
t - (optional) time at which to get pmll
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
... |
def remove_raw_jobs(self, params_list):
""" Remove jobs from a raw queue with their raw params. """
if len(params_list) == 0:
return
# ZSET
if self.is_sorted:
context.connections.redis.zrem(self.redis_key, *iter(params_list))
# SET
elif self.is_... | def function[remove_raw_jobs, parameter[self, params_list]]:
constant[ Remove jobs from a raw queue with their raw params. ]
if compare[call[name[len], parameter[name[params_list]]] equal[==] constant[0]] begin[:]
return[None]
if name[self].is_sorted begin[:]
call[name[co... | keyword[def] identifier[remove_raw_jobs] ( identifier[self] , identifier[params_list] ):
literal[string]
keyword[if] identifier[len] ( identifier[params_list] )== literal[int] :
keyword[return]
keyword[if] identifier[self] . identifier[is_sorted] :
... | def remove_raw_jobs(self, params_list):
""" Remove jobs from a raw queue with their raw params. """
if len(params_list) == 0:
return # depends on [control=['if'], data=[]]
# ZSET
if self.is_sorted:
context.connections.redis.zrem(self.redis_key, *iter(params_list)) # depends on [control... |
def renumber_block_keys(blocks):
"""Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
"""
# There is an implicit block switch to the 0th block at the start of the
# file
... | def function[renumber_block_keys, parameter[blocks]]:
constant[Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
]
variable[byte_switch_keys] assign[=] list[[<ast.Consta... | keyword[def] identifier[renumber_block_keys] ( identifier[blocks] ):
literal[string]
identifier[byte_switch_keys] =[ literal[int] ]
identifier[block_keys] = identifier[list] ( identifier[blocks] . identifier[keys] ())
keyword[for] identifier[block] keyword[in] identifier[list]... | def renumber_block_keys(blocks):
"""Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
"""
# There is an implicit block switch to the 0th block at the start of the
# file
... |
def cli(env, identifier):
"""Edit firewall rules."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
orig_rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
orig_rules = mgr.get_standard_fwl_rule... | def function[cli, parameter[env, identifier]]:
constant[Edit firewall rules.]
variable[mgr] assign[=] call[name[SoftLayer].FirewallManager, parameter[name[env].client]]
<ast.Tuple object at 0x7da18ede7e80> assign[=] call[name[firewall].parse_id, parameter[name[identifier]]]
if compare[na... | keyword[def] identifier[cli] ( identifier[env] , identifier[identifier] ):
literal[string]
identifier[mgr] = identifier[SoftLayer] . identifier[FirewallManager] ( identifier[env] . identifier[client] )
identifier[firewall_type] , identifier[firewall_id] = identifier[firewall] . identifier[parse_id] ... | def cli(env, identifier):
"""Edit firewall rules."""
mgr = SoftLayer.FirewallManager(env.client)
(firewall_type, firewall_id) = firewall.parse_id(identifier)
if firewall_type == 'vlan':
orig_rules = mgr.get_dedicated_fwl_rules(firewall_id) # depends on [control=['if'], data=[]]
else:
... |
def SetColumns( self, columns, sortOrder=None ):
"""Set columns to a set of values other than the originals and recreates column controls"""
self.columns = columns
self.sortOrder = [(x.defaultOrder,x) for x in self.columns if x.sortDefault]
self.CreateColumns() | def function[SetColumns, parameter[self, columns, sortOrder]]:
constant[Set columns to a set of values other than the originals and recreates column controls]
name[self].columns assign[=] name[columns]
name[self].sortOrder assign[=] <ast.ListComp object at 0x7da18f00c6a0>
call[name[self]... | keyword[def] identifier[SetColumns] ( identifier[self] , identifier[columns] , identifier[sortOrder] = keyword[None] ):
literal[string]
identifier[self] . identifier[columns] = identifier[columns]
identifier[self] . identifier[sortOrder] =[( identifier[x] . identifier[defaultOrder] , iden... | def SetColumns(self, columns, sortOrder=None):
"""Set columns to a set of values other than the originals and recreates column controls"""
self.columns = columns
self.sortOrder = [(x.defaultOrder, x) for x in self.columns if x.sortDefault]
self.CreateColumns() |
def from_stream(cls, stream):
"""
Return a |_JfifMarkers| instance containing a |_JfifMarker| subclass
instance for each marker in *stream*.
"""
marker_parser = _MarkerParser.from_stream(stream)
markers = []
for marker in marker_parser.iter_markers():
... | def function[from_stream, parameter[cls, stream]]:
constant[
Return a |_JfifMarkers| instance containing a |_JfifMarker| subclass
instance for each marker in *stream*.
]
variable[marker_parser] assign[=] call[name[_MarkerParser].from_stream, parameter[name[stream]]]
varia... | keyword[def] identifier[from_stream] ( identifier[cls] , identifier[stream] ):
literal[string]
identifier[marker_parser] = identifier[_MarkerParser] . identifier[from_stream] ( identifier[stream] )
identifier[markers] =[]
keyword[for] identifier[marker] keyword[in] identifier[m... | def from_stream(cls, stream):
"""
Return a |_JfifMarkers| instance containing a |_JfifMarker| subclass
instance for each marker in *stream*.
"""
marker_parser = _MarkerParser.from_stream(stream)
markers = []
for marker in marker_parser.iter_markers():
markers.append(marke... |
def erract(op, lenout, action=None):
"""
Retrieve or set the default error action.
spiceypy sets the default error action to "report" on init.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/erract_c.html
:param op: peration, "GET" or "SET".
:type op: str
:param lenout: Length of l... | def function[erract, parameter[op, lenout, action]]:
constant[
Retrieve or set the default error action.
spiceypy sets the default error action to "report" on init.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/erract_c.html
:param op: peration, "GET" or "SET".
:type op: str
... | keyword[def] identifier[erract] ( identifier[op] , identifier[lenout] , identifier[action] = keyword[None] ):
literal[string]
keyword[if] identifier[action] keyword[is] keyword[None] :
identifier[action] = literal[string]
identifier[lenout] = identifier[ctypes] . identifier[c_int] ( ident... | def erract(op, lenout, action=None):
"""
Retrieve or set the default error action.
spiceypy sets the default error action to "report" on init.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/erract_c.html
:param op: peration, "GET" or "SET".
:type op: str
:param lenout: Length of l... |
def diginorm(args):
"""
%prog diginorm fastqfile
Run K-mer based normalization. Based on tutorial:
<http://ged.msu.edu/angus/diginorm-2012/tutorial.html>
Assume input is either an interleaved pairs file, or two separate files.
To set up khmer:
$ git clone git://github.com/ged-lab/screed.g... | def function[diginorm, parameter[args]]:
constant[
%prog diginorm fastqfile
Run K-mer based normalization. Based on tutorial:
<http://ged.msu.edu/angus/diginorm-2012/tutorial.html>
Assume input is either an interleaved pairs file, or two separate files.
To set up khmer:
$ git clone gi... | keyword[def] identifier[diginorm] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[fastq] keyword[import] identifier[shuffle] , identifier[pairinplace] , identifier[split]
keyword[from] identifier[jcvi] . identifier[apps] . identifier[base] ... | def diginorm(args):
"""
%prog diginorm fastqfile
Run K-mer based normalization. Based on tutorial:
<http://ged.msu.edu/angus/diginorm-2012/tutorial.html>
Assume input is either an interleaved pairs file, or two separate files.
To set up khmer:
$ git clone git://github.com/ged-lab/screed.g... |
def add_dimension(self, name, data=None):
"""Add a named dimension to this entity."""
self.dimensions.add(name)
if data is None:
valobj = self.__dimtype__()
else:
valobj = make_object(self.__dimtype__, data)
self._data[name] = valobj
setattr(self, ... | def function[add_dimension, parameter[self, name, data]]:
constant[Add a named dimension to this entity.]
call[name[self].dimensions.add, parameter[name[name]]]
if compare[name[data] is constant[None]] begin[:]
variable[valobj] assign[=] call[name[self].__dimtype__, parameter[]]
... | keyword[def] identifier[add_dimension] ( identifier[self] , identifier[name] , identifier[data] = keyword[None] ):
literal[string]
identifier[self] . identifier[dimensions] . identifier[add] ( identifier[name] )
keyword[if] identifier[data] keyword[is] keyword[None] :
ident... | def add_dimension(self, name, data=None):
"""Add a named dimension to this entity."""
self.dimensions.add(name)
if data is None:
valobj = self.__dimtype__() # depends on [control=['if'], data=[]]
else:
valobj = make_object(self.__dimtype__, data)
self._data[name] = valobj
setatt... |
def str_lower(x):
"""Converts string samples to lower case.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
... | def function[str_lower, parameter[x]]:
constant[Converts string samples to lower case.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
... | keyword[def] identifier[str_lower] ( identifier[x] ):
literal[string]
identifier[sl] = identifier[_to_string_sequence] ( identifier[x] ). identifier[lower] ()
keyword[return] identifier[column] . identifier[ColumnStringArrow] ( identifier[sl] . identifier[bytes] , identifier[sl] . identifier[indices]... | def str_lower(x):
"""Converts string samples to lower case.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
... |
def make_regression(
n_samples=100,
n_features=100,
n_informative=10,
n_targets=1,
bias=0.0,
effective_rank=None,
tail_strength=0.5,
noise=0.0,
shuffle=True,
coef=False,
random_state=None,
chunks=None,
):
"""
Generate a random regression problem.
The input se... | def function[make_regression, parameter[n_samples, n_features, n_informative, n_targets, bias, effective_rank, tail_strength, noise, shuffle, coef, random_state, chunks]]:
constant[
Generate a random regression problem.
The input set can either be well conditioned (by default) or have a low
rank-fa... | keyword[def] identifier[make_regression] (
identifier[n_samples] = literal[int] ,
identifier[n_features] = literal[int] ,
identifier[n_informative] = literal[int] ,
identifier[n_targets] = literal[int] ,
identifier[bias] = literal[int] ,
identifier[effective_rank] = keyword[None] ,
identifier[tail_strength] = ... | def make_regression(n_samples=100, n_features=100, n_informative=10, n_targets=1, bias=0.0, effective_rank=None, tail_strength=0.5, noise=0.0, shuffle=True, coef=False, random_state=None, chunks=None):
"""
Generate a random regression problem.
The input set can either be well conditioned (by default) or ha... |
def TIF_to_jpg_all(path):
"""run TIF_to_jpg() on every TIF of a folder."""
for fname in sorted(glob.glob(path+"/*.tif")):
print(fname)
TIF_to_jpg(fname) | def function[TIF_to_jpg_all, parameter[path]]:
constant[run TIF_to_jpg() on every TIF of a folder.]
for taget[name[fname]] in starred[call[name[sorted], parameter[call[name[glob].glob, parameter[binary_operation[name[path] + constant[/*.tif]]]]]]] begin[:]
call[name[print], parameter[nam... | keyword[def] identifier[TIF_to_jpg_all] ( identifier[path] ):
literal[string]
keyword[for] identifier[fname] keyword[in] identifier[sorted] ( identifier[glob] . identifier[glob] ( identifier[path] + literal[string] )):
identifier[print] ( identifier[fname] )
identifier[TIF_to_jpg] ( id... | def TIF_to_jpg_all(path):
"""run TIF_to_jpg() on every TIF of a folder."""
for fname in sorted(glob.glob(path + '/*.tif')):
print(fname)
TIF_to_jpg(fname) # depends on [control=['for'], data=['fname']] |
def GetFileContents(filename, binary=False, encoding=None, newline=None):
'''
Reads a file and returns its contents. Works for both local and remote files.
:param unicode filename:
:param bool binary:
If True returns the file as is, ignore any EOL conversion.
:param unicode encoding:
... | def function[GetFileContents, parameter[filename, binary, encoding, newline]]:
constant[
Reads a file and returns its contents. Works for both local and remote files.
:param unicode filename:
:param bool binary:
If True returns the file as is, ignore any EOL conversion.
:param unicode... | keyword[def] identifier[GetFileContents] ( identifier[filename] , identifier[binary] = keyword[False] , identifier[encoding] = keyword[None] , identifier[newline] = keyword[None] ):
literal[string]
identifier[source_file] = identifier[OpenFile] ( identifier[filename] , identifier[binary] = identifier[binar... | def GetFileContents(filename, binary=False, encoding=None, newline=None):
"""
Reads a file and returns its contents. Works for both local and remote files.
:param unicode filename:
:param bool binary:
If True returns the file as is, ignore any EOL conversion.
:param unicode encoding:
... |
def tile_decode(tile, tileindex, tileshape, tiledshape,
lsb2msb, decompress, unpack, unpredict, out):
"""Decode tile segment bytes into 5D output array."""
_, imagedepth, imagelength, imagewidth, _ = out.shape
tileddepth, tiledlength, tiledwidth = tiledshape
tiledepth, tilelength, tilewi... | def function[tile_decode, parameter[tile, tileindex, tileshape, tiledshape, lsb2msb, decompress, unpack, unpredict, out]]:
constant[Decode tile segment bytes into 5D output array.]
<ast.Tuple object at 0x7da1b19703a0> assign[=] name[out].shape
<ast.Tuple object at 0x7da1b1971ab0> assign[=] name[... | keyword[def] identifier[tile_decode] ( identifier[tile] , identifier[tileindex] , identifier[tileshape] , identifier[tiledshape] ,
identifier[lsb2msb] , identifier[decompress] , identifier[unpack] , identifier[unpredict] , identifier[out] ):
literal[string]
identifier[_] , identifier[imagedepth] , identif... | def tile_decode(tile, tileindex, tileshape, tiledshape, lsb2msb, decompress, unpack, unpredict, out):
"""Decode tile segment bytes into 5D output array."""
(_, imagedepth, imagelength, imagewidth, _) = out.shape
(tileddepth, tiledlength, tiledwidth) = tiledshape
(tiledepth, tilelength, tilewidth, sample... |
def _get_wmi_sampler(self, instance_key, wmi_class, properties, tag_by="", **kwargs):
"""
Create and cache a WMISampler for the given (class, properties)
"""
properties = list(properties) + [tag_by] if tag_by else list(properties)
if instance_key not in self.wmi_samplers:
... | def function[_get_wmi_sampler, parameter[self, instance_key, wmi_class, properties, tag_by]]:
constant[
Create and cache a WMISampler for the given (class, properties)
]
variable[properties] assign[=] <ast.IfExp object at 0x7da18f810940>
if compare[name[instance_key] <ast.NotIn o... | keyword[def] identifier[_get_wmi_sampler] ( identifier[self] , identifier[instance_key] , identifier[wmi_class] , identifier[properties] , identifier[tag_by] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[properties] = identifier[list] ( identifier[properties] )+[ identifier... | def _get_wmi_sampler(self, instance_key, wmi_class, properties, tag_by='', **kwargs):
"""
Create and cache a WMISampler for the given (class, properties)
"""
properties = list(properties) + [tag_by] if tag_by else list(properties)
if instance_key not in self.wmi_samplers:
wmi_sampler... |
def output(self):
"""
Returns the next available output token.
:return: the next token, None if none available
:rtype: Token
"""
if (self._output is None) or (len(self._output) == 0):
result = None
else:
result = self._output.pop(0)
... | def function[output, parameter[self]]:
constant[
Returns the next available output token.
:return: the next token, None if none available
:rtype: Token
]
if <ast.BoolOp object at 0x7da1b06bfb80> begin[:]
variable[result] assign[=] constant[None]
retur... | keyword[def] identifier[output] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[_output] keyword[is] keyword[None] ) keyword[or] ( identifier[len] ( identifier[self] . identifier[_output] )== literal[int] ):
identifier[result] = keyword[None]
... | def output(self):
"""
Returns the next available output token.
:return: the next token, None if none available
:rtype: Token
"""
if self._output is None or len(self._output) == 0:
result = None # depends on [control=['if'], data=[]]
else:
result = self._outp... |
def set_public_domain(self, public_domain):
"""Sets the public domain flag.
arg: public_domain (boolean): the public domain status
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented f... | def function[set_public_domain, parameter[self, public_domain]]:
constant[Sets the public domain flag.
arg: public_domain (boolean): the public domain status
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
... | keyword[def] identifier[set_public_domain] ( identifier[self] , identifier[public_domain] ):
literal[string]
keyword[if] identifier[self] . identifier[get_public_domain_metadata] (). identifier[is_read_only] ():
keyword[raise] identifier[errors] . identifier[NoAccess] ()
... | def set_public_domain(self, public_domain):
"""Sets the public domain flag.
arg: public_domain (boolean): the public domain status
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from temp... |
def removeNullPadding(str, blocksize=AES_blocksize):
'Remove padding with null bytes'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == '\0':
pad_len += 1
else:
break
str = str[:-pad_len]
return str | def function[removeNullPadding, parameter[str, blocksize]]:
constant[Remove padding with null bytes]
variable[pad_len] assign[=] constant[0]
for taget[name[char]] in starred[call[name[str]][<ast.Slice object at 0x7da1b04a4a30>]] begin[:]
if compare[name[char] equal[==] constant[ ... | keyword[def] identifier[removeNullPadding] ( identifier[str] , identifier[blocksize] = identifier[AES_blocksize] ):
literal[string]
identifier[pad_len] = literal[int]
keyword[for] identifier[char] keyword[in] identifier[str] [::- literal[int] ]:
keyword[if] identifier[char] == literal[st... | def removeNullPadding(str, blocksize=AES_blocksize):
"""Remove padding with null bytes"""
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == '\x00':
pad_len += 1 # depends on [control=['if'], data=[]]
else:
break # depends on [control=['for']... |
def parse_operand(string, location, tokens):
"""Parse instruction operand.
"""
sizes = {
"dqword": 128,
"pointer": 72,
"qword": 64,
"pointer": 40,
"dword": 32,
"word": 16,
"byte": 8,
"bit": 1,
}
if "immediate" in tokens:... | def function[parse_operand, parameter[string, location, tokens]]:
constant[Parse instruction operand.
]
variable[sizes] assign[=] dictionary[[<ast.Constant object at 0x7da18f09fca0>, <ast.Constant object at 0x7da18f09d030>, <ast.Constant object at 0x7da18f09fc10>, <ast.Constant object at 0x7da18f09d... | keyword[def] identifier[parse_operand] ( identifier[string] , identifier[location] , identifier[tokens] ):
literal[string]
identifier[sizes] ={
literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] ,
litera... | def parse_operand(string, location, tokens):
"""Parse instruction operand.
"""
sizes = {'dqword': 128, 'pointer': 72, 'qword': 64, 'pointer': 40, 'dword': 32, 'word': 16, 'byte': 8, 'bit': 1}
if 'immediate' in tokens:
imm_str = ''.join(tokens['immediate'])
base = 16 if imm_str.startswith... |
def use_plenary_catalog_view(self):
"""Pass through to provider CatalogLookupSession.use_plenary_catalog_view"""
self._catalog_view = PLENARY
# self._get_provider_session('catalog_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
... | def function[use_plenary_catalog_view, parameter[self]]:
constant[Pass through to provider CatalogLookupSession.use_plenary_catalog_view]
name[self]._catalog_view assign[=] name[PLENARY]
for taget[name[session]] in starred[call[name[self]._get_provider_sessions, parameter[]]] begin[:]
<a... | keyword[def] identifier[use_plenary_catalog_view] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_catalog_view] = identifier[PLENARY]
keyword[for] identifier[session] keyword[in] identifier[self] . identifier[_get_provider_sessions] ():
keywor... | def use_plenary_catalog_view(self):
"""Pass through to provider CatalogLookupSession.use_plenary_catalog_view"""
self._catalog_view = PLENARY
# self._get_provider_session('catalog_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
... |
def ensure_hist_size(self):
"""
Shrink the history of updates for
a `index/doc_type` combination down to `self.marker_index_hist_size`.
"""
if self.marker_index_hist_size == 0:
return
result = self.es.search(index=self.marker_index,
... | def function[ensure_hist_size, parameter[self]]:
constant[
Shrink the history of updates for
a `index/doc_type` combination down to `self.marker_index_hist_size`.
]
if compare[name[self].marker_index_hist_size equal[==] constant[0]] begin[:]
return[None]
variable[... | keyword[def] identifier[ensure_hist_size] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[marker_index_hist_size] == literal[int] :
keyword[return]
identifier[result] = identifier[self] . identifier[es] . identifier[search] ( identifier[index]... | def ensure_hist_size(self):
"""
Shrink the history of updates for
a `index/doc_type` combination down to `self.marker_index_hist_size`.
"""
if self.marker_index_hist_size == 0:
return # depends on [control=['if'], data=[]]
result = self.es.search(index=self.marker_index, doc... |
def insert_rows(self, row, no_rows=1):
"""Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array... | def function[insert_rows, parameter[self, row, no_rows]]:
constant[Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed
]
call[name[post_command_event], parameter[name[self].main_window, name[self].ContentChangedMsg]]
variable[tab] assign[=] name[sel... | keyword[def] identifier[insert_rows] ( identifier[self] , identifier[row] , identifier[no_rows] = literal[int] ):
literal[string]
identifier[post_command_event] ( identifier[self] . identifier[main_window] , identifier[self] . identifier[ContentChangedMsg] )
identifier[tab] = id... | def insert_rows(self, row, no_rows=1):
"""Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array.insert(row, no_rows, a... |
def fix_facets(self):
"""
This function convert date_histogram facets to datetime
"""
facets = self.facets
for key in list(facets.keys()):
_type = facets[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in facets[key].ge... | def function[fix_facets, parameter[self]]:
constant[
This function convert date_histogram facets to datetime
]
variable[facets] assign[=] name[self].facets
for taget[name[key]] in starred[call[name[list], parameter[call[name[facets].keys, parameter[]]]]] begin[:]
... | keyword[def] identifier[fix_facets] ( identifier[self] ):
literal[string]
identifier[facets] = identifier[self] . identifier[facets]
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[facets] . identifier[keys] ()):
identifier[_type] = identifier[facets... | def fix_facets(self):
"""
This function convert date_histogram facets to datetime
"""
facets = self.facets
for key in list(facets.keys()):
_type = facets[key].get('_type', 'unknown')
if _type == 'date_histogram':
for entry in facets[key].get('entries', []):
... |
def getServiceDependenciesUIDs(self):
"""
This methods returns a list with the service dependencies UIDs
:return: a list of uids
"""
deps = self.getServiceDependencies()
deps_uids = [service.UID() for service in deps]
return deps_uids | def function[getServiceDependenciesUIDs, parameter[self]]:
constant[
This methods returns a list with the service dependencies UIDs
:return: a list of uids
]
variable[deps] assign[=] call[name[self].getServiceDependencies, parameter[]]
variable[deps_uids] assign[=] <ast.L... | keyword[def] identifier[getServiceDependenciesUIDs] ( identifier[self] ):
literal[string]
identifier[deps] = identifier[self] . identifier[getServiceDependencies] ()
identifier[deps_uids] =[ identifier[service] . identifier[UID] () keyword[for] identifier[service] keyword[in] identifier... | def getServiceDependenciesUIDs(self):
"""
This methods returns a list with the service dependencies UIDs
:return: a list of uids
"""
deps = self.getServiceDependencies()
deps_uids = [service.UID() for service in deps]
return deps_uids |
def get_profile_model():
"""
Return the model class for the currently-active user profile
model, as defined by the ``AUTH_PROFILE_MODULE`` setting.
:return: The model that is used as profile.
"""
if (not hasattr(settings, 'AUTH_PROFILE_MODULE')) or \
(not settings.AUTH_PROFILE_MODUL... | def function[get_profile_model, parameter[]]:
constant[
Return the model class for the currently-active user profile
model, as defined by the ``AUTH_PROFILE_MODULE`` setting.
:return: The model that is used as profile.
]
if <ast.BoolOp object at 0x7da18f723520> begin[:]
<ast.Ra... | keyword[def] identifier[get_profile_model] ():
literal[string]
keyword[if] ( keyword[not] identifier[hasattr] ( identifier[settings] , literal[string] )) keyword[or] ( keyword[not] identifier[settings] . identifier[AUTH_PROFILE_MODULE] ):
keyword[raise] identifier[SiteProfileNotAvailable]
... | def get_profile_model():
"""
Return the model class for the currently-active user profile
model, as defined by the ``AUTH_PROFILE_MODULE`` setting.
:return: The model that is used as profile.
"""
if not hasattr(settings, 'AUTH_PROFILE_MODULE') or not settings.AUTH_PROFILE_MODULE:
raise... |
def list_cron_job_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_cron_job_for_all_namespaces(async_req=Tr... | def function[list_cron_job_for_all_namespaces, parameter[self]]:
constant[
list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_cron_job_for_all_namesp... | keyword[def] identifier[list_cron_job_for_all_namespaces] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self... | def list_cron_job_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_cron_job_for_all_namespaces(async_req=True)
... |
def get_agent_rule_str(agent):
"""Construct a string from an Agent as part of a PySB rule name."""
rule_str_list = [_n(agent.name)]
# If it's a molecular agent
if isinstance(agent, ist.Agent):
for mod in agent.mods:
mstr = abbrevs[mod.mod_type]
if mod.residue is not None:... | def function[get_agent_rule_str, parameter[agent]]:
constant[Construct a string from an Agent as part of a PySB rule name.]
variable[rule_str_list] assign[=] list[[<ast.Call object at 0x7da18c4cee60>]]
if call[name[isinstance], parameter[name[agent], name[ist].Agent]] begin[:]
fo... | keyword[def] identifier[get_agent_rule_str] ( identifier[agent] ):
literal[string]
identifier[rule_str_list] =[ identifier[_n] ( identifier[agent] . identifier[name] )]
keyword[if] identifier[isinstance] ( identifier[agent] , identifier[ist] . identifier[Agent] ):
keyword[for] identifi... | def get_agent_rule_str(agent):
"""Construct a string from an Agent as part of a PySB rule name."""
rule_str_list = [_n(agent.name)]
# If it's a molecular agent
if isinstance(agent, ist.Agent):
for mod in agent.mods:
mstr = abbrevs[mod.mod_type]
if mod.residue is not None:... |
def name_globals(s, remove_params=None):
"""
Returns a list of the global parameter names.
Parameters
----------
s : :class:`peri.states.ImageState`
The state to name the globals of.
remove_params : Set or None
A set of unique additional parameters to remove from... | def function[name_globals, parameter[s, remove_params]]:
constant[
Returns a list of the global parameter names.
Parameters
----------
s : :class:`peri.states.ImageState`
The state to name the globals of.
remove_params : Set or None
A set of unique additional... | keyword[def] identifier[name_globals] ( identifier[s] , identifier[remove_params] = keyword[None] ):
literal[string]
identifier[all_params] = identifier[s] . identifier[params]
keyword[for] identifier[p] keyword[in] identifier[s] . identifier[param_particle] ( identifier[np] . identifier[arange] (... | def name_globals(s, remove_params=None):
"""
Returns a list of the global parameter names.
Parameters
----------
s : :class:`peri.states.ImageState`
The state to name the globals of.
remove_params : Set or None
A set of unique additional parameters to remove from... |
def predict(self, X, exposure=None):
"""
preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
containing the inp... | def function[predict, parameter[self, X, exposure]]:
constant[
preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
... | keyword[def] identifier[predict] ( identifier[self] , identifier[X] , identifier[exposure] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_fitted] :
keyword[raise] identifier[AttributeError] ( literal[string] )
identifier[X] = ... | def predict(self, X, exposure=None):
"""
preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
containing the input d... |
def explain_prediction(estimator, doc, **kwargs):
"""
Return an explanation of an estimator prediction.
:func:`explain_prediction` is not doing any work itself, it dispatches
to a concrete implementation based on estimator type.
Parameters
----------
estimator : object
Estimator in... | def function[explain_prediction, parameter[estimator, doc]]:
constant[
Return an explanation of an estimator prediction.
:func:`explain_prediction` is not doing any work itself, it dispatches
to a concrete implementation based on estimator type.
Parameters
----------
estimator : object... | keyword[def] identifier[explain_prediction] ( identifier[estimator] , identifier[doc] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[Explanation] (
identifier[estimator] = identifier[repr] ( identifier[estimator] ),
identifier[error] = literal[string] % identifier[estimator... | def explain_prediction(estimator, doc, **kwargs):
"""
Return an explanation of an estimator prediction.
:func:`explain_prediction` is not doing any work itself, it dispatches
to a concrete implementation based on estimator type.
Parameters
----------
estimator : object
Estimator in... |
def as_ndarray(arr, copy=False, dtype=None, order='K'):
"""Convert an arbitrary array to numpy.ndarray.
In the case of a memmap array, a copy is automatically made to break the
link with the underlying file (whatever the value of the "copy" keyword).
The purpose of this function is mainly to get rid o... | def function[as_ndarray, parameter[arr, copy, dtype, order]]:
constant[Convert an arbitrary array to numpy.ndarray.
In the case of a memmap array, a copy is automatically made to break the
link with the underlying file (whatever the value of the "copy" keyword).
The purpose of this function is mai... | keyword[def] identifier[as_ndarray] ( identifier[arr] , identifier[copy] = keyword[False] , identifier[dtype] = keyword[None] , identifier[order] = literal[string] ):
literal[string]
keyword[if] identifier[order] keyword[not] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[st... | def as_ndarray(arr, copy=False, dtype=None, order='K'):
"""Convert an arbitrary array to numpy.ndarray.
In the case of a memmap array, a copy is automatically made to break the
link with the underlying file (whatever the value of the "copy" keyword).
The purpose of this function is mainly to get rid o... |
def rebuild_proxies(self, prepared_request, proxies):
"""This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
proxy keys for this URL (in c... | def function[rebuild_proxies, parameter[self, prepared_request, proxies]]:
constant[This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
pr... | keyword[def] identifier[rebuild_proxies] ( identifier[self] , identifier[prepared_request] , identifier[proxies] ):
literal[string]
identifier[proxies] = identifier[proxies] keyword[if] identifier[proxies] keyword[is] keyword[not] keyword[None] keyword[else] {}
identifier[headers] = ... | def rebuild_proxies(self, prepared_request, proxies):
"""This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
proxy keys for this URL (in case ... |
def fetch(version='bayestar2017'):
"""
Downloads the specified version of the Bayestar dust map.
Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'bayestar2015'` (G... | def function[fetch, parameter[version]]:
constant[
Downloads the specified version of the Bayestar dust map.
Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'b... | keyword[def] identifier[fetch] ( identifier[version] = literal[string] ):
literal[string]
identifier[doi] ={
literal[string] : literal[string] ,
literal[string] : literal[string]
}
keyword[try] :
identifier[doi] = identifier[doi] [ identifier[version] ]
keyword[exce... | def fetch(version='bayestar2017'):
"""
Downloads the specified version of the Bayestar dust map.
Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'bayestar2015'` (G... |
def nonlinear_odr(x, y, dx, dy, func, params_init, **kwargs):
"""Perform a non-linear orthogonal distance regression, return the results as
ErrorValue() instances.
Inputs:
x: one-dimensional numpy array of the independent variable
y: one-dimensional numpy array of the dependent variable
... | def function[nonlinear_odr, parameter[x, y, dx, dy, func, params_init]]:
constant[Perform a non-linear orthogonal distance regression, return the results as
ErrorValue() instances.
Inputs:
x: one-dimensional numpy array of the independent variable
y: one-dimensional numpy array of the d... | keyword[def] identifier[nonlinear_odr] ( identifier[x] , identifier[y] , identifier[dx] , identifier[dy] , identifier[func] , identifier[params_init] ,** identifier[kwargs] ):
literal[string]
identifier[odrmodel] = identifier[odr] . identifier[Model] ( keyword[lambda] identifier[pars] , identifier[x] : id... | def nonlinear_odr(x, y, dx, dy, func, params_init, **kwargs):
"""Perform a non-linear orthogonal distance regression, return the results as
ErrorValue() instances.
Inputs:
x: one-dimensional numpy array of the independent variable
y: one-dimensional numpy array of the dependent variable
... |
def create_topic(
self, topic_name,
default_message_time_to_live=None,
max_size_in_megabytes=None, requires_duplicate_detection=None,
duplicate_detection_history_time_window=None,
enable_batched_operations=None):
"""Create a topic entity.
:par... | def function[create_topic, parameter[self, topic_name, default_message_time_to_live, max_size_in_megabytes, requires_duplicate_detection, duplicate_detection_history_time_window, enable_batched_operations]]:
constant[Create a topic entity.
:param topic_name: The name of the new topic.
:type top... | keyword[def] identifier[create_topic] (
identifier[self] , identifier[topic_name] ,
identifier[default_message_time_to_live] = keyword[None] ,
identifier[max_size_in_megabytes] = keyword[None] , identifier[requires_duplicate_detection] = keyword[None] ,
identifier[duplicate_detection_history_time_window] = keywor... | def create_topic(self, topic_name, default_message_time_to_live=None, max_size_in_megabytes=None, requires_duplicate_detection=None, duplicate_detection_history_time_window=None, enable_batched_operations=None):
"""Create a topic entity.
:param topic_name: The name of the new topic.
:type topic_nam... |
def choices(tree):
"""
Get the 'address' of each leaf node in terms of internal
node choices
"""
n = len(leaves(tree))
addr = np.nan * np.ones((n, n-1))
def _addresses(node, index, choices):
# index is the index of the current internal node
# choices is a list of (indice, 0/1... | def function[choices, parameter[tree]]:
constant[
Get the 'address' of each leaf node in terms of internal
node choices
]
variable[n] assign[=] call[name[len], parameter[call[name[leaves], parameter[name[tree]]]]]
variable[addr] assign[=] binary_operation[name[np].nan * call[name[np]... | keyword[def] identifier[choices] ( identifier[tree] ):
literal[string]
identifier[n] = identifier[len] ( identifier[leaves] ( identifier[tree] ))
identifier[addr] = identifier[np] . identifier[nan] * identifier[np] . identifier[ones] (( identifier[n] , identifier[n] - literal[int] ))
keyword[def]... | def choices(tree):
"""
Get the 'address' of each leaf node in terms of internal
node choices
"""
n = len(leaves(tree))
addr = np.nan * np.ones((n, n - 1))
def _addresses(node, index, choices):
# index is the index of the current internal node
# choices is a list of (indice, ... |
def wait_for_completion(self, response, timeout=3600, initial_wait=5, scaleup=10):
"""
Poll resource request status until resource is provisioned.
:param response: A response dict, which needs to have a 'requestId' item.
:type response: ``dict``
:param timeout: ... | def function[wait_for_completion, parameter[self, response, timeout, initial_wait, scaleup]]:
constant[
Poll resource request status until resource is provisioned.
:param response: A response dict, which needs to have a 'requestId' item.
:type response: ``dict``
:par... | keyword[def] identifier[wait_for_completion] ( identifier[self] , identifier[response] , identifier[timeout] = literal[int] , identifier[initial_wait] = literal[int] , identifier[scaleup] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[response] :
keyword[return... | def wait_for_completion(self, response, timeout=3600, initial_wait=5, scaleup=10):
"""
Poll resource request status until resource is provisioned.
:param response: A response dict, which needs to have a 'requestId' item.
:type response: ``dict``
:param timeout: Maxi... |
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
return [self.rich_text_action, self.plain_text_action,
self.show_source_action, MENU_SEPARATOR,
self.auto_import_action] | def function[get_plugin_actions, parameter[self]]:
constant[Return a list of actions related to plugin]
return[list[[<ast.Attribute object at 0x7da20c6c6e00>, <ast.Attribute object at 0x7da20c6c6bc0>, <ast.Attribute object at 0x7da20c6c7f70>, <ast.Name object at 0x7da20c6c7a60>, <ast.Attribute object at 0x7... | keyword[def] identifier[get_plugin_actions] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[self] . identifier[rich_text_action] , identifier[self] . identifier[plain_text_action] ,
identifier[self] . identifier[show_source_action] , identifier[MENU_SEPARATOR] ,
... | def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
return [self.rich_text_action, self.plain_text_action, self.show_source_action, MENU_SEPARATOR, self.auto_import_action] |
def MTF(self, px_per_mm):
'''
px_per_mm = cam_resolution / image_size
'''
res = 100 #numeric resolution
r = 4 #range +-r*std
#size of 1 px:
px_size = 1 / px_per_mm
#standard deviation of the point-spread-function (PSF) as normal... | def function[MTF, parameter[self, px_per_mm]]:
constant[
px_per_mm = cam_resolution / image_size
]
variable[res] assign[=] constant[100]
variable[r] assign[=] constant[4]
variable[px_size] assign[=] binary_operation[constant[1] / name[px_per_mm]]
variable[std] ass... | keyword[def] identifier[MTF] ( identifier[self] , identifier[px_per_mm] ):
literal[string]
identifier[res] = literal[int]
identifier[r] = literal[int]
identifier[px_size] = literal[int] / identifier[px_per_mm]
identifier[std] = identifier[s... | def MTF(self, px_per_mm):
"""
px_per_mm = cam_resolution / image_size
"""
res = 100 #numeric resolution
r = 4 #range +-r*std
#size of 1 px:
px_size = 1 / px_per_mm #standard deviation of the point-spread-function (PSF) as normal distributed:
std = self.std * px_size #transfor... |
def kron(*matrices: np.ndarray) -> np.ndarray:
"""Computes the kronecker product of a sequence of matrices.
A *args version of lambda args: functools.reduce(np.kron, args).
Args:
*matrices: The matrices and controls to combine with the kronecker
product.
Returns:
The resul... | def function[kron, parameter[]]:
constant[Computes the kronecker product of a sequence of matrices.
A *args version of lambda args: functools.reduce(np.kron, args).
Args:
*matrices: The matrices and controls to combine with the kronecker
product.
Returns:
The resulting... | keyword[def] identifier[kron] (* identifier[matrices] : identifier[np] . identifier[ndarray] )-> identifier[np] . identifier[ndarray] :
literal[string]
identifier[product] = identifier[np] . identifier[eye] ( literal[int] )
keyword[for] identifier[m] keyword[in] identifier[matrices] :
iden... | def kron(*matrices: np.ndarray) -> np.ndarray:
"""Computes the kronecker product of a sequence of matrices.
A *args version of lambda args: functools.reduce(np.kron, args).
Args:
*matrices: The matrices and controls to combine with the kronecker
product.
Returns:
The resul... |
def post_license_request(request):
"""Submission to create a license acceptance request."""
uuid_ = request.matchdict['uuid']
posted_data = request.json
license_url = posted_data.get('license_url')
licensors = posted_data.get('licensors', [])
with db_connect() as db_conn:
with db_conn.c... | def function[post_license_request, parameter[request]]:
constant[Submission to create a license acceptance request.]
variable[uuid_] assign[=] call[name[request].matchdict][constant[uuid]]
variable[posted_data] assign[=] name[request].json
variable[license_url] assign[=] call[name[posted... | keyword[def] identifier[post_license_request] ( identifier[request] ):
literal[string]
identifier[uuid_] = identifier[request] . identifier[matchdict] [ literal[string] ]
identifier[posted_data] = identifier[request] . identifier[json]
identifier[license_url] = identifier[posted_data] . identif... | def post_license_request(request):
"""Submission to create a license acceptance request."""
uuid_ = request.matchdict['uuid']
posted_data = request.json
license_url = posted_data.get('license_url')
licensors = posted_data.get('licensors', [])
with db_connect() as db_conn:
with db_conn.cu... |
def parse_config(h5path):
"""Parse the RT-DC configuration of an hdf5 file"""
with h5py.File(h5path, mode="r") as fh5:
h5attrs = dict(fh5.attrs)
# Convert byte strings to unicode strings
# https://github.com/h5py/h5py/issues/379
for key in h5attrs:
if isi... | def function[parse_config, parameter[h5path]]:
constant[Parse the RT-DC configuration of an hdf5 file]
with call[name[h5py].File, parameter[name[h5path]]] begin[:]
variable[h5attrs] assign[=] call[name[dict], parameter[name[fh5].attrs]]
for taget[name[key]] in starred[name[h5attr... | keyword[def] identifier[parse_config] ( identifier[h5path] ):
literal[string]
keyword[with] identifier[h5py] . identifier[File] ( identifier[h5path] , identifier[mode] = literal[string] ) keyword[as] identifier[fh5] :
identifier[h5attrs] = identifier[dict] ( identifier[fh5] . identif... | def parse_config(h5path):
"""Parse the RT-DC configuration of an hdf5 file"""
with h5py.File(h5path, mode='r') as fh5:
h5attrs = dict(fh5.attrs) # depends on [control=['with'], data=['fh5']]
# Convert byte strings to unicode strings
# https://github.com/h5py/h5py/issues/379
for key in h5att... |
def get_samples(self, n_samples, log_p_function, burn_in_steps=50):
"""
Generates samples.
Parameters:
n_samples - number of samples to generate
log_p_function - a function that returns log density for a specific sample
burn_in_steps - number of burn-in steps... | def function[get_samples, parameter[self, n_samples, log_p_function, burn_in_steps]]:
constant[
Generates samples.
Parameters:
n_samples - number of samples to generate
log_p_function - a function that returns log density for a specific sample
burn_in_steps -... | keyword[def] identifier[get_samples] ( identifier[self] , identifier[n_samples] , identifier[log_p_function] , identifier[burn_in_steps] = literal[int] ):
literal[string]
identifier[restarts] = identifier[initial_design] ( literal[string] , identifier[self] . identifier[space] , identifier[n_sample... | def get_samples(self, n_samples, log_p_function, burn_in_steps=50):
"""
Generates samples.
Parameters:
n_samples - number of samples to generate
log_p_function - a function that returns log density for a specific sample
burn_in_steps - number of burn-in steps for... |
def _getel(key, value):
"""Returns an element given a key and value."""
if key in ['HorizontalRule', 'Null']:
return elt(key, 0)()
elif key in ['Plain', 'Para', 'BlockQuote', 'BulletList',
'DefinitionList', 'HorizontalRule', 'Null']:
return elt(key, 1)(value)
return elt(... | def function[_getel, parameter[key, value]]:
constant[Returns an element given a key and value.]
if compare[name[key] in list[[<ast.Constant object at 0x7da20c6abbe0>, <ast.Constant object at 0x7da20c6a9780>]]] begin[:]
return[call[call[name[elt], parameter[name[key], constant[0]]], parameter[]]... | keyword[def] identifier[_getel] ( identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[key] keyword[in] [ literal[string] , literal[string] ]:
keyword[return] identifier[elt] ( identifier[key] , literal[int] )()
keyword[elif] identifier[key] keyword[in] [ literal... | def _getel(key, value):
"""Returns an element given a key and value."""
if key in ['HorizontalRule', 'Null']:
return elt(key, 0)() # depends on [control=['if'], data=['key']]
elif key in ['Plain', 'Para', 'BlockQuote', 'BulletList', 'DefinitionList', 'HorizontalRule', 'Null']:
return elt(ke... |
def _create_client_impl(self, api_version):
"""
Creates the client implementation corresponding to the specifeid api_version.
:param api_version:
:return:
"""
if api_version == v7_0_VERSION:
from azure.keyvault.v7_0 import KeyVaultClient as ImplClient
... | def function[_create_client_impl, parameter[self, api_version]]:
constant[
Creates the client implementation corresponding to the specifeid api_version.
:param api_version:
:return:
]
if compare[name[api_version] equal[==] name[v7_0_VERSION]] begin[:]
from relativ... | keyword[def] identifier[_create_client_impl] ( identifier[self] , identifier[api_version] ):
literal[string]
keyword[if] identifier[api_version] == identifier[v7_0_VERSION] :
keyword[from] identifier[azure] . identifier[keyvault] . identifier[v7_0] keyword[import] identifier[KeyVau... | def _create_client_impl(self, api_version):
"""
Creates the client implementation corresponding to the specifeid api_version.
:param api_version:
:return:
"""
if api_version == v7_0_VERSION:
from azure.keyvault.v7_0 import KeyVaultClient as ImplClient # depends on [contr... |
def njsd_geneset(network, ref, query, gene_set, file, verbose=True):
"""Compute gene set-specified nJSD between reference and query expression profiles.
Attribute;
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): File path to a... | def function[njsd_geneset, parameter[network, ref, query, gene_set, file, verbose]]:
constant[Compute gene set-specified nJSD between reference and query expression profiles.
Attribute;
network (str): File path to a network file.
ref (str): File path to a reference expression file.
q... | keyword[def] identifier[njsd_geneset] ( identifier[network] , identifier[ref] , identifier[query] , identifier[gene_set] , identifier[file] , identifier[verbose] = keyword[True] ):
literal[string]
identifier[graph] , identifier[gene_set_total] = identifier[util] . identifier[parse_network] ( identifier[net... | def njsd_geneset(network, ref, query, gene_set, file, verbose=True):
"""Compute gene set-specified nJSD between reference and query expression profiles.
Attribute;
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): File path to a... |
def setSpecialPrice(self, product, special_price=None,
from_date=None, to_date=None, store_view=None,
identifierType=None):
"""
Update product's special price
:param product: ID or SKU of product
:param special_price: Special Price
... | def function[setSpecialPrice, parameter[self, product, special_price, from_date, to_date, store_view, identifierType]]:
constant[
Update product's special price
:param product: ID or SKU of product
:param special_price: Special Price
:param from_date: From date
:param to... | keyword[def] identifier[setSpecialPrice] ( identifier[self] , identifier[product] , identifier[special_price] = keyword[None] ,
identifier[from_date] = keyword[None] , identifier[to_date] = keyword[None] , identifier[store_view] = keyword[None] ,
identifier[identifierType] = keyword[None] ):
literal[string... | def setSpecialPrice(self, product, special_price=None, from_date=None, to_date=None, store_view=None, identifierType=None):
"""
Update product's special price
:param product: ID or SKU of product
:param special_price: Special Price
:param from_date: From date
:param to_date:... |
def delete_user_by_email(self, id, email):
"""Deletes a specified connection user by its email.
Args:
id (str): The id of the connection (must be a database connection).
email (str): The email of the user to delete.
See: https://auth0.com/docs/api/management/v2#!/Connect... | def function[delete_user_by_email, parameter[self, id, email]]:
constant[Deletes a specified connection user by its email.
Args:
id (str): The id of the connection (must be a database connection).
email (str): The email of the user to delete.
See: https://auth0.com/docs/... | keyword[def] identifier[delete_user_by_email] ( identifier[self] , identifier[id] , identifier[email] ):
literal[string]
keyword[return] identifier[self] . identifier[client] . identifier[delete] ( identifier[self] . identifier[_url] ( identifier[id] )+ literal[string] , identifier[params] ={ lite... | def delete_user_by_email(self, id, email):
"""Deletes a specified connection user by its email.
Args:
id (str): The id of the connection (must be a database connection).
email (str): The email of the user to delete.
See: https://auth0.com/docs/api/management/v2#!/Connections... |
def _fix_outgoing(self, son, collection):
"""Apply manipulators to a SON object as it comes out of the database.
:Parameters:
- `son`: the son object coming out of the database
- `collection`: the collection the son object was saved in
"""
for manipulator in reversed... | def function[_fix_outgoing, parameter[self, son, collection]]:
constant[Apply manipulators to a SON object as it comes out of the database.
:Parameters:
- `son`: the son object coming out of the database
- `collection`: the collection the son object was saved in
]
fo... | keyword[def] identifier[_fix_outgoing] ( identifier[self] , identifier[son] , identifier[collection] ):
literal[string]
keyword[for] identifier[manipulator] keyword[in] identifier[reversed] ( identifier[self] . identifier[__outgoing_manipulators] ):
identifier[son] = identifier[mani... | def _fix_outgoing(self, son, collection):
"""Apply manipulators to a SON object as it comes out of the database.
:Parameters:
- `son`: the son object coming out of the database
- `collection`: the collection the son object was saved in
"""
for manipulator in reversed(self.__... |
def update_persistent_boot(self, device_type=[]):
"""Changes the persistent boot device order for the host
:param device_type: ordered list of boot devices
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on ... | def function[update_persistent_boot, parameter[self, device_type]]:
constant[Changes the persistent boot device order for the host
:param device_type: ordered list of boot devices
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not suppor... | keyword[def] identifier[update_persistent_boot] ( identifier[self] , identifier[device_type] =[]):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[device_type] :
keyword[if] identifier[item] . identifier[upper] () keyword[not] keyword[in] identifier[... | def update_persistent_boot(self, device_type=[]):
"""Changes the persistent boot device order for the host
:param device_type: ordered list of boot devices
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.