code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def put_if_empty(self, key, value):
"""
Atomically write data only if the key is not already set.
:param bytes key: Key to check/set.
:param bytes value: Arbitrary data.
:return: Boolean whether key/value was set.
"""
if self.has_data_for_key(key):
re... | def function[put_if_empty, parameter[self, key, value]]:
constant[
Atomically write data only if the key is not already set.
:param bytes key: Key to check/set.
:param bytes value: Arbitrary data.
:return: Boolean whether key/value was set.
]
if call[name[self].h... | keyword[def] identifier[put_if_empty] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[has_data_for_key] ( identifier[key] ):
keyword[return] keyword[False]
identifier[self] . identifier[put_data] ( identi... | def put_if_empty(self, key, value):
"""
Atomically write data only if the key is not already set.
:param bytes key: Key to check/set.
:param bytes value: Arbitrary data.
:return: Boolean whether key/value was set.
"""
if self.has_data_for_key(key):
return False ... |
def uint32_gte(a: int, b: int) -> bool:
"""
Return a >= b.
"""
return (a == b) or uint32_gt(a, b) | def function[uint32_gte, parameter[a, b]]:
constant[
Return a >= b.
]
return[<ast.BoolOp object at 0x7da204962230>] | keyword[def] identifier[uint32_gte] ( identifier[a] : identifier[int] , identifier[b] : identifier[int] )-> identifier[bool] :
literal[string]
keyword[return] ( identifier[a] == identifier[b] ) keyword[or] identifier[uint32_gt] ( identifier[a] , identifier[b] ) | def uint32_gte(a: int, b: int) -> bool:
"""
Return a >= b.
"""
return a == b or uint32_gt(a, b) |
def match_value(expected_type, actual_value):
"""
Matches expected type to a type of a value.
The expected type can be specified by a type, type name or [[TypeCode]].
:param expected_type: an expected type to match.
:param actual_value: a value to match its type to the expected... | def function[match_value, parameter[expected_type, actual_value]]:
constant[
Matches expected type to a type of a value.
The expected type can be specified by a type, type name or [[TypeCode]].
:param expected_type: an expected type to match.
:param actual_value: a value to mat... | keyword[def] identifier[match_value] ( identifier[expected_type] , identifier[actual_value] ):
literal[string]
keyword[if] identifier[expected_type] == keyword[None] :
keyword[return] keyword[True]
keyword[if] identifier[actual_value] == keyword[None] :
keywor... | def match_value(expected_type, actual_value):
"""
Matches expected type to a type of a value.
The expected type can be specified by a type, type name or [[TypeCode]].
:param expected_type: an expected type to match.
:param actual_value: a value to match its type to the expected one... |
def _load_knownGene(filename):
""" Load UCSC knownGene table.
Parameters
----------
filename : str
path to knownGene file
Returns
-------
df : pandas.DataFrame
knownGene table if loading was successful, else None
"""
try:
... | def function[_load_knownGene, parameter[filename]]:
constant[ Load UCSC knownGene table.
Parameters
----------
filename : str
path to knownGene file
Returns
-------
df : pandas.DataFrame
knownGene table if loading was successful, else Non... | keyword[def] identifier[_load_knownGene] ( identifier[filename] ):
literal[string]
keyword[try] :
identifier[df] = identifier[pd] . identifier[read_table] (
identifier[filename] ,
identifier[names] =[
literal[string] ,
literal[string]... | def _load_knownGene(filename):
""" Load UCSC knownGene table.
Parameters
----------
filename : str
path to knownGene file
Returns
-------
df : pandas.DataFrame
knownGene table if loading was successful, else None
"""
try:
... |
def get_dialog(self):
"""Return FormDialog instance"""
dialog = self.parent()
while not isinstance(dialog, QDialog):
dialog = dialog.parent()
return dialog | def function[get_dialog, parameter[self]]:
constant[Return FormDialog instance]
variable[dialog] assign[=] call[name[self].parent, parameter[]]
while <ast.UnaryOp object at 0x7da1b2345600> begin[:]
variable[dialog] assign[=] call[name[dialog].parent, parameter[]]
return[name[... | keyword[def] identifier[get_dialog] ( identifier[self] ):
literal[string]
identifier[dialog] = identifier[self] . identifier[parent] ()
keyword[while] keyword[not] identifier[isinstance] ( identifier[dialog] , identifier[QDialog] ):
identifier[dialog] = identifier[dialog] . ... | def get_dialog(self):
"""Return FormDialog instance"""
dialog = self.parent()
while not isinstance(dialog, QDialog):
dialog = dialog.parent() # depends on [control=['while'], data=[]]
return dialog |
def check_max_filesize(chosen_file, max_size):
"""
Checks file sizes for host
"""
if os.path.getsize(chosen_file) > max_size:
return False
else:
return True | def function[check_max_filesize, parameter[chosen_file, max_size]]:
constant[
Checks file sizes for host
]
if compare[call[name[os].path.getsize, parameter[name[chosen_file]]] greater[>] name[max_size]] begin[:]
return[constant[False]] | keyword[def] identifier[check_max_filesize] ( identifier[chosen_file] , identifier[max_size] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[getsize] ( identifier[chosen_file] )> identifier[max_size] :
keyword[return] keyword[False]
keyword[else] :
ke... | def check_max_filesize(chosen_file, max_size):
"""
Checks file sizes for host
"""
if os.path.getsize(chosen_file) > max_size:
return False # depends on [control=['if'], data=[]]
else:
return True |
def parse(self):
"""
Retreive and parse Event Summary report for the given :py:class:`nhlscrapi.games.game.GameKey`
:returns: ``self`` on success, ``None`` otherwise
"""
try:
return super(EventSummRep, self).parse() \
.parse_away_shots() \
... | def function[parse, parameter[self]]:
constant[
Retreive and parse Event Summary report for the given :py:class:`nhlscrapi.games.game.GameKey`
:returns: ``self`` on success, ``None`` otherwise
]
<ast.Try object at 0x7da20c6e6ad0> | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[super] ( identifier[EventSummRep] , identifier[self] ). identifier[parse] (). identifier[parse_away_shots] (). identifier[parse_home_shots] (). identifier[parse_away_fo] (). ... | def parse(self):
"""
Retreive and parse Event Summary report for the given :py:class:`nhlscrapi.games.game.GameKey`
:returns: ``self`` on success, ``None`` otherwise
"""
try:
return super(EventSummRep, self).parse().parse_away_shots().parse_home_shots().parse_away_fo().p... |
def _prefetch_items(self,change):
""" When the current_row in the model changes (whether from scrolling) or
set by the application. Make sure the results are loaded!
"""
if self.is_initialized:
view = self.item_view
upper_limit = view.iterabl... | def function[_prefetch_items, parameter[self, change]]:
constant[ When the current_row in the model changes (whether from scrolling) or
set by the application. Make sure the results are loaded!
]
if name[self].is_initialized begin[:]
variable[view] assign[=] name... | keyword[def] identifier[_prefetch_items] ( identifier[self] , identifier[change] ):
literal[string]
keyword[if] identifier[self] . identifier[is_initialized] :
identifier[view] = identifier[self] . identifier[item_view]
identifier[upper_limit] = identifier[view] . ident... | def _prefetch_items(self, change):
""" When the current_row in the model changes (whether from scrolling) or
set by the application. Make sure the results are loaded!
"""
if self.is_initialized:
view = self.item_view
upper_limit = view.iterable_index + view.iterable_fetc... |
def send_message(self, msg):
""" Send a message to the client. This should not be used in
remote debugging mode.
"""
if not self.handlers:
return #: Client not connected
for h in self.handlers:
h.write_message(msg) | def function[send_message, parameter[self, msg]]:
constant[ Send a message to the client. This should not be used in
remote debugging mode.
]
if <ast.UnaryOp object at 0x7da20e74beb0> begin[:]
return[None]
for taget[name[h]] in starred[name[self].handlers] begin[... | keyword[def] identifier[send_message] ( identifier[self] , identifier[msg] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[handlers] :
keyword[return]
keyword[for] identifier[h] keyword[in] identifier[self] . identifier[handlers] :
... | def send_message(self, msg):
""" Send a message to the client. This should not be used in
remote debugging mode.
"""
if not self.handlers:
return #: Client not connected # depends on [control=['if'], data=[]]
for h in self.handlers:
h.write_message(msg) # depends ... |
def genl_register(ops):
"""Register Generic Netlink family backed cache.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241
Same as genl_register_family() but additionally registers the specified cache operations using
nl_cache_mngt_register() and associates it with the Generic Net... | def function[genl_register, parameter[ops]]:
constant[Register Generic Netlink family backed cache.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241
Same as genl_register_family() but additionally registers the specified cache operations using
nl_cache_mngt_register() and ass... | keyword[def] identifier[genl_register] ( identifier[ops] ):
literal[string]
keyword[if] identifier[ops] . identifier[co_protocol] != identifier[NETLINK_GENERIC] :
keyword[return] - identifier[NLE_PROTO_MISMATCH]
keyword[if] identifier[ops] . identifier[co_hdrsize] < identifier[GENL_HDRSIZE... | def genl_register(ops):
"""Register Generic Netlink family backed cache.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241
Same as genl_register_family() but additionally registers the specified cache operations using
nl_cache_mngt_register() and associates it with the Generic Net... |
def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HANDLER_REGISTRY
if not isinstance(event, basestring):
# If not basestring, it is a BaseEvent subclass.
# Th... | def function[_register_handler, parameter[event, fun, external]]:
constant[Register a function to be an event handler]
variable[registry] assign[=] name[core].HANDLER_REGISTRY
if name[external] begin[:]
variable[registry] assign[=] name[core].EXTERNAL_HANDLER_REGISTRY
if ... | keyword[def] identifier[_register_handler] ( identifier[event] , identifier[fun] , identifier[external] = keyword[False] ):
literal[string]
identifier[registry] = identifier[core] . identifier[HANDLER_REGISTRY]
keyword[if] identifier[external] :
identifier[registry] = identifier[core] . ide... | def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HANDLER_REGISTRY # depends on [control=['if'], data=[]]
if not isinstance(event, basestring):
# If not basestring, i... |
def long_click(self, x, y):
'''long click at arbitrary coordinates.'''
return self.swipe(x, y, x + 1, y + 1) | def function[long_click, parameter[self, x, y]]:
constant[long click at arbitrary coordinates.]
return[call[name[self].swipe, parameter[name[x], name[y], binary_operation[name[x] + constant[1]], binary_operation[name[y] + constant[1]]]]] | keyword[def] identifier[long_click] ( identifier[self] , identifier[x] , identifier[y] ):
literal[string]
keyword[return] identifier[self] . identifier[swipe] ( identifier[x] , identifier[y] , identifier[x] + literal[int] , identifier[y] + literal[int] ) | def long_click(self, x, y):
"""long click at arbitrary coordinates."""
return self.swipe(x, y, x + 1, y + 1) |
def subscribe_agreement_created(self, agreement_id, timeout, callback, args, wait=False):
"""
Subscribe to an agreement created.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param wait: if true block the listene... | def function[subscribe_agreement_created, parameter[self, agreement_id, timeout, callback, args, wait]]:
constant[
Subscribe to an agreement created.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param wait: if t... | keyword[def] identifier[subscribe_agreement_created] ( identifier[self] , identifier[agreement_id] , identifier[timeout] , identifier[callback] , identifier[args] , identifier[wait] = keyword[False] ):
literal[string]
identifier[logger] . identifier[info] (
literal[string] )
keywo... | def subscribe_agreement_created(self, agreement_id, timeout, callback, args, wait=False):
"""
Subscribe to an agreement created.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param wait: if true block the listener un... |
def to_dict(self):
"""
Returns a dict representation of this instance suitable for
conversion to YAML.
"""
return {
'model_type': 'segmented_regression',
'name': self.name,
'segmentation_col': self.segmentation_col,
'fit_filters': ... | def function[to_dict, parameter[self]]:
constant[
Returns a dict representation of this instance suitable for
conversion to YAML.
]
return[dictionary[[<ast.Constant object at 0x7da18f09d360>, <ast.Constant object at 0x7da18f09d3f0>, <ast.Constant object at 0x7da18f09d9f0>, <ast.Cons... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
keyword[return] {
literal[string] : literal[string] ,
literal[string] : identifier[self] . identifier[name] ,
literal[string] : identifier[self] . identifier[segmentation_col] ,
literal[string... | def to_dict(self):
"""
Returns a dict representation of this instance suitable for
conversion to YAML.
"""
return {'model_type': 'segmented_regression', 'name': self.name, 'segmentation_col': self.segmentation_col, 'fit_filters': self.fit_filters, 'predict_filters': self.predict_filters... |
def integrate(self, wave=None):
"""Integrate the throughput over the specified wavelength set.
If no wavelength set is specified, the built-in one is used.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=throughput``.
Also see :ref:`pys... | def function[integrate, parameter[self, wave]]:
constant[Integrate the throughput over the specified wavelength set.
If no wavelength set is specified, the built-in one is used.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=throughput``.
... | keyword[def] identifier[integrate] ( identifier[self] , identifier[wave] = keyword[None] ):
literal[string]
keyword[if] identifier[wave] keyword[is] keyword[None] :
identifier[wave] = identifier[self] . identifier[wave]
identifier[ans] = identifier[self] . identifier[trap... | def integrate(self, wave=None):
"""Integrate the throughput over the specified wavelength set.
If no wavelength set is specified, the built-in one is used.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=throughput``.
Also see :ref:`pysynph... |
def fetch_recent_submissions(self, max_duration):
"""Fetch recent submissions in subreddit with boundaries.
Does not include posts within the last day as their scores may not be
representative.
:param max_duration: When set, specifies the number of days to include
"""
... | def function[fetch_recent_submissions, parameter[self, max_duration]]:
constant[Fetch recent submissions in subreddit with boundaries.
Does not include posts within the last day as their scores may not be
representative.
:param max_duration: When set, specifies the number of days to in... | keyword[def] identifier[fetch_recent_submissions] ( identifier[self] , identifier[max_duration] ):
literal[string]
keyword[if] identifier[max_duration] :
identifier[self] . identifier[min_date] = identifier[self] . identifier[max_date] - identifier[SECONDS_IN_A_DAY] * identifier[max_d... | def fetch_recent_submissions(self, max_duration):
"""Fetch recent submissions in subreddit with boundaries.
Does not include posts within the last day as their scores may not be
representative.
:param max_duration: When set, specifies the number of days to include
"""
if max_d... |
def render(self, context):
"""Output the content of the `PlaceholdeNode` in the template."""
content = mark_safe(self.get_content_from_context(context))
if not content:
return ''
if self.parsed:
try:
t = template.Template(content, name=self.name)
... | def function[render, parameter[self, context]]:
constant[Output the content of the `PlaceholdeNode` in the template.]
variable[content] assign[=] call[name[mark_safe], parameter[call[name[self].get_content_from_context, parameter[name[context]]]]]
if <ast.UnaryOp object at 0x7da1b1e0ae00> begin[... | keyword[def] identifier[render] ( identifier[self] , identifier[context] ):
literal[string]
identifier[content] = identifier[mark_safe] ( identifier[self] . identifier[get_content_from_context] ( identifier[context] ))
keyword[if] keyword[not] identifier[content] :
keyword[... | def render(self, context):
"""Output the content of the `PlaceholdeNode` in the template."""
content = mark_safe(self.get_content_from_context(context))
if not content:
return '' # depends on [control=['if'], data=[]]
if self.parsed:
try:
t = template.Template(content, name=... |
def _load_tsv_variables(layout, suffix, dataset=None, columns=None,
prepend_type=False, scope='all', **selectors):
''' Reads variables from scans.tsv, sessions.tsv, and participants.tsv.
Args:
layout (BIDSLayout): The BIDSLayout to use.
suffix (str): The suffix of file t... | def function[_load_tsv_variables, parameter[layout, suffix, dataset, columns, prepend_type, scope]]:
constant[ Reads variables from scans.tsv, sessions.tsv, and participants.tsv.
Args:
layout (BIDSLayout): The BIDSLayout to use.
suffix (str): The suffix of file to read from. Must be one of ... | keyword[def] identifier[_load_tsv_variables] ( identifier[layout] , identifier[suffix] , identifier[dataset] = keyword[None] , identifier[columns] = keyword[None] ,
identifier[prepend_type] = keyword[False] , identifier[scope] = literal[string] ,** identifier[selectors] ):
literal[string]
identifier... | def _load_tsv_variables(layout, suffix, dataset=None, columns=None, prepend_type=False, scope='all', **selectors):
""" Reads variables from scans.tsv, sessions.tsv, and participants.tsv.
Args:
layout (BIDSLayout): The BIDSLayout to use.
suffix (str): The suffix of file to read from. Must be one... |
def get_frame(self, idx):
"""Return the frame number of a contour"""
cont = self.data[idx]
frame = int(cont.strip().split(" ", 1)[0])
return frame | def function[get_frame, parameter[self, idx]]:
constant[Return the frame number of a contour]
variable[cont] assign[=] call[name[self].data][name[idx]]
variable[frame] assign[=] call[name[int], parameter[call[call[call[name[cont].strip, parameter[]].split, parameter[constant[ ], constant[1]]]][c... | keyword[def] identifier[get_frame] ( identifier[self] , identifier[idx] ):
literal[string]
identifier[cont] = identifier[self] . identifier[data] [ identifier[idx] ]
identifier[frame] = identifier[int] ( identifier[cont] . identifier[strip] (). identifier[split] ( literal[string] , literal... | def get_frame(self, idx):
"""Return the frame number of a contour"""
cont = self.data[idx]
frame = int(cont.strip().split(' ', 1)[0])
return frame |
def PlayerSeasonFinder(**kwargs):
""" Docstring will be filled in by __init__.py """
if 'offset' not in kwargs:
kwargs['offset'] = 0
playerSeasons = []
while True:
querystring = _kwargs_to_qs(**kwargs)
url = '{}?{}'.format(PSF_URL, querystring)
if kwargs.get('verbose', ... | def function[PlayerSeasonFinder, parameter[]]:
constant[ Docstring will be filled in by __init__.py ]
if compare[constant[offset] <ast.NotIn object at 0x7da2590d7190> name[kwargs]] begin[:]
call[name[kwargs]][constant[offset]] assign[=] constant[0]
variable[playerSeasons] assign[... | keyword[def] identifier[PlayerSeasonFinder] (** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] :
identifier[kwargs] [ literal[string] ]= literal[int]
identifier[playerSeasons] =[]
keyword[while] keyword[True] :
... | def PlayerSeasonFinder(**kwargs):
""" Docstring will be filled in by __init__.py """
if 'offset' not in kwargs:
kwargs['offset'] = 0 # depends on [control=['if'], data=['kwargs']]
playerSeasons = []
while True:
querystring = _kwargs_to_qs(**kwargs)
url = '{}?{}'.format(PSF_URL, ... |
def get_chat_member(self, user_id):
"""
Get information about a member of a chat.
:param int user_id: Unique identifier of the target user
"""
return self.bot.api_call(
"getChatMember", chat_id=str(self.id), user_id=str(user_id)
) | def function[get_chat_member, parameter[self, user_id]]:
constant[
Get information about a member of a chat.
:param int user_id: Unique identifier of the target user
]
return[call[name[self].bot.api_call, parameter[constant[getChatMember]]]] | keyword[def] identifier[get_chat_member] ( identifier[self] , identifier[user_id] ):
literal[string]
keyword[return] identifier[self] . identifier[bot] . identifier[api_call] (
literal[string] , identifier[chat_id] = identifier[str] ( identifier[self] . identifier[id] ), identifier[user_i... | def get_chat_member(self, user_id):
"""
Get information about a member of a chat.
:param int user_id: Unique identifier of the target user
"""
return self.bot.api_call('getChatMember', chat_id=str(self.id), user_id=str(user_id)) |
def fixed_width_binning(data=None, bin_width: Union[float, int] = 1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning:
"""Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
... | def function[fixed_width_binning, parameter[data, bin_width]]:
constant[Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
Must be multiple of bin_width
]
variable[result] assign[=... | keyword[def] identifier[fixed_width_binning] ( identifier[data] = keyword[None] , identifier[bin_width] : identifier[Union] [ identifier[float] , identifier[int] ]= literal[int] ,*, identifier[range] = keyword[None] , identifier[includes_right_edge] = keyword[False] ,** identifier[kwargs] )-> identifier[FixedWidthBin... | def fixed_width_binning(data=None, bin_width: Union[float, int]=1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning:
"""Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
M... |
def get_ordering_field_columns(self):
"""
Returns an OrderedDict of ordering field column numbers and asc/desc
"""
# We must cope with more than one column having the same underlying
# sort field, so we base things on column numbers.
ordering = self._get_default_ordering... | def function[get_ordering_field_columns, parameter[self]]:
constant[
Returns an OrderedDict of ordering field column numbers and asc/desc
]
variable[ordering] assign[=] call[name[self]._get_default_ordering, parameter[]]
variable[ordering_fields] assign[=] call[name[OrderedDict],... | keyword[def] identifier[get_ordering_field_columns] ( identifier[self] ):
literal[string]
identifier[ordering] = identifier[self] . identifier[_get_default_ordering] ()
identifier[ordering_fields] = identifier[OrderedDict] ()
keyword[if] identifier[ORDER_VAR] ... | def get_ordering_field_columns(self):
"""
Returns an OrderedDict of ordering field column numbers and asc/desc
"""
# We must cope with more than one column having the same underlying
# sort field, so we base things on column numbers.
ordering = self._get_default_ordering()
ordering_f... |
def receive_nak_requesting(self, pkt):
"""Receive NAK in REQUESTING state."""
logger.debug("C3.1. Received NAK?, in REQUESTING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in REQUESTING state, "
"raise INIT.")
r... | def function[receive_nak_requesting, parameter[self, pkt]]:
constant[Receive NAK in REQUESTING state.]
call[name[logger].debug, parameter[constant[C3.1. Received NAK?, in REQUESTING state.]]]
if call[name[self].process_received_nak, parameter[name[pkt]]] begin[:]
call[name[logger... | keyword[def] identifier[receive_nak_requesting] ( identifier[self] , identifier[pkt] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identifier[self] . identifier[process_received_nak] ( identifier[pkt] ):
identifier[logger] . identif... | def receive_nak_requesting(self, pkt):
"""Receive NAK in REQUESTING state."""
logger.debug('C3.1. Received NAK?, in REQUESTING state.')
if self.process_received_nak(pkt):
logger.debug('C3.1: T. Received NAK, in REQUESTING state, raise INIT.')
raise self.INIT() # depends on [control=['if'], ... |
def gather_configs(self):
"""
Gather configuration requirements of all plugins
"""
configs = []
for what in self.order:
for key in self.plugins[what]:
mgr = self.plugins[what][key]
c = mgr.config(what='get')
if c is not ... | def function[gather_configs, parameter[self]]:
constant[
Gather configuration requirements of all plugins
]
variable[configs] assign[=] list[[]]
for taget[name[what]] in starred[name[self].order] begin[:]
for taget[name[key]] in starred[call[name[self].plugins][na... | keyword[def] identifier[gather_configs] ( identifier[self] ):
literal[string]
identifier[configs] =[]
keyword[for] identifier[what] keyword[in] identifier[self] . identifier[order] :
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[plugins] [ identi... | def gather_configs(self):
"""
Gather configuration requirements of all plugins
"""
configs = []
for what in self.order:
for key in self.plugins[what]:
mgr = self.plugins[what][key]
c = mgr.config(what='get')
if c is not None:
c.upda... |
def get_location (host):
"""Get translated country and optional city name.
@return: country with optional city or an boolean False if not found
"""
if geoip is None:
# no geoip available
return None
try:
record = get_geoip_record(host)
except (geoip_error, socket.error):... | def function[get_location, parameter[host]]:
constant[Get translated country and optional city name.
@return: country with optional city or an boolean False if not found
]
if compare[name[geoip] is constant[None]] begin[:]
return[constant[None]]
<ast.Try object at 0x7da1b0ab9e10>
... | keyword[def] identifier[get_location] ( identifier[host] ):
literal[string]
keyword[if] identifier[geoip] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[try] :
identifier[record] = identifier[get_geoip_record] ( identifier[host] )
keyword[except] ( i... | def get_location(host):
"""Get translated country and optional city name.
@return: country with optional city or an boolean False if not found
"""
if geoip is None:
# no geoip available
return None # depends on [control=['if'], data=[]]
try:
record = get_geoip_record(host) ... |
def run(self, command, arguments=(), console_mode_stdin=True, skip_cmd_shell=False):
"""This function does something.
:param command: The command to be executed
:type name: str.
:param arguments: A list of arguments to be passed to the command
:type state: str.
:returns: ... | def function[run, parameter[self, command, arguments, console_mode_stdin, skip_cmd_shell]]:
constant[This function does something.
:param command: The command to be executed
:type name: str.
:param arguments: A list of arguments to be passed to the command
:type state: str.
... | keyword[def] identifier[run] ( identifier[self] , identifier[command] , identifier[arguments] =(), identifier[console_mode_stdin] = keyword[True] , identifier[skip_cmd_shell] = keyword[False] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] + identifier[command] )
... | def run(self, command, arguments=(), console_mode_stdin=True, skip_cmd_shell=False):
"""This function does something.
:param command: The command to be executed
:type name: str.
:param arguments: A list of arguments to be passed to the command
:type state: str.
:returns: int... |
def project(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat),
... | def function[project, parameter[self, term_doc_mat, x_dim, y_dim]]:
constant[
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
]
return[call[name[self]._project_category_corpus, parameter[call[name[self]._get_category_me... | keyword[def] identifier[project] ( identifier[self] , identifier[term_doc_mat] , identifier[x_dim] = literal[int] , identifier[y_dim] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_project_category_corpus] ( identifier[self] . identifier[_get_category_metadata_cor... | def project(self, term_doc_mat, x_dim=0, y_dim=1):
"""
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
"""
return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat), x_dim, y_dim) |
def down(self, down_uid):
'''
Download the entity by UID.
'''
down_url = MPost.get_by_uid(down_uid).extinfo.get('tag__file_download', '')
print('=' * 40)
print(down_url)
str_down_url = str(down_url)[15:]
if down_url:
ment_id = MEntity.get_id_... | def function[down, parameter[self, down_uid]]:
constant[
Download the entity by UID.
]
variable[down_url] assign[=] call[call[name[MPost].get_by_uid, parameter[name[down_uid]]].extinfo.get, parameter[constant[tag__file_download], constant[]]]
call[name[print], parameter[binary_op... | keyword[def] identifier[down] ( identifier[self] , identifier[down_uid] ):
literal[string]
identifier[down_url] = identifier[MPost] . identifier[get_by_uid] ( identifier[down_uid] ). identifier[extinfo] . identifier[get] ( literal[string] , literal[string] )
identifier[print] ( literal[str... | def down(self, down_uid):
"""
Download the entity by UID.
"""
down_url = MPost.get_by_uid(down_uid).extinfo.get('tag__file_download', '')
print('=' * 40)
print(down_url)
str_down_url = str(down_url)[15:]
if down_url:
ment_id = MEntity.get_id_by_impath(str_down_url)
... |
def get_lenet():
""" A lenet style net, takes difference of each frame as input.
"""
source = mx.sym.Variable("data")
source = (source - 128) * (1.0/128)
frames = mx.sym.SliceChannel(source, num_outputs=30)
diffs = [frames[i+1] - frames[i] for i in range(29)]
source = mx.sym.Concat(*diffs)
... | def function[get_lenet, parameter[]]:
constant[ A lenet style net, takes difference of each frame as input.
]
variable[source] assign[=] call[name[mx].sym.Variable, parameter[constant[data]]]
variable[source] assign[=] binary_operation[binary_operation[name[source] - constant[128]] * binary_... | keyword[def] identifier[get_lenet] ():
literal[string]
identifier[source] = identifier[mx] . identifier[sym] . identifier[Variable] ( literal[string] )
identifier[source] =( identifier[source] - literal[int] )*( literal[int] / literal[int] )
identifier[frames] = identifier[mx] . identifier[sym] .... | def get_lenet():
""" A lenet style net, takes difference of each frame as input.
"""
source = mx.sym.Variable('data')
source = (source - 128) * (1.0 / 128)
frames = mx.sym.SliceChannel(source, num_outputs=30)
diffs = [frames[i + 1] - frames[i] for i in range(29)]
source = mx.sym.Concat(*diff... |
def create_new_version(
self,
name,
subject,
text='',
template_id=None,
html=None,
locale=None,
timeout=None
):
""" API call to create a new version of a template """
if(html):
payload = {
'name': name,
... | def function[create_new_version, parameter[self, name, subject, text, template_id, html, locale, timeout]]:
constant[ API call to create a new version of a template ]
if name[html] begin[:]
variable[payload] assign[=] dictionary[[<ast.Constant object at 0x7da1aff1e7d0>, <ast.Constant obj... | keyword[def] identifier[create_new_version] (
identifier[self] ,
identifier[name] ,
identifier[subject] ,
identifier[text] = literal[string] ,
identifier[template_id] = keyword[None] ,
identifier[html] = keyword[None] ,
identifier[locale] = keyword[None] ,
identifier[timeout] = keyword[None]
):
lite... | def create_new_version(self, name, subject, text='', template_id=None, html=None, locale=None, timeout=None):
""" API call to create a new version of a template """
if html:
payload = {'name': name, 'subject': subject, 'html': html, 'text': text} # depends on [control=['if'], data=[]]
else:
... |
def _read_serial(self, may_block):
""" Read the serial number from a YubiKey > 2.2. """
frame = yubikey_frame.YubiKeyFrame(command = SLOT.DEVICE_SERIAL)
self._device._write(frame)
response = self._device._read_response(may_block=may_block)
if not yubico_util.validate_crc16(respo... | def function[_read_serial, parameter[self, may_block]]:
constant[ Read the serial number from a YubiKey > 2.2. ]
variable[frame] assign[=] call[name[yubikey_frame].YubiKeyFrame, parameter[]]
call[name[self]._device._write, parameter[name[frame]]]
variable[response] assign[=] call[name[se... | keyword[def] identifier[_read_serial] ( identifier[self] , identifier[may_block] ):
literal[string]
identifier[frame] = identifier[yubikey_frame] . identifier[YubiKeyFrame] ( identifier[command] = identifier[SLOT] . identifier[DEVICE_SERIAL] )
identifier[self] . identifier[_device] . iden... | def _read_serial(self, may_block):
""" Read the serial number from a YubiKey > 2.2. """
frame = yubikey_frame.YubiKeyFrame(command=SLOT.DEVICE_SERIAL)
self._device._write(frame)
response = self._device._read_response(may_block=may_block)
if not yubico_util.validate_crc16(response[:6]):
raise... |
def get_bestfit_line(self, x_min=None, x_max=None, resolution=None):
"""
Method to get bestfit line using the defined
self.bestfit_func method
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x)
... | def function[get_bestfit_line, parameter[self, x_min, x_max, resolution]]:
constant[
Method to get bestfit line using the defined
self.bestfit_func method
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x... | keyword[def] identifier[get_bestfit_line] ( identifier[self] , identifier[x_min] = keyword[None] , identifier[x_max] = keyword[None] , identifier[resolution] = keyword[None] ):
literal[string]
identifier[x] = identifier[self] . identifier[args] [ literal[string] ]
keyword[if] identifier[x... | def get_bestfit_line(self, x_min=None, x_max=None, resolution=None):
"""
Method to get bestfit line using the defined
self.bestfit_func method
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x)
... |
def list_common_lookups(kwargs=None, call=None):
'''
List common lookups for a particular type of item
.. versionadded:: 2015.8.0
'''
if kwargs is None:
kwargs = {}
args = {}
if 'lookup' in kwargs:
args['lookup'] = kwargs['lookup']
response = _query('common', 'lookup/l... | def function[list_common_lookups, parameter[kwargs, call]]:
constant[
List common lookups for a particular type of item
.. versionadded:: 2015.8.0
]
if compare[name[kwargs] is constant[None]] begin[:]
variable[kwargs] assign[=] dictionary[[], []]
variable[args] assig... | keyword[def] identifier[list_common_lookups] ( identifier[kwargs] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[kwargs] keyword[is] keyword[None] :
identifier[kwargs] ={}
identifier[args] ={}
keyword[if] literal[string] keyword[in] id... | def list_common_lookups(kwargs=None, call=None):
"""
List common lookups for a particular type of item
.. versionadded:: 2015.8.0
"""
if kwargs is None:
kwargs = {} # depends on [control=['if'], data=['kwargs']]
args = {}
if 'lookup' in kwargs:
args['lookup'] = kwargs['look... |
def setRoles(self, *args, **kwargs):
"""Adds the role assigned to this user to a 'role' field.
Depends on the 'role' field that comes with a fullDetails=True
build of the MambuUser.
Returns the number of requests done to Mambu.
"""
try:
role = self.mamburole... | def function[setRoles, parameter[self]]:
constant[Adds the role assigned to this user to a 'role' field.
Depends on the 'role' field that comes with a fullDetails=True
build of the MambuUser.
Returns the number of requests done to Mambu.
]
<ast.Try object at 0x7da20c6a91e0>... | keyword[def] identifier[setRoles] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[role] = identifier[self] . identifier[mamburoleclass] ( identifier[entid] = identifier[self] [ literal[string] ][ literal[string] ],* identifier[... | def setRoles(self, *args, **kwargs):
"""Adds the role assigned to this user to a 'role' field.
Depends on the 'role' field that comes with a fullDetails=True
build of the MambuUser.
Returns the number of requests done to Mambu.
"""
try:
role = self.mamburoleclass(*args,... |
def path(self, key):
'''Returns the `path` for given `key`'''
return os.path.join(self.root_path, self.relative_path(key)) | def function[path, parameter[self, key]]:
constant[Returns the `path` for given `key`]
return[call[name[os].path.join, parameter[name[self].root_path, call[name[self].relative_path, parameter[name[key]]]]]] | keyword[def] identifier[path] ( identifier[self] , identifier[key] ):
literal[string]
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[root_path] , identifier[self] . identifier[relative_path] ( identifier[key] )) | def path(self, key):
"""Returns the `path` for given `key`"""
return os.path.join(self.root_path, self.relative_path(key)) |
def get_pyxb(self):
"""Generate a DataONE Exception PyXB object.
The PyXB object supports directly reading and writing the individual values that
may be included in a DataONE Exception.
"""
dataone_exception_pyxb = dataoneErrors.error()
dataone_exception_pyxb.name = sel... | def function[get_pyxb, parameter[self]]:
constant[Generate a DataONE Exception PyXB object.
The PyXB object supports directly reading and writing the individual values that
may be included in a DataONE Exception.
]
variable[dataone_exception_pyxb] assign[=] call[name[dataoneErr... | keyword[def] identifier[get_pyxb] ( identifier[self] ):
literal[string]
identifier[dataone_exception_pyxb] = identifier[dataoneErrors] . identifier[error] ()
identifier[dataone_exception_pyxb] . identifier[name] = identifier[self] . identifier[__class__] . identifier[__name__]
id... | def get_pyxb(self):
"""Generate a DataONE Exception PyXB object.
The PyXB object supports directly reading and writing the individual values that
may be included in a DataONE Exception.
"""
dataone_exception_pyxb = dataoneErrors.error()
dataone_exception_pyxb.name = self.__class__.... |
def weight(weights):
"""
RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS
"""
total = sum(weights)
p = SEED.random()
acc = 0
for i, w in enumerate(weights):
acc += w / total
if p < acc:
return i
return len(weigh... | def function[weight, parameter[weights]]:
constant[
RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS
]
variable[total] assign[=] call[name[sum], parameter[name[weights]]]
variable[p] assign[=] call[name[SEED].random, parameter[]]
variable[acc] assign[=] constant[0]
... | keyword[def] identifier[weight] ( identifier[weights] ):
literal[string]
identifier[total] = identifier[sum] ( identifier[weights] )
identifier[p] = identifier[SEED] . identifier[random] ()
identifier[acc] = literal[int]
keyword[for] identifier[i] , identifier[w] keyw... | def weight(weights):
"""
RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS
"""
total = sum(weights)
p = SEED.random()
acc = 0
for (i, w) in enumerate(weights):
acc += w / total
if p < acc:
return i # depends on [control=['if'], data=[]] # depends on [... |
def cmd_tuneopt(self, args):
'''Select option for Tune Pot on Channel 6 (quadcopter only)'''
usage = "usage: tuneopt <set|show|reset|list>"
if self.mpstate.vehicle_type != 'copter':
print("This command is only available for copter")
return
if len(args) < 1:
... | def function[cmd_tuneopt, parameter[self, args]]:
constant[Select option for Tune Pot on Channel 6 (quadcopter only)]
variable[usage] assign[=] constant[usage: tuneopt <set|show|reset|list>]
if compare[name[self].mpstate.vehicle_type not_equal[!=] constant[copter]] begin[:]
call[... | keyword[def] identifier[cmd_tuneopt] ( identifier[self] , identifier[args] ):
literal[string]
identifier[usage] = literal[string]
keyword[if] identifier[self] . identifier[mpstate] . identifier[vehicle_type] != literal[string] :
identifier[print] ( literal[string] )
... | def cmd_tuneopt(self, args):
"""Select option for Tune Pot on Channel 6 (quadcopter only)"""
usage = 'usage: tuneopt <set|show|reset|list>'
if self.mpstate.vehicle_type != 'copter':
print('This command is only available for copter')
return # depends on [control=['if'], data=[]]
if len(a... |
def reorder_resource_views(self, resource_views):
# type: (List[Union[ResourceView,Dict,str]]) -> None
"""Order resource views in resource.
Args:
resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView obje... | def function[reorder_resource_views, parameter[self, resource_views]]:
constant[Order resource views in resource.
Args:
resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView objects or dictionaries
Retur... | keyword[def] identifier[reorder_resource_views] ( identifier[self] , identifier[resource_views] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[resource_views] , identifier[list] ):
keyword[raise] identifier[HDXError] ( literal[string] )
ide... | def reorder_resource_views(self, resource_views):
# type: (List[Union[ResourceView,Dict,str]]) -> None
'Order resource views in resource.\n\n Args:\n resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView objects or ... |
def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None):
''' Download the PDF copy of the current documents
Args:
signature_request_id (str): Id of the signature request
path_or_file (str or file): A writable File-like objec... | def function[get_signature_request_file, parameter[self, signature_request_id, path_or_file, file_type, filename]]:
constant[ Download the PDF copy of the current documents
Args:
signature_request_id (str): Id of the signature request
path_or_file (str or file): A writable Fil... | keyword[def] identifier[get_signature_request_file] ( identifier[self] , identifier[signature_request_id] , identifier[path_or_file] = keyword[None] , identifier[file_type] = keyword[None] , identifier[filename] = keyword[None] ):
literal[string]
identifier[request] = identifier[self] . identifier[... | def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None):
""" Download the PDF copy of the current documents
Args:
signature_request_id (str): Id of the signature request
path_or_file (str or file): A writable File-like object or... |
def _dataset_report_helper(cls, dataset, catalog_homepage=None):
"""Toma un dict con la metadata de un dataset, y devuelve un dict coni
los valores que dataset_report() usa para reportar sobre él.
Args:
dataset (dict): Diccionario con la metadata de un dataset.
Returns:
... | def function[_dataset_report_helper, parameter[cls, dataset, catalog_homepage]]:
constant[Toma un dict con la metadata de un dataset, y devuelve un dict coni
los valores que dataset_report() usa para reportar sobre él.
Args:
dataset (dict): Diccionario con la metadata de un dataset.... | keyword[def] identifier[_dataset_report_helper] ( identifier[cls] , identifier[dataset] , identifier[catalog_homepage] = keyword[None] ):
literal[string]
identifier[publisher_name] = identifier[helpers] . identifier[traverse_dict] ( identifier[dataset] ,[ literal[string] , literal[string] ])
... | def _dataset_report_helper(cls, dataset, catalog_homepage=None):
"""Toma un dict con la metadata de un dataset, y devuelve un dict coni
los valores que dataset_report() usa para reportar sobre él.
Args:
dataset (dict): Diccionario con la metadata de un dataset.
Returns:
... |
def ResourceEnum(ctx):
"""Resource Type Enumeration."""
return Enum(
ctx,
food=0,
wood=1,
stone=2,
gold=3,
decay=12,
fish=17,
default=Pass # lots of resource types exist
) | def function[ResourceEnum, parameter[ctx]]:
constant[Resource Type Enumeration.]
return[call[name[Enum], parameter[name[ctx]]]] | keyword[def] identifier[ResourceEnum] ( identifier[ctx] ):
literal[string]
keyword[return] identifier[Enum] (
identifier[ctx] ,
identifier[food] = literal[int] ,
identifier[wood] = literal[int] ,
identifier[stone] = literal[int] ,
identifier[gold] = literal[int] ,
identifier[... | def ResourceEnum(ctx):
"""Resource Type Enumeration.""" # lots of resource types exist
return Enum(ctx, food=0, wood=1, stone=2, gold=3, decay=12, fish=17, default=Pass) |
def deriv(self, x: str, ctype: ContentType) -> SchemaPattern:
"""Return derivative of the receiver."""
return (self.pattern.deriv(x, ctype) if self.check_when() else
NotAllowed()) | def function[deriv, parameter[self, x, ctype]]:
constant[Return derivative of the receiver.]
return[<ast.IfExp object at 0x7da1b02e7b80>] | keyword[def] identifier[deriv] ( identifier[self] , identifier[x] : identifier[str] , identifier[ctype] : identifier[ContentType] )-> identifier[SchemaPattern] :
literal[string]
keyword[return] ( identifier[self] . identifier[pattern] . identifier[deriv] ( identifier[x] , identifier[ctype] ) keywor... | def deriv(self, x: str, ctype: ContentType) -> SchemaPattern:
"""Return derivative of the receiver."""
return self.pattern.deriv(x, ctype) if self.check_when() else NotAllowed() |
def get_short_desc(long_desc):
"""Get first sentence of first paragraph of long description."""
found = False
olines = []
for line in [item.rstrip() for item in long_desc.split("\n")]:
if found and (((not line) and (not olines)) or (line and olines)):
olines.append(line)
elif... | def function[get_short_desc, parameter[long_desc]]:
constant[Get first sentence of first paragraph of long description.]
variable[found] assign[=] constant[False]
variable[olines] assign[=] list[[]]
for taget[name[line]] in starred[<ast.ListComp object at 0x7da1b033d3f0>] begin[:]
... | keyword[def] identifier[get_short_desc] ( identifier[long_desc] ):
literal[string]
identifier[found] = keyword[False]
identifier[olines] =[]
keyword[for] identifier[line] keyword[in] [ identifier[item] . identifier[rstrip] () keyword[for] identifier[item] keyword[in] identifier[long_desc] .... | def get_short_desc(long_desc):
"""Get first sentence of first paragraph of long description."""
found = False
olines = []
for line in [item.rstrip() for item in long_desc.split('\n')]:
if found and (not line and (not olines) or (line and olines)):
olines.append(line) # depends on [c... |
def untldict_normalizer(untl_dict, normalizations):
"""Normalize UNTL elements by their qualifier.
Takes a UNTL descriptive metadata dictionary and a dictionary of
the elements and the qualifiers for normalization:
{'element1': ['qualifier1', 'qualifier2'],
'element2': ['qualifier3']}
and norm... | def function[untldict_normalizer, parameter[untl_dict, normalizations]]:
constant[Normalize UNTL elements by their qualifier.
Takes a UNTL descriptive metadata dictionary and a dictionary of
the elements and the qualifiers for normalization:
{'element1': ['qualifier1', 'qualifier2'],
'element2... | keyword[def] identifier[untldict_normalizer] ( identifier[untl_dict] , identifier[normalizations] ):
literal[string]
keyword[for] identifier[element_type] , identifier[element_list] keyword[in] identifier[untl_dict] . identifier[items] ():
keyword[if] identifier[element_type] keywor... | def untldict_normalizer(untl_dict, normalizations):
"""Normalize UNTL elements by their qualifier.
Takes a UNTL descriptive metadata dictionary and a dictionary of
the elements and the qualifiers for normalization:
{'element1': ['qualifier1', 'qualifier2'],
'element2': ['qualifier3']}
and norm... |
def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display. This
function is similar to print_str but will interpret periods not as
characters but as decimal points associated with the previous character.
"""
# Calcu... | def function[print_number_str, parameter[self, value, justify_right]]:
constant[Print a 4 character long string of numeric values to the display. This
function is similar to print_str but will interpret periods not as
characters but as decimal points associated with the previous character.
... | keyword[def] identifier[print_number_str] ( identifier[self] , identifier[value] , identifier[justify_right] = keyword[True] ):
literal[string]
identifier[length] = identifier[len] ( identifier[value] . identifier[translate] ( keyword[None] , literal[string] ))
keyword[if... | def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display. This
function is similar to print_str but will interpret periods not as
characters but as decimal points associated with the previous character.
"""
# Calculate len... |
def start_all(self):
"""
Start all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.start)
yield from pool.join() | def function[start_all, parameter[self]]:
constant[
Start all nodes
]
variable[pool] assign[=] call[name[Pool], parameter[]]
for taget[name[node]] in starred[call[name[self].nodes.values, parameter[]]] begin[:]
call[name[pool].append, parameter[name[node].start]]
... | keyword[def] identifier[start_all] ( identifier[self] ):
literal[string]
identifier[pool] = identifier[Pool] ( identifier[concurrency] = literal[int] )
keyword[for] identifier[node] keyword[in] identifier[self] . identifier[nodes] . identifier[values] ():
identifier[pool] .... | def start_all(self):
"""
Start all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.start) # depends on [control=['for'], data=['node']]
yield from pool.join() |
def as_list_with_options(self):
"""
Similar to list(self) except elements which have an option associated
with them are returned as a ``TListItemWithOption``
"""
it = ROOT.TIter(self)
elem = it.Next()
result = []
while elem:
if it.GetOption():
... | def function[as_list_with_options, parameter[self]]:
constant[
Similar to list(self) except elements which have an option associated
with them are returned as a ``TListItemWithOption``
]
variable[it] assign[=] call[name[ROOT].TIter, parameter[name[self]]]
variable[elem] a... | keyword[def] identifier[as_list_with_options] ( identifier[self] ):
literal[string]
identifier[it] = identifier[ROOT] . identifier[TIter] ( identifier[self] )
identifier[elem] = identifier[it] . identifier[Next] ()
identifier[result] =[]
keyword[while] identifier[elem] :... | def as_list_with_options(self):
"""
Similar to list(self) except elements which have an option associated
with them are returned as a ``TListItemWithOption``
"""
it = ROOT.TIter(self)
elem = it.Next()
result = []
while elem:
if it.GetOption():
result.appen... |
def downgrade(account):
"""Transforms data from v2 format to a v1 format"""
d_account = dict(schema_version=1, metadata={'email': account['email']},
tags=list(set([account['environment']] + account.get('tags', []))))
v1_services = {}
for service in account.get('services', []):
... | def function[downgrade, parameter[account]]:
constant[Transforms data from v2 format to a v1 format]
variable[d_account] assign[=] call[name[dict], parameter[]]
variable[v1_services] assign[=] dictionary[[], []]
for taget[name[service]] in starred[call[name[account].get, parameter[consta... | keyword[def] identifier[downgrade] ( identifier[account] ):
literal[string]
identifier[d_account] = identifier[dict] ( identifier[schema_version] = literal[int] , identifier[metadata] ={ literal[string] : identifier[account] [ literal[string] ]},
identifier[tags] = identifier[list] ( identifier[set] (... | def downgrade(account):
"""Transforms data from v2 format to a v1 format"""
d_account = dict(schema_version=1, metadata={'email': account['email']}, tags=list(set([account['environment']] + account.get('tags', []))))
v1_services = {}
for service in account.get('services', []):
if service['name']... |
def render_search(self, ctx, data):
"""
Render some UI for performing searches, if we know about a search
aggregator.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
searchAggregator = translator.getPageComponen... | def function[render_search, parameter[self, ctx, data]]:
constant[
Render some UI for performing searches, if we know about a search
aggregator.
]
if compare[name[self].username is constant[None]] begin[:]
return[constant[]]
variable[translator] assign[=] call[nam... | keyword[def] identifier[render_search] ( identifier[self] , identifier[ctx] , identifier[data] ):
literal[string]
keyword[if] identifier[self] . identifier[username] keyword[is] keyword[None] :
keyword[return] literal[string]
identifier[translator] = identifier[self] . id... | def render_search(self, ctx, data):
"""
Render some UI for performing searches, if we know about a search
aggregator.
"""
if self.username is None:
return '' # depends on [control=['if'], data=[]]
translator = self._getViewerPrivateApplication()
searchAggregator = transl... |
def get_low_liquidity_transactions(transactions, market_data,
last_n_days=None):
"""
For each traded name, find the daily transaction total that consumed
the greatest proportion of available daily bar volume.
Parameters
----------
transactions : pd.DataFrame
... | def function[get_low_liquidity_transactions, parameter[transactions, market_data, last_n_days]]:
constant[
For each traded name, find the daily transaction total that consumed
the greatest proportion of available daily bar volume.
Parameters
----------
transactions : pd.DataFrame
Pr... | keyword[def] identifier[get_low_liquidity_transactions] ( identifier[transactions] , identifier[market_data] ,
identifier[last_n_days] = keyword[None] ):
literal[string]
identifier[txn_daily_w_bar] = identifier[daily_txns_with_bar_data] ( identifier[transactions] , identifier[market_data] )
identifi... | def get_low_liquidity_transactions(transactions, market_data, last_n_days=None):
"""
For each traded name, find the daily transaction total that consumed
the greatest proportion of available daily bar volume.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of execut... |
def determine_module_class(path, class_path):
"""Determine type of module and return deployment module class."""
if not class_path:
# First check directory name for type-indicating suffix
basename = os.path.basename(path)
if basename.endswith('.sls'):
class_path = 'runway.mod... | def function[determine_module_class, parameter[path, class_path]]:
constant[Determine type of module and return deployment module class.]
if <ast.UnaryOp object at 0x7da1b07630d0> begin[:]
variable[basename] assign[=] call[name[os].path.basename, parameter[name[path]]]
if... | keyword[def] identifier[determine_module_class] ( identifier[path] , identifier[class_path] ):
literal[string]
keyword[if] keyword[not] identifier[class_path] :
identifier[basename] = identifier[os] . identifier[path] . identifier[basename] ( identifier[path] )
keyword[if] identif... | def determine_module_class(path, class_path):
"""Determine type of module and return deployment module class."""
if not class_path:
# First check directory name for type-indicating suffix
basename = os.path.basename(path)
if basename.endswith('.sls'):
class_path = 'runway.mod... |
def _poll_connection(self, fd):
"""Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection
"""
try:
state = self._connections[fd].poll()
... | def function[_poll_connection, parameter[self, fd]]:
constant[Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection
]
<ast.Try object at 0x7da20e74bf40> | keyword[def] identifier[_poll_connection] ( identifier[self] , identifier[fd] ):
literal[string]
keyword[try] :
identifier[state] = identifier[self] . identifier[_connections] [ identifier[fd] ]. identifier[poll] ()
keyword[except] ( identifier[OSError] , identifier[socket] . ... | def _poll_connection(self, fd):
"""Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection
"""
try:
state = self._connections[fd].poll() # depends on [con... |
def filter_user(user, using='records', interaction=None,
part_of_week='allweek', part_of_day='allday'):
"""
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
... | def function[filter_user, parameter[user, using, interaction, part_of_week, part_of_day]]:
constant[
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
'records' or 'r... | keyword[def] identifier[filter_user] ( identifier[user] , identifier[using] = literal[string] , identifier[interaction] = keyword[None] ,
identifier[part_of_week] = literal[string] , identifier[part_of_day] = literal[string] ):
literal[string]
keyword[if] identifier[using] == literal[string] :
... | def filter_user(user, using='records', interaction=None, part_of_week='allweek', part_of_day='allday'):
"""
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
'records' or... |
def parse(self):
""" parse the data
"""
# convert the xlsx file to csv first
delimiter = "|"
csv_file = self.xlsx_to_csv(self.getInputFile(), delimiter=delimiter)
reader = csv.DictReader(csv_file, delimiter=delimiter)
for n, row in enumerate(reader):
... | def function[parse, parameter[self]]:
constant[ parse the data
]
variable[delimiter] assign[=] constant[|]
variable[csv_file] assign[=] call[name[self].xlsx_to_csv, parameter[call[name[self].getInputFile, parameter[]]]]
variable[reader] assign[=] call[name[csv].DictReader, parame... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
identifier[delimiter] = literal[string]
identifier[csv_file] = identifier[self] . identifier[xlsx_to_csv] ( identifier[self] . identifier[getInputFile] (), identifier[delimiter] = identifier[delimiter] )
... | def parse(self):
""" parse the data
"""
# convert the xlsx file to csv first
delimiter = '|'
csv_file = self.xlsx_to_csv(self.getInputFile(), delimiter=delimiter)
reader = csv.DictReader(csv_file, delimiter=delimiter)
for (n, row) in enumerate(reader):
resid = row.get('SampleID',... |
def _run(cmd):
'''
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
'''
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))}) | def function[_run, parameter[cmd]]:
constant[
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
]
return[call[call[name[__salt__]][constant[cmd.run_all]], parameter[name[cmd]]]] | keyword[def] identifier[_run] ( identifier[cmd] ):
literal[string]
keyword[return] identifier[__salt__] [ literal[string] ]( identifier[cmd] , identifier[env] ={ literal[string] : identifier[os] . identifier[path] . identifier[expanduser] ( literal[string] . identifier[format] ( identifier[__opts__] [ lit... | def _run(cmd):
"""
Just a convenience function for ``__salt__['cmd.run_all'](cmd)``
"""
return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))}) |
def set(self):
"""Set the hook."""
if sys.displayhook is not self.hook:
self.old_hook = sys.displayhook
sys.displayhook = self.hook | def function[set, parameter[self]]:
constant[Set the hook.]
if compare[name[sys].displayhook is_not name[self].hook] begin[:]
name[self].old_hook assign[=] name[sys].displayhook
name[sys].displayhook assign[=] name[self].hook | keyword[def] identifier[set] ( identifier[self] ):
literal[string]
keyword[if] identifier[sys] . identifier[displayhook] keyword[is] keyword[not] identifier[self] . identifier[hook] :
identifier[self] . identifier[old_hook] = identifier[sys] . identifier[displayhook]
... | def set(self):
"""Set the hook."""
if sys.displayhook is not self.hook:
self.old_hook = sys.displayhook
sys.displayhook = self.hook # depends on [control=['if'], data=[]] |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
word = split(word) # detect any non-delimited compounds
compound = True if re.search(r'-| |\.', word) else False
syllabify = _syllabify_compound if compound else _syllabify
syll, rules = syllabify(word)
yield syll... | def function[syllabify, parameter[word]]:
constant[Syllabify the given word, whether simplex or complex.]
variable[word] assign[=] call[name[split], parameter[name[word]]]
variable[compound] assign[=] <ast.IfExp object at 0x7da1b11d3250>
variable[syllabify] assign[=] <ast.IfExp object at... | keyword[def] identifier[syllabify] ( identifier[word] ):
literal[string]
identifier[word] = identifier[split] ( identifier[word] )
identifier[compound] = keyword[True] keyword[if] identifier[re] . identifier[search] ( literal[string] , identifier[word] ) keyword[else] keyword[False]
identifie... | def syllabify(word):
"""Syllabify the given word, whether simplex or complex."""
word = split(word) # detect any non-delimited compounds
compound = True if re.search('-| |\\.', word) else False
syllabify = _syllabify_compound if compound else _syllabify
(syll, rules) = syllabify(word)
yield (sy... |
def u_probs(self):
"""Probability P(x_i==1|Non-match) as described in the FS framework."""
log_u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]
return self._prob_inverse_transform(numpy.exp(log_u)) | def function[u_probs, parameter[self]]:
constant[Probability P(x_i==1|Non-match) as described in the FS framework.]
variable[log_u] assign[=] call[name[self].kernel.feature_log_prob_][call[name[self]._nonmatch_class_pos, parameter[]]]
return[call[name[self]._prob_inverse_transform, parameter[call[na... | keyword[def] identifier[u_probs] ( identifier[self] ):
literal[string]
identifier[log_u] = identifier[self] . identifier[kernel] . identifier[feature_log_prob_] [ identifier[self] . identifier[_nonmatch_class_pos] ()]
keyword[return] identifier[self] . identifier[_prob_inverse_transform]... | def u_probs(self):
"""Probability P(x_i==1|Non-match) as described in the FS framework."""
log_u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]
return self._prob_inverse_transform(numpy.exp(log_u)) |
def ms_to_times(ms):
"""
Convert milliseconds to normalized tuple (h, m, s, ms).
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
Should be non-negative.
Returns:
Named tuple (h, m, s, ms) of ints.
Invariants: ``ms in range(1... | def function[ms_to_times, parameter[ms]]:
constant[
Convert milliseconds to normalized tuple (h, m, s, ms).
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
Should be non-negative.
Returns:
Named tuple (h, m, s, ms) of ints.
... | keyword[def] identifier[ms_to_times] ( identifier[ms] ):
literal[string]
identifier[ms] = identifier[int] ( identifier[round] ( identifier[ms] ))
identifier[h] , identifier[ms] = identifier[divmod] ( identifier[ms] , literal[int] )
identifier[m] , identifier[ms] = identifier[divmod] ( identifier[... | def ms_to_times(ms):
"""
Convert milliseconds to normalized tuple (h, m, s, ms).
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
Should be non-negative.
Returns:
Named tuple (h, m, s, ms) of ints.
Invariants: ``ms in range(1... |
def acc_difference(points):
""" Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for before, after in pairwise(points):
data.append(before.acc - after.acc)
... | def function[acc_difference, parameter[points]]:
constant[ Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
]
variable[data] assign[=] list[[<ast.Constant object at 0x7da1b040acb... | keyword[def] identifier[acc_difference] ( identifier[points] ):
literal[string]
identifier[data] =[ literal[int] ]
keyword[for] identifier[before] , identifier[after] keyword[in] identifier[pairwise] ( identifier[points] ):
identifier[data] . identifier[append] ( identifier[before] . ident... | def acc_difference(points):
""" Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for (before, after) in pairwise(points):
data.append(before.acc - after.acc) ... |
def _baton_json_to_irods_entities(self, entities_as_baton_json: List[Dict]) -> List[EntityType]:
"""
Converts the baton representation of multiple iRODS entities to a list of `EntityType` models.
:param entities_as_baton_json: the baton serialization representation of the entities
:retur... | def function[_baton_json_to_irods_entities, parameter[self, entities_as_baton_json]]:
constant[
Converts the baton representation of multiple iRODS entities to a list of `EntityType` models.
:param entities_as_baton_json: the baton serialization representation of the entities
:return: th... | keyword[def] identifier[_baton_json_to_irods_entities] ( identifier[self] , identifier[entities_as_baton_json] : identifier[List] [ identifier[Dict] ])-> identifier[List] [ identifier[EntityType] ]:
literal[string]
keyword[assert] ( identifier[isinstance] ( identifier[entities_as_baton_json] , iden... | def _baton_json_to_irods_entities(self, entities_as_baton_json: List[Dict]) -> List[EntityType]:
"""
Converts the baton representation of multiple iRODS entities to a list of `EntityType` models.
:param entities_as_baton_json: the baton serialization representation of the entities
:return: t... |
def _sync_with_file(self):
"""Clear in-memory structures so table is synced with the file."""
self._records = []
i = -1
for i, line in self._enum_lines():
self._records.append(None)
self._last_synced_index = i | def function[_sync_with_file, parameter[self]]:
constant[Clear in-memory structures so table is synced with the file.]
name[self]._records assign[=] list[[]]
variable[i] assign[=] <ast.UnaryOp object at 0x7da18f58d360>
for taget[tuple[[<ast.Name object at 0x7da18f58cca0>, <ast.Name objec... | keyword[def] identifier[_sync_with_file] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_records] =[]
identifier[i] =- literal[int]
keyword[for] identifier[i] , identifier[line] keyword[in] identifier[self] . identifier[_enum_lines] ():
identi... | def _sync_with_file(self):
"""Clear in-memory structures so table is synced with the file."""
self._records = []
i = -1
for (i, line) in self._enum_lines():
self._records.append(None) # depends on [control=['for'], data=[]]
self._last_synced_index = i |
def make_tuple(obj, cast=True):
"""
Converts an object *obj* to a tuple and returns it. Objects of types *list* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new tuple.
"""
if isinstance(obj, tuple):
return tuple(obj)
elif is_lazy_iter... | def function[make_tuple, parameter[obj, cast]]:
constant[
Converts an object *obj* to a tuple and returns it. Objects of types *list* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new tuple.
]
if call[name[isinstance], parameter[name[obj],... | keyword[def] identifier[make_tuple] ( identifier[obj] , identifier[cast] = keyword[True] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[tuple] ):
keyword[return] identifier[tuple] ( identifier[obj] )
keyword[elif] identifier[is_lazy_iterable] ( identif... | def make_tuple(obj, cast=True):
"""
Converts an object *obj* to a tuple and returns it. Objects of types *list* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new tuple.
"""
if isinstance(obj, tuple):
return tuple(obj) # depends on [contro... |
def to_protobuf(self) -> str:
'''encode vote into protobuf'''
vote = pavoteproto.Vote()
vote.version = self.version
vote.description = self.description
vote.count_mode = vote.MODE.Value(self.count_mode)
vote.start_block = self.start_block
vote.end_block = self.en... | def function[to_protobuf, parameter[self]]:
constant[encode vote into protobuf]
variable[vote] assign[=] call[name[pavoteproto].Vote, parameter[]]
name[vote].version assign[=] name[self].version
name[vote].description assign[=] name[self].description
name[vote].count_mode assign[... | keyword[def] identifier[to_protobuf] ( identifier[self] )-> identifier[str] :
literal[string]
identifier[vote] = identifier[pavoteproto] . identifier[Vote] ()
identifier[vote] . identifier[version] = identifier[self] . identifier[version]
identifier[vote] . identifier[descriptio... | def to_protobuf(self) -> str:
"""encode vote into protobuf"""
vote = pavoteproto.Vote()
vote.version = self.version
vote.description = self.description
vote.count_mode = vote.MODE.Value(self.count_mode)
vote.start_block = self.start_block
vote.end_block = self.end_block
vote.choices.exte... |
async def proposal(self):
"""Get the proposal in question.
Actually just the first proposal with the same name, but the
chance of a collision is tiny.
Returns
-------
awaitable of :class:`aionationstates.Proposal`
The proposal submitted.
Raises
... | <ast.AsyncFunctionDef object at 0x7da1b2749b70> | keyword[async] keyword[def] identifier[proposal] ( identifier[self] ):
literal[string]
identifier[proposals] = keyword[await] identifier[aionationstates] . identifier[wa] . identifier[proposals] ()
keyword[for] identifier[proposal] keyword[in] identifier[proposals] :
keyw... | async def proposal(self):
"""Get the proposal in question.
Actually just the first proposal with the same name, but the
chance of a collision is tiny.
Returns
-------
awaitable of :class:`aionationstates.Proposal`
The proposal submitted.
Raises
... |
def _set_attribute(self, name, value):
"""Make sure namespace gets updated when setting attributes."""
setattr(self, name, value)
self.namespace.update({name: getattr(self, name)}) | def function[_set_attribute, parameter[self, name, value]]:
constant[Make sure namespace gets updated when setting attributes.]
call[name[setattr], parameter[name[self], name[name], name[value]]]
call[name[self].namespace.update, parameter[dictionary[[<ast.Name object at 0x7da1b1cf54b0>], [<ast.... | keyword[def] identifier[_set_attribute] ( identifier[self] , identifier[name] , identifier[value] ):
literal[string]
identifier[setattr] ( identifier[self] , identifier[name] , identifier[value] )
identifier[self] . identifier[namespace] . identifier[update] ({ identifier[name] : identifie... | def _set_attribute(self, name, value):
"""Make sure namespace gets updated when setting attributes."""
setattr(self, name, value)
self.namespace.update({name: getattr(self, name)}) |
def load_by_pub_key(self, public_key):
"""
This method will load a SSHKey object from DigitalOcean
from a public_key. This method will avoid problems like
uploading the same public_key twice.
"""
data = self.get_data("account/keys/")
for jsoned in dat... | def function[load_by_pub_key, parameter[self, public_key]]:
constant[
This method will load a SSHKey object from DigitalOcean
from a public_key. This method will avoid problems like
uploading the same public_key twice.
]
variable[data] assign[=] call[name[self... | keyword[def] identifier[load_by_pub_key] ( identifier[self] , identifier[public_key] ):
literal[string]
identifier[data] = identifier[self] . identifier[get_data] ( literal[string] )
keyword[for] identifier[jsoned] keyword[in] identifier[data] [ literal[string] ]:
keyword[... | def load_by_pub_key(self, public_key):
"""
This method will load a SSHKey object from DigitalOcean
from a public_key. This method will avoid problems like
uploading the same public_key twice.
"""
data = self.get_data('account/keys/')
for jsoned in data['ssh_keys']... |
def append_payment_op(self,
destination,
amount,
asset_code='XLM',
asset_issuer=None,
source=None):
"""Append a :class:`Payment <stellar_base.operation.Payment>` operation
to... | def function[append_payment_op, parameter[self, destination, amount, asset_code, asset_issuer, source]]:
constant[Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations.
:param str destination: Account address that receives the payment.
:param str... | keyword[def] identifier[append_payment_op] ( identifier[self] ,
identifier[destination] ,
identifier[amount] ,
identifier[asset_code] = literal[string] ,
identifier[asset_issuer] = keyword[None] ,
identifier[source] = keyword[None] ):
literal[string]
identifier[asset] = identifier[Asset] ( ide... | def append_payment_op(self, destination, amount, asset_code='XLM', asset_issuer=None, source=None):
"""Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations.
:param str destination: Account address that receives the payment.
:param str amount: The am... |
def put_attachment(self, attachment, content_type, data, headers=None):
"""
Adds a new attachment, or updates an existing attachment, to
the remote document and refreshes the locally cached
Document object accordingly.
:param attachment: Attachment file name used to identify the... | def function[put_attachment, parameter[self, attachment, content_type, data, headers]]:
constant[
Adds a new attachment, or updates an existing attachment, to
the remote document and refreshes the locally cached
Document object accordingly.
:param attachment: Attachment file nam... | keyword[def] identifier[put_attachment] ( identifier[self] , identifier[attachment] , identifier[content_type] , identifier[data] , identifier[headers] = keyword[None] ):
literal[string]
identifier[self] . identifier[fetch] ()
identifier[attachment_url] = literal[string] . identif... | def put_attachment(self, attachment, content_type, data, headers=None):
"""
Adds a new attachment, or updates an existing attachment, to
the remote document and refreshes the locally cached
Document object accordingly.
:param attachment: Attachment file name used to identify the
... |
def is_mod_function(mod, fun):
"""Checks if a function in a module was declared in that module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod: the module
fun: the function
"""
return inspect.isfunction(fun) and inspect.getmodule(fun) == mod | def function[is_mod_function, parameter[mod, fun]]:
constant[Checks if a function in a module was declared in that module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod: the module
fun: the function
]
return[<ast.BoolOp object at 0x7da1b0fe4b80>] | keyword[def] identifier[is_mod_function] ( identifier[mod] , identifier[fun] ):
literal[string]
keyword[return] identifier[inspect] . identifier[isfunction] ( identifier[fun] ) keyword[and] identifier[inspect] . identifier[getmodule] ( identifier[fun] )== identifier[mod] | def is_mod_function(mod, fun):
"""Checks if a function in a module was declared in that module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod: the module
fun: the function
"""
return inspect.isfunction(fun) and inspect.getmodule(fun) == mod |
def phase2radians(phasedata, v0):
""" Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians
"""
fi = [2... | def function[phase2radians, parameter[phasedata, v0]]:
constant[ Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data... | keyword[def] identifier[phase2radians] ( identifier[phasedata] , identifier[v0] ):
literal[string]
identifier[fi] =[ literal[int] * identifier[np] . identifier[pi] * identifier[v0] * identifier[xx] keyword[for] identifier[xx] keyword[in] identifier[phasedata] ]
keyword[return] identifier[fi] | def phase2radians(phasedata, v0):
""" Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians
"""
fi = [2... |
def list_tokens(opts):
'''
List all tokens in the store.
:param opts: Salt master config options
:returns: List of dicts (token_data)
'''
ret = []
redis_client = _redis_client(opts)
if not redis_client:
return []
serial = salt.payload.Serial(opts)
try:
return [k.... | def function[list_tokens, parameter[opts]]:
constant[
List all tokens in the store.
:param opts: Salt master config options
:returns: List of dicts (token_data)
]
variable[ret] assign[=] list[[]]
variable[redis_client] assign[=] call[name[_redis_client], parameter[name[opts]]]
... | keyword[def] identifier[list_tokens] ( identifier[opts] ):
literal[string]
identifier[ret] =[]
identifier[redis_client] = identifier[_redis_client] ( identifier[opts] )
keyword[if] keyword[not] identifier[redis_client] :
keyword[return] []
identifier[serial] = identifier[salt] . i... | def list_tokens(opts):
"""
List all tokens in the store.
:param opts: Salt master config options
:returns: List of dicts (token_data)
"""
ret = []
redis_client = _redis_client(opts)
if not redis_client:
return [] # depends on [control=['if'], data=[]]
serial = salt.payload.... |
def memberness(context):
'''The likelihood that the context is a "member".'''
if context:
texts = context.xpath('.//*[local-name()="explicitMember"]/text()').extract()
text = str(texts).lower()
if len(texts) > 1:
return 2
elif 'country' in text:
return 2
... | def function[memberness, parameter[context]]:
constant[The likelihood that the context is a "member".]
if name[context] begin[:]
variable[texts] assign[=] call[call[name[context].xpath, parameter[constant[.//*[local-name()="explicitMember"]/text()]]].extract, parameter[]]
... | keyword[def] identifier[memberness] ( identifier[context] ):
literal[string]
keyword[if] identifier[context] :
identifier[texts] = identifier[context] . identifier[xpath] ( literal[string] ). identifier[extract] ()
identifier[text] = identifier[str] ( identifier[texts] ). identifier[lowe... | def memberness(context):
"""The likelihood that the context is a "member"."""
if context:
texts = context.xpath('.//*[local-name()="explicitMember"]/text()').extract()
text = str(texts).lower()
if len(texts) > 1:
return 2 # depends on [control=['if'], data=[]]
elif '... |
def datetime(self):
'分钟线结构返回datetime 日线结构返回date'
index = self.data.index.remove_unused_levels()
return pd.to_datetime(index.levels[0]) | def function[datetime, parameter[self]]:
constant[分钟线结构返回datetime 日线结构返回date]
variable[index] assign[=] call[name[self].data.index.remove_unused_levels, parameter[]]
return[call[name[pd].to_datetime, parameter[call[name[index].levels][constant[0]]]]] | keyword[def] identifier[datetime] ( identifier[self] ):
literal[string]
identifier[index] = identifier[self] . identifier[data] . identifier[index] . identifier[remove_unused_levels] ()
keyword[return] identifier[pd] . identifier[to_datetime] ( identifier[index] . identifier[levels] [ lit... | def datetime(self):
"""分钟线结构返回datetime 日线结构返回date"""
index = self.data.index.remove_unused_levels()
return pd.to_datetime(index.levels[0]) |
def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope,
reuse):
"""
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for th... | def function[create_vector_observation_encoder, parameter[observation_input, h_size, activation, num_layers, scope, reuse]]:
constant[
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
... | keyword[def] identifier[create_vector_observation_encoder] ( identifier[observation_input] , identifier[h_size] , identifier[activation] , identifier[num_layers] , identifier[scope] ,
identifier[reuse] ):
literal[string]
keyword[with] identifier[tf] . identifier[variable_scope] ( identifier[scope... | def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope, reuse):
"""
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_inpu... |
def get_assessment_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the assessment query service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentQuerySession) - an
``AssessmentQuerySession``
raise: NullArgument - ``pr... | def function[get_assessment_query_session, parameter[self, proxy]]:
constant[Gets the ``OsidSession`` associated with the assessment query service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentQuerySession) - an
``AssessmentQuerySession``
... | keyword[def] identifier[get_assessment_query_session] ( identifier[self] , identifier[proxy] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_assessment_query] ():
keyword[raise] identifier[errors] . identifier[Unimplemented] ()
... | def get_assessment_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the assessment query service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentQuerySession) - an
``AssessmentQuerySession``
raise: NullArgument - ``proxy`... |
def configure_app(app):
"""Configure Flask/Celery application.
* Rio will find environment variable `RIO_SETTINGS` first::
$ export RIO_SETTINGS=/path/to/settings.cfg
$ rio worker
* If `RIO_SETTINGS` is missing, Rio will try to load configuration
module in `rio.settings` according t... | def function[configure_app, parameter[app]]:
constant[Configure Flask/Celery application.
* Rio will find environment variable `RIO_SETTINGS` first::
$ export RIO_SETTINGS=/path/to/settings.cfg
$ rio worker
* If `RIO_SETTINGS` is missing, Rio will try to load configuration
modul... | keyword[def] identifier[configure_app] ( identifier[app] ):
literal[string]
identifier[app] . identifier[config_from_object] ( literal[string] )
keyword[if] identifier[environ] . identifier[get] ( literal[string] ):
identifier[app] . identifier[config_from_envvar] ( literal[string] )
... | def configure_app(app):
"""Configure Flask/Celery application.
* Rio will find environment variable `RIO_SETTINGS` first::
$ export RIO_SETTINGS=/path/to/settings.cfg
$ rio worker
* If `RIO_SETTINGS` is missing, Rio will try to load configuration
module in `rio.settings` according t... |
def xmlSetup(self, logType, logList):
"""Create xml file with fields from logbook form."""
from xml.etree.ElementTree import Element, SubElement, ElementTree
from datetime import datetime
curr_time = datetime.now()
if logType == "MCC":
# Set up xml t... | def function[xmlSetup, parameter[self, logType, logList]]:
constant[Create xml file with fields from logbook form.]
from relative_module[xml.etree.ElementTree] import module[Element], module[SubElement], module[ElementTree]
from relative_module[datetime] import module[datetime]
variable[curr_tim... | keyword[def] identifier[xmlSetup] ( identifier[self] , identifier[logType] , identifier[logList] ):
literal[string]
keyword[from] identifier[xml] . identifier[etree] . identifier[ElementTree] keyword[import] identifier[Element] , identifier[SubElement] , identifier[ElementTree]
keywor... | def xmlSetup(self, logType, logList):
"""Create xml file with fields from logbook form."""
from xml.etree.ElementTree import Element, SubElement, ElementTree
from datetime import datetime
curr_time = datetime.now()
if logType == 'MCC':
# Set up xml tags
log_entry = Element('log_entry... |
def _process_rval_components(self):
"""This is suspiciously similar to _process_macro_default_arg, probably
want to figure out how to merge the two.
Process the rval of an assignment statement or a do-block
"""
while True:
match = self._expect_match(
... | def function[_process_rval_components, parameter[self]]:
constant[This is suspiciously similar to _process_macro_default_arg, probably
want to figure out how to merge the two.
Process the rval of an assignment statement or a do-block
]
while constant[True] begin[:]
... | keyword[def] identifier[_process_rval_components] ( identifier[self] ):
literal[string]
keyword[while] keyword[True] :
identifier[match] = identifier[self] . identifier[_expect_match] (
literal[string] ,
identifier[STRING_PATTERN] ,
... | def _process_rval_components(self):
"""This is suspiciously similar to _process_macro_default_arg, probably
want to figure out how to merge the two.
Process the rval of an assignment statement or a do-block
"""
while True:
# you could have a string, though that would be weird
... |
def setup_actions(self):
""" Connects slots to signals """
self.actionOpen.triggered.connect(self.on_open)
self.actionNew.triggered.connect(self.on_new)
self.actionSave.triggered.connect(self.on_save)
self.actionSave_as.triggered.connect(self.on_save_as)
self.actionQuit.t... | def function[setup_actions, parameter[self]]:
constant[ Connects slots to signals ]
call[name[self].actionOpen.triggered.connect, parameter[name[self].on_open]]
call[name[self].actionNew.triggered.connect, parameter[name[self].on_new]]
call[name[self].actionSave.triggered.connect, parame... | keyword[def] identifier[setup_actions] ( identifier[self] ):
literal[string]
identifier[self] . identifier[actionOpen] . identifier[triggered] . identifier[connect] ( identifier[self] . identifier[on_open] )
identifier[self] . identifier[actionNew] . identifier[triggered] . identifier[conn... | def setup_actions(self):
""" Connects slots to signals """
self.actionOpen.triggered.connect(self.on_open)
self.actionNew.triggered.connect(self.on_new)
self.actionSave.triggered.connect(self.on_save)
self.actionSave_as.triggered.connect(self.on_save_as)
self.actionQuit.triggered.connect(QtWidge... |
def initialize_repo(self):
"""
Clones repository & sets up usernames.
"""
logging.info('Repo {} doesn\'t exist. Cloning...'.format(self.repo_dir))
clone_args = ['git', 'clone']
if self.depth and self.depth > 0:
clone_args.extend(['--depth', str(self.depth)])
... | def function[initialize_repo, parameter[self]]:
constant[
Clones repository & sets up usernames.
]
call[name[logging].info, parameter[call[constant[Repo {} doesn't exist. Cloning...].format, parameter[name[self].repo_dir]]]]
variable[clone_args] assign[=] list[[<ast.Constant obje... | keyword[def] identifier[initialize_repo] ( identifier[self] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[self] . identifier[repo_dir] ))
identifier[clone_args] =[ literal[string] , literal[string] ]
keyword[if] ide... | def initialize_repo(self):
"""
Clones repository & sets up usernames.
"""
logging.info("Repo {} doesn't exist. Cloning...".format(self.repo_dir))
clone_args = ['git', 'clone']
if self.depth and self.depth > 0:
clone_args.extend(['--depth', str(self.depth)]) # depends on [control... |
def react(reactor, main, argv):
"""
Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should take as
many arguments... | def function[react, parameter[reactor, main, argv]]:
constant[
Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should... | keyword[def] identifier[react] ( identifier[reactor] , identifier[main] , identifier[argv] ):
literal[string]
identifier[stopping] =[]
identifier[reactor] . identifier[addSystemEventTrigger] ( literal[string] , literal[string] , identifier[stopping] . identifier[append] , keyword[True] )
identifi... | def react(reactor, main, argv):
"""
Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should take as
many arguments... |
def p_idcall_expr(p):
""" func_call : ID arg_list %prec UMINUS
""" # This can be a function call or a string index
p[0] = make_call(p[1], p.lineno(1), p[2])
if p[0] is None:
return
if p[0].token in ('STRSLICE', 'VAR', 'STRING'):
entry = SYMBOL_TABLE.access_call(p[1], p.lineno(1))
... | def function[p_idcall_expr, parameter[p]]:
constant[ func_call : ID arg_list %prec UMINUS
]
call[name[p]][constant[0]] assign[=] call[name[make_call], parameter[call[name[p]][constant[1]], call[name[p].lineno, parameter[constant[1]]], call[name[p]][constant[2]]]]
if compare[call[name[p]][con... | keyword[def] identifier[p_idcall_expr] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[make_call] ( identifier[p] [ literal[int] ], identifier[p] . identifier[lineno] ( literal[int] ), identifier[p] [ literal[int] ])
keyword[if] identifier[p] [ literal[int] ] keyword[is]... | def p_idcall_expr(p):
""" func_call : ID arg_list %prec UMINUS
""" # This can be a function call or a string index
p[0] = make_call(p[1], p.lineno(1), p[2])
if p[0] is None:
return # depends on [control=['if'], data=[]]
if p[0].token in ('STRSLICE', 'VAR', 'STRING'):
entry = SYMBOL... |
def __flags(self):
"""
Internal method. Turns arguments into flags.
"""
flags = []
if self._capture:
flags.append("-capture")
if self._spy:
flags.append("-spy")
if self._dbpath:
flags += ["-db-path", self._dbpath]
fl... | def function[__flags, parameter[self]]:
constant[
Internal method. Turns arguments into flags.
]
variable[flags] assign[=] list[[]]
if name[self]._capture begin[:]
call[name[flags].append, parameter[constant[-capture]]]
if name[self]._spy begin[:]
... | keyword[def] identifier[__flags] ( identifier[self] ):
literal[string]
identifier[flags] =[]
keyword[if] identifier[self] . identifier[_capture] :
identifier[flags] . identifier[append] ( literal[string] )
keyword[if] identifier[self] . identifier[_spy] :
... | def __flags(self):
"""
Internal method. Turns arguments into flags.
"""
flags = []
if self._capture:
flags.append('-capture') # depends on [control=['if'], data=[]]
if self._spy:
flags.append('-spy') # depends on [control=['if'], data=[]]
if self._dbpath:
fl... |
def __find_column(self, column_names, part_first_line):
"""
Finds the column for the column_name in sar type definition,
and returns its index.
:param column_names: Names of the column we look for (regex) put in
the list
:param part_first_line: First line ... | def function[__find_column, parameter[self, column_names, part_first_line]]:
constant[
Finds the column for the column_name in sar type definition,
and returns its index.
:param column_names: Names of the column we look for (regex) put in
the list
:param p... | keyword[def] identifier[__find_column] ( identifier[self] , identifier[column_names] , identifier[part_first_line] ):
literal[string]
identifier[part_parts] = identifier[part_first_line] . identifier[split] ()
identifier[return_dict] ={}
identifier[counter] = ... | def __find_column(self, column_names, part_first_line):
"""
Finds the column for the column_name in sar type definition,
and returns its index.
:param column_names: Names of the column we look for (regex) put in
the list
:param part_first_line: First line of t... |
def unzipper(filename, dir_tmp):
"""
Unzip .lpd file contents to tmp directory.
:param str filename: filename.lpd
:param str dir_tmp: Tmp folder to extract contents to
:return None:
"""
logger_zips.info("enter unzip")
# Unzip contents to the tmp directory
try:
with zipfile.Zi... | def function[unzipper, parameter[filename, dir_tmp]]:
constant[
Unzip .lpd file contents to tmp directory.
:param str filename: filename.lpd
:param str dir_tmp: Tmp folder to extract contents to
:return None:
]
call[name[logger_zips].info, parameter[constant[enter unzip]]]
<ast.T... | keyword[def] identifier[unzipper] ( identifier[filename] , identifier[dir_tmp] ):
literal[string]
identifier[logger_zips] . identifier[info] ( literal[string] )
keyword[try] :
keyword[with] identifier[zipfile] . identifier[ZipFile] ( identifier[filename] ) keyword[as] identifier[f] :
... | def unzipper(filename, dir_tmp):
"""
Unzip .lpd file contents to tmp directory.
:param str filename: filename.lpd
:param str dir_tmp: Tmp folder to extract contents to
:return None:
"""
logger_zips.info('enter unzip')
# Unzip contents to the tmp directory
try:
with zipfile.Zi... |
def environ(self):
"""
Add path_info to the request's META dictionary.
"""
environ = dict(self._request.META)
environ['PATH_INFO'] = self._request.path_info
return environ | def function[environ, parameter[self]]:
constant[
Add path_info to the request's META dictionary.
]
variable[environ] assign[=] call[name[dict], parameter[name[self]._request.META]]
call[name[environ]][constant[PATH_INFO]] assign[=] name[self]._request.path_info
return[name[e... | keyword[def] identifier[environ] ( identifier[self] ):
literal[string]
identifier[environ] = identifier[dict] ( identifier[self] . identifier[_request] . identifier[META] )
identifier[environ] [ literal[string] ]= identifier[self] . identifier[_request] . identifier[path_info]
... | def environ(self):
"""
Add path_info to the request's META dictionary.
"""
environ = dict(self._request.META)
environ['PATH_INFO'] = self._request.path_info
return environ |
def grant(self, fail_on_found=False, **kwargs):
"""Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a r... | def function[grant, parameter[self, fail_on_found]]:
constant[Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a ... | keyword[def] identifier[grant] ( identifier[self] , identifier[fail_on_found] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[role_write] ( identifier[fail_on_found] = identifier[fail_on_found] ,** identifier[kwargs] ) | def grant(self, fail_on_found=False, **kwargs):
"""Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a role.... |
def connections(self, hotspot=None):
"""
Returns a list of all the connection instances that are in this scene.
:return <list> [ <XNodeConnection>, .. ]
"""
cons = self.findItems(XNodeConnection)
if hotspot is not None:
filt = lambda ... | def function[connections, parameter[self, hotspot]]:
constant[
Returns a list of all the connection instances that are in this scene.
:return <list> [ <XNodeConnection>, .. ]
]
variable[cons] assign[=] call[name[self].findItems, parameter[name[XNodeConne... | keyword[def] identifier[connections] ( identifier[self] , identifier[hotspot] = keyword[None] ):
literal[string]
identifier[cons] = identifier[self] . identifier[findItems] ( identifier[XNodeConnection] )
keyword[if] identifier[hotspot] keyword[is] keyword[not] keyword[None] :
... | def connections(self, hotspot=None):
"""
Returns a list of all the connection instances that are in this scene.
:return <list> [ <XNodeConnection>, .. ]
"""
cons = self.findItems(XNodeConnection)
if hotspot is not None:
filt = lambda x: hotspot in (x... |
def upd_textures(self, *args):
"""Create one :class:`SwatchButton` for each texture"""
if self.canvas is None:
Clock.schedule_once(self.upd_textures, 0)
return
for name in list(self.swatches.keys()):
if name not in self.atlas.textures:
self.rem... | def function[upd_textures, parameter[self]]:
constant[Create one :class:`SwatchButton` for each texture]
if compare[name[self].canvas is constant[None]] begin[:]
call[name[Clock].schedule_once, parameter[name[self].upd_textures, constant[0]]]
return[None]
for taget[name[n... | keyword[def] identifier[upd_textures] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[self] . identifier[canvas] keyword[is] keyword[None] :
identifier[Clock] . identifier[schedule_once] ( identifier[self] . identifier[upd_textures] , literal[int] )
... | def upd_textures(self, *args):
"""Create one :class:`SwatchButton` for each texture"""
if self.canvas is None:
Clock.schedule_once(self.upd_textures, 0)
return # depends on [control=['if'], data=[]]
for name in list(self.swatches.keys()):
if name not in self.atlas.textures:
... |
def _authn_response(self, in_response_to, consumer_url,
sp_entity_id, identity=None, name_id=None,
status=None, authn=None, issuer=None, policy=None,
sign_assertion=False, sign_response=False,
best_effort=False, encrypt_asse... | def function[_authn_response, parameter[self, in_response_to, consumer_url, sp_entity_id, identity, name_id, status, authn, issuer, policy, sign_assertion, sign_response, best_effort, encrypt_assertion, encrypt_cert_advice, encrypt_cert_assertion, authn_statement, encrypt_assertion_self_contained, encrypted_advice_attr... | keyword[def] identifier[_authn_response] ( identifier[self] , identifier[in_response_to] , identifier[consumer_url] ,
identifier[sp_entity_id] , identifier[identity] = keyword[None] , identifier[name_id] = keyword[None] ,
identifier[status] = keyword[None] , identifier[authn] = keyword[None] , identifier[issuer] = ... | def _authn_response(self, in_response_to, consumer_url, sp_entity_id, identity=None, name_id=None, status=None, authn=None, issuer=None, policy=None, sign_assertion=False, sign_response=False, best_effort=False, encrypt_assertion=False, encrypt_cert_advice=None, encrypt_cert_assertion=None, authn_statement=None, encryp... |
def remove_sources(self, sources):
""" Remove sources from the decomposition.
This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and
connectivity estimates.
Parameters
----------
sources : {slice, int, array of ints}
... | def function[remove_sources, parameter[self, sources]]:
constant[ Remove sources from the decomposition.
This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and
connectivity estimates.
Parameters
----------
sources : {s... | keyword[def] identifier[remove_sources] ( identifier[self] , identifier[sources] ):
literal[string]
keyword[if] identifier[self] . identifier[unmixing_] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[mixing_] keyword[is] keyword[None] :
keyword[raise] ident... | def remove_sources(self, sources):
""" Remove sources from the decomposition.
This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and
connectivity estimates.
Parameters
----------
sources : {slice, int, array of ints}
... |
def setdefault(self, key, default=None):
"""
If *key* is in the dictionary, return its value. If not, insert *key*
with a value of *default* and return *default*. *default* defaults to
``None``.
"""
if key in self:
return self[key]
else:
... | def function[setdefault, parameter[self, key, default]]:
constant[
If *key* is in the dictionary, return its value. If not, insert *key*
with a value of *default* and return *default*. *default* defaults to
``None``.
]
if compare[name[key] in name[self]] begin[:]
... | keyword[def] identifier[setdefault] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] :
keyword[return] identifier[self] [ identifier[key] ]
keyword[else] :
id... | def setdefault(self, key, default=None):
"""
If *key* is in the dictionary, return its value. If not, insert *key*
with a value of *default* and return *default*. *default* defaults to
``None``.
"""
if key in self:
return self[key] # depends on [control=['if'], data=['... |
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
scope ... | def function[get_redirect_args, parameter[self, request, callback]]:
constant[Get request parameters for redirect url.]
variable[callback] assign[=] call[name[request].build_absolute_uri, parameter[name[callback]]]
variable[args] assign[=] dictionary[[<ast.Constant object at 0x7da1b26a5ea0>, <as... | keyword[def] identifier[get_redirect_args] ( identifier[self] , identifier[request] , identifier[callback] ):
literal[string]
identifier[callback] = identifier[request] . identifier[build_absolute_uri] ( identifier[callback] )
identifier[args] ={
literal[string] : identifier[self]... | def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = request.build_absolute_uri(callback)
args = {'client_id': self.consumer_key, 'redirect_uri': callback, 'response_type': 'code'}
scope = self.get_scope(request)
if scope:
args['scope'] = ... |
def calculate_statistics(self):
"Jam some data through to generate statistics"
rev_ids = range(0, 100, 1)
feature_values = zip(rev_ids, [0] * 100)
scores = [self.score(f) for f in feature_values]
labels = [s['prediction'] for s in scores]
statistics = Classification(label... | def function[calculate_statistics, parameter[self]]:
constant[Jam some data through to generate statistics]
variable[rev_ids] assign[=] call[name[range], parameter[constant[0], constant[100], constant[1]]]
variable[feature_values] assign[=] call[name[zip], parameter[name[rev_ids], binary_operati... | keyword[def] identifier[calculate_statistics] ( identifier[self] ):
literal[string]
identifier[rev_ids] = identifier[range] ( literal[int] , literal[int] , literal[int] )
identifier[feature_values] = identifier[zip] ( identifier[rev_ids] ,[ literal[int] ]* literal[int] )
identifie... | def calculate_statistics(self):
"""Jam some data through to generate statistics"""
rev_ids = range(0, 100, 1)
feature_values = zip(rev_ids, [0] * 100)
scores = [self.score(f) for f in feature_values]
labels = [s['prediction'] for s in scores]
statistics = Classification(labels, threshold_ndigits... |
def reply_inform(self, inform, orig_req):
"""Send an inform as part of the reply to an earlier request.
Parameters
----------
inform : Message object
The inform message to send.
orig_req : Message object
The request message being replied to. The inform me... | def function[reply_inform, parameter[self, inform, orig_req]]:
constant[Send an inform as part of the reply to an earlier request.
Parameters
----------
inform : Message object
The inform message to send.
orig_req : Message object
The request message bein... | keyword[def] identifier[reply_inform] ( identifier[self] , identifier[inform] , identifier[orig_req] ):
literal[string]
keyword[assert] ( identifier[inform] . identifier[mtype] == identifier[Message] . identifier[INFORM] )
keyword[assert] ( identifier[inform] . identifier[name] == identifi... | def reply_inform(self, inform, orig_req):
"""Send an inform as part of the reply to an earlier request.
Parameters
----------
inform : Message object
The inform message to send.
orig_req : Message object
The request message being replied to. The inform messag... |
def create_data(datatype='ChanTime', n_trial=1, s_freq=256,
chan_name=None, n_chan=8,
time=None, freq=None, start_time=None,
signal='random', amplitude=1, color=0, sine_freq=10,
attr=None):
"""Create data of different datatype from scratch.
Parame... | def function[create_data, parameter[datatype, n_trial, s_freq, chan_name, n_chan, time, freq, start_time, signal, amplitude, color, sine_freq, attr]]:
constant[Create data of different datatype from scratch.
Parameters
----------
datatype : str
one of 'ChanTime', 'ChanFreq', 'ChanTimeFreq'
... | keyword[def] identifier[create_data] ( identifier[datatype] = literal[string] , identifier[n_trial] = literal[int] , identifier[s_freq] = literal[int] ,
identifier[chan_name] = keyword[None] , identifier[n_chan] = literal[int] ,
identifier[time] = keyword[None] , identifier[freq] = keyword[None] , identifier[start_... | def create_data(datatype='ChanTime', n_trial=1, s_freq=256, chan_name=None, n_chan=8, time=None, freq=None, start_time=None, signal='random', amplitude=1, color=0, sine_freq=10, attr=None):
"""Create data of different datatype from scratch.
Parameters
----------
datatype : str
one of 'ChanTime'... |
def metadata_and_language_from_option_line(self, line):
"""Parse code options on the given line. When a start of a code cell
is found, self.metadata is set to a dictionary."""
if self.start_code_re.match(line):
self.language, self.metadata = self.options_to_metadata(self.start_code_r... | def function[metadata_and_language_from_option_line, parameter[self, line]]:
constant[Parse code options on the given line. When a start of a code cell
is found, self.metadata is set to a dictionary.]
if call[name[self].start_code_re.match, parameter[name[line]]] begin[:]
<ast.Tu... | keyword[def] identifier[metadata_and_language_from_option_line] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] identifier[self] . identifier[start_code_re] . identifier[match] ( identifier[line] ):
identifier[self] . identifier[language] , identifier[self] . iden... | def metadata_and_language_from_option_line(self, line):
"""Parse code options on the given line. When a start of a code cell
is found, self.metadata is set to a dictionary."""
if self.start_code_re.match(line):
(self.language, self.metadata) = self.options_to_metadata(self.start_code_re.findall(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.