code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def post(self, request, *args, **kwargs):
""" Post a service request (requires authentication) """
service_code = request.data['service_code']
if service_code not in SERVICES.keys():
return Response({ 'detail': _('Service not found') }, status=404)
serializers = {
... | def function[post, parameter[self, request]]:
constant[ Post a service request (requires authentication) ]
variable[service_code] assign[=] call[name[request].data][constant[service_code]]
if compare[name[service_code] <ast.NotIn object at 0x7da2590d7190> call[name[SERVICES].keys, parameter[]]] ... | keyword[def] identifier[post] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[service_code] = identifier[request] . identifier[data] [ literal[string] ]
keyword[if] identifier[service_code] keyword[not] keyword[in] iden... | def post(self, request, *args, **kwargs):
""" Post a service request (requires authentication) """
service_code = request.data['service_code']
if service_code not in SERVICES.keys():
return Response({'detail': _('Service not found')}, status=404) # depends on [control=['if'], data=[]]
serialize... |
def read(self, fieldname):
"""
Read the next field from the stream. `fieldname` is used
to verify that your application logic matches the message
field order, and if `fieldname` does not match the next
field in the message definition, :class:`SendlibError`
is raised.
... | def function[read, parameter[self, fieldname]]:
constant[
Read the next field from the stream. `fieldname` is used
to verify that your application logic matches the message
field order, and if `fieldname` does not match the next
field in the message definition, :class:`SendlibErr... | keyword[def] identifier[read] ( identifier[self] , identifier[fieldname] ):
literal[string]
keyword[if] identifier[self] . identifier[_pos] ==- literal[int] :
identifier[self] . identifier[_pos] = literal[int]
keyword[if] identifier[PREFIX] [ literal[string] ]!= identif... | def read(self, fieldname):
"""
Read the next field from the stream. `fieldname` is used
to verify that your application logic matches the message
field order, and if `fieldname` does not match the next
field in the message definition, :class:`SendlibError`
is raised.
... |
def make_dataloader(data_train, data_val, data_test, args,
use_average_length=False, num_shards=0, num_workers=8):
"""Create data loaders for training/validation/test."""
data_train_lengths = get_data_lengths(data_train)
data_val_lengths = get_data_lengths(data_val)
data_test_lengths... | def function[make_dataloader, parameter[data_train, data_val, data_test, args, use_average_length, num_shards, num_workers]]:
constant[Create data loaders for training/validation/test.]
variable[data_train_lengths] assign[=] call[name[get_data_lengths], parameter[name[data_train]]]
variable[data... | keyword[def] identifier[make_dataloader] ( identifier[data_train] , identifier[data_val] , identifier[data_test] , identifier[args] ,
identifier[use_average_length] = keyword[False] , identifier[num_shards] = literal[int] , identifier[num_workers] = literal[int] ):
literal[string]
identifier[data_train_le... | def make_dataloader(data_train, data_val, data_test, args, use_average_length=False, num_shards=0, num_workers=8):
"""Create data loaders for training/validation/test."""
data_train_lengths = get_data_lengths(data_train)
data_val_lengths = get_data_lengths(data_val)
data_test_lengths = get_data_lengths(... |
def keep_types(self, base_key, out_key, *types):
"""
Method to keep only specific parameters from a parameter documentation.
This method extracts the given `type` from the `base_key` item in the
:attr:`params` dictionary and creates a new item with the original
documentation wit... | def function[keep_types, parameter[self, base_key, out_key]]:
constant[
Method to keep only specific parameters from a parameter documentation.
This method extracts the given `type` from the `base_key` item in the
:attr:`params` dictionary and creates a new item with the original
... | keyword[def] identifier[keep_types] ( identifier[self] , identifier[base_key] , identifier[out_key] ,* identifier[types] ):
literal[string]
identifier[self] . identifier[params] [ literal[string] %( identifier[base_key] , identifier[out_key] )]= identifier[self] . identifier[keep_types_s] (
... | def keep_types(self, base_key, out_key, *types):
"""
Method to keep only specific parameters from a parameter documentation.
This method extracts the given `type` from the `base_key` item in the
:attr:`params` dictionary and creates a new item with the original
documentation with on... |
def mac(self, mac):
"""Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi.
"""
self._mac = mac
if mac:
self.duid = ... | def function[mac, parameter[self, mac]]:
constant[Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi.
]
name[self]._mac assign[=] name[... | keyword[def] identifier[mac] ( identifier[self] , identifier[mac] ):
literal[string]
identifier[self] . identifier[_mac] = identifier[mac]
keyword[if] identifier[mac] :
identifier[self] . identifier[duid] = identifier[ib_utils] . identifier[generate_duid] ( identifier[mac] )... | def mac(self, mac):
"""Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi.
"""
self._mac = mac
if mac:
self.duid = ib_utils.generat... |
def partition_query(
self,
sql,
params=None,
param_types=None,
partition_size_bytes=None,
max_partitions=None,
):
"""Perform a ``ParitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> c... | def function[partition_query, parameter[self, sql, params, param_types, partition_size_bytes, max_partitions]]:
constant[Perform a ``ParitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for p... | keyword[def] identifier[partition_query] (
identifier[self] ,
identifier[sql] ,
identifier[params] = keyword[None] ,
identifier[param_types] = keyword[None] ,
identifier[partition_size_bytes] = keyword[None] ,
identifier[max_partitions] = keyword[None] ,
):
literal[string]
keyword[if] keywor... | def partition_query(self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None):
"""Perform a ``ParitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter re... |
def loads(self, config_str, as_defaults=False):
"""
Load configuration values from the specified source string.
Args:
config_str:
as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
"""
self._rw.load_... | def function[loads, parameter[self, config_str, as_defaults]]:
constant[
Load configuration values from the specified source string.
Args:
config_str:
as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
]
... | keyword[def] identifier[loads] ( identifier[self] , identifier[config_str] , identifier[as_defaults] = keyword[False] ):
literal[string]
identifier[self] . identifier[_rw] . identifier[load_config_from_string] ( identifier[self] . identifier[_config] , identifier[config_str] , identifier[as_default... | def loads(self, config_str, as_defaults=False):
"""
Load configuration values from the specified source string.
Args:
config_str:
as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
"""
self._rw.load_config_f... |
def ReadUserNotifications(self,
username,
state=None,
timerange=None,
cursor=None):
"""Reads notifications scheduled for a user within a given timerange."""
query = ("SELECT UNIX_TIMESTAMP(timestamp)... | def function[ReadUserNotifications, parameter[self, username, state, timerange, cursor]]:
constant[Reads notifications scheduled for a user within a given timerange.]
variable[query] assign[=] constant[SELECT UNIX_TIMESTAMP(timestamp), notification_state, notification FROM user_notification WHERE... | keyword[def] identifier[ReadUserNotifications] ( identifier[self] ,
identifier[username] ,
identifier[state] = keyword[None] ,
identifier[timerange] = keyword[None] ,
identifier[cursor] = keyword[None] ):
literal[string]
identifier[query] =( literal[string]
literal[string]
literal[string] ... | def ReadUserNotifications(self, username, state=None, timerange=None, cursor=None):
"""Reads notifications scheduled for a user within a given timerange."""
query = 'SELECT UNIX_TIMESTAMP(timestamp), notification_state, notification FROM user_notification WHERE username_hash = %s '
args = [mysql_util... |
def metabolite_summary(met, solution=None, threshold=0.01, fva=False,
names=False, floatfmt='.3g'):
"""
Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
so... | def function[metabolite_summary, parameter[met, solution, threshold, fva, names, floatfmt]]:
constant[
Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
solution : cobra.Solut... | keyword[def] identifier[metabolite_summary] ( identifier[met] , identifier[solution] = keyword[None] , identifier[threshold] = literal[int] , identifier[fva] = keyword[False] ,
identifier[names] = keyword[False] , identifier[floatfmt] = literal[string] ):
literal[string]
keyword[if] identifier[names] :
... | def metabolite_summary(met, solution=None, threshold=0.01, fva=False, names=False, floatfmt='.3g'):
"""
Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
solution : cobra.Solution... |
def islice(self, start=None, stop=None, reverse=False):
"""
Returns an iterator that slices `self` from `start` to `stop` index,
inclusive and exclusive respectively.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
Both `start` and `stop... | def function[islice, parameter[self, start, stop, reverse]]:
constant[
Returns an iterator that slices `self` from `start` to `stop` index,
inclusive and exclusive respectively.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
Both `start... | keyword[def] identifier[islice] ( identifier[self] , identifier[start] = keyword[None] , identifier[stop] = keyword[None] , identifier[reverse] = keyword[False] ):
literal[string]
identifier[_len] = identifier[self] . identifier[_len]
keyword[if] keyword[not] identifier[_len] :
... | def islice(self, start=None, stop=None, reverse=False):
"""
Returns an iterator that slices `self` from `start` to `stop` index,
inclusive and exclusive respectively.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
Both `start` and `stop` de... |
def ipshuffle(l, random=None):
r"""Shuffle list `l` inplace and return it."""
import random as _random
_random.shuffle(l, random)
return l | def function[ipshuffle, parameter[l, random]]:
constant[Shuffle list `l` inplace and return it.]
import module[random] as alias[_random]
call[name[_random].shuffle, parameter[name[l], name[random]]]
return[name[l]] | keyword[def] identifier[ipshuffle] ( identifier[l] , identifier[random] = keyword[None] ):
literal[string]
keyword[import] identifier[random] keyword[as] identifier[_random]
identifier[_random] . identifier[shuffle] ( identifier[l] , identifier[random] )
keyword[return] identifier[l] | def ipshuffle(l, random=None):
"""Shuffle list `l` inplace and return it."""
import random as _random
_random.shuffle(l, random)
return l |
def remove_query_param(self, key, value=None):
"""
Remove a query param from a URL
Set the value parameter if removing from a list.
:param string key: The key to delete
:param string value: The value of the param to delete (of more than one)
"""
parse_result = s... | def function[remove_query_param, parameter[self, key, value]]:
constant[
Remove a query param from a URL
Set the value parameter if removing from a list.
:param string key: The key to delete
:param string value: The value of the param to delete (of more than one)
]
... | keyword[def] identifier[remove_query_param] ( identifier[self] , identifier[key] , identifier[value] = keyword[None] ):
literal[string]
identifier[parse_result] = identifier[self] . identifier[query_params] ()
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
... | def remove_query_param(self, key, value=None):
"""
Remove a query param from a URL
Set the value parameter if removing from a list.
:param string key: The key to delete
:param string value: The value of the param to delete (of more than one)
"""
parse_result = self.quer... |
def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb... | def function[_get_color_definitions, parameter[data]]:
constant[Returns the list of custom color definitions for the TikZ file.
]
variable[definitions] assign[=] list[[]]
variable[fmt] assign[=] binary_operation[binary_operation[constant[\definecolor{{{}}}{{rgb}}{{] + call[constant[,].join, ... | keyword[def] identifier[_get_color_definitions] ( identifier[data] ):
literal[string]
identifier[definitions] =[]
identifier[fmt] = literal[string] + literal[string] . identifier[join] ( literal[int] *[ identifier[data] [ literal[string] ]])+ literal[string]
keyword[for] identifier[name] , iden... | def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = '\\definecolor{{{}}}{{rgb}}{{' + ','.join(3 * [data['float format']]) + '}}'
for (name, rgb) in data['custom colors'].items():
definitions.append(fmt.format(name, r... |
def fold_list(input_list, max_width=None):
"""
Fold the entries in input_list. If max_width is not None, fold only if it
is longer than max_width. Otherwise fold each entry.
"""
if not input_list:
return ""
if not isinstance(input_list[0], six.string_types):
input_list = [str(ite... | def function[fold_list, parameter[input_list, max_width]]:
constant[
Fold the entries in input_list. If max_width is not None, fold only if it
is longer than max_width. Otherwise fold each entry.
]
if <ast.UnaryOp object at 0x7da1b0ef4c10> begin[:]
return[constant[]]
if <ast.... | keyword[def] identifier[fold_list] ( identifier[input_list] , identifier[max_width] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[input_list] :
keyword[return] literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[input_list] [ literal[int... | def fold_list(input_list, max_width=None):
"""
Fold the entries in input_list. If max_width is not None, fold only if it
is longer than max_width. Otherwise fold each entry.
"""
if not input_list:
return '' # depends on [control=['if'], data=[]]
if not isinstance(input_list[0], six.stri... |
def construct_reference_system(
symbols,
candidates=None,
options=None,
):
"""Take a list of symbols and construct gas phase
references system, when possible avoiding O2.
Candidates can be rearranged, where earlier candidates
get higher preference than later candidates
assume symbols so... | def function[construct_reference_system, parameter[symbols, candidates, options]]:
constant[Take a list of symbols and construct gas phase
references system, when possible avoiding O2.
Candidates can be rearranged, where earlier candidates
get higher preference than later candidates
assume symb... | keyword[def] identifier[construct_reference_system] (
identifier[symbols] ,
identifier[candidates] = keyword[None] ,
identifier[options] = keyword[None] ,
):
literal[string]
keyword[if] identifier[hasattr] ( identifier[options] , literal[string] ) keyword[and] identifier[options] . identifier[no_hydro... | def construct_reference_system(symbols, candidates=None, options=None):
"""Take a list of symbols and construct gas phase
references system, when possible avoiding O2.
Candidates can be rearranged, where earlier candidates
get higher preference than later candidates
assume symbols sorted by atomic ... |
def fmt_size(size, binary=True):
'''
Get size and unit.
:param size: size in bytes
:type size: int
:param binary: whether use binary or standard units, defaults to True
:type binary: bool
:return: size and unit
:rtype: tuple of int and unit as str
'''
if binary:
fmt_size... | def function[fmt_size, parameter[size, binary]]:
constant[
Get size and unit.
:param size: size in bytes
:type size: int
:param binary: whether use binary or standard units, defaults to True
:type binary: bool
:return: size and unit
:rtype: tuple of int and unit as str
]
... | keyword[def] identifier[fmt_size] ( identifier[size] , identifier[binary] = keyword[True] ):
literal[string]
keyword[if] identifier[binary] :
identifier[fmt_sizes] = identifier[binary_units]
identifier[fmt_divider] = literal[int]
keyword[else] :
identifier[fmt_sizes] = id... | def fmt_size(size, binary=True):
"""
Get size and unit.
:param size: size in bytes
:type size: int
:param binary: whether use binary or standard units, defaults to True
:type binary: bool
:return: size and unit
:rtype: tuple of int and unit as str
"""
if binary:
fmt_size... |
def set(self, document_data, merge=False):
"""Replace the current document in the Firestore database.
A write ``option`` can be specified to indicate preconditions of
the "set" operation. If no ``option`` is specified and this document
doesn't exist yet, this method will create it.
... | def function[set, parameter[self, document_data, merge]]:
constant[Replace the current document in the Firestore database.
A write ``option`` can be specified to indicate preconditions of
the "set" operation. If no ``option`` is specified and this document
doesn't exist yet, this method... | keyword[def] identifier[set] ( identifier[self] , identifier[document_data] , identifier[merge] = keyword[False] ):
literal[string]
identifier[batch] = identifier[self] . identifier[_client] . identifier[batch] ()
identifier[batch] . identifier[set] ( identifier[self] , identifier[document... | def set(self, document_data, merge=False):
"""Replace the current document in the Firestore database.
A write ``option`` can be specified to indicate preconditions of
the "set" operation. If no ``option`` is specified and this document
doesn't exist yet, this method will create it.
... |
def __writepid(self, pid):
"""
HoverFly fails to launch if it's already running on
the same ports. So we have to keep track of them using
temp files with the proxy port and admin port, containing
the processe's PID.
"""
import tempfile
d = tempfile.gettem... | def function[__writepid, parameter[self, pid]]:
constant[
HoverFly fails to launch if it's already running on
the same ports. So we have to keep track of them using
temp files with the proxy port and admin port, containing
the processe's PID.
]
import module[tempfile... | keyword[def] identifier[__writepid] ( identifier[self] , identifier[pid] ):
literal[string]
keyword[import] identifier[tempfile]
identifier[d] = identifier[tempfile] . identifier[gettempdir] ()
identifier[name] = identifier[os] . identifier[path] . identifier[join] ( identifier[... | def __writepid(self, pid):
"""
HoverFly fails to launch if it's already running on
the same ports. So we have to keep track of them using
temp files with the proxy port and admin port, containing
the processe's PID.
"""
import tempfile
d = tempfile.gettempdir()
n... |
def translate(
nucleotide_sequence,
first_codon_is_start=True,
to_stop=True,
truncate=False):
"""Translates cDNA coding sequence into amino acid protein sequence.
Should typically start with a start codon but allowing non-methionine
first residues since the CDS we're transla... | def function[translate, parameter[nucleotide_sequence, first_codon_is_start, to_stop, truncate]]:
constant[Translates cDNA coding sequence into amino acid protein sequence.
Should typically start with a start codon but allowing non-methionine
first residues since the CDS we're translating might have be... | keyword[def] identifier[translate] (
identifier[nucleotide_sequence] ,
identifier[first_codon_is_start] = keyword[True] ,
identifier[to_stop] = keyword[True] ,
identifier[truncate] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[nucleotide_sequence] , ... | def translate(nucleotide_sequence, first_codon_is_start=True, to_stop=True, truncate=False):
"""Translates cDNA coding sequence into amino acid protein sequence.
Should typically start with a start codon but allowing non-methionine
first residues since the CDS we're translating might have been affected
... |
def shift(self, modelResult):
"""Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction in our
FIFO and would not b... | def function[shift, parameter[self, modelResult]]:
constant[Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction ... | keyword[def] identifier[shift] ( identifier[self] , identifier[modelResult] ):
literal[string]
identifier[inferencesToWrite] ={}
keyword[if] identifier[self] . identifier[_inferenceBuffer] keyword[is] keyword[None] :
identifier[maxDelay] = identifier[InferenceElement] . identifier[getMaxDel... | def shift(self, modelResult):
"""Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction in our
FIFO and would not b... |
def readlines(self, timeout=1):
"""
read all lines that are available. abort after timeout
when no more data arrives.
"""
lines = []
while 1:
line = self.readline(timeout=timeout)
if line:
lines.append(line)
if not line ... | def function[readlines, parameter[self, timeout]]:
constant[
read all lines that are available. abort after timeout
when no more data arrives.
]
variable[lines] assign[=] list[[]]
while constant[1] begin[:]
variable[line] assign[=] call[name[self].readline... | keyword[def] identifier[readlines] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
identifier[lines] =[]
keyword[while] literal[int] :
identifier[line] = identifier[self] . identifier[readline] ( identifier[timeout] = identifier[timeout] )
... | def readlines(self, timeout=1):
"""
read all lines that are available. abort after timeout
when no more data arrives.
"""
lines = []
while 1:
line = self.readline(timeout=timeout)
if line:
lines.append(line) # depends on [control=['if'], data=[]]
... |
def _Open(self, path_spec, mode='rb'):
"""Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode. The default is 'rb'
read-only binary.
Raises:
AccessError: if the access to open the file was d... | def function[_Open, parameter[self, path_spec, mode]]:
constant[Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode. The default is 'rb'
read-only binary.
Raises:
AccessError: if the acc... | keyword[def] identifier[_Open] ( identifier[self] , identifier[path_spec] , identifier[mode] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[path_spec] . identifier[HasParent] ():
keyword[raise] identifier[errors] . identifier[PathSpecError] (
literal[string] )
... | def _Open(self, path_spec, mode='rb'):
"""Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode. The default is 'rb'
read-only binary.
Raises:
AccessError: if the access to open the file was d... |
def save_to_file(self, filename: str) -> ConfigFile:
"""
This converts the NetworkedConfigFile into a normal ConfigFile object.
This requires the normal class hooks to be provided.
"""
newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0],
... | def function[save_to_file, parameter[self, filename]]:
constant[
This converts the NetworkedConfigFile into a normal ConfigFile object.
This requires the normal class hooks to be provided.
]
variable[newclass] assign[=] call[name[ConfigFile], parameter[]]
return[name[newclas... | keyword[def] identifier[save_to_file] ( identifier[self] , identifier[filename] : identifier[str] )-> identifier[ConfigFile] :
literal[string]
identifier[newclass] = identifier[ConfigFile] ( identifier[fd] = identifier[filename] , identifier[load_hook] = identifier[self] . identifier[normal_class_h... | def save_to_file(self, filename: str) -> ConfigFile:
"""
This converts the NetworkedConfigFile into a normal ConfigFile object.
This requires the normal class hooks to be provided.
"""
newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0], dump_hook=self.normal_class_ho... |
def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type,
budget):
"""Add a Campaign to the client account.
Args:
client_customer_id: str Client Customer Id to use when creating Campaign.
campaign_name: str Name of the campaign to be added.
ad_channel_type: s... | def function[AddCampaign, parameter[self, client_customer_id, campaign_name, ad_channel_type, budget]]:
constant[Add a Campaign to the client account.
Args:
client_customer_id: str Client Customer Id to use when creating Campaign.
campaign_name: str Name of the campaign to be added.
ad_ch... | keyword[def] identifier[AddCampaign] ( identifier[self] , identifier[client_customer_id] , identifier[campaign_name] , identifier[ad_channel_type] ,
identifier[budget] ):
literal[string]
identifier[self] . identifier[client] . identifier[SetClientCustomerId] ( identifier[client_customer_id] )
identif... | def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type, budget):
"""Add a Campaign to the client account.
Args:
client_customer_id: str Client Customer Id to use when creating Campaign.
campaign_name: str Name of the campaign to be added.
ad_channel_type: str Primary serving... |
def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None):
"""
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the b... | def function[edit_message_text, parameter[self, text, chat_id, message_id, inline_message_id, parse_mode, disable_web_page_preview, reply_markup]]:
constant[
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot,... | keyword[def] identifier[edit_message_text] ( identifier[self] , identifier[text] , identifier[chat_id] = keyword[None] , identifier[message_id] = keyword[None] , identifier[inline_message_id] = keyword[None] , identifier[parse_mode] = keyword[None] , identifier[disable_web_page_preview] = keyword[None] , identifier[r... | def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None):
"""
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, ... |
def get_cached(location, **kwargs):
"""
Simple wrapper that adds Django caching support to 'geocoder.get()'.
"""
result = cache.get(location)
# Result is not cached or wrong
if not result or not result.ok:
result = geocoder.get(location, **kwargs)
if result.ok:
cache... | def function[get_cached, parameter[location]]:
constant[
Simple wrapper that adds Django caching support to 'geocoder.get()'.
]
variable[result] assign[=] call[name[cache].get, parameter[name[location]]]
if <ast.BoolOp object at 0x7da1b2524310> begin[:]
variable[result] a... | keyword[def] identifier[get_cached] ( identifier[location] ,** identifier[kwargs] ):
literal[string]
identifier[result] = identifier[cache] . identifier[get] ( identifier[location] )
keyword[if] keyword[not] identifier[result] keyword[or] keyword[not] identifier[result] . identifier[ok] :
... | def get_cached(location, **kwargs):
"""
Simple wrapper that adds Django caching support to 'geocoder.get()'.
"""
result = cache.get(location)
# Result is not cached or wrong
if not result or not result.ok:
result = geocoder.get(location, **kwargs)
if result.ok:
cache.... |
def rotate_z(self, angle):
"""
Rotates mesh about the z-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the z-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='z') | def function[rotate_z, parameter[self, angle]]:
constant[
Rotates mesh about the z-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the z-axis.
]
call[name[axis_rotation], parameter[name[self].points, name[angle]]] | keyword[def] identifier[rotate_z] ( identifier[self] , identifier[angle] ):
literal[string]
identifier[axis_rotation] ( identifier[self] . identifier[points] , identifier[angle] , identifier[inplace] = keyword[True] , identifier[axis] = literal[string] ) | def rotate_z(self, angle):
"""
Rotates mesh about the z-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the z-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='z') |
def tie_weights(self):
""" Run this to be sure output and input (adaptive) softmax weights are tied """
# sampled softmax
if self.sample_softmax > 0:
if self.config.tie_weight:
self.out_layer.weight = self.transformer.word_emb.weight
# adaptive softmax (includ... | def function[tie_weights, parameter[self]]:
constant[ Run this to be sure output and input (adaptive) softmax weights are tied ]
if compare[name[self].sample_softmax greater[>] constant[0]] begin[:]
if name[self].config.tie_weight begin[:]
name[self].out_layer.wei... | keyword[def] identifier[tie_weights] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[sample_softmax] > literal[int] :
keyword[if] identifier[self] . identifier[config] . identifier[tie_weight] :
identifier[self] . identifier[o... | def tie_weights(self):
""" Run this to be sure output and input (adaptive) softmax weights are tied """
# sampled softmax
if self.sample_softmax > 0:
if self.config.tie_weight:
self.out_layer.weight = self.transformer.word_emb.weight # depends on [control=['if'], data=[]] # depends on ... |
def register_frontend_media(request, media):
"""
Add a :class:`~django.forms.Media` class to the current request.
This will be rendered by the ``render_plugin_media`` template tag.
"""
if not hasattr(request, '_fluent_contents_frontend_media'):
request._fluent_contents_frontend_media = Media... | def function[register_frontend_media, parameter[request, media]]:
constant[
Add a :class:`~django.forms.Media` class to the current request.
This will be rendered by the ``render_plugin_media`` template tag.
]
if <ast.UnaryOp object at 0x7da1b10e5450> begin[:]
name[request]._... | keyword[def] identifier[register_frontend_media] ( identifier[request] , identifier[media] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[request] , literal[string] ):
identifier[request] . identifier[_fluent_contents_frontend_media] = identifier[Media] ()
ide... | def register_frontend_media(request, media):
"""
Add a :class:`~django.forms.Media` class to the current request.
This will be rendered by the ``render_plugin_media`` template tag.
"""
if not hasattr(request, '_fluent_contents_frontend_media'):
request._fluent_contents_frontend_media = Media... |
def initialize_sentry_integration(): # pragma: no cover
"""\
Used to optionally initialize the Sentry service with this app.
See https://docs.sentry.io/platforms/python/pyramid/
"""
# This function is not under coverage because it is boilerplate
# from the Sentry documentation.
try:
... | def function[initialize_sentry_integration, parameter[]]:
constant[ Used to optionally initialize the Sentry service with this app.
See https://docs.sentry.io/platforms/python/pyramid/
]
<ast.Try object at 0x7da1b003d960>
<ast.Try object at 0x7da1b003c700> | keyword[def] identifier[initialize_sentry_integration] ():
literal[string]
keyword[try] :
keyword[import] identifier[sentry_sdk]
keyword[from] identifier[sentry_sdk] . identifier[integrations] . identifier[pyramid] keyword[import] identifier[PyramidIntegration]
ke... | def initialize_sentry_integration(): # pragma: no cover
' Used to optionally initialize the Sentry service with this app.\n See https://docs.sentry.io/platforms/python/pyramid/\n\n '
# This function is not under coverage because it is boilerplate
# from the Sentry documentation.
try:
i... |
def fingerprint_from_var(var):
"""Extract a fingerprint from a GPG public key"""
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append("--with-fingerprint")
output = polite_string(stderr_with_input(cmd, var)).split('\n')
if not output[0... | def function[fingerprint_from_var, parameter[var]]:
constant[Extract a fingerprint from a GPG public key]
variable[vsn] assign[=] call[name[gpg_version], parameter[]]
variable[cmd] assign[=] call[name[flatten], parameter[list[[<ast.Call object at 0x7da1b18e4190>, <ast.Call object at 0x7da1b18e5c... | keyword[def] identifier[fingerprint_from_var] ( identifier[var] ):
literal[string]
identifier[vsn] = identifier[gpg_version] ()
identifier[cmd] = identifier[flatten] ([ identifier[gnupg_bin] (), identifier[gnupg_home] ()])
keyword[if] identifier[vsn] [ literal[int] ]>= literal[int] keyword[and]... | def fingerprint_from_var(var):
"""Extract a fingerprint from a GPG public key"""
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append('--with-fingerprint') # depends on [control=['if'], data=[]]
output = polite_string(stderr_with_input(cmd... |
def remove_datasource(jboss_config, name, profile=None):
'''
Remove an existing datasource from the running jboss instance.
jboss_config
Configuration dictionary with properties specified above.
name
Datasource name
profile
The profile (JBoss domain mode only)
CLI Examp... | def function[remove_datasource, parameter[jboss_config, name, profile]]:
constant[
Remove an existing datasource from the running jboss instance.
jboss_config
Configuration dictionary with properties specified above.
name
Datasource name
profile
The profile (JBoss domain... | keyword[def] identifier[remove_datasource] ( identifier[jboss_config] , identifier[name] , identifier[profile] = keyword[None] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[name] , identifier[profile] )
identifier[operation] = literal[string] . identifier[forma... | def remove_datasource(jboss_config, name, profile=None):
"""
Remove an existing datasource from the running jboss instance.
jboss_config
Configuration dictionary with properties specified above.
name
Datasource name
profile
The profile (JBoss domain mode only)
CLI Examp... |
def getVMstats(self):
"""Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(vmstatFile, 'r')
data = fp.read()
fp.close()
except:
raise IOError('Failed... | def function[getVMstats, parameter[self]]:
constant[Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
]
variable[info_dict] assign[=] dictionary[[], []]
<ast.Try object at 0x7da2054a45e0>
for taget[name[line]] in starred[call[name[data... | keyword[def] identifier[getVMstats] ( identifier[self] ):
literal[string]
identifier[info_dict] ={}
keyword[try] :
identifier[fp] = identifier[open] ( identifier[vmstatFile] , literal[string] )
identifier[data] = identifier[fp] . identifier[read] ()
i... | def getVMstats(self):
"""Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(vmstatFile, 'r')
data = fp.read()
fp.close() # depends on [control=['try'], data=[]]
except:
raise IOErro... |
def _preprocess(self, data, train):
"""Zero-mean, unit-variance normalization by default"""
if train:
inputs, labels = data
self.data_mean = inputs.mean(axis=0)
self.data_std = inputs.std(axis=0)
self.labels_mean = labels.mean(axis=0)
self.lab... | def function[_preprocess, parameter[self, data, train]]:
constant[Zero-mean, unit-variance normalization by default]
if name[train] begin[:]
<ast.Tuple object at 0x7da1b1ceec50> assign[=] name[data]
name[self].data_mean assign[=] call[name[inputs].mean, parameter[]]
... | keyword[def] identifier[_preprocess] ( identifier[self] , identifier[data] , identifier[train] ):
literal[string]
keyword[if] identifier[train] :
identifier[inputs] , identifier[labels] = identifier[data]
identifier[self] . identifier[data_mean] = identifier[inputs] . id... | def _preprocess(self, data, train):
"""Zero-mean, unit-variance normalization by default"""
if train:
(inputs, labels) = data
self.data_mean = inputs.mean(axis=0)
self.data_std = inputs.std(axis=0)
self.labels_mean = labels.mean(axis=0)
self.labels_std = labels.std(axis=0... |
def rename_file(self, relativePath, newRelativePath,
force=False, raiseError=True, ntrials=3):
"""
Rename a file in the repository. It insures renaming the file in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
... | def function[rename_file, parameter[self, relativePath, newRelativePath, force, raiseError, ntrials]]:
constant[
Rename a file in the repository. It insures renaming the file in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
... | keyword[def] identifier[rename_file] ( identifier[self] , identifier[relativePath] , identifier[newRelativePath] ,
identifier[force] = keyword[False] , identifier[raiseError] = keyword[True] , identifier[ntrials] = literal[int] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifie... | def rename_file(self, relativePath, newRelativePath, force=False, raiseError=True, ntrials=3):
"""
Rename a file in the repository. It insures renaming the file in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
the file that need... |
def query(url, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.que... | def function[query, parameter[url]]:
constant[
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
... | keyword[def] identifier[query] ( identifier[url] ,** identifier[kwargs] ):
literal[string]
identifier[opts] = identifier[__opts__] . identifier[copy] ()
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[opts] . identifier[update] ( identifier[kwargs] [ literal[string]... | def query(url, **kwargs):
"""
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.que... |
def delete(self, port, qos_policy=None):
"""Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port.
"""
LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s",
dict(qos_policy=qos_policy, port=port... | def function[delete, parameter[self, port, qos_policy]]:
constant[Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port.
]
call[name[LOG].info, parameter[constant[Deleting QoS policy %(qos_policy)s on port %(port)s], call... | keyword[def] identifier[delete] ( identifier[self] , identifier[port] , identifier[qos_policy] = keyword[None] ):
literal[string]
identifier[LOG] . identifier[info] ( literal[string] ,
identifier[dict] ( identifier[qos_policy] = identifier[qos_policy] , identifier[port] = identifier[port] ... | def delete(self, port, qos_policy=None):
"""Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port.
"""
LOG.info('Deleting QoS policy %(qos_policy)s on port %(port)s', dict(qos_policy=qos_policy, port=port))
self._utils.remove... |
def rows(self) -> List[List[str]]:
"""
Returns the table rows.
"""
return [list(d.values()) for d in self.data] | def function[rows, parameter[self]]:
constant[
Returns the table rows.
]
return[<ast.ListComp object at 0x7da20c796b30>] | keyword[def] identifier[rows] ( identifier[self] )-> identifier[List] [ identifier[List] [ identifier[str] ]]:
literal[string]
keyword[return] [ identifier[list] ( identifier[d] . identifier[values] ()) keyword[for] identifier[d] keyword[in] identifier[self] . identifier[data] ] | def rows(self) -> List[List[str]]:
"""
Returns the table rows.
"""
return [list(d.values()) for d in self.data] |
def get_search_token_from_orcid(self, scope='/read-public'):
"""Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
"""
... | def function[get_search_token_from_orcid, parameter[self, scope]]:
constant[Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
... | keyword[def] identifier[get_search_token_from_orcid] ( identifier[self] , identifier[scope] = literal[string] ):
literal[string]
identifier[payload] ={ literal[string] : identifier[self] . identifier[_key] ,
literal[string] : identifier[self] . identifier[_secret] ,
literal[string... | def get_search_token_from_orcid(self, scope='/read-public'):
"""Get a token for searching ORCID records.
Parameters
----------
:param scope: string
/read-public or /read-member
Returns
-------
:returns: string
The token.
"""
paylo... |
def Flavio_to_Fierz_nunu(C, ddll, parameters, norm_gf=True):
"""From Flavio semileptonic basis to semileptonic Fierz basis for Class V.
C should be the corresponding leptonic Fierz basis and
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc."""
p = parameters
V = ckmutil.ckm.ckm_tree(p["... | def function[Flavio_to_Fierz_nunu, parameter[C, ddll, parameters, norm_gf]]:
constant[From Flavio semileptonic basis to semileptonic Fierz basis for Class V.
C should be the corresponding leptonic Fierz basis and
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.]
variable[p] assign[... | keyword[def] identifier[Flavio_to_Fierz_nunu] ( identifier[C] , identifier[ddll] , identifier[parameters] , identifier[norm_gf] = keyword[True] ):
literal[string]
identifier[p] = identifier[parameters]
identifier[V] = identifier[ckmutil] . identifier[ckm] . identifier[ckm_tree] ( identifier[p] [ lite... | def Flavio_to_Fierz_nunu(C, ddll, parameters, norm_gf=True):
"""From Flavio semileptonic basis to semileptonic Fierz basis for Class V.
C should be the corresponding leptonic Fierz basis and
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc."""
p = parameters
V = ckmutil.ckm.ckm_tree(p['... |
def sys_munmap(self, addr, size):
"""
Unmaps a file from memory. It deletes the mappings for the specified address range
:rtype: int
:param addr: the starting address to unmap.
:param size: the size of the portion to unmap.
:return: C{0} on success.
"""
s... | def function[sys_munmap, parameter[self, addr, size]]:
constant[
Unmaps a file from memory. It deletes the mappings for the specified address range
:rtype: int
:param addr: the starting address to unmap.
:param size: the size of the portion to unmap.
:return: C{0} on suc... | keyword[def] identifier[sys_munmap] ( identifier[self] , identifier[addr] , identifier[size] ):
literal[string]
identifier[self] . identifier[current] . identifier[memory] . identifier[munmap] ( identifier[addr] , identifier[size] )
keyword[return] literal[int] | def sys_munmap(self, addr, size):
"""
Unmaps a file from memory. It deletes the mappings for the specified address range
:rtype: int
:param addr: the starting address to unmap.
:param size: the size of the portion to unmap.
:return: C{0} on success.
"""
self.curr... |
def recent_comments(context):
"""
Dashboard widget for displaying recent comments.
"""
latest = context["settings"].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related("user")
context["comments"] = comments.order_by("-id")[:latest]
return context | def function[recent_comments, parameter[context]]:
constant[
Dashboard widget for displaying recent comments.
]
variable[latest] assign[=] call[name[context]][constant[settings]].COMMENTS_NUM_LATEST
variable[comments] assign[=] call[call[name[ThreadedComment].objects.all, parameter[]].se... | keyword[def] identifier[recent_comments] ( identifier[context] ):
literal[string]
identifier[latest] = identifier[context] [ literal[string] ]. identifier[COMMENTS_NUM_LATEST]
identifier[comments] = identifier[ThreadedComment] . identifier[objects] . identifier[all] (). identifier[select_related] ( l... | def recent_comments(context):
"""
Dashboard widget for displaying recent comments.
"""
latest = context['settings'].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related('user')
context['comments'] = comments.order_by('-id')[:latest]
return context |
def format_tsv_line(source, edge, target, value=None, metadata=None):
"""
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
"""
return '{source}\t{edge}\t{target}\t{value}\... | def function[format_tsv_line, parameter[source, edge, target, value, metadata]]:
constant[
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
]
return[call[call[constant... | keyword[def] identifier[format_tsv_line] ( identifier[source] , identifier[edge] , identifier[target] , identifier[value] = keyword[None] , identifier[metadata] = keyword[None] ):
literal[string]
keyword[return] literal[string] . identifier[format] (
identifier[source] = identifier[source] ,
ide... | def format_tsv_line(source, edge, target, value=None, metadata=None):
"""
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
"""
return '{source}\t{edge}\t{target}\t{value}\... |
def publish(self,topic,options=None,args=None,kwargs=None):
""" Publishes a messages to the server
"""
topic = self.get_full_uri(topic)
if options is None:
options = {'acknowledge':True}
if options.get('acknowledge'):
request = PUBLISH(
... | def function[publish, parameter[self, topic, options, args, kwargs]]:
constant[ Publishes a messages to the server
]
variable[topic] assign[=] call[name[self].get_full_uri, parameter[name[topic]]]
if compare[name[options] is constant[None]] begin[:]
variable[options] assi... | keyword[def] identifier[publish] ( identifier[self] , identifier[topic] , identifier[options] = keyword[None] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] ):
literal[string]
identifier[topic] = identifier[self] . identifier[get_full_uri] ( identifier[topic] )
key... | def publish(self, topic, options=None, args=None, kwargs=None):
""" Publishes a messages to the server
"""
topic = self.get_full_uri(topic)
if options is None:
options = {'acknowledge': True} # depends on [control=['if'], data=['options']]
if options.get('acknowledge'):
request ... |
def default_callback(pending, timeout):
"""This is the default shutdown callback that is set on the options.
It prints out a message to stderr that informs the user that some events
are still pending and the process is waiting for them to flush out.
"""
def echo(msg):
sys.stderr.write(msg +... | def function[default_callback, parameter[pending, timeout]]:
constant[This is the default shutdown callback that is set on the options.
It prints out a message to stderr that informs the user that some events
are still pending and the process is waiting for them to flush out.
]
def function[... | keyword[def] identifier[default_callback] ( identifier[pending] , identifier[timeout] ):
literal[string]
keyword[def] identifier[echo] ( identifier[msg] ):
identifier[sys] . identifier[stderr] . identifier[write] ( identifier[msg] + literal[string] )
identifier[echo] ( literal[string] % id... | def default_callback(pending, timeout):
"""This is the default shutdown callback that is set on the options.
It prints out a message to stderr that informs the user that some events
are still pending and the process is waiting for them to flush out.
"""
def echo(msg):
sys.stderr.write(msg +... |
def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None):
"""Updates a lbaas_member."""
return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member),
body=body) | def function[update_lbaas_member, parameter[self, lbaas_member, lbaas_pool, body]]:
constant[Updates a lbaas_member.]
return[call[name[self].put, parameter[binary_operation[name[self].lbaas_member_path <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18f00f130>, <ast.Name object at 0x7da18... | keyword[def] identifier[update_lbaas_member] ( identifier[self] , identifier[lbaas_member] , identifier[lbaas_pool] , identifier[body] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[put] ( identifier[self] . identifier[lbaas_member_path] %( identifier[lbaas_pool] ... | def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None):
"""Updates a lbaas_member."""
return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member), body=body) |
def _reset_non_empty(self, indices):
"""Reset the batch of environments.
Args:
indices: The batch indices of the environments to reset; defaults to all.
Returns:
Batch tensor of the new observations.
"""
observ = tf.py_func(
self._batch_env.reset, [indices], self.observ_dtype, ... | def function[_reset_non_empty, parameter[self, indices]]:
constant[Reset the batch of environments.
Args:
indices: The batch indices of the environments to reset; defaults to all.
Returns:
Batch tensor of the new observations.
]
variable[observ] assign[=] call[name[tf].py_func,... | keyword[def] identifier[_reset_non_empty] ( identifier[self] , identifier[indices] ):
literal[string]
identifier[observ] = identifier[tf] . identifier[py_func] (
identifier[self] . identifier[_batch_env] . identifier[reset] ,[ identifier[indices] ], identifier[self] . identifier[observ_dtype] , identi... | def _reset_non_empty(self, indices):
"""Reset the batch of environments.
Args:
indices: The batch indices of the environments to reset; defaults to all.
Returns:
Batch tensor of the new observations.
"""
observ = tf.py_func(self._batch_env.reset, [indices], self.observ_dtype, name='res... |
def _normalize_instancemethod(instance_method):
"""
wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up;
we want the original repr to show up in the logs, therefore we do this trick
"""
if not hasattr(instance_method, 'im_self'):
return instance_met... | def function[_normalize_instancemethod, parameter[instance_method]]:
constant[
wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up;
we want the original repr to show up in the logs, therefore we do this trick
]
if <ast.UnaryOp object at 0x7da20c6a8b... | keyword[def] identifier[_normalize_instancemethod] ( identifier[instance_method] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[instance_method] , literal[string] ):
keyword[return] identifier[instance_method]
keyword[def] identifier[_func] (* identifier[ar... | def _normalize_instancemethod(instance_method):
"""
wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up;
we want the original repr to show up in the logs, therefore we do this trick
"""
if not hasattr(instance_method, 'im_self'):
return instance_met... |
def get_team(self, id):
"""
:calls: `GET /teams/:id <http://developer.github.com/v3/orgs/teams>`_
:param id: integer
:rtype: :class:`github.Team.Team`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"GET"... | def function[get_team, parameter[self, id]]:
constant[
:calls: `GET /teams/:id <http://developer.github.com/v3/orgs/teams>`_
:param id: integer
:rtype: :class:`github.Team.Team`
]
assert[call[name[isinstance], parameter[name[id], tuple[[<ast.Name object at 0x7da20c7caf50>, <a... | keyword[def] identifier[get_team] ( identifier[self] , identifier[id] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[id] ,( identifier[int] , identifier[long] )), identifier[id]
identifier[headers] , identifier[data] = identifier[self] . identifier[_requester] . i... | def get_team(self, id):
"""
:calls: `GET /teams/:id <http://developer.github.com/v3/orgs/teams>`_
:param id: integer
:rtype: :class:`github.Team.Team`
"""
assert isinstance(id, (int, long)), id
(headers, data) = self._requester.requestJsonAndCheck('GET', '/teams/' + str(id))
... |
def update(self, E=None, **F):
'''flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
... | def function[update, parameter[self, E]]:
constant[flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub'... | keyword[def] identifier[update] ( identifier[self] , identifier[E] = keyword[None] ,** identifier[F] ):
literal[string]
keyword[def] identifier[_update] ( identifier[D] ):
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[D] . identifier[items] ():
... | def update(self, E=None, **F):
"""flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
{'... |
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs):
"""
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot the ydata's real and imaginary parts versus xdata.
Parameters
----------
xscrip... | def function[realimag_files, parameter[xscript, yscript, eyscript, exscript, paths, g]]:
constant[
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot the ydata's real and imaginary parts versus xdata.
Parameters
----------
xscript=0
Scr... | keyword[def] identifier[realimag_files] ( identifier[xscript] = literal[int] , identifier[yscript] = literal[string] , identifier[eyscript] = keyword[None] , identifier[exscript] = keyword[None] , identifier[paths] = keyword[None] , identifier[g] = keyword[None] ,** identifier[kwargs] ):
literal[string]
ke... | def realimag_files(xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, paths=None, g=None, **kwargs):
"""
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot the ydata's real and imaginary parts versus xdata.
Parameters
----------
xscrip... |
def compress(obj, level=6, return_type="bytes"):
"""Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode by... | def function[compress, parameter[obj, level, return_type]]:
constant[Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
... | keyword[def] identifier[compress] ( identifier[obj] , identifier[level] = literal[int] , identifier[return_type] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[binary_type] ):
identifier[b] = identifier[_compress_bytes] ( identifier[obj] , i... | def compress(obj, level=6, return_type='bytes'):
"""Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode by... |
def running_window(iterable, size):
"""Generate n-size running window.
Example::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
**中文文档**
简单滑窗函数。
"""
if size > len(iterable):
raise ValueErro... | def function[running_window, parameter[iterable, size]]:
constant[Generate n-size running window.
Example::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
**中文文档**
简单滑窗函数。
]
if compare[name... | keyword[def] identifier[running_window] ( identifier[iterable] , identifier[size] ):
literal[string]
keyword[if] identifier[size] > identifier[len] ( identifier[iterable] ):
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[fifo] = identifier[collections] . identifier[de... | def running_window(iterable, size):
"""Generate n-size running window.
Example::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
**中文文档**
简单滑窗函数。
"""
if size > len(iterable):
raise ValueErro... |
def read_analysis(self, file_handle):
"""Read the ANALYSIS segment of the FCS file and store it in self.analysis.
Warning: This has never been tested with an actual fcs file that contains an
analysis segment.
Args:
file_handle: buffer containing FCS data
"""
... | def function[read_analysis, parameter[self, file_handle]]:
constant[Read the ANALYSIS segment of the FCS file and store it in self.analysis.
Warning: This has never been tested with an actual fcs file that contains an
analysis segment.
Args:
file_handle: buffer containing F... | keyword[def] identifier[read_analysis] ( identifier[self] , identifier[file_handle] ):
literal[string]
identifier[start] = identifier[self] . identifier[annotation] [ literal[string] ][ literal[string] ]
identifier[end] = identifier[self] . identifier[annotation] [ literal[string] ][ liter... | def read_analysis(self, file_handle):
"""Read the ANALYSIS segment of the FCS file and store it in self.analysis.
Warning: This has never been tested with an actual fcs file that contains an
analysis segment.
Args:
file_handle: buffer containing FCS data
"""
start =... |
def to_bytes(self):
'''
Return packed byte representation of the TCP header.
'''
header = self._make_header(self._checksum)
return header + self._options.to_bytes() | def function[to_bytes, parameter[self]]:
constant[
Return packed byte representation of the TCP header.
]
variable[header] assign[=] call[name[self]._make_header, parameter[name[self]._checksum]]
return[binary_operation[name[header] + call[name[self]._options.to_bytes, parameter[]]]] | keyword[def] identifier[to_bytes] ( identifier[self] ):
literal[string]
identifier[header] = identifier[self] . identifier[_make_header] ( identifier[self] . identifier[_checksum] )
keyword[return] identifier[header] + identifier[self] . identifier[_options] . identifier[to_bytes] () | def to_bytes(self):
"""
Return packed byte representation of the TCP header.
"""
header = self._make_header(self._checksum)
return header + self._options.to_bytes() |
def update(self):
"""Update |C2| based on :math:`c_2 = 1.-c_1-c_3`.
Examples:
The following examples show the calculated value of |C2| are
clipped when to low or to high:
>>> from hydpy.models.hstream import *
>>> parameterstep('1d')
>>> der... | def function[update, parameter[self]]:
constant[Update |C2| based on :math:`c_2 = 1.-c_1-c_3`.
Examples:
The following examples show the calculated value of |C2| are
clipped when to low or to high:
>>> from hydpy.models.hstream import *
>>> parameterste... | keyword[def] identifier[update] ( identifier[self] ):
literal[string]
identifier[der] = identifier[self] . identifier[subpars]
identifier[self] ( identifier[numpy] . identifier[clip] ( literal[int] - identifier[der] . identifier[c1] - identifier[der] . identifier[c3] , literal[int] , lite... | def update(self):
"""Update |C2| based on :math:`c_2 = 1.-c_1-c_3`.
Examples:
The following examples show the calculated value of |C2| are
clipped when to low or to high:
>>> from hydpy.models.hstream import *
>>> parameterstep('1d')
>>> derived... |
def get_mechs_available():
"""
Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may not be available by default.... | def function[get_mechs_available, parameter[]]:
constant[
Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may n... | keyword[def] identifier[get_mechs_available] ():
literal[string]
identifier[ntlm_oid] = identifier[GSSAPIContext] . identifier[_AUTH_MECHANISMS] [ literal[string] ]
identifier[ntlm_mech] = identifier[gssapi] . identifier[OID] . identifier[from_int_seq] ( identifier[ntlm_oid] )
... | def get_mechs_available():
"""
Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may not be available by default.
... |
def json_2_routing_area(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 RoutingArea object
"""
LOGGER.debug("RoutingArea.json_2_routing_area")
return RoutingArea(rai... | def function[json_2_routing_area, parameter[json_obj]]:
constant[
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 RoutingArea object
]
call[name[LOGGER].debug, parameter[constant[RoutingAr... | keyword[def] identifier[json_2_routing_area] ( identifier[json_obj] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[return] identifier[RoutingArea] ( identifier[raid] = identifier[json_obj] [ literal[string] ],
identifier[name] = identifier[j... | def json_2_routing_area(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 RoutingArea object
"""
LOGGER.debug('RoutingArea.json_2_routing_area')
return RoutingArea(raid=json_obj['... |
def add_badge(self, kind):
'''Perform an atomic prepend for a new badge'''
badge = self.get_badge(kind)
if badge:
return badge
if kind not in getattr(self, '__badges__', {}):
msg = 'Unknown badge type for {model}: {kind}'
raise db.ValidationError(msg.f... | def function[add_badge, parameter[self, kind]]:
constant[Perform an atomic prepend for a new badge]
variable[badge] assign[=] call[name[self].get_badge, parameter[name[kind]]]
if name[badge] begin[:]
return[name[badge]]
if compare[name[kind] <ast.NotIn object at 0x7da2590d7190> c... | keyword[def] identifier[add_badge] ( identifier[self] , identifier[kind] ):
literal[string]
identifier[badge] = identifier[self] . identifier[get_badge] ( identifier[kind] )
keyword[if] identifier[badge] :
keyword[return] identifier[badge]
keyword[if] identifier[k... | def add_badge(self, kind):
"""Perform an atomic prepend for a new badge"""
badge = self.get_badge(kind)
if badge:
return badge # depends on [control=['if'], data=[]]
if kind not in getattr(self, '__badges__', {}):
msg = 'Unknown badge type for {model}: {kind}'
raise db.Validatio... |
def get_initial_array(events, slots, seed=None):
"""
Obtain a random initial array.
"""
if seed is not None:
np.random.seed(seed)
m = len(events)
n = len(slots)
X = np.zeros((m, n))
for i, row in enumerate(X):
X[i, i] = 1
np.random.shuffle(X)
return X | def function[get_initial_array, parameter[events, slots, seed]]:
constant[
Obtain a random initial array.
]
if compare[name[seed] is_not constant[None]] begin[:]
call[name[np].random.seed, parameter[name[seed]]]
variable[m] assign[=] call[name[len], parameter[name[events]... | keyword[def] identifier[get_initial_array] ( identifier[events] , identifier[slots] , identifier[seed] = keyword[None] ):
literal[string]
keyword[if] identifier[seed] keyword[is] keyword[not] keyword[None] :
identifier[np] . identifier[random] . identifier[seed] ( identifier[seed] )
iden... | def get_initial_array(events, slots, seed=None):
"""
Obtain a random initial array.
"""
if seed is not None:
np.random.seed(seed) # depends on [control=['if'], data=['seed']]
m = len(events)
n = len(slots)
X = np.zeros((m, n))
for (i, row) in enumerate(X):
X[i, i] = 1 #... |
def quantize(
self,
input=None,
qout=False,
cutoff=0,
retrain=False,
epoch=None,
lr=None,
thread=None,
verbose=None,
dsub=2,
qnorm=False
):
"""
Quantize the model reducing the size of the model and
it's m... | def function[quantize, parameter[self, input, qout, cutoff, retrain, epoch, lr, thread, verbose, dsub, qnorm]]:
constant[
Quantize the model reducing the size of the model and
it's memory footprint.
]
variable[a] assign[=] call[name[self].f.getArgs, parameter[]]
if <ast.U... | keyword[def] identifier[quantize] (
identifier[self] ,
identifier[input] = keyword[None] ,
identifier[qout] = keyword[False] ,
identifier[cutoff] = literal[int] ,
identifier[retrain] = keyword[False] ,
identifier[epoch] = keyword[None] ,
identifier[lr] = keyword[None] ,
identifier[thread] = keyword[None] ,
i... | def quantize(self, input=None, qout=False, cutoff=0, retrain=False, epoch=None, lr=None, thread=None, verbose=None, dsub=2, qnorm=False):
"""
Quantize the model reducing the size of the model and
it's memory footprint.
"""
a = self.f.getArgs()
if not epoch:
epoch = a.epoch #... |
def _get_vm_by_id(vmid, allDetails=False):
'''
Retrieve a VM based on the ID.
'''
for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)):
if six.text_type(vm_details['vmid']) == six.text_type(vmid):
return vm_details
log.info('VM with ID "%s" could... | def function[_get_vm_by_id, parameter[vmid, allDetails]]:
constant[
Retrieve a VM based on the ID.
]
for taget[tuple[[<ast.Name object at 0x7da18bc722c0>, <ast.Name object at 0x7da18bc73040>]]] in starred[call[name[six].iteritems, parameter[call[name[get_resources_vms], parameter[]]]]] begin[:]
... | keyword[def] identifier[_get_vm_by_id] ( identifier[vmid] , identifier[allDetails] = keyword[False] ):
literal[string]
keyword[for] identifier[vm_name] , identifier[vm_details] keyword[in] identifier[six] . identifier[iteritems] ( identifier[get_resources_vms] ( identifier[includeConfig] = identifier[al... | def _get_vm_by_id(vmid, allDetails=False):
"""
Retrieve a VM based on the ID.
"""
for (vm_name, vm_details) in six.iteritems(get_resources_vms(includeConfig=allDetails)):
if six.text_type(vm_details['vmid']) == six.text_type(vmid):
return vm_details # depends on [control=['if'], dat... |
def index(credentials=None):
"""Get list of projects"""
user, oauth_access_token = parsecredentials(credentials)
if not settings.ADMINS or user not in settings.ADMINS:
return flask.make_response('You shall not pass!!! You are not an administrator!',403)
usersprojects = {}
... | def function[index, parameter[credentials]]:
constant[Get list of projects]
<ast.Tuple object at 0x7da20c6e6d40> assign[=] call[name[parsecredentials], parameter[name[credentials]]]
if <ast.BoolOp object at 0x7da1b1800e20> begin[:]
return[call[name[flask].make_response, parameter[constan... | keyword[def] identifier[index] ( identifier[credentials] = keyword[None] ):
literal[string]
identifier[user] , identifier[oauth_access_token] = identifier[parsecredentials] ( identifier[credentials] )
keyword[if] keyword[not] identifier[settings] . identifier[ADMINS] keyword[or] identi... | def index(credentials=None):
"""Get list of projects"""
(user, oauth_access_token) = parsecredentials(credentials)
if not settings.ADMINS or user not in settings.ADMINS:
return flask.make_response('You shall not pass!!! You are not an administrator!', 403) # depends on [control=['if'], data=[]]
... |
def set_attributes(
name,
attributes,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Set attributes on an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.set_attributes myqueue '{ReceiveMessageWaitTimeSeconds: 20}' region=us-east-1
'''
... | def function[set_attributes, parameter[name, attributes, region, key, keyid, profile]]:
constant[
Set attributes on an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.set_attributes myqueue '{ReceiveMessageWaitTimeSeconds: 20}' region=us-east-1
]
variable[c... | keyword[def] identifier[set_attributes] (
identifier[name] ,
identifier[attributes] ,
identifier[region] = keyword[None] ,
identifier[key] = keyword[None] ,
identifier[keyid] = keyword[None] ,
identifier[profile] = keyword[None] ,
):
literal[string]
identifier[conn] = identifier[_get_conn] ( identifi... | def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None):
"""
Set attributes on an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.set_attributes myqueue '{ReceiveMessageWaitTimeSeconds: 20}' region=us-east-1
"""
conn = _get_conn(region... |
def track_request(self, name: str, url: str, success: bool, start_time: str=None,
duration: int=None, response_code: str =None, http_method: str=None,
properties: Dict[str, object]=None, measurements: Dict[str, object]=None,
request_id: str=None):
"... | def function[track_request, parameter[self, name, url, success, start_time, duration, response_code, http_method, properties, measurements, request_id]]:
constant[
Sends a single request that was captured for the application.
:param name: The name for this request. All requests with the same nam... | keyword[def] identifier[track_request] ( identifier[self] , identifier[name] : identifier[str] , identifier[url] : identifier[str] , identifier[success] : identifier[bool] , identifier[start_time] : identifier[str] = keyword[None] ,
identifier[duration] : identifier[int] = keyword[None] , identifier[response_code] :... | def track_request(self, name: str, url: str, success: bool, start_time: str=None, duration: int=None, response_code: str=None, http_method: str=None, properties: Dict[str, object]=None, measurements: Dict[str, object]=None, request_id: str=None):
"""
Sends a single request that was captured for the applicat... |
def immutable(members='', name='Immutable', verbose=False):
"""
Produces a class that either can be used standalone or as a base class for persistent classes.
This is a thin wrapper around a named tuple.
Constructing a type and using it to instantiate objects:
>>> Point = immutable('x, y', name='... | def function[immutable, parameter[members, name, verbose]]:
constant[
Produces a class that either can be used standalone or as a base class for persistent classes.
This is a thin wrapper around a named tuple.
Constructing a type and using it to instantiate objects:
>>> Point = immutable('x, ... | keyword[def] identifier[immutable] ( identifier[members] = literal[string] , identifier[name] = literal[string] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[members] , identifier[six] . identifier[string_types] ):
identifier[members] =... | def immutable(members='', name='Immutable', verbose=False):
"""
Produces a class that either can be used standalone or as a base class for persistent classes.
This is a thin wrapper around a named tuple.
Constructing a type and using it to instantiate objects:
>>> Point = immutable('x, y', name='... |
def inv_edges(json):
"""Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)"""
for edge in json['edges']:
sub, obj = edge['sub'], edge['obj']
edge['sub'] = obj
edge['obj'] = sub
edge['pred'] += 'INVERTED' | def function[inv_edges, parameter[json]]:
constant[Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)]
for taget[name[edge]] in starred[call[name[json]][constant[edges]]] begin[:]
<ast.Tuple object at 0x7da1b1be7a30> assign[=] tuple[[<ast.Subscript object at... | keyword[def] identifier[inv_edges] ( identifier[json] ):
literal[string]
keyword[for] identifier[edge] keyword[in] identifier[json] [ literal[string] ]:
identifier[sub] , identifier[obj] = identifier[edge] [ literal[string] ], identifier[edge] [ literal[string] ]
identifier[edge] [ lit... | def inv_edges(json):
"""Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)"""
for edge in json['edges']:
(sub, obj) = (edge['sub'], edge['obj'])
edge['sub'] = obj
edge['obj'] = sub
edge['pred'] += 'INVERTED' # depends on [control=['for'], data=['edg... |
def _commit(self):
"""Commits the batch.
This is called by :meth:`commit`.
"""
if self._id is None:
mode = _datastore_pb2.CommitRequest.NON_TRANSACTIONAL
else:
mode = _datastore_pb2.CommitRequest.TRANSACTIONAL
commit_response_pb = self._client._d... | def function[_commit, parameter[self]]:
constant[Commits the batch.
This is called by :meth:`commit`.
]
if compare[name[self]._id is constant[None]] begin[:]
variable[mode] assign[=] name[_datastore_pb2].CommitRequest.NON_TRANSACTIONAL
variable[commit_response_pb... | keyword[def] identifier[_commit] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_id] keyword[is] keyword[None] :
identifier[mode] = identifier[_datastore_pb2] . identifier[CommitRequest] . identifier[NON_TRANSACTIONAL]
keyword[else] :
... | def _commit(self):
"""Commits the batch.
This is called by :meth:`commit`.
"""
if self._id is None:
mode = _datastore_pb2.CommitRequest.NON_TRANSACTIONAL # depends on [control=['if'], data=[]]
else:
mode = _datastore_pb2.CommitRequest.TRANSACTIONAL
commit_response_pb = ... |
def build_boolCoeff(self):
''' Compute coefficients for tuple space.
'''
# coefficients for hill functions from boolean update rules
self.boolCoeff = collections.OrderedDict([(s,[]) for s in self.varNames.keys()])
# parents
self.pas = collections.OrderedDict([(s,[]) for s... | def function[build_boolCoeff, parameter[self]]:
constant[ Compute coefficients for tuple space.
]
name[self].boolCoeff assign[=] call[name[collections].OrderedDict, parameter[<ast.ListComp object at 0x7da18eb55cf0>]]
name[self].pas assign[=] call[name[collections].OrderedDict, parameter[... | keyword[def] identifier[build_boolCoeff] ( identifier[self] ):
literal[string]
identifier[self] . identifier[boolCoeff] = identifier[collections] . identifier[OrderedDict] ([( identifier[s] ,[]) keyword[for] identifier[s] keyword[in] identifier[self] . identifier[varNames] . identifier[... | def build_boolCoeff(self):
""" Compute coefficients for tuple space.
"""
# coefficients for hill functions from boolean update rules
self.boolCoeff = collections.OrderedDict([(s, []) for s in self.varNames.keys()])
# parents
self.pas = collections.OrderedDict([(s, []) for s in self.varNames.... |
def reload_cache_config(self, call_params):
"""REST Reload Plivo Cache Config helper
"""
path = '/' + self.api_version + '/ReloadCacheConfig/'
method = 'POST'
return self.request(path, method, call_params) | def function[reload_cache_config, parameter[self, call_params]]:
constant[REST Reload Plivo Cache Config helper
]
variable[path] assign[=] binary_operation[binary_operation[constant[/] + name[self].api_version] + constant[/ReloadCacheConfig/]]
variable[method] assign[=] constant[POST]
... | keyword[def] identifier[reload_cache_config] ( identifier[self] , identifier[call_params] ):
literal[string]
identifier[path] = literal[string] + identifier[self] . identifier[api_version] + literal[string]
identifier[method] = literal[string]
keyword[return] identifier[self] .... | def reload_cache_config(self, call_params):
"""REST Reload Plivo Cache Config helper
"""
path = '/' + self.api_version + '/ReloadCacheConfig/'
method = 'POST'
return self.request(path, method, call_params) |
def version_id(self):
"""Return the version of the community.
:returns: hash which encodes the community id and its las update.
:rtype: str
"""
return hashlib.sha1('{0}__{1}'.format(
self.id, self.updated).encode('utf-8')).hexdigest() | def function[version_id, parameter[self]]:
constant[Return the version of the community.
:returns: hash which encodes the community id and its las update.
:rtype: str
]
return[call[call[name[hashlib].sha1, parameter[call[call[constant[{0}__{1}].format, parameter[name[self].id, name[... | keyword[def] identifier[version_id] ( identifier[self] ):
literal[string]
keyword[return] identifier[hashlib] . identifier[sha1] ( literal[string] . identifier[format] (
identifier[self] . identifier[id] , identifier[self] . identifier[updated] ). identifier[encode] ( literal[string] )). ... | def version_id(self):
"""Return the version of the community.
:returns: hash which encodes the community id and its las update.
:rtype: str
"""
return hashlib.sha1('{0}__{1}'.format(self.id, self.updated).encode('utf-8')).hexdigest() |
def irfft(a, n=None, axis=-1, norm=None):
"""
Compute the inverse of the n-point DFT for real input.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
... | def function[irfft, parameter[a, n, axis, norm]]:
constant[
Compute the inverse of the n-point DFT for real input.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to ... | keyword[def] identifier[irfft] ( identifier[a] , identifier[n] = keyword[None] , identifier[axis] =- literal[int] , identifier[norm] = keyword[None] ):
literal[string]
identifier[output] = identifier[mkl_fft] . identifier[irfft_numpy] ( identifier[a] , identifier[n] = identifier[n] , identifier[axis] = ide... | def irfft(a, n=None, axis=-1, norm=None):
"""
Compute the inverse of the n-point DFT for real input.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
... |
def to_dict(self, data=True):
"""Dictionary representation of variable."""
item = {'dims': self.dims,
'attrs': decode_numpy_dict_values(self.attrs)}
if data:
item['data'] = ensure_us_time_resolution(self.values).tolist()
else:
item.update({'dtype':... | def function[to_dict, parameter[self, data]]:
constant[Dictionary representation of variable.]
variable[item] assign[=] dictionary[[<ast.Constant object at 0x7da18eb542e0>, <ast.Constant object at 0x7da18eb55b70>], [<ast.Attribute object at 0x7da18eb57190>, <ast.Call object at 0x7da18eb54af0>]]
... | keyword[def] identifier[to_dict] ( identifier[self] , identifier[data] = keyword[True] ):
literal[string]
identifier[item] ={ literal[string] : identifier[self] . identifier[dims] ,
literal[string] : identifier[decode_numpy_dict_values] ( identifier[self] . identifier[attrs] )}
ke... | def to_dict(self, data=True):
"""Dictionary representation of variable."""
item = {'dims': self.dims, 'attrs': decode_numpy_dict_values(self.attrs)}
if data:
item['data'] = ensure_us_time_resolution(self.values).tolist() # depends on [control=['if'], data=[]]
else:
item.update({'dtype':... |
def unwrap(value):
"""
Unwraps the given Document or DocumentList as applicable.
"""
if isinstance(value, Document):
return value.to_dict()
elif isinstance(value, DocumentList):
return value.to_list()
else:
return value | def function[unwrap, parameter[value]]:
constant[
Unwraps the given Document or DocumentList as applicable.
]
if call[name[isinstance], parameter[name[value], name[Document]]] begin[:]
return[call[name[value].to_dict, parameter[]]] | keyword[def] identifier[unwrap] ( identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[Document] ):
keyword[return] identifier[value] . identifier[to_dict] ()
keyword[elif] identifier[isinstance] ( identifier[value] , identifier[DocumentL... | def unwrap(value):
"""
Unwraps the given Document or DocumentList as applicable.
"""
if isinstance(value, Document):
return value.to_dict() # depends on [control=['if'], data=[]]
elif isinstance(value, DocumentList):
return value.to_list() # depends on [control=['if'], data=[]]
... |
def read_content_types(archive):
"""Read content types."""
xml_source = archive.read(ARC_CONTENT_TYPES)
root = fromstring(xml_source)
contents_root = root.findall('{%s}Override' % CONTYPES_NS)
for type in contents_root:
yield type.get('ContentType'), type.get('PartName') | def function[read_content_types, parameter[archive]]:
constant[Read content types.]
variable[xml_source] assign[=] call[name[archive].read, parameter[name[ARC_CONTENT_TYPES]]]
variable[root] assign[=] call[name[fromstring], parameter[name[xml_source]]]
variable[contents_root] assign[=] c... | keyword[def] identifier[read_content_types] ( identifier[archive] ):
literal[string]
identifier[xml_source] = identifier[archive] . identifier[read] ( identifier[ARC_CONTENT_TYPES] )
identifier[root] = identifier[fromstring] ( identifier[xml_source] )
identifier[contents_root] = identifier[root] ... | def read_content_types(archive):
"""Read content types."""
xml_source = archive.read(ARC_CONTENT_TYPES)
root = fromstring(xml_source)
contents_root = root.findall('{%s}Override' % CONTYPES_NS)
for type in contents_root:
yield (type.get('ContentType'), type.get('PartName')) # depends on [con... |
def submit(self, func, *args, **kwargs):
"""Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`"""
with self._shutdown_lock:
if PY3 and self._broken:
raise BrokenProcessPool(
"A child process terminated "
"abruptly,... | def function[submit, parameter[self, func]]:
constant[Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`]
with name[self]._shutdown_lock begin[:]
if <ast.BoolOp object at 0x7da20e9b3a90> begin[:]
<ast.Raise object at 0x7da20e9b1720>
if nam... | keyword[def] identifier[submit] ( identifier[self] , identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[self] . identifier[_shutdown_lock] :
keyword[if] identifier[PY3] keyword[and] identifier[self] . identifier[_broken] :
... | def submit(self, func, *args, **kwargs):
"""Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`"""
with self._shutdown_lock:
if PY3 and self._broken:
raise BrokenProcessPool('A child process terminated abruptly, the process pool is not usable anymore') # depends on [cont... |
def genkeyhex():
'''
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format.
'''
while True:
key = hash256(
hexlify(os.urandom(40) + str(datetime.datetime.now())
.encode("utf-8")))
# 40 byt... | def function[genkeyhex, parameter[]]:
constant[
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format.
]
while constant[True] begin[:]
variable[key] assign[=] call[name[hash256], parameter[call[name[hexlify], parameter[binary_operation[call[... | keyword[def] identifier[genkeyhex] ():
literal[string]
keyword[while] keyword[True] :
identifier[key] = identifier[hash256] (
identifier[hexlify] ( identifier[os] . identifier[urandom] ( literal[int] )+ identifier[str] ( identifier[datetime] . identifier[datetime] . identifier[now] ())
... | def genkeyhex():
"""
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format.
"""
while True:
key = hash256(hexlify(os.urandom(40) + str(datetime.datetime.now()).encode('utf-8')))
# 40 bytes used instead of 32, as a buffer for any slight
# ... |
def resize(self, flavor):
"""Set the size of this instance to a different flavor."""
# We need the flavorRef, not the flavor or size.
flavorRef = self.manager.api._get_flavor_ref(flavor)
body = {"flavorRef": flavorRef}
self.manager.action(self, "resize", body=body) | def function[resize, parameter[self, flavor]]:
constant[Set the size of this instance to a different flavor.]
variable[flavorRef] assign[=] call[name[self].manager.api._get_flavor_ref, parameter[name[flavor]]]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b055aef0>], [<ast.N... | keyword[def] identifier[resize] ( identifier[self] , identifier[flavor] ):
literal[string]
identifier[flavorRef] = identifier[self] . identifier[manager] . identifier[api] . identifier[_get_flavor_ref] ( identifier[flavor] )
identifier[body] ={ literal[string] : identifier[flavorR... | def resize(self, flavor):
"""Set the size of this instance to a different flavor."""
# We need the flavorRef, not the flavor or size.
flavorRef = self.manager.api._get_flavor_ref(flavor)
body = {'flavorRef': flavorRef}
self.manager.action(self, 'resize', body=body) |
def InferUserAndSubjectFromUrn(self):
"""Infers user name and subject urn from self.urn."""
_, cron_str, cron_job_name, user, _ = self.urn.Split(5)
if cron_str != "cron":
raise access_control.UnauthorizedAccess(
"Approval object has invalid urn %s." % self.urn,
requested_access=se... | def function[InferUserAndSubjectFromUrn, parameter[self]]:
constant[Infers user name and subject urn from self.urn.]
<ast.Tuple object at 0x7da1b1b44a00> assign[=] call[name[self].urn.Split, parameter[constant[5]]]
if compare[name[cron_str] not_equal[!=] constant[cron]] begin[:]
<ast.Rai... | keyword[def] identifier[InferUserAndSubjectFromUrn] ( identifier[self] ):
literal[string]
identifier[_] , identifier[cron_str] , identifier[cron_job_name] , identifier[user] , identifier[_] = identifier[self] . identifier[urn] . identifier[Split] ( literal[int] )
keyword[if] identifier[cron_str] != ... | def InferUserAndSubjectFromUrn(self):
"""Infers user name and subject urn from self.urn."""
(_, cron_str, cron_job_name, user, _) = self.urn.Split(5)
if cron_str != 'cron':
raise access_control.UnauthorizedAccess('Approval object has invalid urn %s.' % self.urn, requested_access=self.token.requested... |
def write_config(filename, config, mode="w"):
'''use configparser to write a config object to filename
'''
with open(filename, mode) as filey:
config.write(filey)
return filename | def function[write_config, parameter[filename, config, mode]]:
constant[use configparser to write a config object to filename
]
with call[name[open], parameter[name[filename], name[mode]]] begin[:]
call[name[config].write, parameter[name[filey]]]
return[name[filename]] | keyword[def] identifier[write_config] ( identifier[filename] , identifier[config] , identifier[mode] = literal[string] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , identifier[mode] ) keyword[as] identifier[filey] :
identifier[config] . identifier[write] ( identifier... | def write_config(filename, config, mode='w'):
"""use configparser to write a config object to filename
"""
with open(filename, mode) as filey:
config.write(filey) # depends on [control=['with'], data=['filey']]
return filename |
def cjkFragSplit(frags, maxWidths, calcBounds, encoding='utf8'):
"""
This attempts to be wordSplit for frags using the dumb algorithm
"""
from reportlab.rl_config import _FUZZ
U = [] # get a list of single glyphs with their widths etc etc
for f in frags:
text = f.text
if not i... | def function[cjkFragSplit, parameter[frags, maxWidths, calcBounds, encoding]]:
constant[
This attempts to be wordSplit for frags using the dumb algorithm
]
from relative_module[reportlab.rl_config] import module[_FUZZ]
variable[U] assign[=] list[[]]
for taget[name[f]] in starred[name... | keyword[def] identifier[cjkFragSplit] ( identifier[frags] , identifier[maxWidths] , identifier[calcBounds] , identifier[encoding] = literal[string] ):
literal[string]
keyword[from] identifier[reportlab] . identifier[rl_config] keyword[import] identifier[_FUZZ]
identifier[U] =[]
keyword[for]... | def cjkFragSplit(frags, maxWidths, calcBounds, encoding='utf8'):
"""
This attempts to be wordSplit for frags using the dumb algorithm
"""
from reportlab.rl_config import _FUZZ
U = [] # get a list of single glyphs with their widths etc etc
for f in frags:
text = f.text
if not isi... |
def starts(self, layer):
"""Retrieve start positions of elements if given layer."""
starts = []
for data in self[layer]:
starts.append(data[START])
return starts | def function[starts, parameter[self, layer]]:
constant[Retrieve start positions of elements if given layer.]
variable[starts] assign[=] list[[]]
for taget[name[data]] in starred[call[name[self]][name[layer]]] begin[:]
call[name[starts].append, parameter[call[name[data]][name[STAR... | keyword[def] identifier[starts] ( identifier[self] , identifier[layer] ):
literal[string]
identifier[starts] =[]
keyword[for] identifier[data] keyword[in] identifier[self] [ identifier[layer] ]:
identifier[starts] . identifier[append] ( identifier[data] [ identifier[START] ... | def starts(self, layer):
"""Retrieve start positions of elements if given layer."""
starts = []
for data in self[layer]:
starts.append(data[START]) # depends on [control=['for'], data=['data']]
return starts |
def find_function(self, context, funname):
"""Find a function in the given context by name.
This function will first search the list of builtins and if the
desired function is not a builtin, it will continue to search
the given context.
Args:
context (object): A dic... | def function[find_function, parameter[self, context, funname]]:
constant[Find a function in the given context by name.
This function will first search the list of builtins and if the
desired function is not a builtin, it will continue to search
the given context.
Args:
... | keyword[def] identifier[find_function] ( identifier[self] , identifier[context] , identifier[funname] ):
literal[string]
keyword[if] identifier[funname] keyword[in] identifier[self] . identifier[builtins] :
keyword[return] identifier[self] . identifier[builtins] [ identifier[funna... | def find_function(self, context, funname):
"""Find a function in the given context by name.
This function will first search the list of builtins and if the
desired function is not a builtin, it will continue to search
the given context.
Args:
context (object): A dict or... |
def __get_idxs(self, words):
"""Returns indexes to appropriate words."""
if self.bow:
return list(itertools.chain.from_iterable(
[self.positions[z] for z in words]))
else:
return self.positions[words] | def function[__get_idxs, parameter[self, words]]:
constant[Returns indexes to appropriate words.]
if name[self].bow begin[:]
return[call[name[list], parameter[call[name[itertools].chain.from_iterable, parameter[<ast.ListComp object at 0x7da1b208e020>]]]]] | keyword[def] identifier[__get_idxs] ( identifier[self] , identifier[words] ):
literal[string]
keyword[if] identifier[self] . identifier[bow] :
keyword[return] identifier[list] ( identifier[itertools] . identifier[chain] . identifier[from_iterable] (
[ identifier[self] . i... | def __get_idxs(self, words):
"""Returns indexes to appropriate words."""
if self.bow:
return list(itertools.chain.from_iterable([self.positions[z] for z in words])) # depends on [control=['if'], data=[]]
else:
return self.positions[words] |
def load(self, coll):
"""Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent
... | def function[load, parameter[self, coll]]:
constant[Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and... | keyword[def] identifier[load] ( identifier[self] , identifier[coll] ):
literal[string]
identifier[path] = identifier[self] . identifier[template_str] . identifier[format] ( identifier[coll] = identifier[coll] )
keyword[try] :
identifier[mtime] = identifier[os] . identifier[pat... | def load(self, coll):
"""Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent
t... |
def scrape(cls, start, end, output):
"""
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory
"""
# Logger setting
logging.basicConfig(
level=logging.INFO,
format="time:... | def function[scrape, parameter[cls, start, end, output]]:
constant[
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory
]
call[name[logging].basicConfig, parameter[]]
for taget[name[param_day]... | keyword[def] identifier[scrape] ( identifier[cls] , identifier[start] , identifier[end] , identifier[output] ):
literal[string]
identifier[logging] . identifier[basicConfig] (
identifier[level] = identifier[logging] . identifier[INFO] ,
identifier[format] = literal[string... | def scrape(cls, start, end, output):
"""
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory
"""
# Logger setting
logging.basicConfig(level=logging.INFO, format='time:%(asctime)s.%(msecs)03d' + '\tmessage... |
def chunks(self, include_inactive=False):
"""
@return A generator that yields the chunks of the log file
starting with the first chunk, which is always found directly
after the FileHeader.
If `include_inactive` is set to true, enumerate chunks beyond those
declared i... | def function[chunks, parameter[self, include_inactive]]:
constant[
@return A generator that yields the chunks of the log file
starting with the first chunk, which is always found directly
after the FileHeader.
If `include_inactive` is set to true, enumerate chunks beyond tho... | keyword[def] identifier[chunks] ( identifier[self] , identifier[include_inactive] = keyword[False] ):
literal[string]
keyword[if] identifier[include_inactive] :
identifier[chunk_count] = identifier[sys] . identifier[maxsize]
keyword[else] :
identifier[chunk_coun... | def chunks(self, include_inactive=False):
"""
@return A generator that yields the chunks of the log file
starting with the first chunk, which is always found directly
after the FileHeader.
If `include_inactive` is set to true, enumerate chunks beyond those
declared in th... |
def get_n_resources_for_iteration(self, iteration, bracket_iteration):
"""Return the number of iterations to run for this barcket_i
This is just util function around `get_n_resources`
"""
bracket = self.get_bracket(iteration=iteration)
n_resources = self.get_resources(bracket=br... | def function[get_n_resources_for_iteration, parameter[self, iteration, bracket_iteration]]:
constant[Return the number of iterations to run for this barcket_i
This is just util function around `get_n_resources`
]
variable[bracket] assign[=] call[name[self].get_bracket, parameter[]]
... | keyword[def] identifier[get_n_resources_for_iteration] ( identifier[self] , identifier[iteration] , identifier[bracket_iteration] ):
literal[string]
identifier[bracket] = identifier[self] . identifier[get_bracket] ( identifier[iteration] = identifier[iteration] )
identifier[n_resources] = ... | def get_n_resources_for_iteration(self, iteration, bracket_iteration):
"""Return the number of iterations to run for this barcket_i
This is just util function around `get_n_resources`
"""
bracket = self.get_bracket(iteration=iteration)
n_resources = self.get_resources(bracket=bracket)
r... |
def v_reference_leaf_leafref(ctx, stmt):
"""Verify that all leafrefs in a leaf or leaf-list have correct path"""
if (hasattr(stmt, 'i_leafref') and
stmt.i_leafref is not None and
stmt.i_leafref_expanded is False):
path_type_spec = stmt.i_leafref
not_req_inst = not(path_type_spec... | def function[v_reference_leaf_leafref, parameter[ctx, stmt]]:
constant[Verify that all leafrefs in a leaf or leaf-list have correct path]
if <ast.BoolOp object at 0x7da18bc73490> begin[:]
variable[path_type_spec] assign[=] name[stmt].i_leafref
variable[not_req_inst] assig... | keyword[def] identifier[v_reference_leaf_leafref] ( identifier[ctx] , identifier[stmt] ):
literal[string]
keyword[if] ( identifier[hasattr] ( identifier[stmt] , literal[string] ) keyword[and]
identifier[stmt] . identifier[i_leafref] keyword[is] keyword[not] keyword[None] keyword[and]
ident... | def v_reference_leaf_leafref(ctx, stmt):
"""Verify that all leafrefs in a leaf or leaf-list have correct path"""
if hasattr(stmt, 'i_leafref') and stmt.i_leafref is not None and (stmt.i_leafref_expanded is False):
path_type_spec = stmt.i_leafref
not_req_inst = not path_type_spec.require_instance... |
def determinize(self):
"""
Transforms a Non Deterministic DFA into a Deterministic
Args:
None
Returns:
DFA: The resulting DFA
Creating an equivalent DFA is done using the standard algorithm.
A nice description can be found in the book:
Har... | def function[determinize, parameter[self]]:
constant[
Transforms a Non Deterministic DFA into a Deterministic
Args:
None
Returns:
DFA: The resulting DFA
Creating an equivalent DFA is done using the standard algorithm.
A nice description can be fou... | keyword[def] identifier[determinize] ( identifier[self] ):
literal[string]
identifier[epsilon_closure] ={}
keyword[for] identifier[state] keyword[in] identifier[self] . identifier[states] :
identifier[sid] = identifier[state] . identifier[stateid]
id... | def determinize(self):
"""
Transforms a Non Deterministic DFA into a Deterministic
Args:
None
Returns:
DFA: The resulting DFA
Creating an equivalent DFA is done using the standard algorithm.
A nice description can be found in the book:
Harry R... |
def _check_cython_sources(self, extension):
"""
Where relevant, make sure that the .c files associated with .pyx
modules are present (if building without Cython installed).
"""
# Determine the compiler we'll be using
if self.compiler is None:
compiler = get_d... | def function[_check_cython_sources, parameter[self, extension]]:
constant[
Where relevant, make sure that the .c files associated with .pyx
modules are present (if building without Cython installed).
]
if compare[name[self].compiler is constant[None]] begin[:]
var... | keyword[def] identifier[_check_cython_sources] ( identifier[self] , identifier[extension] ):
literal[string]
keyword[if] identifier[self] . identifier[compiler] keyword[is] keyword[None] :
identifier[compiler] = identifier[get_default_compiler] ()
keyword[else] :
... | def _check_cython_sources(self, extension):
"""
Where relevant, make sure that the .c files associated with .pyx
modules are present (if building without Cython installed).
"""
# Determine the compiler we'll be using
if self.compiler is None:
compiler = get_default_compiler()... |
def topil(self):
"""Returns a PIL.Image version of this Pix"""
from PIL import Image
# Leptonica manages data in words, so it implicitly does an endian
# swap. Tell Pillow about this when it reads the data.
pix = self
if sys.byteorder == 'little':
if self.mo... | def function[topil, parameter[self]]:
constant[Returns a PIL.Image version of this Pix]
from relative_module[PIL] import module[Image]
variable[pix] assign[=] name[self]
if compare[name[sys].byteorder equal[==] constant[little]] begin[:]
if compare[name[self].mode equal[==] c... | keyword[def] identifier[topil] ( identifier[self] ):
literal[string]
keyword[from] identifier[PIL] keyword[import] identifier[Image]
identifier[pix] = identifier[self]
keyword[if] identifier[sys] . identifier[byteorder] == literal[string] :
ke... | def topil(self):
"""Returns a PIL.Image version of this Pix"""
from PIL import Image
# Leptonica manages data in words, so it implicitly does an endian
# swap. Tell Pillow about this when it reads the data.
pix = self
if sys.byteorder == 'little':
if self.mode == 'RGB':
raw_... |
def atomic_to_cim_xml(obj):
"""
Convert an "atomic" scalar value to a CIM-XML string and return that
string.
The returned CIM-XML string is ready for use as the text of a CIM-XML
'VALUE' element.
Parameters:
obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`):
The ... | def function[atomic_to_cim_xml, parameter[obj]]:
constant[
Convert an "atomic" scalar value to a CIM-XML string and return that
string.
The returned CIM-XML string is ready for use as the text of a CIM-XML
'VALUE' element.
Parameters:
obj (:term:`CIM data type`, :term:`number`, :cla... | keyword[def] identifier[atomic_to_cim_xml] ( identifier[obj] ):
literal[string]
keyword[if] identifier[obj] keyword[is] keyword[None] :
keyword[return] identifier[obj]
keyword[elif] identifier[isinstance] ( identifier[obj] , identifier[six] . identifier[text_type] ):
keyword[re... | def atomic_to_cim_xml(obj):
"""
Convert an "atomic" scalar value to a CIM-XML string and return that
string.
The returned CIM-XML string is ready for use as the text of a CIM-XML
'VALUE' element.
Parameters:
obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`):
The ... |
def _import_module(name, package=None):
"""
根据模块名载入模块
:param name:
:param package:
:return:
"""
if name.startswith('.'):
name = '{package}.{module}'.format(package=package, module=str(name).strip('.'))
__import__(name)
return sys.modules[name] | def function[_import_module, parameter[name, package]]:
constant[
根据模块名载入模块
:param name:
:param package:
:return:
]
if call[name[name].startswith, parameter[constant[.]]] begin[:]
variable[name] assign[=] call[constant[{package}.{module}].format, parameter[]]
... | keyword[def] identifier[_import_module] ( identifier[name] , identifier[package] = keyword[None] ):
literal[string]
keyword[if] identifier[name] . identifier[startswith] ( literal[string] ):
identifier[name] = literal[string] . identifier[format] ( identifier[package] = identifier[package] , iden... | def _import_module(name, package=None):
"""
根据模块名载入模块
:param name:
:param package:
:return:
"""
if name.startswith('.'):
name = '{package}.{module}'.format(package=package, module=str(name).strip('.')) # depends on [control=['if'], data=[]]
__import__(name)
return sys.module... |
def main(pyc_file, asm_path):
"""
Create Python bytecode from a Python assembly file.
ASM_PATH gives the input Python assembly file. We suggest ending the
file in .pyc
If --pyc-file is given, that indicates the path to write the
Python bytecode. The path should end in '.pyc'.
See https://... | def function[main, parameter[pyc_file, asm_path]]:
constant[
Create Python bytecode from a Python assembly file.
ASM_PATH gives the input Python assembly file. We suggest ending the
file in .pyc
If --pyc-file is given, that indicates the path to write the
Python bytecode. The path should e... | keyword[def] identifier[main] ( identifier[pyc_file] , identifier[asm_path] ):
literal[string]
keyword[if] identifier[os] . identifier[stat] ( identifier[asm_path] ). identifier[st_size] == literal[int] :
identifier[print] ( literal[string] % identifier[asm_path] )
identifier[sys] . iden... | def main(pyc_file, asm_path):
"""
Create Python bytecode from a Python assembly file.
ASM_PATH gives the input Python assembly file. We suggest ending the
file in .pyc
If --pyc-file is given, that indicates the path to write the
Python bytecode. The path should end in '.pyc'.
See https://... |
def _lock(self, name, client_id, request_id):
"""Handles locking
Locking time is stored to determine time out.
If a lock is timed out it can be acquired by a different client.
"""
if name in self._locks:
other_client_id, other_request_id, lock_time = self._locks[nam... | def function[_lock, parameter[self, name, client_id, request_id]]:
constant[Handles locking
Locking time is stored to determine time out.
If a lock is timed out it can be acquired by a different client.
]
if compare[name[name] in name[self]._locks] begin[:]
<ast... | keyword[def] identifier[_lock] ( identifier[self] , identifier[name] , identifier[client_id] , identifier[request_id] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[_locks] :
identifier[other_client_id] , identifier[other_request_id] , iden... | def _lock(self, name, client_id, request_id):
"""Handles locking
Locking time is stored to determine time out.
If a lock is timed out it can be acquired by a different client.
"""
if name in self._locks:
(other_client_id, other_request_id, lock_time) = self._locks[name]
... |
def reduce(self, sum1, sum2, *args):
"""
The internal reduce function that sums the results from various
processors
"""
self.sum1g[...] += sum1
if not self.pts_only: self.sum2g[...] += sum2
if self.compute_mean_coords:
N, centers_sum = args
... | def function[reduce, parameter[self, sum1, sum2]]:
constant[
The internal reduce function that sums the results from various
processors
]
<ast.AugAssign object at 0x7da1b18bac20>
if <ast.UnaryOp object at 0x7da1b18ba650> begin[:]
<ast.AugAssign object at 0x7da1b18bb91... | keyword[def] identifier[reduce] ( identifier[self] , identifier[sum1] , identifier[sum2] ,* identifier[args] ):
literal[string]
identifier[self] . identifier[sum1g] [...]+= identifier[sum1]
keyword[if] keyword[not] identifier[self] . identifier[pts_only] : identifier[self] . identifier[... | def reduce(self, sum1, sum2, *args):
"""
The internal reduce function that sums the results from various
processors
"""
self.sum1g[...] += sum1
if not self.pts_only:
self.sum2g[...] += sum2 # depends on [control=['if'], data=[]]
if self.compute_mean_coords:
(N, c... |
def zremrangebyrank(self, name, rank_start, rank_end):
"""
Remove the elements of the zset which have rank in the range
[rank_start,rank_end].
.. note:: The range is [``rank_start``, ``rank_end``]
:param string name: the zset name
:param int rank_start: zero or ... | def function[zremrangebyrank, parameter[self, name, rank_start, rank_end]]:
constant[
Remove the elements of the zset which have rank in the range
[rank_start,rank_end].
.. note:: The range is [``rank_start``, ``rank_end``]
:param string name: the zset name
:par... | keyword[def] identifier[zremrangebyrank] ( identifier[self] , identifier[name] , identifier[rank_start] , identifier[rank_end] ):
literal[string]
identifier[rank_start] = identifier[get_nonnegative_integer] ( literal[string] , identifier[rank_start] )
identifier[rank_end] = identifier[get_... | def zremrangebyrank(self, name, rank_start, rank_end):
"""
Remove the elements of the zset which have rank in the range
[rank_start,rank_end].
.. note:: The range is [``rank_start``, ``rank_end``]
:param string name: the zset name
:param int rank_start: zero or posi... |
def list_instances(self, tags=None, cpus=None, memory=None, hostname=None,
disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
... | def function[list_instances, parameter[self, tags, cpus, memory, hostname, disk, datacenter]]:
constant[Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter ... | keyword[def] identifier[list_instances] ( identifier[self] , identifier[tags] = keyword[None] , identifier[cpus] = keyword[None] , identifier[memory] = keyword[None] , identifier[hostname] = keyword[None] ,
identifier[disk] = keyword[None] , identifier[datacenter] = keyword[None] ,** identifier[kwargs] ):
l... | def list_instances(self, tags=None, cpus=None, memory=None, hostname=None, disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory... |
def ensure_on():
"""
Start the DbServer if it is off
"""
if get_status() == 'not-running':
if config.dbserver.multi_user:
sys.exit('Please start the DbServer: '
'see the documentation for details')
# otherwise start the DbServer automatically; NB: I tried... | def function[ensure_on, parameter[]]:
constant[
Start the DbServer if it is off
]
if compare[call[name[get_status], parameter[]] equal[==] constant[not-running]] begin[:]
if name[config].dbserver.multi_user begin[:]
call[name[sys].exit, parameter[constant[... | keyword[def] identifier[ensure_on] ():
literal[string]
keyword[if] identifier[get_status] ()== literal[string] :
keyword[if] identifier[config] . identifier[dbserver] . identifier[multi_user] :
identifier[sys] . identifier[exit] ( literal[string]
literal[string] )
... | def ensure_on():
"""
Start the DbServer if it is off
"""
if get_status() == 'not-running':
if config.dbserver.multi_user:
sys.exit('Please start the DbServer: see the documentation for details') # depends on [control=['if'], data=[]]
# otherwise start the DbServer automatica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.