code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _get_pool(name=None, session=None):
'''
Get XEN resource pool object reference
'''
if session is None:
session = _get_session()
pools = session.xenapi.pool.get_all()
for pool in pools:
pool_record = session.xenapi.pool.get_record(pool)
if name in pool_record.get('name... | def function[_get_pool, parameter[name, session]]:
constant[
Get XEN resource pool object reference
]
if compare[name[session] is constant[None]] begin[:]
variable[session] assign[=] call[name[_get_session], parameter[]]
variable[pools] assign[=] call[name[session].xenapi... | keyword[def] identifier[_get_pool] ( identifier[name] = keyword[None] , identifier[session] = keyword[None] ):
literal[string]
keyword[if] identifier[session] keyword[is] keyword[None] :
identifier[session] = identifier[_get_session] ()
identifier[pools] = identifier[session] . identifier[... | def _get_pool(name=None, session=None):
"""
Get XEN resource pool object reference
"""
if session is None:
session = _get_session() # depends on [control=['if'], data=['session']]
pools = session.xenapi.pool.get_all()
for pool in pools:
pool_record = session.xenapi.pool.get_reco... |
def start_dashboard(self):
"""Start the dashboard."""
stdout_file, stderr_file = self.new_log_files("dashboard", True)
self._webui_url, process_info = ray.services.start_dashboard(
self.redis_address,
self._temp_dir,
stdout_file=stdout_file,
stderr... | def function[start_dashboard, parameter[self]]:
constant[Start the dashboard.]
<ast.Tuple object at 0x7da18eb54160> assign[=] call[name[self].new_log_files, parameter[constant[dashboard], constant[True]]]
<ast.Tuple object at 0x7da18eb579d0> assign[=] call[name[ray].services.start_dashboard, par... | keyword[def] identifier[start_dashboard] ( identifier[self] ):
literal[string]
identifier[stdout_file] , identifier[stderr_file] = identifier[self] . identifier[new_log_files] ( literal[string] , keyword[True] )
identifier[self] . identifier[_webui_url] , identifier[process_info] = identif... | def start_dashboard(self):
"""Start the dashboard."""
(stdout_file, stderr_file) = self.new_log_files('dashboard', True)
(self._webui_url, process_info) = ray.services.start_dashboard(self.redis_address, self._temp_dir, stdout_file=stdout_file, stderr_file=stderr_file, redis_password=self._ray_params.redis_... |
def delete(self):
"""Delete the Router."""
if lib.EnvDeleteRouter(self._env, self._name.encode()) == 0:
raise RuntimeError("Unable to delete router %s" % self._name) | def function[delete, parameter[self]]:
constant[Delete the Router.]
if compare[call[name[lib].EnvDeleteRouter, parameter[name[self]._env, call[name[self]._name.encode, parameter[]]]] equal[==] constant[0]] begin[:]
<ast.Raise object at 0x7da18f58f6d0> | keyword[def] identifier[delete] ( identifier[self] ):
literal[string]
keyword[if] identifier[lib] . identifier[EnvDeleteRouter] ( identifier[self] . identifier[_env] , identifier[self] . identifier[_name] . identifier[encode] ())== literal[int] :
keyword[raise] identifier[RuntimeErro... | def delete(self):
"""Delete the Router."""
if lib.EnvDeleteRouter(self._env, self._name.encode()) == 0:
raise RuntimeError('Unable to delete router %s' % self._name) # depends on [control=['if'], data=[]] |
def bootstrap_falsealarmprob(lspinfo,
times,
mags,
errs,
nbootstrap=250,
magsarefluxes=False,
sigclip=10.0,
npeaks=No... | def function[bootstrap_falsealarmprob, parameter[lspinfo, times, mags, errs, nbootstrap, magsarefluxes, sigclip, npeaks]]:
constant[Calculates the false alarm probabilities of periodogram peaks using
bootstrap resampling of the magnitude time series.
The false alarm probability here is defined as::
... | keyword[def] identifier[bootstrap_falsealarmprob] ( identifier[lspinfo] ,
identifier[times] ,
identifier[mags] ,
identifier[errs] ,
identifier[nbootstrap] = literal[int] ,
identifier[magsarefluxes] = keyword[False] ,
identifier[sigclip] = literal[int] ,
identifier[npeaks] = keyword[None] ):
literal[string... | def bootstrap_falsealarmprob(lspinfo, times, mags, errs, nbootstrap=250, magsarefluxes=False, sigclip=10.0, npeaks=None):
"""Calculates the false alarm probabilities of periodogram peaks using
bootstrap resampling of the magnitude time series.
The false alarm probability here is defined as::
(1.0 ... |
def _on_permission_result(self, code, perms, results):
""" Handles a permission request result by passing it to the
handler with the given code.
"""
#: Get the handler for this request
handler = self._permission_requests.get(code, None)
if handler is not None:
... | def function[_on_permission_result, parameter[self, code, perms, results]]:
constant[ Handles a permission request result by passing it to the
handler with the given code.
]
variable[handler] assign[=] call[name[self]._permission_requests.get, parameter[name[code], constant[No... | keyword[def] identifier[_on_permission_result] ( identifier[self] , identifier[code] , identifier[perms] , identifier[results] ):
literal[string]
identifier[handler] = identifier[self] . identifier[_permission_requests] . identifier[get] ( identifier[code] , keyword[None] )
keywor... | def _on_permission_result(self, code, perms, results):
""" Handles a permission request result by passing it to the
handler with the given code.
"""
#: Get the handler for this request
handler = self._permission_requests.get(code, None)
if handler is not None:
del self... |
def config_attributes(self):
"""
Helper method used by TorConfig when generating a torrc file.
"""
rtn = [('HiddenServiceDir', str(self.dir))]
if self.conf._supports['HiddenServiceDirGroupReadable'] \
and self.group_readable:
rtn.append(('HiddenServiceDirG... | def function[config_attributes, parameter[self]]:
constant[
Helper method used by TorConfig when generating a torrc file.
]
variable[rtn] assign[=] list[[<ast.Tuple object at 0x7da20e9b1ea0>]]
if <ast.BoolOp object at 0x7da20e9b1600> begin[:]
call[name[rtn].append... | keyword[def] identifier[config_attributes] ( identifier[self] ):
literal[string]
identifier[rtn] =[( literal[string] , identifier[str] ( identifier[self] . identifier[dir] ))]
keyword[if] identifier[self] . identifier[conf] . identifier[_supports] [ literal[string] ] keyword[and] identi... | def config_attributes(self):
"""
Helper method used by TorConfig when generating a torrc file.
"""
rtn = [('HiddenServiceDir', str(self.dir))]
if self.conf._supports['HiddenServiceDirGroupReadable'] and self.group_readable:
rtn.append(('HiddenServiceDirGroupReadable', str(1))) # dep... |
def graph(data):
"""Draws graph of rating vs episode number"""
title = data['name'] + ' (' + data['rating'] + ') '
plt.title(title)
plt.xlabel('Episode Number')
plt.ylabel('Ratings')
rf,ef=graphdata(data)
col=['red', 'green' , 'orange']
for i in range(len(rf)):
x,y=ef[i],rf[i]
... | def function[graph, parameter[data]]:
constant[Draws graph of rating vs episode number]
variable[title] assign[=] binary_operation[binary_operation[binary_operation[call[name[data]][constant[name]] + constant[ (]] + call[name[data]][constant[rating]]] + constant[) ]]
call[name[plt].title, parame... | keyword[def] identifier[graph] ( identifier[data] ):
literal[string]
identifier[title] = identifier[data] [ literal[string] ]+ literal[string] + identifier[data] [ literal[string] ]+ literal[string]
identifier[plt] . identifier[title] ( identifier[title] )
identifier[plt] . identifier[xlabel] ( ... | def graph(data):
"""Draws graph of rating vs episode number"""
title = data['name'] + ' (' + data['rating'] + ') '
plt.title(title)
plt.xlabel('Episode Number')
plt.ylabel('Ratings')
(rf, ef) = graphdata(data)
col = ['red', 'green', 'orange']
for i in range(len(rf)):
(x, y) = (ef... |
def ddp_frames_from_message(self, message):
"""Yield DDP messages from a raw WebSocket message."""
# parse message set
try:
msgs = ejson.loads(message)
except ValueError:
self.reply(
'error', error=400, reason='Data is not valid EJSON',
... | def function[ddp_frames_from_message, parameter[self, message]]:
constant[Yield DDP messages from a raw WebSocket message.]
<ast.Try object at 0x7da1b26ae290>
if <ast.UnaryOp object at 0x7da1b26afd60> begin[:]
call[name[self].reply, parameter[constant[error]]]
<ast.Raise obje... | keyword[def] identifier[ddp_frames_from_message] ( identifier[self] , identifier[message] ):
literal[string]
keyword[try] :
identifier[msgs] = identifier[ejson] . identifier[loads] ( identifier[message] )
keyword[except] identifier[ValueError] :
identifi... | def ddp_frames_from_message(self, message):
"""Yield DDP messages from a raw WebSocket message."""
# parse message set
try:
msgs = ejson.loads(message) # depends on [control=['try'], data=[]]
except ValueError:
self.reply('error', error=400, reason='Data is not valid EJSON')
rai... |
def quote_as2name(unquoted_name):
"""
Function converts as2 name from unquoted to quoted format
:param unquoted_name: the as2 name in unquoted format
:return: the as2 name in unquoted format
"""
if re.search(r'[\\" ]', unquoted_name, re.M):
return '"' + email.utils.quote(unquoted_name) ... | def function[quote_as2name, parameter[unquoted_name]]:
constant[
Function converts as2 name from unquoted to quoted format
:param unquoted_name: the as2 name in unquoted format
:return: the as2 name in unquoted format
]
if call[name[re].search, parameter[constant[[\\" ]], name[unquoted_n... | keyword[def] identifier[quote_as2name] ( identifier[unquoted_name] ):
literal[string]
keyword[if] identifier[re] . identifier[search] ( literal[string] , identifier[unquoted_name] , identifier[re] . identifier[M] ):
keyword[return] literal[string] + identifier[email] . identifier[utils] . ident... | def quote_as2name(unquoted_name):
"""
Function converts as2 name from unquoted to quoted format
:param unquoted_name: the as2 name in unquoted format
:return: the as2 name in unquoted format
"""
if re.search('[\\\\" ]', unquoted_name, re.M):
return '"' + email.utils.quote(unquoted_name) ... |
def egress(self, envelope, http_headers, operation, binding_options):
"""Overrides the egress function ror request logging.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An... | def function[egress, parameter[self, envelope, http_headers, operation, binding_options]]:
constant[Overrides the egress function ror request logging.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation inst... | keyword[def] identifier[egress] ( identifier[self] , identifier[envelope] , identifier[http_headers] , identifier[operation] , identifier[binding_options] ):
literal[string]
keyword[if] identifier[self] . identifier[_logger] . identifier[isEnabledFor] ( identifier[logging] . identifier[INFO] ):
ide... | def egress(self, envelope, http_headers, operation, binding_options):
"""Overrides the egress function ror request logging.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An... |
def emojis(self):
"""Retrieves a dictionary of all of the emojis that GitHub supports.
:returns: dictionary where the key is what would be in between the
colons and the value is the URL to the image, e.g., ::
{
'+1': 'https://github.global.ssl.fastly.net... | def function[emojis, parameter[self]]:
constant[Retrieves a dictionary of all of the emojis that GitHub supports.
:returns: dictionary where the key is what would be in between the
colons and the value is the URL to the image, e.g., ::
{
'+1': 'https://g... | keyword[def] identifier[emojis] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[_build_url] ( literal[string] )
keyword[return] identifier[self] . identifier[_json] ( identifier[self] . identifier[_get] ( identifier[url] ), literal[int] ) | def emojis(self):
"""Retrieves a dictionary of all of the emojis that GitHub supports.
:returns: dictionary where the key is what would be in between the
colons and the value is the URL to the image, e.g., ::
{
'+1': 'https://github.global.ssl.fastly.net/ima... |
def login_required(func):
"""
A wrapper around the flask_login.login_required.
But it also checks the presence of the decorator: @no_login_required
On a "@login_required" class, method containing "@no_login_required" will
still be able to access without authentication
:param func:
:return:
... | def function[login_required, parameter[func]]:
constant[
A wrapper around the flask_login.login_required.
But it also checks the presence of the decorator: @no_login_required
On a "@login_required" class, method containing "@no_login_required" will
still be able to access without authentication
... | keyword[def] identifier[login_required] ( identifier[func] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[func] )
keyword[def] identifier[decorated_view] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] literal[string] keyword[not] keyword[in] identif... | def login_required(func):
"""
A wrapper around the flask_login.login_required.
But it also checks the presence of the decorator: @no_login_required
On a "@login_required" class, method containing "@no_login_required" will
still be able to access without authentication
:param func:
:return:
... |
def _proper_namespace(self, owner=None, app=None, sharing=None):
"""Produce a namespace sans wildcards for use in entity requests.
This method tries to fill in the fields of the namespace which are `None`
or wildcard (`'-'`) from the entity's namespace. If that fails, it uses
the servic... | def function[_proper_namespace, parameter[self, owner, app, sharing]]:
constant[Produce a namespace sans wildcards for use in entity requests.
This method tries to fill in the fields of the namespace which are `None`
or wildcard (`'-'`) from the entity's namespace. If that fails, it uses
... | keyword[def] identifier[_proper_namespace] ( identifier[self] , identifier[owner] = keyword[None] , identifier[app] = keyword[None] , identifier[sharing] = keyword[None] ):
literal[string]
keyword[if] identifier[owner] keyword[is] keyword[None] keyword[and] identifier[app] keyword[is] keywor... | def _proper_namespace(self, owner=None, app=None, sharing=None):
"""Produce a namespace sans wildcards for use in entity requests.
This method tries to fill in the fields of the namespace which are `None`
or wildcard (`'-'`) from the entity's namespace. If that fails, it uses
the service's ... |
def wait_for_host(self, host):
"""Throttle requests to one host."""
t = time.time()
if host in self.times:
due_time = self.times[host]
if due_time > t:
wait = due_time - t
time.sleep(wait)
t = time.time()
wait_time =... | def function[wait_for_host, parameter[self, host]]:
constant[Throttle requests to one host.]
variable[t] assign[=] call[name[time].time, parameter[]]
if compare[name[host] in name[self].times] begin[:]
variable[due_time] assign[=] call[name[self].times][name[host]]
... | keyword[def] identifier[wait_for_host] ( identifier[self] , identifier[host] ):
literal[string]
identifier[t] = identifier[time] . identifier[time] ()
keyword[if] identifier[host] keyword[in] identifier[self] . identifier[times] :
identifier[due_time] = identifier[self] . i... | def wait_for_host(self, host):
"""Throttle requests to one host."""
t = time.time()
if host in self.times:
due_time = self.times[host]
if due_time > t:
wait = due_time - t
time.sleep(wait)
t = time.time() # depends on [control=['if'], data=['due_time', 't... |
def get_queryset(self, raw_query=False):
# Call the base implementation
if not self.haystack:
queryset = super(GenList, self).get_queryset()
else:
queryset = SearchQuerySet().models(self.model)
# Optional tweak methods
Mfields = None
MlimitQ = Non... | def function[get_queryset, parameter[self, raw_query]]:
if <ast.UnaryOp object at 0x7da1b0d04ca0> begin[:]
variable[queryset] assign[=] call[call[name[super], parameter[name[GenList], name[self]]].get_queryset, parameter[]]
variable[Mfields] assign[=] constant[None]
variable[Mlim... | keyword[def] identifier[get_queryset] ( identifier[self] , identifier[raw_query] = keyword[False] ):
keyword[if] keyword[not] identifier[self] . identifier[haystack] :
identifier[queryset] = identifier[super] ( identifier[GenList] , identifier[self] ). identifier[get_queryset] ()
key... | def get_queryset(self, raw_query=False):
# Call the base implementation
if not self.haystack:
queryset = super(GenList, self).get_queryset() # depends on [control=['if'], data=[]]
else:
queryset = SearchQuerySet().models(self.model)
# Optional tweak methods
Mfields = None
Mlimit... |
def find_serial_devices(serial_matcher="ED"):
"""
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
"""
objWMIService = win32com.client... | def function[find_serial_devices, parameter[serial_matcher]]:
constant[
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
]
var... | keyword[def] identifier[find_serial_devices] ( identifier[serial_matcher] = literal[string] ):
literal[string]
identifier[objWMIService] = identifier[win32com] . identifier[client] . identifier[Dispatch] ( literal[string] )
identifier[objSWbemServices] = identifier[objWMIService] . identifier[ConnectS... | def find_serial_devices(serial_matcher='ED'):
"""
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
"""
objWMIService = win32com.client... |
def increase_verbosity():
"""
Increase the verbosity of the root handler by one defined level.
Understands custom logging levels like defined by my ``verboselogs``
module.
"""
defined_levels = sorted(set(find_defined_levels().values()))
current_index = defined_levels.index(get_level())
... | def function[increase_verbosity, parameter[]]:
constant[
Increase the verbosity of the root handler by one defined level.
Understands custom logging levels like defined by my ``verboselogs``
module.
]
variable[defined_levels] assign[=] call[name[sorted], parameter[call[name[set], parame... | keyword[def] identifier[increase_verbosity] ():
literal[string]
identifier[defined_levels] = identifier[sorted] ( identifier[set] ( identifier[find_defined_levels] (). identifier[values] ()))
identifier[current_index] = identifier[defined_levels] . identifier[index] ( identifier[get_level] ())
id... | def increase_verbosity():
"""
Increase the verbosity of the root handler by one defined level.
Understands custom logging levels like defined by my ``verboselogs``
module.
"""
defined_levels = sorted(set(find_defined_levels().values()))
current_index = defined_levels.index(get_level())
... |
def go_through_dict(key, d, setdefault=None):
"""
Split up the `key` by . and get the value from the base dictionary `d`
Parameters
----------
key: str
The key in the `config` configuration. %(get_value_note)s
d: dict
The configuration dictionary containing the key
setdefaul... | def function[go_through_dict, parameter[key, d, setdefault]]:
constant[
Split up the `key` by . and get the value from the base dictionary `d`
Parameters
----------
key: str
The key in the `config` configuration. %(get_value_note)s
d: dict
The configuration dictionary contai... | keyword[def] identifier[go_through_dict] ( identifier[key] , identifier[d] , identifier[setdefault] = keyword[None] ):
literal[string]
identifier[patt] = identifier[re] . identifier[compile] ( literal[string] )
identifier[sub_d] = identifier[d]
identifier[splitted] = identifier[patt] . identifie... | def go_through_dict(key, d, setdefault=None):
"""
Split up the `key` by . and get the value from the base dictionary `d`
Parameters
----------
key: str
The key in the `config` configuration. %(get_value_note)s
d: dict
The configuration dictionary containing the key
setdefaul... |
def hydrate_time(nanoseconds, tz=None):
""" Hydrator for `Time` and `LocalTime` values.
:param nanoseconds:
:param tz:
:return: Time
"""
seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000))
minutes, seconds = map(int, divmod(seconds, 60))
hours, minutes = map(int, divmod(min... | def function[hydrate_time, parameter[nanoseconds, tz]]:
constant[ Hydrator for `Time` and `LocalTime` values.
:param nanoseconds:
:param tz:
:return: Time
]
<ast.Tuple object at 0x7da18f09d5a0> assign[=] call[name[map], parameter[name[int], call[name[divmod], parameter[name[nanoseconds]... | keyword[def] identifier[hydrate_time] ( identifier[nanoseconds] , identifier[tz] = keyword[None] ):
literal[string]
identifier[seconds] , identifier[nanoseconds] = identifier[map] ( identifier[int] , identifier[divmod] ( identifier[nanoseconds] , literal[int] ))
identifier[minutes] , identifier[second... | def hydrate_time(nanoseconds, tz=None):
""" Hydrator for `Time` and `LocalTime` values.
:param nanoseconds:
:param tz:
:return: Time
"""
(seconds, nanoseconds) = map(int, divmod(nanoseconds, 1000000000))
(minutes, seconds) = map(int, divmod(seconds, 60))
(hours, minutes) = map(int, divm... |
def unpack_data(cls, argument_count, payload):
"""Unpack payload by splitting up the raw payload into list of locator_ids
:param argument_count: number of locator_ids in payload is equal to argument_count
:param payload: BytesIO instance with list of concatenated locator_ids, where each locator_... | def function[unpack_data, parameter[cls, argument_count, payload]]:
constant[Unpack payload by splitting up the raw payload into list of locator_ids
:param argument_count: number of locator_ids in payload is equal to argument_count
:param payload: BytesIO instance with list of concatenated locat... | keyword[def] identifier[unpack_data] ( identifier[cls] , identifier[argument_count] , identifier[payload] ):
literal[string]
identifier[pl] = identifier[payload] . identifier[read] ()
identifier[locator_ids] =[ identifier[pl] [ identifier[start] : identifier[start] + literal[int] ] keyword... | def unpack_data(cls, argument_count, payload):
"""Unpack payload by splitting up the raw payload into list of locator_ids
:param argument_count: number of locator_ids in payload is equal to argument_count
:param payload: BytesIO instance with list of concatenated locator_ids, where each locator_id i... |
def map_region(self, addr, length, permissions, init_zero=False):
"""
Map a number of pages at address `addr` with permissions `permissions`.
:param addr: address to map the pages at
:param length: length in bytes of region to map, will be rounded upwards to the page size
:param ... | def function[map_region, parameter[self, addr, length, permissions, init_zero]]:
constant[
Map a number of pages at address `addr` with permissions `permissions`.
:param addr: address to map the pages at
:param length: length in bytes of region to map, will be rounded upwards to the page... | keyword[def] identifier[map_region] ( identifier[self] , identifier[addr] , identifier[length] , identifier[permissions] , identifier[init_zero] = keyword[False] ):
literal[string]
identifier[l] . identifier[info] ( literal[string] , identifier[addr] , identifier[addr] + identifier[length] - litera... | def map_region(self, addr, length, permissions, init_zero=False):
"""
Map a number of pages at address `addr` with permissions `permissions`.
:param addr: address to map the pages at
:param length: length in bytes of region to map, will be rounded upwards to the page size
:param perm... |
def _CheckPythonVersionAndDisableWarnings(self):
"""Checks python version, and disables SSL warnings.
urllib3 will warn on each HTTPS request made by older versions of Python.
Rather than spamming the user, we print one warning message, then disable
warnings in urllib3.
"""
if self._checked_for... | def function[_CheckPythonVersionAndDisableWarnings, parameter[self]]:
constant[Checks python version, and disables SSL warnings.
urllib3 will warn on each HTTPS request made by older versions of Python.
Rather than spamming the user, we print one warning message, then disable
warnings in urllib3.
... | keyword[def] identifier[_CheckPythonVersionAndDisableWarnings] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_checked_for_old_python_version] :
keyword[return]
keyword[if] identifier[sys] . identifier[version_info] [ literal[int] : literal[int] ]<( literal[i... | def _CheckPythonVersionAndDisableWarnings(self):
"""Checks python version, and disables SSL warnings.
urllib3 will warn on each HTTPS request made by older versions of Python.
Rather than spamming the user, we print one warning message, then disable
warnings in urllib3.
"""
if self._checked_for... |
def get_working_path(self):
"""
Gets the working path. If the path starts with a ~, this will be replaced by the current user's home path.
:return:
"""
self.set_section('Files')
raw_path = self.option("working_path")
if raw_path.startswith('~'):
raw_pa... | def function[get_working_path, parameter[self]]:
constant[
Gets the working path. If the path starts with a ~, this will be replaced by the current user's home path.
:return:
]
call[name[self].set_section, parameter[constant[Files]]]
variable[raw_path] assign[=] call[name... | keyword[def] identifier[get_working_path] ( identifier[self] ):
literal[string]
identifier[self] . identifier[set_section] ( literal[string] )
identifier[raw_path] = identifier[self] . identifier[option] ( literal[string] )
keyword[if] identifier[raw_path] . identifier[startswith... | def get_working_path(self):
"""
Gets the working path. If the path starts with a ~, this will be replaced by the current user's home path.
:return:
"""
self.set_section('Files')
raw_path = self.option('working_path')
if raw_path.startswith('~'):
raw_path = os.path.expandu... |
def parse_buffer(stream, separator=None):
"""
Returns a dictionary of the lines of a stream, an array of rows of the
stream (split by separator), and an array of the columns of the stream
(also split by separator)
:param stream:
:param separator:
:return: dict
"""
rows = []
li... | def function[parse_buffer, parameter[stream, separator]]:
constant[
Returns a dictionary of the lines of a stream, an array of rows of the
stream (split by separator), and an array of the columns of the stream
(also split by separator)
:param stream:
:param separator:
:return: dict
... | keyword[def] identifier[parse_buffer] ( identifier[stream] , identifier[separator] = keyword[None] ):
literal[string]
identifier[rows] =[]
identifier[lines] =[]
keyword[for] identifier[line] , identifier[row] keyword[in] identifier[parse_lines] ( identifier[stream] , identifier[separator] ):
... | def parse_buffer(stream, separator=None):
"""
Returns a dictionary of the lines of a stream, an array of rows of the
stream (split by separator), and an array of the columns of the stream
(also split by separator)
:param stream:
:param separator:
:return: dict
"""
rows = []
li... |
def char_on_predicate(compiler, cont, test):
'''return current char and step if @test succeed, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
test = test.interlang()
text = compiler.new_var(il.C... | def function[char_on_predicate, parameter[compiler, cont, test]]:
constant[return current char and step if @test succeed, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function]
variable[test] assign[... | keyword[def] identifier[char_on_predicate] ( identifier[compiler] , identifier[cont] , identifier[test] ):
literal[string]
identifier[test] = identifier[test] . identifier[interlang] ()
identifier[text] = identifier[compiler] . identifier[new_var] ( identifier[il] . identifier[ConstLocalVar] ( literal[st... | def char_on_predicate(compiler, cont, test):
"""return current char and step if @test succeed, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function"""
test = test.interlang()
text = compiler.new_var(il.... |
def decision_function(self, X):
""" Predict confidence scores for samples.
The confidence score for a sample is the signed distance of that
sample to the hyperplane.
Args:
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
Samples.
Returns:
array, shape=(n_samples,) if n_classes == ... | def function[decision_function, parameter[self, X]]:
constant[ Predict confidence scores for samples.
The confidence score for a sample is the signed distance of that
sample to the hyperplane.
Args:
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
Samples.
Returns:
array, sh... | keyword[def] identifier[decision_function] ( identifier[self] , identifier[X] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[or] identifier[self] . identifier[coef_] keyword[is] keyword[None] :
keyword[raise] identifier[NotFittedError] (... | def decision_function(self, X):
""" Predict confidence scores for samples.
The confidence score for a sample is the signed distance of that
sample to the hyperplane.
Args:
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
Samples.
Returns:
array, shape=(n_samples,) if n_classes =... |
def query(cls, name, type_=Type.String, description=None, required=None, default=None,
minimum=None, maximum=None, enum=None, **options):
"""
Define a query parameter
"""
if minimum is not None and maximum is not None and minimum > maximum:
raise ValueError("Min... | def function[query, parameter[cls, name, type_, description, required, default, minimum, maximum, enum]]:
constant[
Define a query parameter
]
if <ast.BoolOp object at 0x7da20c6a9fc0> begin[:]
<ast.Raise object at 0x7da1b26adde0>
return[call[name[cls], parameter[name[name], n... | keyword[def] identifier[query] ( identifier[cls] , identifier[name] , identifier[type_] = identifier[Type] . identifier[String] , identifier[description] = keyword[None] , identifier[required] = keyword[None] , identifier[default] = keyword[None] ,
identifier[minimum] = keyword[None] , identifier[maximum] = keyword[... | def query(cls, name, type_=Type.String, description=None, required=None, default=None, minimum=None, maximum=None, enum=None, **options):
"""
Define a query parameter
"""
if minimum is not None and maximum is not None and (minimum > maximum):
raise ValueError('Minimum must be less than o... |
def update_pagenumber(self):
"""300 page number."""
pages = record_get_field_instances(self.record, '300')
for field in pages:
for idx, (key, value) in enumerate(field[0]):
if key == 'a':
field[0][idx] = ('a', "{0} p".format(value)) | def function[update_pagenumber, parameter[self]]:
constant[300 page number.]
variable[pages] assign[=] call[name[record_get_field_instances], parameter[name[self].record, constant[300]]]
for taget[name[field]] in starred[name[pages]] begin[:]
for taget[tuple[[<ast.Name object at ... | keyword[def] identifier[update_pagenumber] ( identifier[self] ):
literal[string]
identifier[pages] = identifier[record_get_field_instances] ( identifier[self] . identifier[record] , literal[string] )
keyword[for] identifier[field] keyword[in] identifier[pages] :
keyword[for... | def update_pagenumber(self):
"""300 page number."""
pages = record_get_field_instances(self.record, '300')
for field in pages:
for (idx, (key, value)) in enumerate(field[0]):
if key == 'a':
field[0][idx] = ('a', '{0} p'.format(value)) # depends on [control=['if'], data=[... |
def get_language_from_json(language, key):
"""Finds the given language in a json file."""
file_name = os.path.join(
os.path.dirname(__file__),
'languages',
'{0}.json').format(key.lower())
if os.path.exists(file_name):
try:
with open(file_name, 'r', encoding='utf... | def function[get_language_from_json, parameter[language, key]]:
constant[Finds the given language in a json file.]
variable[file_name] assign[=] call[call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[__file__]]], constant[languages], constant[{0}.json]]].format, parameter[cal... | keyword[def] identifier[get_language_from_json] ( identifier[language] , identifier[key] ):
literal[string]
identifier[file_name] = identifier[os] . identifier[path] . identifier[join] (
identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ),
literal[string] ,
lite... | def get_language_from_json(language, key):
"""Finds the given language in a json file."""
file_name = os.path.join(os.path.dirname(__file__), 'languages', '{0}.json').format(key.lower())
if os.path.exists(file_name):
try:
with open(file_name, 'r', encoding='utf-8') as fh:
... |
def patch_namespaced_deployment_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_deployment_scale # noqa: E501
partially update scale of the specified Deployment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronou... | def function[patch_namespaced_deployment_scale, parameter[self, name, namespace, body]]:
constant[patch_namespaced_deployment_scale # noqa: E501
partially update scale of the specified Deployment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchro... | keyword[def] identifier[patch_namespaced_deployment_scale] ( identifier[self] , identifier[name] , identifier[namespace] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( l... | def patch_namespaced_deployment_scale(self, name, namespace, body, **kwargs): # noqa: E501
"patch_namespaced_deployment_scale # noqa: E501\n\n partially update scale of the specified Deployment # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous ... |
def delete_contacts(
self,
ids: List[int]
):
"""Use this method to delete contacts from your Telegram address book.
Args:
ids (List of ``int``):
A list of unique identifiers for the target users.
Can be an ID (int), a username (string) or ... | def function[delete_contacts, parameter[self, ids]]:
constant[Use this method to delete contacts from your Telegram address book.
Args:
ids (List of ``int``):
A list of unique identifiers for the target users.
Can be an ID (int), a username (string) or phone ... | keyword[def] identifier[delete_contacts] (
identifier[self] ,
identifier[ids] : identifier[List] [ identifier[int] ]
):
literal[string]
identifier[contacts] =[]
keyword[for] identifier[i] keyword[in] identifier[ids] :
keyword[try] :
identifier[input_user... | def delete_contacts(self, ids: List[int]):
"""Use this method to delete contacts from your Telegram address book.
Args:
ids (List of ``int``):
A list of unique identifiers for the target users.
Can be an ID (int), a username (string) or phone number (string).
... |
def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain ... | def function[read_external_annotation, parameter[fn]]:
constant[Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should hav... | keyword[def] identifier[read_external_annotation] ( identifier[fn] ):
literal[string]
keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[fn] )
identifier[extDF] = identifier[pd] . identifier[read_table] ( identifier[fn] , identifier[index_col] = literal[int] , identif... | def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain ... |
def write(self, s):
"""Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
"""
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.... | def function[write, parameter[self, s]]:
constant[Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
]
variable[should_write_s] assign[=] compare[call[name[os].getenv, parameter[constant[PRO... | keyword[def] identifier[write] ( identifier[self] , identifier[s] ):
literal[string]
identifier[should_write_s] = identifier[os] . identifier[getenv] ( literal[string] )!= literal[string]
keyword[if] identifier[should_write_s] :
identifier[self] . identifier[_stream] . ident... | def write(self, s):
"""Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
"""
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != 'True'
if should_write_s:
self._stream.write(s) # depe... |
def to_dicts(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> List[dict]:
"""From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which... | def function[to_dicts, parameter[self, ignore_none, force_value, ignore_empty]]:
constant[From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inherited if True
... | keyword[def] identifier[to_dicts] ( identifier[self] , identifier[ignore_none] : identifier[bool] = keyword[True] , identifier[force_value] : identifier[bool] = keyword[True] , identifier[ignore_empty] : identifier[bool] = keyword[False] )-> identifier[List] [ identifier[dict] ]:
literal[string]
ke... | def to_dicts(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> List[dict]:
"""From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inh... |
def _send_stream_features(self):
"""Send stream <features/>.
[receiving entity only]"""
self.features = self._make_stream_features()
self._write_element(self.features) | def function[_send_stream_features, parameter[self]]:
constant[Send stream <features/>.
[receiving entity only]]
name[self].features assign[=] call[name[self]._make_stream_features, parameter[]]
call[name[self]._write_element, parameter[name[self].features]] | keyword[def] identifier[_send_stream_features] ( identifier[self] ):
literal[string]
identifier[self] . identifier[features] = identifier[self] . identifier[_make_stream_features] ()
identifier[self] . identifier[_write_element] ( identifier[self] . identifier[features] ) | def _send_stream_features(self):
"""Send stream <features/>.
[receiving entity only]"""
self.features = self._make_stream_features()
self._write_element(self.features) |
def flatten(self, l):
"""Turn a list of lists into a list."""
if l == []:
return l
if isinstance(l[0], list):
return self.flatten(l[0]) + self.flatten(l[1:])
return l[:1] + self.flatten(l[1:]) | def function[flatten, parameter[self, l]]:
constant[Turn a list of lists into a list.]
if compare[name[l] equal[==] list[[]]] begin[:]
return[name[l]]
if call[name[isinstance], parameter[call[name[l]][constant[0]], name[list]]] begin[:]
return[binary_operation[call[name[self].fla... | keyword[def] identifier[flatten] ( identifier[self] , identifier[l] ):
literal[string]
keyword[if] identifier[l] ==[]:
keyword[return] identifier[l]
keyword[if] identifier[isinstance] ( identifier[l] [ literal[int] ], identifier[list] ):
keyword[return] ident... | def flatten(self, l):
"""Turn a list of lists into a list."""
if l == []:
return l # depends on [control=['if'], data=['l']]
if isinstance(l[0], list):
return self.flatten(l[0]) + self.flatten(l[1:]) # depends on [control=['if'], data=[]]
return l[:1] + self.flatten(l[1:]) |
def wrap(s, width=80):
"""
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1
"""
return '\n'.join(textwrap.wrap(str(s... | def function[wrap, parameter[s, width]]:
constant[
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1
]
return[cal... | keyword[def] identifier[wrap] ( identifier[s] , identifier[width] = literal[int] ):
literal[string]
keyword[return] literal[string] . identifier[join] ( identifier[textwrap] . identifier[wrap] ( identifier[str] ( identifier[s] ), identifier[width] = identifier[width] )) | def wrap(s, width=80):
"""
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1
"""
return '\n'.join(textwrap.wrap(str(s... |
def _ack_coord_handle(
coord, coord_handle, queue_mapper, msg_tracker, timing_state,
tile_proc_logger, stats_handler):
"""share code for acknowledging a coordinate"""
# returns tuple of (handle, error), either of which can be None
track_result = msg_tracker.done(coord_handle)
queue_han... | def function[_ack_coord_handle, parameter[coord, coord_handle, queue_mapper, msg_tracker, timing_state, tile_proc_logger, stats_handler]]:
constant[share code for acknowledging a coordinate]
variable[track_result] assign[=] call[name[msg_tracker].done, parameter[name[coord_handle]]]
variable[que... | keyword[def] identifier[_ack_coord_handle] (
identifier[coord] , identifier[coord_handle] , identifier[queue_mapper] , identifier[msg_tracker] , identifier[timing_state] ,
identifier[tile_proc_logger] , identifier[stats_handler] ):
literal[string]
identifier[track_result] = identifier[msg_tracker]... | def _ack_coord_handle(coord, coord_handle, queue_mapper, msg_tracker, timing_state, tile_proc_logger, stats_handler):
"""share code for acknowledging a coordinate"""
# returns tuple of (handle, error), either of which can be None
track_result = msg_tracker.done(coord_handle)
queue_handle = track_result.... |
def filter_noexpand_columns(columns):
"""Return columns not containing and containing the noexpand prefix.
Parameters
----------
columns: sequence of str
A sequence of strings to be split
Returns
-------
Two lists, the first containing strings without the noexpand prefix, the
... | def function[filter_noexpand_columns, parameter[columns]]:
constant[Return columns not containing and containing the noexpand prefix.
Parameters
----------
columns: sequence of str
A sequence of strings to be split
Returns
-------
Two lists, the first containing strings without... | keyword[def] identifier[filter_noexpand_columns] ( identifier[columns] ):
literal[string]
identifier[prefix_len] = identifier[len] ( identifier[NOEXPAND_PREFIX] )
identifier[noexpand] =[ identifier[c] [ identifier[prefix_len] :] keyword[for] identifier[c] keyword[in] identifier[columns] keyword[if... | def filter_noexpand_columns(columns):
"""Return columns not containing and containing the noexpand prefix.
Parameters
----------
columns: sequence of str
A sequence of strings to be split
Returns
-------
Two lists, the first containing strings without the noexpand prefix, the
... |
def obfuscate_global_import_methods(module, tokens, name_generator, table=None):
"""
Replaces the used methods of globally-imported modules with obfuscated
equivalents. Updates *tokens* in-place.
*module* must be the name of the module we're currently obfuscating
If *table* is provided, replaceme... | def function[obfuscate_global_import_methods, parameter[module, tokens, name_generator, table]]:
constant[
Replaces the used methods of globally-imported modules with obfuscated
equivalents. Updates *tokens* in-place.
*module* must be the name of the module we're currently obfuscating
If *tab... | keyword[def] identifier[obfuscate_global_import_methods] ( identifier[module] , identifier[tokens] , identifier[name_generator] , identifier[table] = keyword[None] ):
literal[string]
identifier[global_imports] = identifier[analyze] . identifier[enumerate_global_imports] ( identifier[tokens] )
ide... | def obfuscate_global_import_methods(module, tokens, name_generator, table=None):
"""
Replaces the used methods of globally-imported modules with obfuscated
equivalents. Updates *tokens* in-place.
*module* must be the name of the module we're currently obfuscating
If *table* is provided, replaceme... |
def initialize_options(self):
"""Find all files of all locales."""
self.paths = []
self.separators = (',', ':')
self.data_dir = join(here, 'mimesis', 'data')
self.before_total = 0
self.after_total = 0
for root, _, files in os.walk(self.data_dir):
for ... | def function[initialize_options, parameter[self]]:
constant[Find all files of all locales.]
name[self].paths assign[=] list[[]]
name[self].separators assign[=] tuple[[<ast.Constant object at 0x7da20c6c7280>, <ast.Constant object at 0x7da20c6c5540>]]
name[self].data_dir assign[=] call[nam... | keyword[def] identifier[initialize_options] ( identifier[self] ):
literal[string]
identifier[self] . identifier[paths] =[]
identifier[self] . identifier[separators] =( literal[string] , literal[string] )
identifier[self] . identifier[data_dir] = identifier[join] ( identifier[here]... | def initialize_options(self):
"""Find all files of all locales."""
self.paths = []
self.separators = (',', ':')
self.data_dir = join(here, 'mimesis', 'data')
self.before_total = 0
self.after_total = 0
for (root, _, files) in os.walk(self.data_dir):
for file in sorted(files):
... |
def as_dict(df, ix=':'):
""" converts df to dict and adds a datetime field if df is datetime """
if isinstance(df.index, pd.DatetimeIndex):
df['datetime'] = df.index
return df.to_dict(orient='records')[ix] | def function[as_dict, parameter[df, ix]]:
constant[ converts df to dict and adds a datetime field if df is datetime ]
if call[name[isinstance], parameter[name[df].index, name[pd].DatetimeIndex]] begin[:]
call[name[df]][constant[datetime]] assign[=] name[df].index
return[call[call[nam... | keyword[def] identifier[as_dict] ( identifier[df] , identifier[ix] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[df] . identifier[index] , identifier[pd] . identifier[DatetimeIndex] ):
identifier[df] [ literal[string] ]= identifier[df] . identifier[index]
... | def as_dict(df, ix=':'):
""" converts df to dict and adds a datetime field if df is datetime """
if isinstance(df.index, pd.DatetimeIndex):
df['datetime'] = df.index # depends on [control=['if'], data=[]]
return df.to_dict(orient='records')[ix] |
def soap_fault(message=None, actor=None, code=None, detail=None):
""" Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a string
... | def function[soap_fault, parameter[message, actor, code, detail]]:
constant[ Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a ... | keyword[def] identifier[soap_fault] ( identifier[message] = keyword[None] , identifier[actor] = keyword[None] , identifier[code] = keyword[None] , identifier[detail] = keyword[None] ):
literal[string]
identifier[_string] = identifier[_actor] = identifier[_code] = identifier[_detail] = keyword[None]
... | def soap_fault(message=None, actor=None, code=None, detail=None):
""" Create a SOAP Fault message
:param message: Human readable error message
:param actor: Who discovered the error
:param code: Error code
:param detail: More specific error message
:return: A SOAP Fault message as a string
... |
def scan_diff(
self,
diff,
baseline_filename='',
last_commit_hash='',
repo_name='',
):
"""For optimization purposes, our scanning strategy focuses on looking
at incremental differences, rather than re-scanning the codebase every time.
This function sup... | def function[scan_diff, parameter[self, diff, baseline_filename, last_commit_hash, repo_name]]:
constant[For optimization purposes, our scanning strategy focuses on looking
at incremental differences, rather than re-scanning the codebase every time.
This function supports this, and adds informat... | keyword[def] identifier[scan_diff] (
identifier[self] ,
identifier[diff] ,
identifier[baseline_filename] = literal[string] ,
identifier[last_commit_hash] = literal[string] ,
identifier[repo_name] = literal[string] ,
):
literal[string]
keyword[from] identifier[unidiff] keywo... | def scan_diff(self, diff, baseline_filename='', last_commit_hash='', repo_name=''):
"""For optimization purposes, our scanning strategy focuses on looking
at incremental differences, rather than re-scanning the codebase every time.
This function supports this, and adds information to self.data.
... |
def show_bgp_peer(self, peer_id, **_params):
"""Fetches information of a certain BGP peer."""
return self.get(self.bgp_peer_path % peer_id,
params=_params) | def function[show_bgp_peer, parameter[self, peer_id]]:
constant[Fetches information of a certain BGP peer.]
return[call[name[self].get, parameter[binary_operation[name[self].bgp_peer_path <ast.Mod object at 0x7da2590d6920> name[peer_id]]]]] | keyword[def] identifier[show_bgp_peer] ( identifier[self] , identifier[peer_id] ,** identifier[_params] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[self] . identifier[bgp_peer_path] % identifier[peer_id] ,
identifier[params] = identifier[_params] ) | def show_bgp_peer(self, peer_id, **_params):
"""Fetches information of a certain BGP peer."""
return self.get(self.bgp_peer_path % peer_id, params=_params) |
def pip_compile(*packages: str):
"""Run pip-compile to pin down packages, also resolve their transitive dependencies."""
result = None
packages = "\n".join(packages)
with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname):
with open("requirements.in", "w") as requirements_file:
... | def function[pip_compile, parameter[]]:
constant[Run pip-compile to pin down packages, also resolve their transitive dependencies.]
variable[result] assign[=] constant[None]
variable[packages] assign[=] call[constant[
].join, parameter[name[packages]]]
with call[name[tempfile].TemporaryD... | keyword[def] identifier[pip_compile] (* identifier[packages] : identifier[str] ):
literal[string]
identifier[result] = keyword[None]
identifier[packages] = literal[string] . identifier[join] ( identifier[packages] )
keyword[with] identifier[tempfile] . identifier[TemporaryDirectory] () keyword... | def pip_compile(*packages: str):
"""Run pip-compile to pin down packages, also resolve their transitive dependencies."""
result = None
packages = '\n'.join(packages)
with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname):
with open('requirements.in', 'w') as requirements_file:
... |
def error(self, msg, repeat_at_end=True):
"""Log a non-fatal error message to stderr, which is repeated at program termination.
:param msg: Message to be printed.
:param repeat_at_end: Set to false if the message should be printed, but not repeated at program termination."""
print(msg, ... | def function[error, parameter[self, msg, repeat_at_end]]:
constant[Log a non-fatal error message to stderr, which is repeated at program termination.
:param msg: Message to be printed.
:param repeat_at_end: Set to false if the message should be printed, but not repeated at program termination.]... | keyword[def] identifier[error] ( identifier[self] , identifier[msg] , identifier[repeat_at_end] = keyword[True] ):
literal[string]
identifier[print] ( identifier[msg] , identifier[file] = identifier[sys] . identifier[stderr] )
keyword[if] identifier[repeat_at_end] :
identifie... | def error(self, msg, repeat_at_end=True):
"""Log a non-fatal error message to stderr, which is repeated at program termination.
:param msg: Message to be printed.
:param repeat_at_end: Set to false if the message should be printed, but not repeated at program termination."""
print(msg, file=sys... |
def _zeep_to_dict(cls, obj):
"""Convert a zeep object to a dictionary."""
res = serialize_object(obj)
res = cls._get_non_empty_dict(res)
return res | def function[_zeep_to_dict, parameter[cls, obj]]:
constant[Convert a zeep object to a dictionary.]
variable[res] assign[=] call[name[serialize_object], parameter[name[obj]]]
variable[res] assign[=] call[name[cls]._get_non_empty_dict, parameter[name[res]]]
return[name[res]] | keyword[def] identifier[_zeep_to_dict] ( identifier[cls] , identifier[obj] ):
literal[string]
identifier[res] = identifier[serialize_object] ( identifier[obj] )
identifier[res] = identifier[cls] . identifier[_get_non_empty_dict] ( identifier[res] )
keyword[return] identifier[res]... | def _zeep_to_dict(cls, obj):
"""Convert a zeep object to a dictionary."""
res = serialize_object(obj)
res = cls._get_non_empty_dict(res)
return res |
def rename(self, new_name):
"""
Rename this collection
"""
new_collection = Collection(self.db, new_name, create=False)
assert not new_collection.exists()
self.db.execute("alter table %s rename to %s" % (self.name, new_name))
self.name = new_name | def function[rename, parameter[self, new_name]]:
constant[
Rename this collection
]
variable[new_collection] assign[=] call[name[Collection], parameter[name[self].db, name[new_name]]]
assert[<ast.UnaryOp object at 0x7da18dc9bd00>]
call[name[self].db.execute, parameter[binary_... | keyword[def] identifier[rename] ( identifier[self] , identifier[new_name] ):
literal[string]
identifier[new_collection] = identifier[Collection] ( identifier[self] . identifier[db] , identifier[new_name] , identifier[create] = keyword[False] )
keyword[assert] keyword[not] identifier[new_... | def rename(self, new_name):
"""
Rename this collection
"""
new_collection = Collection(self.db, new_name, create=False)
assert not new_collection.exists()
self.db.execute('alter table %s rename to %s' % (self.name, new_name))
self.name = new_name |
def idgen(idbase, tint=None, bits=64):
'''
Generate an IRI as a hash of given information, or just make one up if None given
idbase -- Base URI for generating links
tint -- String that affects the sequence of IDs generated if sent None
>>> from bibframe.contrib.datachefids import idgen
>>> g = ... | def function[idgen, parameter[idbase, tint, bits]]:
constant[
Generate an IRI as a hash of given information, or just make one up if None given
idbase -- Base URI for generating links
tint -- String that affects the sequence of IDs generated if sent None
>>> from bibframe.contrib.datachefids im... | keyword[def] identifier[idgen] ( identifier[idbase] , identifier[tint] = keyword[None] , identifier[bits] = literal[int] ):
literal[string]
identifier[counter] =- literal[int]
identifier[to_hash] = keyword[None]
keyword[while] keyword[True] :
keyword[if] identifier[to_hash] keyword[... | def idgen(idbase, tint=None, bits=64):
"""
Generate an IRI as a hash of given information, or just make one up if None given
idbase -- Base URI for generating links
tint -- String that affects the sequence of IDs generated if sent None
>>> from bibframe.contrib.datachefids import idgen
>>> g = ... |
def fail_steamid(channel):
"""Creates an embed UI for invalid SteamIDs
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object
"""
gui = ui_embed.UI(
channel,
"That SteamID doesn't exist.",
"Y... | def function[fail_steamid, parameter[channel]]:
constant[Creates an embed UI for invalid SteamIDs
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object
]
variable[gui] assign[=] call[name[ui_embed].UI, param... | keyword[def] identifier[fail_steamid] ( identifier[channel] ):
literal[string]
identifier[gui] = identifier[ui_embed] . identifier[UI] (
identifier[channel] ,
literal[string] ,
literal[string]
literal[string] ,
identifier[modulename] = identifier[modulename] ,
identifier[col... | def fail_steamid(channel):
"""Creates an embed UI for invalid SteamIDs
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object
"""
gui = ui_embed.UI(channel, "That SteamID doesn't exist.", 'You can get your SteamID by... |
def poll_ignore_interrupts(fds, timeout=None):
'''Simple wrapper around poll to register file descriptors and
ignore signals.'''
if timeout is not None:
end_time = time.time() + timeout
poller = select.poll()
for fd in fds:
poller.register(fd, select.POLLIN | select.POLLPRI | selec... | def function[poll_ignore_interrupts, parameter[fds, timeout]]:
constant[Simple wrapper around poll to register file descriptors and
ignore signals.]
if compare[name[timeout] is_not constant[None]] begin[:]
variable[end_time] assign[=] binary_operation[call[name[time].time, parameter[... | keyword[def] identifier[poll_ignore_interrupts] ( identifier[fds] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] identifier[timeout] keyword[is] keyword[not] keyword[None] :
identifier[end_time] = identifier[time] . identifier[time] ()+ identifier[timeout]
identif... | def poll_ignore_interrupts(fds, timeout=None):
"""Simple wrapper around poll to register file descriptors and
ignore signals."""
if timeout is not None:
end_time = time.time() + timeout # depends on [control=['if'], data=['timeout']]
poller = select.poll()
for fd in fds:
poller.regi... |
def get_info(self):
"""
Return plugin information.
"""
plugin_infos = {}
for pc in self.plugins:
plugin_infos.update(pc.get_info())
return {
self.get_plugin_name() : {
"version" : self.get_version(),
"sub-plugin... | def function[get_info, parameter[self]]:
constant[
Return plugin information.
]
variable[plugin_infos] assign[=] dictionary[[], []]
for taget[name[pc]] in starred[name[self].plugins] begin[:]
call[name[plugin_infos].update, parameter[call[name[pc].get_info, param... | keyword[def] identifier[get_info] ( identifier[self] ):
literal[string]
identifier[plugin_infos] ={}
keyword[for] identifier[pc] keyword[in] identifier[self] . identifier[plugins] :
identifier[plugin_infos] . identifier[update] ( identifier[pc] . identifier[get_info] ())
... | def get_info(self):
"""
Return plugin information.
"""
plugin_infos = {}
for pc in self.plugins:
plugin_infos.update(pc.get_info()) # depends on [control=['for'], data=['pc']]
return {self.get_plugin_name(): {'version': self.get_version(), 'sub-plugins': plugin_infos, 'params':... |
def find_by_extension(extension):
"""
Find and return a format by extension.
:param extension: A string describing the extension of the format.
"""
for format in FORMATS:
if extension in format.extensions:
return format
raise UnknownFormat('No format found with extension "%... | def function[find_by_extension, parameter[extension]]:
constant[
Find and return a format by extension.
:param extension: A string describing the extension of the format.
]
for taget[name[format]] in starred[name[FORMATS]] begin[:]
if compare[name[extension] in name[format].... | keyword[def] identifier[find_by_extension] ( identifier[extension] ):
literal[string]
keyword[for] identifier[format] keyword[in] identifier[FORMATS] :
keyword[if] identifier[extension] keyword[in] identifier[format] . identifier[extensions] :
keyword[return] identifier[format]... | def find_by_extension(extension):
"""
Find and return a format by extension.
:param extension: A string describing the extension of the format.
"""
for format in FORMATS:
if extension in format.extensions:
return format # depends on [control=['if'], data=[]] # depends on [cont... |
def context_complete(self, ctxt):
"""Check for missing data for the required context data.
Set self.missing_data if it exists and return False.
Set self.complete if no missing data and return True.
"""
# Fresh start
self.complete = False
self.missing_data = []
... | def function[context_complete, parameter[self, ctxt]]:
constant[Check for missing data for the required context data.
Set self.missing_data if it exists and return False.
Set self.complete if no missing data and return True.
]
name[self].complete assign[=] constant[False]
... | keyword[def] identifier[context_complete] ( identifier[self] , identifier[ctxt] ):
literal[string]
identifier[self] . identifier[complete] = keyword[False]
identifier[self] . identifier[missing_data] =[]
keyword[for] identifier[k] , identifier[v] keyword[in] identifie... | def context_complete(self, ctxt):
"""Check for missing data for the required context data.
Set self.missing_data if it exists and return False.
Set self.complete if no missing data and return True.
"""
# Fresh start
self.complete = False
self.missing_data = []
for (k, v) in s... |
def Save(self, token=None):
"""Generate a histogram object and store in the specified attribute."""
graph_series_by_label = {}
for active_time in self.active_days:
for label in self.categories[active_time]:
graphs_for_label = graph_series_by_label.setdefault(
label, rdf_stats.Clien... | def function[Save, parameter[self, token]]:
constant[Generate a histogram object and store in the specified attribute.]
variable[graph_series_by_label] assign[=] dictionary[[], []]
for taget[name[active_time]] in starred[name[self].active_days] begin[:]
for taget[name[label]] in ... | keyword[def] identifier[Save] ( identifier[self] , identifier[token] = keyword[None] ):
literal[string]
identifier[graph_series_by_label] ={}
keyword[for] identifier[active_time] keyword[in] identifier[self] . identifier[active_days] :
keyword[for] identifier[label] keyword[in] identifier... | def Save(self, token=None):
"""Generate a histogram object and store in the specified attribute."""
graph_series_by_label = {}
for active_time in self.active_days:
for label in self.categories[active_time]:
graphs_for_label = graph_series_by_label.setdefault(label, rdf_stats.ClientGraphS... |
def key_pair(i, region):
"""Returns the ith default (aws_key_pair_name, key_pair_path)."""
if i == 0:
return ("{}_{}".format(RAY, region),
os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
return ("{}_{}_{}".format(RAY, i, region),
os.path.expanduser("~/.ssh/{}_... | def function[key_pair, parameter[i, region]]:
constant[Returns the ith default (aws_key_pair_name, key_pair_path).]
if compare[name[i] equal[==] constant[0]] begin[:]
return[tuple[[<ast.Call object at 0x7da20e963880>, <ast.Call object at 0x7da20e962980>]]]
return[tuple[[<ast.Call object at 0... | keyword[def] identifier[key_pair] ( identifier[i] , identifier[region] ):
literal[string]
keyword[if] identifier[i] == literal[int] :
keyword[return] ( literal[string] . identifier[format] ( identifier[RAY] , identifier[region] ),
identifier[os] . identifier[path] . identifier[expanduser... | def key_pair(i, region):
"""Returns the ith default (aws_key_pair_name, key_pair_path)."""
if i == 0:
return ('{}_{}'.format(RAY, region), os.path.expanduser('~/.ssh/{}_{}.pem'.format(RAY, region))) # depends on [control=['if'], data=[]]
return ('{}_{}_{}'.format(RAY, i, region), os.path.expanduser... |
def get_poll_option_formset(self, formset_class):
""" Returns an instance of the poll option formset to be used in the view. """
if self.request.forum_permission_handler.can_create_polls(
self.get_forum(), self.request.user,
):
return formset_class(**self.get_poll_option_... | def function[get_poll_option_formset, parameter[self, formset_class]]:
constant[ Returns an instance of the poll option formset to be used in the view. ]
if call[name[self].request.forum_permission_handler.can_create_polls, parameter[call[name[self].get_forum, parameter[]], name[self].request.user]] beg... | keyword[def] identifier[get_poll_option_formset] ( identifier[self] , identifier[formset_class] ):
literal[string]
keyword[if] identifier[self] . identifier[request] . identifier[forum_permission_handler] . identifier[can_create_polls] (
identifier[self] . identifier[get_forum] (), identi... | def get_poll_option_formset(self, formset_class):
""" Returns an instance of the poll option formset to be used in the view. """
if self.request.forum_permission_handler.can_create_polls(self.get_forum(), self.request.user):
return formset_class(**self.get_poll_option_formset_kwargs()) # depends on [co... |
def custodian_archive(packages=None):
"""Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: yaml
policy:
... | def function[custodian_archive, parameter[packages]]:
constant[Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: ya... | keyword[def] identifier[custodian_archive] ( identifier[packages] = keyword[None] ):
literal[string]
identifier[modules] ={ literal[string] , literal[string] }
keyword[if] identifier[packages] :
identifier[modules] = identifier[filter] ( keyword[None] , identifier[modules] . identifier[union... | def custodian_archive(packages=None):
"""Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: yaml
policy:
... |
def _frame_title(self, key, group_size=2, separator='\n'):
"""
Returns the formatted dimension group strings
for a particular frame.
"""
if self.layout_dimensions is not None:
dimensions, key = zip(*self.layout_dimensions.items())
elif not self.dynamic and (no... | def function[_frame_title, parameter[self, key, group_size, separator]]:
constant[
Returns the formatted dimension group strings
for a particular frame.
]
if compare[name[self].layout_dimensions is_not constant[None]] begin[:]
<ast.Tuple object at 0x7da20c6ab430> ... | keyword[def] identifier[_frame_title] ( identifier[self] , identifier[key] , identifier[group_size] = literal[int] , identifier[separator] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[layout_dimensions] keyword[is] keyword[not] keyword[None] :
iden... | def _frame_title(self, key, group_size=2, separator='\n'):
"""
Returns the formatted dimension group strings
for a particular frame.
"""
if self.layout_dimensions is not None:
(dimensions, key) = zip(*self.layout_dimensions.items()) # depends on [control=['if'], data=[]]
eli... |
def load_vcf(
path,
genome=None,
reference_vcf_key="reference",
only_passing=True,
allow_extended_nucleotides=False,
include_info=True,
chunk_size=10 ** 5,
max_variants=None,
sort_key=variant_ascending_position_sort_key,
distinct=True):
... | def function[load_vcf, parameter[path, genome, reference_vcf_key, only_passing, allow_extended_nucleotides, include_info, chunk_size, max_variants, sort_key, distinct]]:
constant[
Load reference name and Variant objects from the given VCF filename.
Currently only local files are supported by this funct... | keyword[def] identifier[load_vcf] (
identifier[path] ,
identifier[genome] = keyword[None] ,
identifier[reference_vcf_key] = literal[string] ,
identifier[only_passing] = keyword[True] ,
identifier[allow_extended_nucleotides] = keyword[False] ,
identifier[include_info] = keyword[True] ,
identifier[chunk_size] = ... | def load_vcf(path, genome=None, reference_vcf_key='reference', only_passing=True, allow_extended_nucleotides=False, include_info=True, chunk_size=10 ** 5, max_variants=None, sort_key=variant_ascending_position_sort_key, distinct=True):
"""
Load reference name and Variant objects from the given VCF filename.
... |
def a_send_password(password, ctx):
"""Send the password text.
Before sending the password local echo is disabled.
If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception.
"""
if password:
ctx.ctrl.send_command(password, password=True)
... | def function[a_send_password, parameter[password, ctx]]:
constant[Send the password text.
Before sending the password local echo is disabled.
If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception.
]
if name[password] begin[:]
... | keyword[def] identifier[a_send_password] ( identifier[password] , identifier[ctx] ):
literal[string]
keyword[if] identifier[password] :
identifier[ctx] . identifier[ctrl] . identifier[send_command] ( identifier[password] , identifier[password] = keyword[True] )
keyword[return] keyword[T... | def a_send_password(password, ctx):
"""Send the password text.
Before sending the password local echo is disabled.
If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception.
"""
if password:
ctx.ctrl.send_command(password, password=True)
... |
def read_relative_file(filename):
"""Returns contents of the given file, which path is supposed relative
to this module."""
with open(join(dirname(abspath(__file__)), filename)) as f:
return f.read() | def function[read_relative_file, parameter[filename]]:
constant[Returns contents of the given file, which path is supposed relative
to this module.]
with call[name[open], parameter[call[name[join], parameter[call[name[dirname], parameter[call[name[abspath], parameter[name[__file__]]]]], name[filenam... | keyword[def] identifier[read_relative_file] ( identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[join] ( identifier[dirname] ( identifier[abspath] ( identifier[__file__] )), identifier[filename] )) keyword[as] identifier[f] :
keyword[return] identifier[f] . iden... | def read_relative_file(filename):
"""Returns contents of the given file, which path is supposed relative
to this module."""
with open(join(dirname(abspath(__file__)), filename)) as f:
return f.read() # depends on [control=['with'], data=['f']] |
def find(self, entry_id, query=None):
"""
Gets a single entry by ID.
"""
if query is None:
query = {}
if self.content_type_id is not None:
query['content_type'] = self.content_type_id
normalize_select(query)
return super(EntriesProxy, s... | def function[find, parameter[self, entry_id, query]]:
constant[
Gets a single entry by ID.
]
if compare[name[query] is constant[None]] begin[:]
variable[query] assign[=] dictionary[[], []]
if compare[name[self].content_type_id is_not constant[None]] begin[:]
... | keyword[def] identifier[find] ( identifier[self] , identifier[entry_id] , identifier[query] = keyword[None] ):
literal[string]
keyword[if] identifier[query] keyword[is] keyword[None] :
identifier[query] ={}
keyword[if] identifier[self] . identifier[content_type_id] keyw... | def find(self, entry_id, query=None):
"""
Gets a single entry by ID.
"""
if query is None:
query = {} # depends on [control=['if'], data=['query']]
if self.content_type_id is not None:
query['content_type'] = self.content_type_id # depends on [control=['if'], data=[]]
n... |
def send_media_group(
self,
chat_id: Union[int, str],
media: List[Union["pyrogram.InputMediaPhoto", "pyrogram.InputMediaVideo"]],
disable_notification: bool = None,
reply_to_message_id: int = None
):
"""Use this method to send a group of photos or videos as an album.
... | def function[send_media_group, parameter[self, chat_id, media, disable_notification, reply_to_message_id]]:
constant[Use this method to send a group of photos or videos as an album.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target ch... | keyword[def] identifier[send_media_group] (
identifier[self] ,
identifier[chat_id] : identifier[Union] [ identifier[int] , identifier[str] ],
identifier[media] : identifier[List] [ identifier[Union] [ literal[string] , literal[string] ]],
identifier[disable_notification] : identifier[bool] = keyword[None] ,
iden... | def send_media_group(self, chat_id: Union[int, str], media: List[Union['pyrogram.InputMediaPhoto', 'pyrogram.InputMediaVideo']], disable_notification: bool=None, reply_to_message_id: int=None):
"""Use this method to send a group of photos or videos as an album.
Args:
chat_id (``int`` | ``str``)... |
def publish(self, topic, payload=None, qos=0, retain=False):
"""Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
... | def function[publish, parameter[self, topic, payload, qos, retain]]:
constant[Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be publish... | keyword[def] identifier[publish] ( identifier[self] , identifier[topic] , identifier[payload] = keyword[None] , identifier[qos] = literal[int] , identifier[retain] = keyword[False] ):
literal[string]
keyword[if] identifier[topic] keyword[is] keyword[None] keyword[or] identifier[len] ( identifi... | def publish(self, topic, payload=None, qos=0, retain=False):
"""Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
pay... |
def safe_dump(data, stream=None, **kwds):
"""implementation of safe dumper using Ordered Dict Yaml Dumper"""
return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds) | def function[safe_dump, parameter[data, stream]]:
constant[implementation of safe dumper using Ordered Dict Yaml Dumper]
return[call[name[yaml].dump, parameter[name[data]]]] | keyword[def] identifier[safe_dump] ( identifier[data] , identifier[stream] = keyword[None] ,** identifier[kwds] ):
literal[string]
keyword[return] identifier[yaml] . identifier[dump] ( identifier[data] , identifier[stream] = identifier[stream] , identifier[Dumper] = identifier[ODYD] ,** identifier[kwds] ) | def safe_dump(data, stream=None, **kwds):
"""implementation of safe dumper using Ordered Dict Yaml Dumper"""
return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds) |
def write_data(X, dir='sim/test', append=False, header='',
varNames={}, Adj=np.array([]), Coupl=np.array([]),
boolRules={}, model='', modelType='', invTimeStep=1):
""" Write simulated data.
Accounts for saving at the same time an ID
and a model file.
"""
# chec... | def function[write_data, parameter[X, dir, append, header, varNames, Adj, Coupl, boolRules, model, modelType, invTimeStep]]:
constant[ Write simulated data.
Accounts for saving at the same time an ID
and a model file.
]
if <ast.UnaryOp object at 0x7da18f7225f0> begin[:]
... | keyword[def] identifier[write_data] ( identifier[X] , identifier[dir] = literal[string] , identifier[append] = keyword[False] , identifier[header] = literal[string] ,
identifier[varNames] ={}, identifier[Adj] = identifier[np] . identifier[array] ([]), identifier[Coupl] = identifier[np] . identifier[array] ([]),
ide... | def write_data(X, dir='sim/test', append=False, header='', varNames={}, Adj=np.array([]), Coupl=np.array([]), boolRules={}, model='', modelType='', invTimeStep=1):
""" Write simulated data.
Accounts for saving at the same time an ID
and a model file.
"""
# check if output directory exists
... |
def _Close(self):
"""Closes the file-like object."""
self._cpio_archive_file_entry = None
self._cpio_archive_file = None
self._file_system.Close()
self._file_system = None | def function[_Close, parameter[self]]:
constant[Closes the file-like object.]
name[self]._cpio_archive_file_entry assign[=] constant[None]
name[self]._cpio_archive_file assign[=] constant[None]
call[name[self]._file_system.Close, parameter[]]
name[self]._file_system assign[=] con... | keyword[def] identifier[_Close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_cpio_archive_file_entry] = keyword[None]
identifier[self] . identifier[_cpio_archive_file] = keyword[None]
identifier[self] . identifier[_file_system] . identifier[Close] ()
identifier[sel... | def _Close(self):
"""Closes the file-like object."""
self._cpio_archive_file_entry = None
self._cpio_archive_file = None
self._file_system.Close()
self._file_system = None |
def downstream(self, f, n=1):
"""find n downstream features where downstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
ret... | def function[downstream, parameter[self, f, n]]:
constant[find n downstream features where downstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return
]
if compare[... | keyword[def] identifier[downstream] ( identifier[self] , identifier[f] , identifier[n] = literal[int] ):
literal[string]
keyword[if] identifier[f] . identifier[strand] ==- literal[int] :
keyword[return] identifier[self] . identifier[left] ( identifier[f] , identifier[n] )
ke... | def downstream(self, f, n=1):
"""find n downstream features where downstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
return self.lef... |
def read_igor_VJ_palindrome_parameters(self, params_file_name):
"""Read V and J palindrome parameters from file.
Sets the attributes max_delV_palindrome and max_delJ_palindrome.
Parameters
----------
params_file_name : str
File name for an IGoR parameter... | def function[read_igor_VJ_palindrome_parameters, parameter[self, params_file_name]]:
constant[Read V and J palindrome parameters from file.
Sets the attributes max_delV_palindrome and max_delJ_palindrome.
Parameters
----------
params_file_name : str
File... | keyword[def] identifier[read_igor_VJ_palindrome_parameters] ( identifier[self] , identifier[params_file_name] ):
literal[string]
identifier[params_file] = identifier[open] ( identifier[params_file_name] , literal[string] )
identifier[in_delV] = keyword[False]
identifier[in_delJ... | def read_igor_VJ_palindrome_parameters(self, params_file_name):
"""Read V and J palindrome parameters from file.
Sets the attributes max_delV_palindrome and max_delJ_palindrome.
Parameters
----------
params_file_name : str
File name for an IGoR parameter fil... |
def add_missing_particles(st, rad='calc', tries=50, **kwargs):
"""
Attempts to add missing particles to the state.
Operates by:
(1) featuring the difference image using feature_guess,
(2) attempting to add the featured positions using check_add_particles.
Parameters
----------
st : :cl... | def function[add_missing_particles, parameter[st, rad, tries]]:
constant[
Attempts to add missing particles to the state.
Operates by:
(1) featuring the difference image using feature_guess,
(2) attempting to add the featured positions using check_add_particles.
Parameters
----------
... | keyword[def] identifier[add_missing_particles] ( identifier[st] , identifier[rad] = literal[string] , identifier[tries] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[rad] == literal[string] :
identifier[rad] = identifier[guess_add_radii] ( identifier[st] )
... | def add_missing_particles(st, rad='calc', tries=50, **kwargs):
"""
Attempts to add missing particles to the state.
Operates by:
(1) featuring the difference image using feature_guess,
(2) attempting to add the featured positions using check_add_particles.
Parameters
----------
st : :cl... |
def unbind(meta, name=None, dynamo_name=None) -> None:
"""Unconditionally remove any columns or indexes bound to the given name or dynamo_name.
.. code-block:: python
import bloop.models
class User(BaseModel):
id = Column(String, hash_key=True)
email = Column(String, ... | def function[unbind, parameter[meta, name, dynamo_name]]:
constant[Unconditionally remove any columns or indexes bound to the given name or dynamo_name.
.. code-block:: python
import bloop.models
class User(BaseModel):
id = Column(String, hash_key=True)
email = Co... | keyword[def] identifier[unbind] ( identifier[meta] , identifier[name] = keyword[None] , identifier[dynamo_name] = keyword[None] )-> keyword[None] :
literal[string]
keyword[if] identifier[name] keyword[is] keyword[not] keyword[None] :
identifier[columns] ={ identifier[x] keyword[for] identifi... | def unbind(meta, name=None, dynamo_name=None) -> None:
"""Unconditionally remove any columns or indexes bound to the given name or dynamo_name.
.. code-block:: python
import bloop.models
class User(BaseModel):
id = Column(String, hash_key=True)
email = Column(String, ... |
def asDictionary(self):
""" returns object as dictionary """
template = {
"type" : "uniqueValue",
"field1" : self._field1,
"field2" : self._field2,
"field3" : self._field3,
"fieldDelimiter" : self._fieldDelimiter,
"defaultSymbol" : ... | def function[asDictionary, parameter[self]]:
constant[ returns object as dictionary ]
variable[template] assign[=] dictionary[[<ast.Constant object at 0x7da1b12286a0>, <ast.Constant object at 0x7da1b1228970>, <ast.Constant object at 0x7da1b1228160>, <ast.Constant object at 0x7da1b12282b0>, <ast.Constant... | keyword[def] identifier[asDictionary] ( identifier[self] ):
literal[string]
identifier[template] ={
literal[string] : literal[string] ,
literal[string] : identifier[self] . identifier[_field1] ,
literal[string] : identifier[self] . identifier[_field2] ,
literal[s... | def asDictionary(self):
""" returns object as dictionary """
template = {'type': 'uniqueValue', 'field1': self._field1, 'field2': self._field2, 'field3': self._field3, 'fieldDelimiter': self._fieldDelimiter, 'defaultSymbol': self._defaultSymbol.asDictionary, 'defaultLabel': self._defaultLabel, 'uniqueValueInfos... |
def load_remote_system(url, format=None):
'''Load a system from the remote location specified by *url*.
**Example**
::
load_remote_system('https://raw.github.com/chemlab/chemlab-testdata/master/naclwater.gro')
'''
filename, headers = urlretrieve(url)
return load_system(filename, forma... | def function[load_remote_system, parameter[url, format]]:
constant[Load a system from the remote location specified by *url*.
**Example**
::
load_remote_system('https://raw.github.com/chemlab/chemlab-testdata/master/naclwater.gro')
]
<ast.Tuple object at 0x7da2054a7be0> assign[=] ... | keyword[def] identifier[load_remote_system] ( identifier[url] , identifier[format] = keyword[None] ):
literal[string]
identifier[filename] , identifier[headers] = identifier[urlretrieve] ( identifier[url] )
keyword[return] identifier[load_system] ( identifier[filename] , identifier[format] = identifi... | def load_remote_system(url, format=None):
"""Load a system from the remote location specified by *url*.
**Example**
::
load_remote_system('https://raw.github.com/chemlab/chemlab-testdata/master/naclwater.gro')
"""
(filename, headers) = urlretrieve(url)
return load_system(filename, for... |
def plot(self,*args,**kwargs):
"""
NAME:
plot
PURPOSE:
plot the angles vs. each other, to check whether the isochrone
approximation is good
INPUT:
Either:
a) R,vR,vT,z,vz:
floats: phase-space value for single obje... | def function[plot, parameter[self]]:
constant[
NAME:
plot
PURPOSE:
plot the angles vs. each other, to check whether the isochrone
approximation is good
INPUT:
Either:
a) R,vR,vT,z,vz:
floats: phase-space value for... | keyword[def] identifier[plot] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[type] = identifier[kwargs] . identifier[pop] ( literal[string] , literal[string] )
identifier[deperiod] = identifier[kwargs] . identifier[pop] ( literal[string... | def plot(self, *args, **kwargs):
"""
NAME:
plot
PURPOSE:
plot the angles vs. each other, to check whether the isochrone
approximation is good
INPUT:
Either:
a) R,vR,vT,z,vz:
floats: phase-space value for single object... |
def specific_gravity(self, value):
""" Set the relative weight of the solid """
value = clean_float(value)
if value is None:
return
specific_gravity = self._calc_specific_gravity()
if specific_gravity is not None and not ct.isclose(specific_gravity, value, rel_tol=sel... | def function[specific_gravity, parameter[self, value]]:
constant[ Set the relative weight of the solid ]
variable[value] assign[=] call[name[clean_float], parameter[name[value]]]
if compare[name[value] is constant[None]] begin[:]
return[None]
variable[specific_gravity] assign[=] ... | keyword[def] identifier[specific_gravity] ( identifier[self] , identifier[value] ):
literal[string]
identifier[value] = identifier[clean_float] ( identifier[value] )
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return]
identifier[specific_grav... | def specific_gravity(self, value):
""" Set the relative weight of the solid """
value = clean_float(value)
if value is None:
return # depends on [control=['if'], data=[]]
specific_gravity = self._calc_specific_gravity()
if specific_gravity is not None and (not ct.isclose(specific_gravity, v... |
def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
'''
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0... | def function[set_relay_ip_list, parameter[addresses, server]]:
constant[
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, sett... | keyword[def] identifier[set_relay_ip_list] ( identifier[addresses] = keyword[None] , identifier[server] = identifier[_DEFAULT_SERVER] ):
literal[string]
identifier[setting] = literal[string]
identifier[formatted_addresses] = identifier[list] ()
identifier[current_addresses] = identifier[get_rel... | def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
"""
Set the RelayIpList list for the SMTP virtual server.
Due to the unusual way that Windows stores the relay IPs, it is advisable to retrieve
the existing list you wish to set from a pre-configured server.
For example, setting '127.0... |
def split(self, n):
"""Evenly split this range into contiguous, non overlapping subranges.
Args:
n: number of splits.
Returns:
a list of contiguous, non overlapping sub PropertyRanges. Maybe less than
n when not enough subranges.
"""
new_range_filters = []
name = self.start[0]
... | def function[split, parameter[self, n]]:
constant[Evenly split this range into contiguous, non overlapping subranges.
Args:
n: number of splits.
Returns:
a list of contiguous, non overlapping sub PropertyRanges. Maybe less than
n when not enough subranges.
]
variable[new_ra... | keyword[def] identifier[split] ( identifier[self] , identifier[n] ):
literal[string]
identifier[new_range_filters] =[]
identifier[name] = identifier[self] . identifier[start] [ literal[int] ]
identifier[prop_cls] = identifier[self] . identifier[prop] . identifier[__class__]
keyword[if] ide... | def split(self, n):
"""Evenly split this range into contiguous, non overlapping subranges.
Args:
n: number of splits.
Returns:
a list of contiguous, non overlapping sub PropertyRanges. Maybe less than
n when not enough subranges.
"""
new_range_filters = []
name = self.start[0]
... |
def __run(self):
"""
Main execution method, which consists of: get an up-to-date list of WARC files, and for each of them: download
and extract articles. Each article is checked against a filter. Finally, for each valid article the method
on_valid_article_extracted will be invoked after ... | def function[__run, parameter[self]]:
constant[
Main execution method, which consists of: get an up-to-date list of WARC files, and for each of them: download
and extract articles. Each article is checked against a filter. Finally, for each valid article the method
on_valid_article_extra... | keyword[def] identifier[__run] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__setup] ()
identifier[local_path_name] = identifier[self] . identifier[__download] ( identifier[self] . identifier[__warc_download_url] )
identifier[self] . identifier[__process_wa... | def __run(self):
"""
Main execution method, which consists of: get an up-to-date list of WARC files, and for each of them: download
and extract articles. Each article is checked against a filter. Finally, for each valid article the method
on_valid_article_extracted will be invoked after the ... |
def delete(block_id):
"""Processing block detail resource."""
_url = get_root_url()
try:
DB.delete_processing_block(block_id)
response = dict(message='Deleted block',
id='{}'.format(block_id),
links=dict(list='{}/processing-blocks'.format(_url)... | def function[delete, parameter[block_id]]:
constant[Processing block detail resource.]
variable[_url] assign[=] call[name[get_root_url], parameter[]]
<ast.Try object at 0x7da18f00ddb0> | keyword[def] identifier[delete] ( identifier[block_id] ):
literal[string]
identifier[_url] = identifier[get_root_url] ()
keyword[try] :
identifier[DB] . identifier[delete_processing_block] ( identifier[block_id] )
identifier[response] = identifier[dict] ( identifier[message] = litera... | def delete(block_id):
"""Processing block detail resource."""
_url = get_root_url()
try:
DB.delete_processing_block(block_id)
response = dict(message='Deleted block', id='{}'.format(block_id), links=dict(list='{}/processing-blocks'.format(_url), home='{}'.format(_url)))
return (respo... |
def com_google_fonts_check_name_rfn(ttFont):
"""Name table strings must not contain the string 'Reserved Font Name'."""
failed = False
for entry in ttFont["name"].names:
string = entry.toUnicode()
if "reserved font name" in string.lower():
yield WARN, ("Name table entry (\"{}\")"
... | def function[com_google_fonts_check_name_rfn, parameter[ttFont]]:
constant[Name table strings must not contain the string 'Reserved Font Name'.]
variable[failed] assign[=] constant[False]
for taget[name[entry]] in starred[call[name[ttFont]][constant[name]].names] begin[:]
variabl... | keyword[def] identifier[com_google_fonts_check_name_rfn] ( identifier[ttFont] ):
literal[string]
identifier[failed] = keyword[False]
keyword[for] identifier[entry] keyword[in] identifier[ttFont] [ literal[string] ]. identifier[names] :
identifier[string] = identifier[entry] . identifier[toUnicode] ... | def com_google_fonts_check_name_rfn(ttFont):
"""Name table strings must not contain the string 'Reserved Font Name'."""
failed = False
for entry in ttFont['name'].names:
string = entry.toUnicode()
if 'reserved font name' in string.lower():
yield (WARN, 'Name table entry ("{}") co... |
def get_live_url(con_pool,
method,
host,
url,
headers,
retries=1,
redirect=True,
body=None,
service_name=None):
"""
Return a connection from the pool and perform an HTTP reques... | def function[get_live_url, parameter[con_pool, method, host, url, headers, retries, redirect, body, service_name]]:
constant[
Return a connection from the pool and perform an HTTP request.
:param con_pool:
is the http connection pool associated with the service
:param method:
HTTP re... | keyword[def] identifier[get_live_url] ( identifier[con_pool] ,
identifier[method] ,
identifier[host] ,
identifier[url] ,
identifier[headers] ,
identifier[retries] = literal[int] ,
identifier[redirect] = keyword[True] ,
identifier[body] = keyword[None] ,
identifier[service_name] = keyword[None] ):
literal... | def get_live_url(con_pool, method, host, url, headers, retries=1, redirect=True, body=None, service_name=None):
"""
Return a connection from the pool and perform an HTTP request.
:param con_pool:
is the http connection pool associated with the service
:param method:
HTTP request method (... |
def clone(self, default):
"""
Make a copy of this parameter, supplying a different default.
@type default: C{unicode} or C{NoneType}
@param default: A value which will be initially presented in the view
as the value for this parameter, or C{None} if no such value is to be
... | def function[clone, parameter[self, default]]:
constant[
Make a copy of this parameter, supplying a different default.
@type default: C{unicode} or C{NoneType}
@param default: A value which will be initially presented in the view
as the value for this parameter, or C{None} if no... | keyword[def] identifier[clone] ( identifier[self] , identifier[default] ):
literal[string]
keyword[return] identifier[self] . identifier[__class__] (
identifier[self] . identifier[name] ,
identifier[self] . identifier[type] ,
identifier[self] . identifier[coercer] ,
... | def clone(self, default):
"""
Make a copy of this parameter, supplying a different default.
@type default: C{unicode} or C{NoneType}
@param default: A value which will be initially presented in the view
as the value for this parameter, or C{None} if no such value is to be
pr... |
def set_option(name, option):
"""
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
"""
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name),
_encode_strin... | def function[set_option, parameter[name, option]]:
constant[
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
]
call[name[ffi].lib.LLVMPY_SetCommandLine, parameter[call[name[_enc... | keyword[def] identifier[set_option] ( identifier[name] , identifier[option] ):
literal[string]
identifier[ffi] . identifier[lib] . identifier[LLVMPY_SetCommandLine] ( identifier[_encode_string] ( identifier[name] ),
identifier[_encode_string] ( identifier[option] )) | def set_option(name, option):
"""
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
"""
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option)) |
def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False):
"""Set the permissions and ownership of a path.
Args:
path: string, the path for which owner ID and group ID needs to be setup.
mode: octal string, the permissions to set on the path.
uid: int, the owner ID to be set for the path.
... | def function[SetPermissions, parameter[path, mode, uid, gid, mkdir]]:
constant[Set the permissions and ownership of a path.
Args:
path: string, the path for which owner ID and group ID needs to be setup.
mode: octal string, the permissions to set on the path.
uid: int, the owner ID to be set for ... | keyword[def] identifier[SetPermissions] ( identifier[path] , identifier[mode] = keyword[None] , identifier[uid] = keyword[None] , identifier[gid] = keyword[None] , identifier[mkdir] = keyword[False] ):
literal[string]
keyword[if] identifier[mkdir] keyword[and] keyword[not] identifier[os] . identifier[path]... | def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False):
"""Set the permissions and ownership of a path.
Args:
path: string, the path for which owner ID and group ID needs to be setup.
mode: octal string, the permissions to set on the path.
uid: int, the owner ID to be set for the path.
... |
def serialize_paragraph(ctx, document, par, root, embed=True):
"""Serializes paragraph element.
This is the most important serializer of them all.
"""
style = get_style(document, par)
elem = etree.Element('p')
if ctx.options['embed_styles']:
_style = get_style_css(ctx, par)
... | def function[serialize_paragraph, parameter[ctx, document, par, root, embed]]:
constant[Serializes paragraph element.
This is the most important serializer of them all.
]
variable[style] assign[=] call[name[get_style], parameter[name[document], name[par]]]
variable[elem] assign[=] c... | keyword[def] identifier[serialize_paragraph] ( identifier[ctx] , identifier[document] , identifier[par] , identifier[root] , identifier[embed] = keyword[True] ):
literal[string]
identifier[style] = identifier[get_style] ( identifier[document] , identifier[par] )
identifier[elem] = identifier[etree] ... | def serialize_paragraph(ctx, document, par, root, embed=True):
"""Serializes paragraph element.
This is the most important serializer of them all.
"""
style = get_style(document, par)
elem = etree.Element('p')
if ctx.options['embed_styles']:
_style = get_style_css(ctx, par)
... |
def convert_join(value):
"""
Fix a Join ;)
"""
if not isinstance(value, list) or len(value) != 2:
# Cowardly refuse
return value
sep, parts = value[0], value[1]
if isinstance(parts, six.string_types):
return parts
if not isinstance(parts, list):
# This loo... | def function[convert_join, parameter[value]]:
constant[
Fix a Join ;)
]
if <ast.BoolOp object at 0x7da1b16abc40> begin[:]
return[name[value]]
<ast.Tuple object at 0x7da1b16a8970> assign[=] tuple[[<ast.Subscript object at 0x7da1b16a9780>, <ast.Subscript object at 0x7da1b16a84c0>]]... | keyword[def] identifier[convert_join] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[list] ) keyword[or] identifier[len] ( identifier[value] )!= literal[int] :
keyword[return] identifier[value]
identifier[sep... | def convert_join(value):
"""
Fix a Join ;)
"""
if not isinstance(value, list) or len(value) != 2:
# Cowardly refuse
return value # depends on [control=['if'], data=[]]
(sep, parts) = (value[0], value[1])
if isinstance(parts, six.string_types):
return parts # depends on ... |
def write_string(self, string):
"""Write a string to this packet."""
self.write_uint16(len(string))
self.write_bytes(string, len(string)) | def function[write_string, parameter[self, string]]:
constant[Write a string to this packet.]
call[name[self].write_uint16, parameter[call[name[len], parameter[name[string]]]]]
call[name[self].write_bytes, parameter[name[string], call[name[len], parameter[name[string]]]]] | keyword[def] identifier[write_string] ( identifier[self] , identifier[string] ):
literal[string]
identifier[self] . identifier[write_uint16] ( identifier[len] ( identifier[string] ))
identifier[self] . identifier[write_bytes] ( identifier[string] , identifier[len] ( identifier[string] )) | def write_string(self, string):
"""Write a string to this packet."""
self.write_uint16(len(string))
self.write_bytes(string, len(string)) |
def collect_yarn_application_diagnostics(self, *application_ids):
"""
DEPRECATED: use create_yarn_application_diagnostics_bundle on the Yarn service. Deprecated since v10.
Collects the Diagnostics data for Yarn applications.
@param application_ids: An array of strings containing the ids of the
... | def function[collect_yarn_application_diagnostics, parameter[self]]:
constant[
DEPRECATED: use create_yarn_application_diagnostics_bundle on the Yarn service. Deprecated since v10.
Collects the Diagnostics data for Yarn applications.
@param application_ids: An array of strings containing the ids o... | keyword[def] identifier[collect_yarn_application_diagnostics] ( identifier[self] ,* identifier[application_ids] ):
literal[string]
identifier[args] = identifier[dict] ( identifier[applicationIds] = identifier[application_ids] )
keyword[return] identifier[self] . identifier[_cmd] ( literal[string] , i... | def collect_yarn_application_diagnostics(self, *application_ids):
"""
DEPRECATED: use create_yarn_application_diagnostics_bundle on the Yarn service. Deprecated since v10.
Collects the Diagnostics data for Yarn applications.
@param application_ids: An array of strings containing the ids of the
... |
def find_analyses(ar_or_sample):
""" This function is used to find keywords that are not on the analysis
but keywords that are on the interim fields.
This function and is is_keyword function should probably be in
resultsimport.py or somewhere central where it can be used by other
in... | def function[find_analyses, parameter[ar_or_sample]]:
constant[ This function is used to find keywords that are not on the analysis
but keywords that are on the interim fields.
This function and is is_keyword function should probably be in
resultsimport.py or somewhere central where it ... | keyword[def] identifier[find_analyses] ( identifier[ar_or_sample] ):
literal[string]
identifier[bc] = identifier[api] . identifier[get_tool] ( identifier[CATALOG_ANALYSIS_REQUEST_LISTING] )
identifier[ar] = identifier[bc] ( identifier[portal_type] = literal[string] , identifier[id] = identifier[ar_or_... | def find_analyses(ar_or_sample):
""" This function is used to find keywords that are not on the analysis
but keywords that are on the interim fields.
This function and is is_keyword function should probably be in
resultsimport.py or somewhere central where it can be used by other
in... |
def AdditiveGaussianNoise(loc=0, scale=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Add gaussian noise (aka white noise) to images.
dtype support::
See ``imgaug.augmenters.arithmetic.AddElementwise``.
Parameters
----------
loc : number or tuple of numb... | def function[AdditiveGaussianNoise, parameter[loc, scale, per_channel, name, deterministic, random_state]]:
constant[
Add gaussian noise (aka white noise) to images.
dtype support::
See ``imgaug.augmenters.arithmetic.AddElementwise``.
Parameters
----------
loc : number or tuple of... | keyword[def] identifier[AdditiveGaussianNoise] ( identifier[loc] = literal[int] , identifier[scale] = literal[int] , identifier[per_channel] = keyword[False] , identifier[name] = keyword[None] , identifier[deterministic] = keyword[False] , identifier[random_state] = keyword[None] ):
literal[string]
identif... | def AdditiveGaussianNoise(loc=0, scale=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Add gaussian noise (aka white noise) to images.
dtype support::
See ``imgaug.augmenters.arithmetic.AddElementwise``.
Parameters
----------
loc : number or tuple of numb... |
def signature_cert_chain_url(url):
"""Validate URL specified by SignatureCertChainUrl.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
bool: True if valid, False otherwise.
"""
r = urlparse(url)
if no... | def function[signature_cert_chain_url, parameter[url]]:
constant[Validate URL specified by SignatureCertChainUrl.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
bool: True if valid, False otherwise.
]
... | keyword[def] identifier[signature_cert_chain_url] ( identifier[url] ):
literal[string]
identifier[r] = identifier[urlparse] ( identifier[url] )
keyword[if] keyword[not] identifier[r] . identifier[scheme] . identifier[lower] ()== literal[string] :
identifier[warnings] . identifier[warn] ( li... | def signature_cert_chain_url(url):
"""Validate URL specified by SignatureCertChainUrl.
See `validate.request` for additional info.
Args:
url: str. SignatureCertChainUrl header value sent by request.
Returns:
bool: True if valid, False otherwise.
"""
r = urlparse(url)
if no... |
def validate_payment_form(self):
"""Try to validate and then process the DirectPayment form."""
warn_untested()
form = self.payment_form_cls(self.request.POST)
if form.is_valid():
success = form.process(self.request, self.item)
if success:
return H... | def function[validate_payment_form, parameter[self]]:
constant[Try to validate and then process the DirectPayment form.]
call[name[warn_untested], parameter[]]
variable[form] assign[=] call[name[self].payment_form_cls, parameter[name[self].request.POST]]
if call[name[form].is_valid, para... | keyword[def] identifier[validate_payment_form] ( identifier[self] ):
literal[string]
identifier[warn_untested] ()
identifier[form] = identifier[self] . identifier[payment_form_cls] ( identifier[self] . identifier[request] . identifier[POST] )
keyword[if] identifier[form] . identi... | def validate_payment_form(self):
"""Try to validate and then process the DirectPayment form."""
warn_untested()
form = self.payment_form_cls(self.request.POST)
if form.is_valid():
success = form.process(self.request, self.item)
if success:
return HttpResponseRedirect(self.suc... |
def create_producer(self):
"""Context manager that yields an instance of ``Producer``."""
with current_celery_app.pool.acquire(block=True) as conn:
yield Producer(
conn,
exchange=self.mq_exchange,
routing_key=self.mq_routing_key,
... | def function[create_producer, parameter[self]]:
constant[Context manager that yields an instance of ``Producer``.]
with call[name[current_celery_app].pool.acquire, parameter[]] begin[:]
<ast.Yield object at 0x7da1b257f040> | keyword[def] identifier[create_producer] ( identifier[self] ):
literal[string]
keyword[with] identifier[current_celery_app] . identifier[pool] . identifier[acquire] ( identifier[block] = keyword[True] ) keyword[as] identifier[conn] :
keyword[yield] identifier[Producer] (
... | def create_producer(self):
"""Context manager that yields an instance of ``Producer``."""
with current_celery_app.pool.acquire(block=True) as conn:
yield Producer(conn, exchange=self.mq_exchange, routing_key=self.mq_routing_key, auto_declare=True) # depends on [control=['with'], data=['conn']] |
def create_readme(data):
"""
Create README.md text for the given module data.
"""
out = ['<a name="top"></a>Modules\n========\n\n']
# Links
for module in sorted(data.keys()):
desc = "".join(data[module]).strip().split("\n")[0]
format_str = "\n**[{name}](#{name})** — {desc}\n"
... | def function[create_readme, parameter[data]]:
constant[
Create README.md text for the given module data.
]
variable[out] assign[=] list[[<ast.Constant object at 0x7da204963190>]]
for taget[name[module]] in starred[call[name[sorted], parameter[call[name[data].keys, parameter[]]]]] begin[:... | keyword[def] identifier[create_readme] ( identifier[data] ):
literal[string]
identifier[out] =[ literal[string] ]
keyword[for] identifier[module] keyword[in] identifier[sorted] ( identifier[data] . identifier[keys] ()):
identifier[desc] = literal[string] . identifier[join] ( identifie... | def create_readme(data):
"""
Create README.md text for the given module data.
"""
out = ['<a name="top"></a>Modules\n========\n\n']
# Links
for module in sorted(data.keys()):
desc = ''.join(data[module]).strip().split('\n')[0]
format_str = '\n**[{name}](#{name})** — {desc}\n'
... |
def auto_find_instance_path(self):
"""Tries to locate the instance path if it was not provided to the
constructor of the application class. It will basically calculate
the path to a folder named ``instance`` next to your main file or
the package.
.. versionadded:: 0.8
"... | def function[auto_find_instance_path, parameter[self]]:
constant[Tries to locate the instance path if it was not provided to the
constructor of the application class. It will basically calculate
the path to a folder named ``instance`` next to your main file or
the package.
.. v... | keyword[def] identifier[auto_find_instance_path] ( identifier[self] ):
literal[string]
identifier[prefix] , identifier[package_path] = identifier[find_package] ( identifier[self] . identifier[import_name] )
keyword[if] identifier[prefix] keyword[is] keyword[None] :
keyword[... | def auto_find_instance_path(self):
"""Tries to locate the instance path if it was not provided to the
constructor of the application class. It will basically calculate
the path to a folder named ``instance`` next to your main file or
the package.
.. versionadded:: 0.8
"""
... |
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance:
""" The user's balance with planned withdrawals deducted. """
fn = getattr(self.proxy.contract.functions, 'effectiveBalance')
balance = fn(address).call(block_identifier=block_identifier)
if ... | def function[effective_balance, parameter[self, address, block_identifier]]:
constant[ The user's balance with planned withdrawals deducted. ]
variable[fn] assign[=] call[name[getattr], parameter[name[self].proxy.contract.functions, constant[effectiveBalance]]]
variable[balance] assign[=] call[c... | keyword[def] identifier[effective_balance] ( identifier[self] , identifier[address] : identifier[Address] , identifier[block_identifier] : identifier[BlockSpecification] )-> identifier[Balance] :
literal[string]
identifier[fn] = identifier[getattr] ( identifier[self] . identifier[proxy] . identifie... | def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance:
""" The user's balance with planned withdrawals deducted. """
fn = getattr(self.proxy.contract.functions, 'effectiveBalance')
balance = fn(address).call(block_identifier=block_identifier)
if balance == b'':
... |
def _get_parsed_url(url):
# type: (S) -> Url
"""
This is a stand-in function for `urllib3.util.parse_url`
The orignal function doesn't handle special characters very well, this simply splits
out the authentication section, creates the parsed url, then puts the authentication
section back in, by... | def function[_get_parsed_url, parameter[url]]:
constant[
This is a stand-in function for `urllib3.util.parse_url`
The orignal function doesn't handle special characters very well, this simply splits
out the authentication section, creates the parsed url, then puts the authentication
section bac... | keyword[def] identifier[_get_parsed_url] ( identifier[url] ):
literal[string]
keyword[try] :
identifier[parsed] = identifier[urllib3_parse] ( identifier[url] )
keyword[except] identifier[ValueError] :
identifier[scheme] , identifier[_] , identifier[url] = identifier[url] . identif... | def _get_parsed_url(url):
# type: (S) -> Url
"\n This is a stand-in function for `urllib3.util.parse_url`\n\n The orignal function doesn't handle special characters very well, this simply splits\n out the authentication section, creates the parsed url, then puts the authentication\n section back in,... |
def logs(self):
"""获取收藏夹日志
:return: 收藏夹日志中的操作,返回生成器
:rtype: CollectActivity.Iterable
"""
import time
from datetime import datetime
from .answer import Answer
from .question import Question
from .acttype import CollectActType
self._make_so... | def function[logs, parameter[self]]:
constant[获取收藏夹日志
:return: 收藏夹日志中的操作,返回生成器
:rtype: CollectActivity.Iterable
]
import module[time]
from relative_module[datetime] import module[datetime]
from relative_module[answer] import module[Answer]
from relative_module[question] ... | keyword[def] identifier[logs] ( identifier[self] ):
literal[string]
keyword[import] identifier[time]
keyword[from] identifier[datetime] keyword[import] identifier[datetime]
keyword[from] . identifier[answer] keyword[import] identifier[Answer]
keyword[from] . iden... | def logs(self):
"""获取收藏夹日志
:return: 收藏夹日志中的操作,返回生成器
:rtype: CollectActivity.Iterable
"""
import time
from datetime import datetime
from .answer import Answer
from .question import Question
from .acttype import CollectActType
self._make_soup()
gotten_feed_num = 20... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.