code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def eventFilter(self, object, event):
"""
Listens for tab/backtab to modify list information.
:param event | <QKeyPressEvent>
"""
if event.type() != event.KeyPress:
return super(XRichTextEdit, self).eventFilter(object, event)
cu... | def function[eventFilter, parameter[self, object, event]]:
constant[
Listens for tab/backtab to modify list information.
:param event | <QKeyPressEvent>
]
if compare[call[name[event].type, parameter[]] not_equal[!=] name[event].KeyPress] begin[:]
return[call... | keyword[def] identifier[eventFilter] ( identifier[self] , identifier[object] , identifier[event] ):
literal[string]
keyword[if] identifier[event] . identifier[type] ()!= identifier[event] . identifier[KeyPress] :
keyword[return] identifier[super] ( identifier[XRichTextEdit] , iden... | def eventFilter(self, object, event):
"""
Listens for tab/backtab to modify list information.
:param event | <QKeyPressEvent>
"""
if event.type() != event.KeyPress:
return super(XRichTextEdit, self).eventFilter(object, event) # depends on [control=['if'], data=[]]
... |
def from_nodes(cls, nodes, _copy=True):
"""Create a :class:`.Surface` from nodes.
Computes the ``degree`` based on the shape of ``nodes``.
Args:
nodes (numpy.ndarray): The nodes in the surface. The columns
represent each node while the rows are the dimension
... | def function[from_nodes, parameter[cls, nodes, _copy]]:
constant[Create a :class:`.Surface` from nodes.
Computes the ``degree`` based on the shape of ``nodes``.
Args:
nodes (numpy.ndarray): The nodes in the surface. The columns
represent each node while the rows are... | keyword[def] identifier[from_nodes] ( identifier[cls] , identifier[nodes] , identifier[_copy] = keyword[True] ):
literal[string]
identifier[_] , identifier[num_nodes] = identifier[nodes] . identifier[shape]
identifier[degree] = identifier[cls] . identifier[_get_degree] ( identifier[num_no... | def from_nodes(cls, nodes, _copy=True):
"""Create a :class:`.Surface` from nodes.
Computes the ``degree`` based on the shape of ``nodes``.
Args:
nodes (numpy.ndarray): The nodes in the surface. The columns
represent each node while the rows are the dimension
... |
def bgzip_and_index(in_file, config=None, remove_orig=True, prep_cmd="", tabix_args=None, out_dir=None):
"""bgzip and tabix index an input file, handling VCF and BED.
"""
if config is None:
config = {}
out_file = in_file if in_file.endswith(".gz") else in_file + ".gz"
if out_dir:
rem... | def function[bgzip_and_index, parameter[in_file, config, remove_orig, prep_cmd, tabix_args, out_dir]]:
constant[bgzip and tabix index an input file, handling VCF and BED.
]
if compare[name[config] is constant[None]] begin[:]
variable[config] assign[=] dictionary[[], []]
varia... | keyword[def] identifier[bgzip_and_index] ( identifier[in_file] , identifier[config] = keyword[None] , identifier[remove_orig] = keyword[True] , identifier[prep_cmd] = literal[string] , identifier[tabix_args] = keyword[None] , identifier[out_dir] = keyword[None] ):
literal[string]
keyword[if] identifier[co... | def bgzip_and_index(in_file, config=None, remove_orig=True, prep_cmd='', tabix_args=None, out_dir=None):
"""bgzip and tabix index an input file, handling VCF and BED.
"""
if config is None:
config = {} # depends on [control=['if'], data=['config']]
out_file = in_file if in_file.endswith('.gz') ... |
def delete_image(image_id, profile, **libcloud_kwargs):
'''
Delete an image of a node
:param image_id: Image to delete
:type image_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's delete_image method
:type li... | def function[delete_image, parameter[image_id, profile]]:
constant[
Delete an image of a node
:param image_id: Image to delete
:type image_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's delete_image method
... | keyword[def] identifier[delete_image] ( identifier[image_id] , identifier[profile] ,** identifier[libcloud_kwargs] ):
literal[string]
identifier[conn] = identifier[_get_driver] ( identifier[profile] = identifier[profile] )
identifier[libcloud_kwargs] = identifier[salt] . identifier[utils] . identifier... | def delete_image(image_id, profile, **libcloud_kwargs):
"""
Delete an image of a node
:param image_id: Image to delete
:type image_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's delete_image method
:type li... |
def addText(self, text):
"""append text in the chosen color"""
# move to the end of the doc
self.moveCursor(QtGui.QTextCursor.End)
# insert the text
self.setTextColor(self._currentColor)
self.textCursor().insertText(text) | def function[addText, parameter[self, text]]:
constant[append text in the chosen color]
call[name[self].moveCursor, parameter[name[QtGui].QTextCursor.End]]
call[name[self].setTextColor, parameter[name[self]._currentColor]]
call[call[name[self].textCursor, parameter[]].insertText, paramet... | keyword[def] identifier[addText] ( identifier[self] , identifier[text] ):
literal[string]
identifier[self] . identifier[moveCursor] ( identifier[QtGui] . identifier[QTextCursor] . identifier[End] )
identifier[self] . identifier[setTextColor] ( identifier[self] . identifie... | def addText(self, text):
"""append text in the chosen color"""
# move to the end of the doc
self.moveCursor(QtGui.QTextCursor.End)
# insert the text
self.setTextColor(self._currentColor)
self.textCursor().insertText(text) |
def del_permission(self, role, name):
""" revoke authorization of a group """
if not self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
target = AuthPermission.objects(groups=targetGroup, name=name, creator=sel... | def function[del_permission, parameter[self, role, name]]:
constant[ revoke authorization of a group ]
if <ast.UnaryOp object at 0x7da1b0fddd50> begin[:]
return[constant[True]]
variable[targetGroup] assign[=] call[call[name[AuthGroup].objects, parameter[]].first, parameter[]]
var... | keyword[def] identifier[del_permission] ( identifier[self] , identifier[role] , identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[has_permission] ( identifier[role] , identifier[name] ):
keyword[return] keyword[True]
identifier[targ... | def del_permission(self, role, name):
""" revoke authorization of a group """
if not self.has_permission(role, name):
return True # depends on [control=['if'], data=[]]
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
target = AuthPermission.objects(groups=targetGroup, na... |
def get_mac_address(
interface=None, ip=None, ip6=None,
hostname=None, network_request=True
):
# type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Optional[str]
"""Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.
You must only use one of... | def function[get_mac_address, parameter[interface, ip, ip6, hostname, network_request]]:
constant[Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.
You must only use one of the first four arguments. If none of the arguments
are selected, the default network interface for the ... | keyword[def] identifier[get_mac_address] (
identifier[interface] = keyword[None] , identifier[ip] = keyword[None] , identifier[ip6] = keyword[None] ,
identifier[hostname] = keyword[None] , identifier[network_request] = keyword[True]
):
literal[string]
keyword[if] ( identifier[hostname] keyword[and] i... | def get_mac_address(interface=None, ip=None, ip6=None, hostname=None, network_request=True):
# type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Optional[str]
'Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.\n\n You must only use one of the first four ar... |
def parse(number, region=None, keep_raw_input=False,
numobj=None, _check_region=True):
"""Parse a string and return a corresponding PhoneNumber object.
The method is quite lenient and looks for a number in the input text
(raw input) and does not check whether the string is definitely only a
p... | def function[parse, parameter[number, region, keep_raw_input, numobj, _check_region]]:
constant[Parse a string and return a corresponding PhoneNumber object.
The method is quite lenient and looks for a number in the input text
(raw input) and does not check whether the string is definitely only a
p... | keyword[def] identifier[parse] ( identifier[number] , identifier[region] = keyword[None] , identifier[keep_raw_input] = keyword[False] ,
identifier[numobj] = keyword[None] , identifier[_check_region] = keyword[True] ):
literal[string]
keyword[if] identifier[numobj] keyword[is] keyword[None] :
... | def parse(number, region=None, keep_raw_input=False, numobj=None, _check_region=True):
"""Parse a string and return a corresponding PhoneNumber object.
The method is quite lenient and looks for a number in the input text
(raw input) and does not check whether the string is definitely only a
phone numbe... |
def run_experiment(methods, data, n_classes, true_labels, n_runs=10, use_purity=True, use_nmi=False, use_ari=False, use_nne=False, consensus=False):
"""
runs a pre-processing + clustering experiment...
exactly one of use_purity, use_nmi, or use_ari can be true
Args:
methods: list of 2-tuples. ... | def function[run_experiment, parameter[methods, data, n_classes, true_labels, n_runs, use_purity, use_nmi, use_ari, use_nne, consensus]]:
constant[
runs a pre-processing + clustering experiment...
exactly one of use_purity, use_nmi, or use_ari can be true
Args:
methods: list of 2-tuples. T... | keyword[def] identifier[run_experiment] ( identifier[methods] , identifier[data] , identifier[n_classes] , identifier[true_labels] , identifier[n_runs] = literal[int] , identifier[use_purity] = keyword[True] , identifier[use_nmi] = keyword[False] , identifier[use_ari] = keyword[False] , identifier[use_nne] = keyword[... | def run_experiment(methods, data, n_classes, true_labels, n_runs=10, use_purity=True, use_nmi=False, use_ari=False, use_nne=False, consensus=False):
"""
runs a pre-processing + clustering experiment...
exactly one of use_purity, use_nmi, or use_ari can be true
Args:
methods: list of 2-tuples. ... |
def get_event_canned_questions(self, id, **data):
"""
GET /events/:id/canned_questions/
This endpoint returns canned questions of a single event (examples: first name, last name, company, prefix, etc.). This endpoint will return :format:`question`.
"""
return self.get("/... | def function[get_event_canned_questions, parameter[self, id]]:
constant[
GET /events/:id/canned_questions/
This endpoint returns canned questions of a single event (examples: first name, last name, company, prefix, etc.). This endpoint will return :format:`question`.
]
return[call[na... | keyword[def] identifier[get_event_canned_questions] ( identifier[self] , identifier[id] ,** identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( literal[string] . identifier[format] ( identifier[id] ), identifier[data] = identifier[data] ) | def get_event_canned_questions(self, id, **data):
"""
GET /events/:id/canned_questions/
This endpoint returns canned questions of a single event (examples: first name, last name, company, prefix, etc.). This endpoint will return :format:`question`.
"""
return self.get('/events/{0}/canned... |
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
... | def function[find_cached_job, parameter[jid]]:
constant[
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
]
variable[... | keyword[def] identifier[find_cached_job] ( identifier[jid] ):
literal[string]
identifier[serial] = identifier[salt] . identifier[payload] . identifier[Serial] ( identifier[__opts__] )
identifier[proc_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[__opts__] [ literal[string] ]... | def find_cached_job(jid):
"""
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
"""
serial = salt.payload.Serial(__opts__)
... |
def _run_check(self):
"""Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False.
"""
cmd = shlex.split(self.config['check_cmd'])
self.log.info("running %s", ' '.join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PI... | def function[_run_check, parameter[self]]:
constant[Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False.
]
variable[cmd] assign[=] call[name[shlex].split, parameter[call[name[self].config][constant[check_cmd]]]]
call[name[self... | keyword[def] identifier[_run_check] ( identifier[self] ):
literal[string]
identifier[cmd] = identifier[shlex] . identifier[split] ( identifier[self] . identifier[config] [ literal[string] ])
identifier[self] . identifier[log] . identifier[info] ( literal[string] , literal[string] . identif... | def _run_check(self):
"""Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False.
"""
cmd = shlex.split(self.config['check_cmd'])
self.log.info('running %s', ' '.join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subpr... |
def set_filter_raw(self, filter_raw):
"""Filter to be used when getting items from Ocean index"""
self.filter_raw = filter_raw
self.filter_raw_dict = []
splitted = re.compile(FILTER_SEPARATOR).split(filter_raw)
for fltr_raw in splitted:
fltr = self.__process_filter(... | def function[set_filter_raw, parameter[self, filter_raw]]:
constant[Filter to be used when getting items from Ocean index]
name[self].filter_raw assign[=] name[filter_raw]
name[self].filter_raw_dict assign[=] list[[]]
variable[splitted] assign[=] call[call[name[re].compile, parameter[nam... | keyword[def] identifier[set_filter_raw] ( identifier[self] , identifier[filter_raw] ):
literal[string]
identifier[self] . identifier[filter_raw] = identifier[filter_raw]
identifier[self] . identifier[filter_raw_dict] =[]
identifier[splitted] = identifier[re] . identifier[compil... | def set_filter_raw(self, filter_raw):
"""Filter to be used when getting items from Ocean index"""
self.filter_raw = filter_raw
self.filter_raw_dict = []
splitted = re.compile(FILTER_SEPARATOR).split(filter_raw)
for fltr_raw in splitted:
fltr = self.__process_filter(fltr_raw)
self.fil... |
def sections(self):
'''
List of section titles from the table of contents on the page.
'''
if not getattr(self, '_sections', False):
query_params = {
'action': 'parse',
'prop': 'sections',
}
query_params.update(self.__title_query_param)
request = _wiki_request(q... | def function[sections, parameter[self]]:
constant[
List of section titles from the table of contents on the page.
]
if <ast.UnaryOp object at 0x7da204564430> begin[:]
variable[query_params] assign[=] dictionary[[<ast.Constant object at 0x7da2045656f0>, <ast.Constant object at 0x7... | keyword[def] identifier[sections] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[getattr] ( identifier[self] , literal[string] , keyword[False] ):
identifier[query_params] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
}
... | def sections(self):
"""
List of section titles from the table of contents on the page.
"""
if not getattr(self, '_sections', False):
query_params = {'action': 'parse', 'prop': 'sections'}
query_params.update(self.__title_query_param)
request = _wiki_request(query_params)
... |
def create_cluster(
self,
parent,
cluster_id,
cluster,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a cluster within an instance.
Example:
>>>... | def function[create_cluster, parameter[self, parent, cluster_id, cluster, retry, timeout, metadata]]:
constant[
Creates a cluster within an instance.
Example:
>>> from google.cloud import bigtable_admin_v2
>>>
>>> client = bigtable_admin_v2.BigtableInstanceAd... | keyword[def] identifier[create_cluster] (
identifier[self] ,
identifier[parent] ,
identifier[cluster_id] ,
identifier[cluster] ,
identifier[retry] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] ,
identifier[timeout] = identifier[google] . identifier... | def create_cluster(self, parent, cluster_id, cluster, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
"""
Creates a cluster within an instance.
Example:
>>> from google.cloud import bigtable_admin_v2
>>>
... |
def get_metric_group_definitions(self):
"""
Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric group definitions of its manag... | def function[get_metric_group_definitions, parameter[self]]:
constant[
Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric gro... | keyword[def] identifier[get_metric_group_definitions] ( identifier[self] ):
literal[string]
identifier[group_names] = identifier[self] . identifier[properties] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] keyword[not] identifier[group_names] :
identifier... | def get_metric_group_definitions(self):
"""
Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric group definitions of its manager o... |
def _process_all(self, limit):
"""
This takes the list of omim identifiers from the omim.txt.Z file,
and iteratively queries the omim api for the json-formatted data.
This will create OMIM classes, with the label,
definition, and some synonyms.
If an entry is "removed",
... | def function[_process_all, parameter[self, limit]]:
constant[
This takes the list of omim identifiers from the omim.txt.Z file,
and iteratively queries the omim api for the json-formatted data.
This will create OMIM classes, with the label,
definition, and some synonyms.
... | keyword[def] identifier[_process_all] ( identifier[self] , identifier[limit] ):
literal[string]
identifier[omimids] = identifier[self] . identifier[_get_omim_ids] ()
identifier[LOG] . identifier[info] ( literal[string] , identifier[len] ( identifier[omimids] ))
identifier[LOG] . ... | def _process_all(self, limit):
"""
This takes the list of omim identifiers from the omim.txt.Z file,
and iteratively queries the omim api for the json-formatted data.
This will create OMIM classes, with the label,
definition, and some synonyms.
If an entry is "removed",
... |
def run_snr(self):
"""Run the snr calculation.
Takes results from ``self.set_parameters`` and other inputs and inputs these
into the snr calculator.
"""
if self.ecc:
required_kwargs = {'dist_type': self.dist_type,
'initial_cond_type':... | def function[run_snr, parameter[self]]:
constant[Run the snr calculation.
Takes results from ``self.set_parameters`` and other inputs and inputs these
into the snr calculator.
]
if name[self].ecc begin[:]
variable[required_kwargs] assign[=] dictionary[[<ast.Cons... | keyword[def] identifier[run_snr] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[ecc] :
identifier[required_kwargs] ={ literal[string] : identifier[self] . identifier[dist_type] ,
literal[string] : identifier[self] . identifier[initial_con... | def run_snr(self):
"""Run the snr calculation.
Takes results from ``self.set_parameters`` and other inputs and inputs these
into the snr calculator.
"""
if self.ecc:
required_kwargs = {'dist_type': self.dist_type, 'initial_cond_type': self.initial_cond_type, 'ecc': True}
... |
def bell_set(self, collection, ordinal=False):
"""
Calculates the Bell set
"""
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in self.bell_set(collection[1:]):
for n, subset in enumerate(smaller)... | def function[bell_set, parameter[self, collection, ordinal]]:
constant[
Calculates the Bell set
]
if compare[call[name[len], parameter[name[collection]]] equal[==] constant[1]] begin[:]
<ast.Yield object at 0x7da1b064ead0>
return[None]
variable[first] assi... | keyword[def] identifier[bell_set] ( identifier[self] , identifier[collection] , identifier[ordinal] = keyword[False] ):
literal[string]
keyword[if] identifier[len] ( identifier[collection] )== literal[int] :
keyword[yield] [ identifier[collection] ]
keyword[return]
... | def bell_set(self, collection, ordinal=False):
"""
Calculates the Bell set
"""
if len(collection) == 1:
yield [collection]
return # depends on [control=['if'], data=[]]
first = collection[0]
for smaller in self.bell_set(collection[1:]):
for (n, subset) in enumera... |
def compare_3PC_keys(key1, key2) -> int:
"""
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
"""
if key1[0] == key2[0]:
return key2[1] - key1[1]
else:
return key2[0] - key1[0] | def function[compare_3PC_keys, parameter[key1, key2]]:
constant[
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
]
if compare[call[name[key1]][constant[0]] equal[==] call[name[key2]][constant[0]]] begin[:]
return[binary_operation[call[name[key2]][constant[1]] - call[nam... | keyword[def] identifier[compare_3PC_keys] ( identifier[key1] , identifier[key2] )-> identifier[int] :
literal[string]
keyword[if] identifier[key1] [ literal[int] ]== identifier[key2] [ literal[int] ]:
keyword[return] identifier[key2] [ literal[int] ]- identifier[key1] [ literal[int] ]
keywo... | def compare_3PC_keys(key1, key2) -> int:
"""
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
"""
if key1[0] == key2[0]:
return key2[1] - key1[1] # depends on [control=['if'], data=[]]
else:
return key2[0] - key1[0] |
def _ParseFilterOptions(self, options):
"""Parses the filter options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
self._event_filter_expression = self.ParseStringOption(options, 'filter')
if self._event_filter... | def function[_ParseFilterOptions, parameter[self, options]]:
constant[Parses the filter options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
]
name[self]._event_filter_expression assign[=] call[name[self].Pars... | keyword[def] identifier[_ParseFilterOptions] ( identifier[self] , identifier[options] ):
literal[string]
identifier[self] . identifier[_event_filter_expression] = identifier[self] . identifier[ParseStringOption] ( identifier[options] , literal[string] )
keyword[if] identifier[self] . identifier[_even... | def _ParseFilterOptions(self, options):
"""Parses the filter options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
self._event_filter_expression = self.ParseStringOption(options, 'filter')
if self._event_filter... |
def ximshow_rectified(self, slitlet2d_rect):
"""Display rectified image with spectrails and frontiers.
Parameters
----------
slitlet2d_rect : numpy array
Array containing the rectified slitlet image
"""
title = "Slitlet#" + str(self.islitlet) + " (rectify)"... | def function[ximshow_rectified, parameter[self, slitlet2d_rect]]:
constant[Display rectified image with spectrails and frontiers.
Parameters
----------
slitlet2d_rect : numpy array
Array containing the rectified slitlet image
]
variable[title] assign[=] bina... | keyword[def] identifier[ximshow_rectified] ( identifier[self] , identifier[slitlet2d_rect] ):
literal[string]
identifier[title] = literal[string] + identifier[str] ( identifier[self] . identifier[islitlet] )+ literal[string]
identifier[ax] = identifier[ximshow] ( identifier[slitlet2d_rec... | def ximshow_rectified(self, slitlet2d_rect):
"""Display rectified image with spectrails and frontiers.
Parameters
----------
slitlet2d_rect : numpy array
Array containing the rectified slitlet image
"""
title = 'Slitlet#' + str(self.islitlet) + ' (rectify)'
ax =... |
def create_ecs_service_role(provider, context, **kwargs):
"""Used to create the ecsServieRole, which has to be named exactly that
currently, so cannot be created via CloudFormation. See:
http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role
Args:
provide... | def function[create_ecs_service_role, parameter[provider, context]]:
constant[Used to create the ecsServieRole, which has to be named exactly that
currently, so cannot be created via CloudFormation. See:
http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role
... | keyword[def] identifier[create_ecs_service_role] ( identifier[provider] , identifier[context] ,** identifier[kwargs] ):
literal[string]
identifier[role_name] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] )
identifier[client] = identifier[get_session] ( identifier[provider]... | def create_ecs_service_role(provider, context, **kwargs):
"""Used to create the ecsServieRole, which has to be named exactly that
currently, so cannot be created via CloudFormation. See:
http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role
Args:
provide... |
def with_claims(self, issuer=None, subject=None, audience=None,
additional_claims=None):
"""Returns a copy of these credentials with modified claims.
Args:
issuer (str): The `iss` claim. If unspecified the current issuer
claim will be used.
su... | def function[with_claims, parameter[self, issuer, subject, audience, additional_claims]]:
constant[Returns a copy of these credentials with modified claims.
Args:
issuer (str): The `iss` claim. If unspecified the current issuer
claim will be used.
subject (str): ... | keyword[def] identifier[with_claims] ( identifier[self] , identifier[issuer] = keyword[None] , identifier[subject] = keyword[None] , identifier[audience] = keyword[None] ,
identifier[additional_claims] = keyword[None] ):
literal[string]
identifier[new_additional_claims] = identifier[copy] . identi... | def with_claims(self, issuer=None, subject=None, audience=None, additional_claims=None):
"""Returns a copy of these credentials with modified claims.
Args:
issuer (str): The `iss` claim. If unspecified the current issuer
claim will be used.
subject (str): The `sub` c... |
def addApplication(self, name, version=None, path=None, disk_num=0, soft=-1):
"""Add a new application in some disk."""
fapp = Features()
fapp.features.append(Feature("name", "=", name))
if version:
fapp.features.append(Feature("version", "=", version))
if path:
... | def function[addApplication, parameter[self, name, version, path, disk_num, soft]]:
constant[Add a new application in some disk.]
variable[fapp] assign[=] call[name[Features], parameter[]]
call[name[fapp].features.append, parameter[call[name[Feature], parameter[constant[name], constant[=], name[... | keyword[def] identifier[addApplication] ( identifier[self] , identifier[name] , identifier[version] = keyword[None] , identifier[path] = keyword[None] , identifier[disk_num] = literal[int] , identifier[soft] =- literal[int] ):
literal[string]
identifier[fapp] = identifier[Features] ()
ide... | def addApplication(self, name, version=None, path=None, disk_num=0, soft=-1):
"""Add a new application in some disk."""
fapp = Features()
fapp.features.append(Feature('name', '=', name))
if version:
fapp.features.append(Feature('version', '=', version)) # depends on [control=['if'], data=[]]
... |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.Timestamp = reader.ReadUInt32()
self.Services = reader.ReadUInt64()
addr = bytearray(reader.ReadFixedString(16))
addr.reverse()
ad... | def function[Deserialize, parameter[self, reader]]:
constant[
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
]
name[self].Timestamp assign[=] call[name[reader].ReadUInt32, parameter[]]
name[self].Services assign[=] call[name[reader].ReadUInt64, ... | keyword[def] identifier[Deserialize] ( identifier[self] , identifier[reader] ):
literal[string]
identifier[self] . identifier[Timestamp] = identifier[reader] . identifier[ReadUInt32] ()
identifier[self] . identifier[Services] = identifier[reader] . identifier[ReadUInt64] ()
identi... | def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.Timestamp = reader.ReadUInt32()
self.Services = reader.ReadUInt64()
addr = bytearray(reader.ReadFixedString(16))
addr.reverse()
addr.strip(b'\x00')
nu... |
def _check_and_convert_bools(self):
"""Replace boolean variables by the characters 'F'/'T'
"""
replacements = {
True: 'T',
False: 'F',
}
for key in self.bools:
if isinstance(self[key], bool):
self[key] = replacements[self[key]] | def function[_check_and_convert_bools, parameter[self]]:
constant[Replace boolean variables by the characters 'F'/'T'
]
variable[replacements] assign[=] dictionary[[<ast.Constant object at 0x7da1b225d3c0>, <ast.Constant object at 0x7da1b225df60>], [<ast.Constant object at 0x7da1b225f3a0>, <ast.C... | keyword[def] identifier[_check_and_convert_bools] ( identifier[self] ):
literal[string]
identifier[replacements] ={
keyword[True] : literal[string] ,
keyword[False] : literal[string] ,
}
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[bo... | def _check_and_convert_bools(self):
"""Replace boolean variables by the characters 'F'/'T'
"""
replacements = {True: 'T', False: 'F'}
for key in self.bools:
if isinstance(self[key], bool):
self[key] = replacements[self[key]] # depends on [control=['if'], data=[]] # depends on [... |
def end(self):
"""Write all JSON data to files."""
for comic in self.data:
with codecs.open(self.jsonFn(comic), 'w', self.encoding) as f:
json.dump(self.data[comic], f, indent=2, separators=(',', ': '), sort_keys=True) | def function[end, parameter[self]]:
constant[Write all JSON data to files.]
for taget[name[comic]] in starred[name[self].data] begin[:]
with call[name[codecs].open, parameter[call[name[self].jsonFn, parameter[name[comic]]], constant[w], name[self].encoding]] begin[:]
... | keyword[def] identifier[end] ( identifier[self] ):
literal[string]
keyword[for] identifier[comic] keyword[in] identifier[self] . identifier[data] :
keyword[with] identifier[codecs] . identifier[open] ( identifier[self] . identifier[jsonFn] ( identifier[comic] ), literal[string] , i... | def end(self):
"""Write all JSON data to files."""
for comic in self.data:
with codecs.open(self.jsonFn(comic), 'w', self.encoding) as f:
json.dump(self.data[comic], f, indent=2, separators=(',', ': '), sort_keys=True) # depends on [control=['with'], data=['f']] # depends on [control=['for... |
def plot_groups_unplaced(self, fout_dir=".", **kws_usr):
"""Plot each GO group."""
# kws: go2color max_gos upper_trigger max_upper
plotobj = PltGroupedGos(self)
return plotobj.plot_groups_unplaced(fout_dir, **kws_usr) | def function[plot_groups_unplaced, parameter[self, fout_dir]]:
constant[Plot each GO group.]
variable[plotobj] assign[=] call[name[PltGroupedGos], parameter[name[self]]]
return[call[name[plotobj].plot_groups_unplaced, parameter[name[fout_dir]]]] | keyword[def] identifier[plot_groups_unplaced] ( identifier[self] , identifier[fout_dir] = literal[string] ,** identifier[kws_usr] ):
literal[string]
identifier[plotobj] = identifier[PltGroupedGos] ( identifier[self] )
keyword[return] identifier[plotobj] . identifier[plot_groups_u... | def plot_groups_unplaced(self, fout_dir='.', **kws_usr):
"""Plot each GO group."""
# kws: go2color max_gos upper_trigger max_upper
plotobj = PltGroupedGos(self)
return plotobj.plot_groups_unplaced(fout_dir, **kws_usr) |
def get_principal_name(graph_object):
"""Attempts to resolve a principal name.
:param graph_object: the Azure AD Graph Object
:return: The resolved value or an empty string if unsuccessful.
"""
if hasattr(graph_object, 'user_principal_name'):
return graph_object.user_... | def function[get_principal_name, parameter[graph_object]]:
constant[Attempts to resolve a principal name.
:param graph_object: the Azure AD Graph Object
:return: The resolved value or an empty string if unsuccessful.
]
if call[name[hasattr], parameter[name[graph_object], constant... | keyword[def] identifier[get_principal_name] ( identifier[graph_object] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[graph_object] , literal[string] ):
keyword[return] identifier[graph_object] . identifier[user_principal_name]
keyword[elif] identifier[has... | def get_principal_name(graph_object):
"""Attempts to resolve a principal name.
:param graph_object: the Azure AD Graph Object
:return: The resolved value or an empty string if unsuccessful.
"""
if hasattr(graph_object, 'user_principal_name'):
return graph_object.user_principal_na... |
def stop_gracefully(self):
'''Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
'''
if self.shutting_down:
self.log(logging.INFO,
... | def function[stop_gracefully, parameter[self]]:
constant[Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
]
if name[self].shutting_down begin[:]
... | keyword[def] identifier[stop_gracefully] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[shutting_down] :
identifier[self] . identifier[log] ( identifier[logging] . identifier[INFO] ,
literal[string] )
identifier[self] . identi... | def stop_gracefully(self):
"""Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
"""
if self.shutting_down:
self.log(logging.INFO, 'second shutdown request, ... |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
BDEFileEntry: file entry or None.
"""
path_spec = bde_path_spec.BDEPathSpec(parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | def function[GetRootFileEntry, parameter[self]]:
constant[Retrieves the root file entry.
Returns:
BDEFileEntry: file entry or None.
]
variable[path_spec] assign[=] call[name[bde_path_spec].BDEPathSpec, parameter[]]
return[call[name[self].GetFileEntryByPathSpec, parameter[name[path_spe... | keyword[def] identifier[GetRootFileEntry] ( identifier[self] ):
literal[string]
identifier[path_spec] = identifier[bde_path_spec] . identifier[BDEPathSpec] ( identifier[parent] = identifier[self] . identifier[_path_spec] . identifier[parent] )
keyword[return] identifier[self] . identifier[GetFileEntr... | def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
BDEFileEntry: file entry or None.
"""
path_spec = bde_path_spec.BDEPathSpec(parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) |
def unpublish(self):
"""
Un-publish the current object.
"""
if self.is_draft and self.publishing_linked:
publishing_signals.publishing_pre_unpublish.send(
sender=type(self), instance=self)
# Unlink draft and published copies then delete published.
... | def function[unpublish, parameter[self]]:
constant[
Un-publish the current object.
]
if <ast.BoolOp object at 0x7da2043451b0> begin[:]
call[name[publishing_signals].publishing_pre_unpublish.send, parameter[]]
call[call[call[name[type], parameter[name[self]... | keyword[def] identifier[unpublish] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_draft] keyword[and] identifier[self] . identifier[publishing_linked] :
identifier[publishing_signals] . identifier[publishing_pre_unpublish] . identifier[send] (
... | def unpublish(self):
"""
Un-publish the current object.
"""
if self.is_draft and self.publishing_linked:
publishing_signals.publishing_pre_unpublish.send(sender=type(self), instance=self)
# Unlink draft and published copies then delete published.
# NOTE: This indirect dan... |
def _attach_params(self, params, **kwargs):
"""Attach a list of parameters (or ParameterSet) to this ParameterSet.
:parameter list params: list of parameters, or ParameterSet
:parameter **kwargs: attributes to set for each parameter (ie tags)
"""
lst = params.to_list() if isinst... | def function[_attach_params, parameter[self, params]]:
constant[Attach a list of parameters (or ParameterSet) to this ParameterSet.
:parameter list params: list of parameters, or ParameterSet
:parameter **kwargs: attributes to set for each parameter (ie tags)
]
variable[lst] ass... | keyword[def] identifier[_attach_params] ( identifier[self] , identifier[params] ,** identifier[kwargs] ):
literal[string]
identifier[lst] = identifier[params] . identifier[to_list] () keyword[if] identifier[isinstance] ( identifier[params] , identifier[ParameterSet] ) keyword[else] identifier[par... | def _attach_params(self, params, **kwargs):
"""Attach a list of parameters (or ParameterSet) to this ParameterSet.
:parameter list params: list of parameters, or ParameterSet
:parameter **kwargs: attributes to set for each parameter (ie tags)
"""
lst = params.to_list() if isinstance(par... |
def insert_rows(self, table, rows, target_fields=None, commit_every=1000,
replace=False):
"""
A generic way to insert a set of tuples into a table,
a new transaction is created every commit_every rows
:param table: Name of the target table
:type table: str
... | def function[insert_rows, parameter[self, table, rows, target_fields, commit_every, replace]]:
constant[
A generic way to insert a set of tuples into a table,
a new transaction is created every commit_every rows
:param table: Name of the target table
:type table: str
:pa... | keyword[def] identifier[insert_rows] ( identifier[self] , identifier[table] , identifier[rows] , identifier[target_fields] = keyword[None] , identifier[commit_every] = literal[int] ,
identifier[replace] = keyword[False] ):
literal[string]
keyword[if] identifier[target_fields] :
ident... | def insert_rows(self, table, rows, target_fields=None, commit_every=1000, replace=False):
"""
A generic way to insert a set of tuples into a table,
a new transaction is created every commit_every rows
:param table: Name of the target table
:type table: str
:param rows: The r... |
def _config(self, **kargs):
""" ReConfigure Package """
for key, value in kargs.items():
setattr(self, key, value) | def function[_config, parameter[self]]:
constant[ ReConfigure Package ]
for taget[tuple[[<ast.Name object at 0x7da18bcc9330>, <ast.Name object at 0x7da18bcca590>]]] in starred[call[name[kargs].items, parameter[]]] begin[:]
call[name[setattr], parameter[name[self], name[key], name[value]]... | keyword[def] identifier[_config] ( identifier[self] ,** identifier[kargs] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[kargs] . identifier[items] ():
identifier[setattr] ( identifier[self] , identifier[key] , identifier[value] ) | def _config(self, **kargs):
""" ReConfigure Package """
for (key, value) in kargs.items():
setattr(self, key, value) # depends on [control=['for'], data=[]] |
def reset_tag(self, name):
"""
Reset the tag and return the new tag identifier.
:param name: The tag
:type name: str
:rtype: str
"""
id_ = str(uuid.uuid4()).replace('-', '')
self._store.forever(self.tag_key(name), id_)
return id_ | def function[reset_tag, parameter[self, name]]:
constant[
Reset the tag and return the new tag identifier.
:param name: The tag
:type name: str
:rtype: str
]
variable[id_] assign[=] call[call[name[str], parameter[call[name[uuid].uuid4, parameter[]]]].replace, pa... | keyword[def] identifier[reset_tag] ( identifier[self] , identifier[name] ):
literal[string]
identifier[id_] = identifier[str] ( identifier[uuid] . identifier[uuid4] ()). identifier[replace] ( literal[string] , literal[string] )
identifier[self] . identifier[_store] . identifier[forever] (... | def reset_tag(self, name):
"""
Reset the tag and return the new tag identifier.
:param name: The tag
:type name: str
:rtype: str
"""
id_ = str(uuid.uuid4()).replace('-', '')
self._store.forever(self.tag_key(name), id_)
return id_ |
def do_next(self, line):
"""Jump to the next entities (ontology, class or property) depending on context"""
if not self.current:
print("Please select an ontology first. E.g. use the 'ls ontologies' or 'get ontology <name>' commands.")
elif self.currentEntity:
g = self.cur... | def function[do_next, parameter[self, line]]:
constant[Jump to the next entities (ontology, class or property) depending on context]
if <ast.UnaryOp object at 0x7da1b11ab970> begin[:]
call[name[print], parameter[constant[Please select an ontology first. E.g. use the 'ls ontologies' or 'g... | keyword[def] identifier[do_next] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[current] :
identifier[print] ( literal[string] )
keyword[elif] identifier[self] . identifier[currentEntity] :
identi... | def do_next(self, line):
"""Jump to the next entities (ontology, class or property) depending on context"""
if not self.current:
print("Please select an ontology first. E.g. use the 'ls ontologies' or 'get ontology <name>' commands.") # depends on [control=['if'], data=[]]
elif self.currentEntity:
... |
def shutdown_abort():
'''
Abort a shutdown. Only available while the dialog box is being
displayed to the user. Once the shutdown has initiated, it cannot be
aborted.
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion... | def function[shutdown_abort, parameter[]]:
constant[
Abort a shutdown. Only available while the dialog box is being
displayed to the user. Once the shutdown has initiated, it cannot be
aborted.
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-blo... | keyword[def] identifier[shutdown_abort] ():
literal[string]
keyword[try] :
identifier[win32api] . identifier[AbortSystemShutdown] ( literal[string] )
keyword[return] keyword[True]
keyword[except] identifier[pywintypes] . identifier[error] keyword[as] identifier[exc] :
( ... | def shutdown_abort():
"""
Abort a shutdown. Only available while the dialog box is being
displayed to the user. Once the shutdown has initiated, it cannot be
aborted.
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion... |
def product_path(cls, project, location, product):
"""Return a fully-qualified product string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/products/{product}",
project=project,
location=location,
product=product... | def function[product_path, parameter[cls, project, location, product]]:
constant[Return a fully-qualified product string.]
return[call[name[google].api_core.path_template.expand, parameter[constant[projects/{project}/locations/{location}/products/{product}]]]] | keyword[def] identifier[product_path] ( identifier[cls] , identifier[project] , identifier[location] , identifier[product] ):
literal[string]
keyword[return] identifier[google] . identifier[api_core] . identifier[path_template] . identifier[expand] (
literal[string] ,
identifier[... | def product_path(cls, project, location, product):
"""Return a fully-qualified product string."""
return google.api_core.path_template.expand('projects/{project}/locations/{location}/products/{product}', project=project, location=location, product=product) |
def get_median(data_np):
"""Like :func:`get_mean` but for median."""
i = np.isfinite(data_np)
if not np.any(i):
return np.nan
return np.median(data_np[i]) | def function[get_median, parameter[data_np]]:
constant[Like :func:`get_mean` but for median.]
variable[i] assign[=] call[name[np].isfinite, parameter[name[data_np]]]
if <ast.UnaryOp object at 0x7da1b0c27220> begin[:]
return[name[np].nan]
return[call[name[np].median, parameter[call[na... | keyword[def] identifier[get_median] ( identifier[data_np] ):
literal[string]
identifier[i] = identifier[np] . identifier[isfinite] ( identifier[data_np] )
keyword[if] keyword[not] identifier[np] . identifier[any] ( identifier[i] ):
keyword[return] identifier[np] . identifier[nan]
key... | def get_median(data_np):
"""Like :func:`get_mean` but for median."""
i = np.isfinite(data_np)
if not np.any(i):
return np.nan # depends on [control=['if'], data=[]]
return np.median(data_np[i]) |
def calc_mean_time_deviation(timepoints, weights, mean_time=None):
"""Return the weighted deviation of the given timepoints from their mean
time.
With equal given weights, the is simply the standard deviation of the
given time points:
>>> from hydpy import calc_mean_time_deviation
>>> calc_mea... | def function[calc_mean_time_deviation, parameter[timepoints, weights, mean_time]]:
constant[Return the weighted deviation of the given timepoints from their mean
time.
With equal given weights, the is simply the standard deviation of the
given time points:
>>> from hydpy import calc_mean_time_... | keyword[def] identifier[calc_mean_time_deviation] ( identifier[timepoints] , identifier[weights] , identifier[mean_time] = keyword[None] ):
literal[string]
identifier[timepoints] = identifier[numpy] . identifier[array] ( identifier[timepoints] )
identifier[weights] = identifier[numpy] . identifier[arr... | def calc_mean_time_deviation(timepoints, weights, mean_time=None):
"""Return the weighted deviation of the given timepoints from their mean
time.
With equal given weights, the is simply the standard deviation of the
given time points:
>>> from hydpy import calc_mean_time_deviation
>>> calc_mea... |
def finish():
# type: () -> None
""" Merge current feature into develop. """
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err(
"You have uncommitted changes in your repo!\n"
"You need to stash them before you merge the ... | def function[finish, parameter[]]:
constant[ Merge current feature into develop. ]
variable[pretend] assign[=] call[name[context].get, parameter[constant[pretend], constant[False]]]
if <ast.BoolOp object at 0x7da1b10afac0> begin[:]
call[name[log].err, parameter[constant[You have ... | keyword[def] identifier[finish] ():
literal[string]
identifier[pretend] = identifier[context] . identifier[get] ( literal[string] , keyword[False] )
keyword[if] keyword[not] identifier[pretend] keyword[and] ( identifier[git] . identifier[staged] () keyword[or] identifier[git] . identifier[unstag... | def finish():
# type: () -> None
' Merge current feature into develop. '
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err('You have uncommitted changes in your repo!\nYou need to stash them before you merge the hotfix branch')
sys.exit(... |
def position_to_value(self, y):
"""Convert position in pixels to value"""
vsb = self.editor.verticalScrollBar()
return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()]) | def function[position_to_value, parameter[self, y]]:
constant[Convert position in pixels to value]
variable[vsb] assign[=] call[name[self].editor.verticalScrollBar, parameter[]]
return[binary_operation[call[name[vsb].minimum, parameter[]] + call[name[max], parameter[list[[<ast.Constant object at 0x7... | keyword[def] identifier[position_to_value] ( identifier[self] , identifier[y] ):
literal[string]
identifier[vsb] = identifier[self] . identifier[editor] . identifier[verticalScrollBar] ()
keyword[return] identifier[vsb] . identifier[minimum] ()+ identifier[max] ([ literal[int] ,( identifi... | def position_to_value(self, y):
"""Convert position in pixels to value"""
vsb = self.editor.verticalScrollBar()
return vsb.minimum() + max([0, (y - self.offset) / self.get_scale_factor()]) |
def evaluate_emb(emb, labels):
"""Evaluate embeddings based on Recall@k."""
d_mat = get_distance_matrix(emb)
d_mat = d_mat.asnumpy()
labels = labels.asnumpy()
names = []
accs = []
for k in [1, 2, 4, 8, 16]:
names.append('Recall@%d' % k)
correct, cnt = 0.0, 0.0
for i ... | def function[evaluate_emb, parameter[emb, labels]]:
constant[Evaluate embeddings based on Recall@k.]
variable[d_mat] assign[=] call[name[get_distance_matrix], parameter[name[emb]]]
variable[d_mat] assign[=] call[name[d_mat].asnumpy, parameter[]]
variable[labels] assign[=] call[name[label... | keyword[def] identifier[evaluate_emb] ( identifier[emb] , identifier[labels] ):
literal[string]
identifier[d_mat] = identifier[get_distance_matrix] ( identifier[emb] )
identifier[d_mat] = identifier[d_mat] . identifier[asnumpy] ()
identifier[labels] = identifier[labels] . identifier[asnumpy] ()
... | def evaluate_emb(emb, labels):
"""Evaluate embeddings based on Recall@k."""
d_mat = get_distance_matrix(emb)
d_mat = d_mat.asnumpy()
labels = labels.asnumpy()
names = []
accs = []
for k in [1, 2, 4, 8, 16]:
names.append('Recall@%d' % k)
(correct, cnt) = (0.0, 0.0)
for... |
def get_node(self, name, memory=False, binary=False):
"""
An individual node in the RabbitMQ cluster. Set "memory=true" to get
memory statistics, and "binary=true" to get a breakdown of binary
memory use (may be expensive if there are many small binaries in the
system).
"... | def function[get_node, parameter[self, name, memory, binary]]:
constant[
An individual node in the RabbitMQ cluster. Set "memory=true" to get
memory statistics, and "binary=true" to get a breakdown of binary
memory use (may be expensive if there are many small binaries in the
sys... | keyword[def] identifier[get_node] ( identifier[self] , identifier[name] , identifier[memory] = keyword[False] , identifier[binary] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_api_get] (
identifier[url] = literal[string] . identifier[format] ( identif... | def get_node(self, name, memory=False, binary=False):
"""
An individual node in the RabbitMQ cluster. Set "memory=true" to get
memory statistics, and "binary=true" to get a breakdown of binary
memory use (may be expensive if there are many small binaries in the
system).
"""
... |
def Validate(self, value):
"""Validate an RDFValue instance.
Args:
value: An RDFValue instance or something which may be used to instantiate
the correct instance.
Raises:
TypeValueError: If the value is not a valid RDFValue instance or the
required type.
Returns:
A V... | def function[Validate, parameter[self, value]]:
constant[Validate an RDFValue instance.
Args:
value: An RDFValue instance or something which may be used to instantiate
the correct instance.
Raises:
TypeValueError: If the value is not a valid RDFValue instance or the
require... | keyword[def] identifier[Validate] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[self] . identifier[rdfclass] ):
... | def Validate(self, value):
"""Validate an RDFValue instance.
Args:
value: An RDFValue instance or something which may be used to instantiate
the correct instance.
Raises:
TypeValueError: If the value is not a valid RDFValue instance or the
required type.
Returns:
A V... |
def _logic(self, value=None):
# type: (Any) -> Tuple[Union[bool, None], str]
"""Process the inner logic of the validator.
The validation results are returned as tuple (boolean (true/false), reasontext)
"""
self._validation_result, self._validation_reason = None, 'No reason'
... | def function[_logic, parameter[self, value]]:
constant[Process the inner logic of the validator.
The validation results are returned as tuple (boolean (true/false), reasontext)
]
<ast.Tuple object at 0x7da2049605b0> assign[=] tuple[[<ast.Constant object at 0x7da204960580>, <ast.Constant... | keyword[def] identifier[_logic] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
identifier[self] . identifier[_validation_result] , identifier[self] . identifier[_validation_reason] = keyword[None] , literal[string]
keyword[return] identifier[self] . identifier... | def _logic(self, value=None):
# type: (Any) -> Tuple[Union[bool, None], str]
'Process the inner logic of the validator.\n\n The validation results are returned as tuple (boolean (true/false), reasontext)\n '
(self._validation_result, self._validation_reason) = (None, 'No reason')
return (s... |
def write_packages(self, reqs_file):
"""
Dump the packages in the catalog in a requirements file
"""
write_file_lines(reqs_file, ('{}\n'.format(package) for package in self.packages)) | def function[write_packages, parameter[self, reqs_file]]:
constant[
Dump the packages in the catalog in a requirements file
]
call[name[write_file_lines], parameter[name[reqs_file], <ast.GeneratorExp object at 0x7da20c6c5300>]] | keyword[def] identifier[write_packages] ( identifier[self] , identifier[reqs_file] ):
literal[string]
identifier[write_file_lines] ( identifier[reqs_file] ,( literal[string] . identifier[format] ( identifier[package] ) keyword[for] identifier[package] keyword[in] identifier[self] . identifier[pa... | def write_packages(self, reqs_file):
"""
Dump the packages in the catalog in a requirements file
"""
write_file_lines(reqs_file, ('{}\n'.format(package) for package in self.packages)) |
def add_tags(self, tags, **kwargs):
"""
:param tags: Tags to add to the app
:type tags: array
Adds the specified application name tags (aliases) to this app.
The current user must be a developer of the app.
"""
if self._dxid is not None:
return dxpy... | def function[add_tags, parameter[self, tags]]:
constant[
:param tags: Tags to add to the app
:type tags: array
Adds the specified application name tags (aliases) to this app.
The current user must be a developer of the app.
]
if compare[name[self]._dxid is_not ... | keyword[def] identifier[add_tags] ( identifier[self] , identifier[tags] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[_dxid] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[dxpy] . identifier[api] . identifier[app_add_tags]... | def add_tags(self, tags, **kwargs):
"""
:param tags: Tags to add to the app
:type tags: array
Adds the specified application name tags (aliases) to this app.
The current user must be a developer of the app.
"""
if self._dxid is not None:
return dxpy.api.app_add... |
def set_cluster_info(self,
disallow_cluster_termination=None,
enable_ganglia_monitoring=None,
datadog_api_token=None,
datadog_app_token=None,
node_bootstrap=None,
master_... | def function[set_cluster_info, parameter[self, disallow_cluster_termination, enable_ganglia_monitoring, datadog_api_token, datadog_app_token, node_bootstrap, master_instance_type, slave_instance_type, min_nodes, max_nodes, slave_request_type, fallback_to_ondemand, node_base_cooldown_period, node_spot_cooldown_period, c... | keyword[def] identifier[set_cluster_info] ( identifier[self] ,
identifier[disallow_cluster_termination] = keyword[None] ,
identifier[enable_ganglia_monitoring] = keyword[None] ,
identifier[datadog_api_token] = keyword[None] ,
identifier[datadog_app_token] = keyword[None] ,
identifier[node_bootstrap] = keyword[No... | def set_cluster_info(self, disallow_cluster_termination=None, enable_ganglia_monitoring=None, datadog_api_token=None, datadog_app_token=None, node_bootstrap=None, master_instance_type=None, slave_instance_type=None, min_nodes=None, max_nodes=None, slave_request_type=None, fallback_to_ondemand=None, node_base_cooldown_p... |
def _valid_numpy_subdtype(x, numpy_types):
"""
Is any dtype from numpy_types superior to the dtype of x?
"""
# If any of the types given in numpy_types is understood as numpy.generic,
# all possible x will be considered valid. This is probably unwanted.
for t in numpy_types:
assert not ... | def function[_valid_numpy_subdtype, parameter[x, numpy_types]]:
constant[
Is any dtype from numpy_types superior to the dtype of x?
]
for taget[name[t]] in starred[name[numpy_types]] begin[:]
assert[<ast.UnaryOp object at 0x7da204347a00>]
return[call[name[any], parameter[<ast.Generat... | keyword[def] identifier[_valid_numpy_subdtype] ( identifier[x] , identifier[numpy_types] ):
literal[string]
keyword[for] identifier[t] keyword[in] identifier[numpy_types] :
keyword[assert] keyword[not] identifier[np] . identifier[issubdtype] ( identifier[np] . identifier[generic] , ... | def _valid_numpy_subdtype(x, numpy_types):
"""
Is any dtype from numpy_types superior to the dtype of x?
"""
# If any of the types given in numpy_types is understood as numpy.generic,
# all possible x will be considered valid. This is probably unwanted.
for t in numpy_types:
assert not ... |
def run(self, timeout=None):
"""
Run the map/reduce operation synchronously. Returns a list of
results, or a list of links if the last phase is a link phase.
Shortcut for :meth:`riak.client.RiakClient.mapred`.
:param timeout: Timeout in milliseconds
:type timeout: intege... | def function[run, parameter[self, timeout]]:
constant[
Run the map/reduce operation synchronously. Returns a list of
results, or a list of links if the last phase is a link phase.
Shortcut for :meth:`riak.client.RiakClient.mapred`.
:param timeout: Timeout in milliseconds
... | keyword[def] identifier[run] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[query] , identifier[link_results_flag] = identifier[self] . identifier[_normalize_query] ()
keyword[try] :
identifier[result] = identifier[self] . identifier[_c... | def run(self, timeout=None):
"""
Run the map/reduce operation synchronously. Returns a list of
results, or a list of links if the last phase is a link phase.
Shortcut for :meth:`riak.client.RiakClient.mapred`.
:param timeout: Timeout in milliseconds
:type timeout: integer, N... |
def list_subnets(auth=None, **kwargs):
'''
List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets \
filters='{"tenant_id": "1dcac318a83b4610b7a7... | def function[list_subnets, parameter[auth]]:
constant[
List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets filters='{"tenant_id": "1dcac3... | keyword[def] identifier[list_subnets] ( identifier[auth] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[cloud] = identifier[get_operator_cloud] ( identifier[auth] )
identifier[kwargs] = identifier[_clean_kwargs] (** identifier[kwargs] )
keyword[return] identifier[cloud] . i... | def list_subnets(auth=None, **kwargs):
"""
List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets filters='{"tenant_id": "1dcac318a83b4610b7a7f7... |
def removeChild(self, child_id):
"""Remove a child from current workitem
:param child_id: the child workitem id/number
(integer or equivalent string)
"""
self.log.debug("Try to remove a child <Workitem %s> from current "
"<Workitem %s>",
... | def function[removeChild, parameter[self, child_id]]:
constant[Remove a child from current workitem
:param child_id: the child workitem id/number
(integer or equivalent string)
]
call[name[self].log.debug, parameter[constant[Try to remove a child <Workitem %s> from current <... | keyword[def] identifier[removeChild] ( identifier[self] , identifier[child_id] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string]
literal[string] ,
identifier[child_id] ,
identifier[self] )
identifier[self] . identifier[... | def removeChild(self, child_id):
"""Remove a child from current workitem
:param child_id: the child workitem id/number
(integer or equivalent string)
"""
self.log.debug('Try to remove a child <Workitem %s> from current <Workitem %s>', child_id, self)
self._removeChildren([child_... |
def recreate_relationship(self, attribute_name, key):
'''
Recreates one-to-one relationship
'''
iterable = self.record_keeper.foreign_to_foreign_map["banner_link_page"] # noqa
for foreign_page_id, linked_page_foreign_id in iteritems(iterable):
# get local banner page... | def function[recreate_relationship, parameter[self, attribute_name, key]]:
constant[
Recreates one-to-one relationship
]
variable[iterable] assign[=] call[name[self].record_keeper.foreign_to_foreign_map][constant[banner_link_page]]
for taget[tuple[[<ast.Name object at 0x7da1b05fb... | keyword[def] identifier[recreate_relationship] ( identifier[self] , identifier[attribute_name] , identifier[key] ):
literal[string]
identifier[iterable] = identifier[self] . identifier[record_keeper] . identifier[foreign_to_foreign_map] [ literal[string] ]
keyword[for] identifier[foreign_... | def recreate_relationship(self, attribute_name, key):
"""
Recreates one-to-one relationship
"""
iterable = self.record_keeper.foreign_to_foreign_map['banner_link_page'] # noqa
for (foreign_page_id, linked_page_foreign_id) in iteritems(iterable):
# get local banner page
local... |
def get_sub_comp_info(source_info, comp):
"""Build and return information about a sub-component for a particular selection
"""
sub_comps = source_info.get('components', None)
if sub_comps is None:
return source_info.copy()
moving = source_info.get('moving', False)
... | def function[get_sub_comp_info, parameter[source_info, comp]]:
constant[Build and return information about a sub-component for a particular selection
]
variable[sub_comps] assign[=] call[name[source_info].get, parameter[constant[components], constant[None]]]
if compare[name[sub_comps] is... | keyword[def] identifier[get_sub_comp_info] ( identifier[source_info] , identifier[comp] ):
literal[string]
identifier[sub_comps] = identifier[source_info] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[sub_comps] keyword[is] keyword[None] :
key... | def get_sub_comp_info(source_info, comp):
"""Build and return information about a sub-component for a particular selection
"""
sub_comps = source_info.get('components', None)
if sub_comps is None:
return source_info.copy() # depends on [control=['if'], data=[]]
moving = source_info.get(... |
def remove(self,
entity_id,
property_uri,
value):
"""Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return... | def function[remove, parameter[self, entity_id, property_uri, value]]:
constant[Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return:
bool... | keyword[def] identifier[remove] ( identifier[self] ,
identifier[entity_id] ,
identifier[property_uri] ,
identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[entity_id] . identifier[startswith] ( literal[string] ):
identifier[entity_uri] = identifier[urllib] . i... | def remove(self, entity_id, property_uri, value):
"""Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return:
boolean: True if triple was removed... |
def diff_values(value_a, value_b, raw=False):
"""Returns a human-readable diff between two values
:param value_a: First value to compare
:param value_b: Second value to compare
:param raw: True to compare the raw values, e.g. UIDs
:returns a list of diff tuples
"""
if not raw:
valu... | def function[diff_values, parameter[value_a, value_b, raw]]:
constant[Returns a human-readable diff between two values
:param value_a: First value to compare
:param value_b: Second value to compare
:param raw: True to compare the raw values, e.g. UIDs
:returns a list of diff tuples
]
... | keyword[def] identifier[diff_values] ( identifier[value_a] , identifier[value_b] , identifier[raw] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[raw] :
identifier[value_a] = identifier[_process_value] ( identifier[value_a] )
identifier[value_b] = identifier[_p... | def diff_values(value_a, value_b, raw=False):
"""Returns a human-readable diff between two values
:param value_a: First value to compare
:param value_b: Second value to compare
:param raw: True to compare the raw values, e.g. UIDs
:returns a list of diff tuples
"""
if not raw:
value... |
def export_mesh(mesh, file_obj, file_type=None, **kwargs):
"""
Export a Trimesh object to a file- like object, or to a filename
Parameters
---------
file_obj : str, file-like
Where should mesh be exported to
file_type : str or None
Represents file type (eg: 'stl')
Returns
-... | def function[export_mesh, parameter[mesh, file_obj, file_type]]:
constant[
Export a Trimesh object to a file- like object, or to a filename
Parameters
---------
file_obj : str, file-like
Where should mesh be exported to
file_type : str or None
Represents file type (eg: 'stl')
... | keyword[def] identifier[export_mesh] ( identifier[mesh] , identifier[file_obj] , identifier[file_type] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[was_opened] = keyword[False]
keyword[if] identifier[util] . identifier[is_string] ( identifier[file_obj] ):
... | def export_mesh(mesh, file_obj, file_type=None, **kwargs):
"""
Export a Trimesh object to a file- like object, or to a filename
Parameters
---------
file_obj : str, file-like
Where should mesh be exported to
file_type : str or None
Represents file type (eg: 'stl')
Returns
-... |
def delete(self, request, bot_id, id, format=None):
"""
Delete existing Messenger Bot
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(MessengerBotDetail, self).delete(request, bot_id, id, format) | def function[delete, parameter[self, request, bot_id, id, format]]:
constant[
Delete existing Messenger Bot
---
responseMessages:
- code: 401
message: Not authenticated
]
return[call[call[name[super], parameter[name[MessengerBotDetail], name[self]]].... | keyword[def] identifier[delete] ( identifier[self] , identifier[request] , identifier[bot_id] , identifier[id] , identifier[format] = keyword[None] ):
literal[string]
keyword[return] identifier[super] ( identifier[MessengerBotDetail] , identifier[self] ). identifier[delete] ( identifier[request] ,... | def delete(self, request, bot_id, id, format=None):
"""
Delete existing Messenger Bot
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(MessengerBotDetail, self).delete(request, bot_id, id, format) |
def setup_prefix_logging(logdir):
"""
Sets up a file logger that will create a log in the given logdir (usually a
lago prefix)
Args:
logdir (str): path to create the log into, will be created if it does
not exist
Returns:
None
"""
if not os.path.exists(logdir):
... | def function[setup_prefix_logging, parameter[logdir]]:
constant[
Sets up a file logger that will create a log in the given logdir (usually a
lago prefix)
Args:
logdir (str): path to create the log into, will be created if it does
not exist
Returns:
None
]
... | keyword[def] identifier[setup_prefix_logging] ( identifier[logdir] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[logdir] ):
identifier[os] . identifier[mkdir] ( identifier[logdir] )
identifier[file_handler] = identifier[logg... | def setup_prefix_logging(logdir):
"""
Sets up a file logger that will create a log in the given logdir (usually a
lago prefix)
Args:
logdir (str): path to create the log into, will be created if it does
not exist
Returns:
None
"""
if not os.path.exists(logdir):
... |
def parse_datetime(value):
"""Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ValueError if the input is well formatted but not a valid datetime.
Returns None if t... | def function[parse_datetime, parameter[value]]:
constant[Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ValueError if the input is well formatted but not a valid ... | keyword[def] identifier[parse_datetime] ( identifier[value] ):
literal[string]
identifier[match] = identifier[datetime_re] . identifier[match] ( identifier[value] )
keyword[if] identifier[match] :
identifier[kw] = identifier[match] . identifier[groupdict] ()
keyword[if] identifier[... | def parse_datetime(value):
"""Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ValueError if the input is well formatted but not a valid datetime.
Returns None if t... |
def setup_opt_parser():
"""
Setup the optparser
@returns: opt_parser.OptionParser
"""
#pylint: disable-msg=C0301
#line too long
usage = "usage: %prog [options]"
opt_parser = optparse.OptionParser(usage=usage)
opt_parser.add_option("--version", action='store_true', dest=
... | def function[setup_opt_parser, parameter[]]:
constant[
Setup the optparser
@returns: opt_parser.OptionParser
]
variable[usage] assign[=] constant[usage: %prog [options]]
variable[opt_parser] assign[=] call[name[optparse].OptionParser, parameter[]]
call[name[opt_parser].add_... | keyword[def] identifier[setup_opt_parser] ():
literal[string]
identifier[usage] = literal[string]
identifier[opt_parser] = identifier[optparse] . identifier[OptionParser] ( identifier[usage] = identifier[usage] )
identifier[opt_parser] . identifier[add_option] ( literal[string] , ide... | def setup_opt_parser():
"""
Setup the optparser
@returns: opt_parser.OptionParser
"""
#pylint: disable-msg=C0301
#line too long
usage = 'usage: %prog [options]'
opt_parser = optparse.OptionParser(usage=usage)
opt_parser.add_option('--version', action='store_true', dest='yolk_versio... |
def plot_ppc(self, nsims=1000, T=np.mean, **kwargs):
""" Plots histogram of the discrepancy from draws of the posterior
Parameters
----------
nsims : int (default : 1000)
How many draws for the PPC
T : function
A discrepancy measure - e.g. np.mean, np.st... | def function[plot_ppc, parameter[self, nsims, T]]:
constant[ Plots histogram of the discrepancy from draws of the posterior
Parameters
----------
nsims : int (default : 1000)
How many draws for the PPC
T : function
A discrepancy measure - e.g. np.mean, n... | keyword[def] identifier[plot_ppc] ( identifier[self] , identifier[nsims] = literal[int] , identifier[T] = identifier[np] . identifier[mean] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[latent_variables] . identifier[estimation_method] keyword[not] keyword[i... | def plot_ppc(self, nsims=1000, T=np.mean, **kwargs):
""" Plots histogram of the discrepancy from draws of the posterior
Parameters
----------
nsims : int (default : 1000)
How many draws for the PPC
T : function
A discrepancy measure - e.g. np.mean, np.std, n... |
def diag(ax=None, linecolor='0.0', linestyle='--', **kwargs):
"""Plot the diagonal."""
ax = get_ax(ax)
xy_min = np.min((ax.get_xlim(), ax.get_ylim()))
xy_max = np.max((ax.get_ylim(), ax.get_xlim()))
return ax.plot([xy_min, xy_max], [xy_min, xy_max],
ls=linestyle,
... | def function[diag, parameter[ax, linecolor, linestyle]]:
constant[Plot the diagonal.]
variable[ax] assign[=] call[name[get_ax], parameter[name[ax]]]
variable[xy_min] assign[=] call[name[np].min, parameter[tuple[[<ast.Call object at 0x7da1b2351780>, <ast.Call object at 0x7da1b2351240>]]]]
... | keyword[def] identifier[diag] ( identifier[ax] = keyword[None] , identifier[linecolor] = literal[string] , identifier[linestyle] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[ax] = identifier[get_ax] ( identifier[ax] )
identifier[xy_min] = identifier[np] . identifier[min] (( i... | def diag(ax=None, linecolor='0.0', linestyle='--', **kwargs):
"""Plot the diagonal."""
ax = get_ax(ax)
xy_min = np.min((ax.get_xlim(), ax.get_ylim()))
xy_max = np.max((ax.get_ylim(), ax.get_xlim()))
return ax.plot([xy_min, xy_max], [xy_min, xy_max], ls=linestyle, c=linecolor, **kwargs) |
def find_keywords(string, parser, top=10, frequency={}, **kwargs):
""" Returns a sorted list of keywords in the given string.
The given parser (e.g., pattern.en.parser) is used to identify noun phrases.
The given frequency dictionary can be a reference corpus,
with relative document frequenc... | def function[find_keywords, parameter[string, parser, top, frequency]]:
constant[ Returns a sorted list of keywords in the given string.
The given parser (e.g., pattern.en.parser) is used to identify noun phrases.
The given frequency dictionary can be a reference corpus,
with relative do... | keyword[def] identifier[find_keywords] ( identifier[string] , identifier[parser] , identifier[top] = literal[int] , identifier[frequency] ={},** identifier[kwargs] ):
literal[string]
identifier[lemmata] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[kwargs] . identifier[pop] ( litera... | def find_keywords(string, parser, top=10, frequency={}, **kwargs):
""" Returns a sorted list of keywords in the given string.
The given parser (e.g., pattern.en.parser) is used to identify noun phrases.
The given frequency dictionary can be a reference corpus,
with relative document frequenc... |
def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter):
"""Calendar Importer for iCal (ics) files
"""
log('iCal importer running')
objectmodels = ctx.obj['db'].objectmodels
if objectmodels['user'].count({'name': owner}) > 0:
owner_object =... | def function[ICALImporter, parameter[ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter]]:
constant[Calendar Importer for iCal (ics) files
]
call[name[log], parameter[constant[iCal importer running]]]
variable[objectmodels] assign[=] call[name[ctx].obj][co... | keyword[def] identifier[ICALImporter] ( identifier[ctx] , identifier[filename] , identifier[all] , identifier[owner] , identifier[calendar] , identifier[create_calendar] , identifier[clear_calendar] , identifier[dry] , identifier[execfilter] ):
literal[string]
identifier[log] ( literal[string] )
ide... | def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter):
"""Calendar Importer for iCal (ics) files
"""
log('iCal importer running')
objectmodels = ctx.obj['db'].objectmodels
if objectmodels['user'].count({'name': owner}) > 0:
owner_object = ob... |
def get_instance():
"""Return an instance of Client."""
global _instances
user_agents = _config['user-agents']
user_agent = user_agents[
random.randint(0, len(user_agents) - 1)
] if len(user_agents) > 0 else DEFAULT_UA
instance_key = user_agent
try:
instance = _instances[i... | def function[get_instance, parameter[]]:
constant[Return an instance of Client.]
<ast.Global object at 0x7da1b14d9cf0>
variable[user_agents] assign[=] call[name[_config]][constant[user-agents]]
variable[user_agent] assign[=] <ast.IfExp object at 0x7da1b14d9ab0>
variable[instance_key]... | keyword[def] identifier[get_instance] ():
literal[string]
keyword[global] identifier[_instances]
identifier[user_agents] = identifier[_config] [ literal[string] ]
identifier[user_agent] = identifier[user_agents] [
identifier[random] . identifier[randint] ( literal[int] , identifier[len] (... | def get_instance():
"""Return an instance of Client."""
global _instances
user_agents = _config['user-agents']
user_agent = user_agents[random.randint(0, len(user_agents) - 1)] if len(user_agents) > 0 else DEFAULT_UA
instance_key = user_agent
try:
instance = _instances[instance_key] # d... |
def get_author_tags(index_page):
"""
Parse `authors` from HTML ``<meta>`` and dublin core.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects.
"""
dom = dhtmlparser.parseString(index_page)
authors = ... | def function[get_author_tags, parameter[index_page]]:
constant[
Parse `authors` from HTML ``<meta>`` and dublin core.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects.
]
variable[dom] assign[=] ... | keyword[def] identifier[get_author_tags] ( identifier[index_page] ):
literal[string]
identifier[dom] = identifier[dhtmlparser] . identifier[parseString] ( identifier[index_page] )
identifier[authors] =[
identifier[get_html_authors] ( identifier[dom] ),
identifier[get_dc_authors] ( identifie... | def get_author_tags(index_page):
"""
Parse `authors` from HTML ``<meta>`` and dublin core.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects.
"""
dom = dhtmlparser.parseString(index_page)
authors = [... |
def make_alembic_config(temporary_dir, migrations_dir):
"""
Alembic uses the `alembic.ini` file to configure where it looks for everything else.
Not only is this file an unnecessary complication around a single-valued configuration,
the single-value it chooses to use (the alembic configuration director... | def function[make_alembic_config, parameter[temporary_dir, migrations_dir]]:
constant[
Alembic uses the `alembic.ini` file to configure where it looks for everything else.
Not only is this file an unnecessary complication around a single-valued configuration,
the single-value it chooses to use (the... | keyword[def] identifier[make_alembic_config] ( identifier[temporary_dir] , identifier[migrations_dir] ):
literal[string]
identifier[config] = identifier[Config] ()
identifier[config] . identifier[set_main_option] ( literal[string] , identifier[temporary_dir] )
identifier[config] . identifier[set_... | def make_alembic_config(temporary_dir, migrations_dir):
"""
Alembic uses the `alembic.ini` file to configure where it looks for everything else.
Not only is this file an unnecessary complication around a single-valued configuration,
the single-value it chooses to use (the alembic configuration director... |
def get_notebook_app_versions():
"""
Get the valid version numbers of the notebook app.
"""
notebook_apps = dxpy.find_apps(name=NOTEBOOK_APP, all_versions=True)
versions = [str(dxpy.describe(app['id'])['version']) for app in notebook_apps]
return versions | def function[get_notebook_app_versions, parameter[]]:
constant[
Get the valid version numbers of the notebook app.
]
variable[notebook_apps] assign[=] call[name[dxpy].find_apps, parameter[]]
variable[versions] assign[=] <ast.ListComp object at 0x7da204960cd0>
return[name[versions]] | keyword[def] identifier[get_notebook_app_versions] ():
literal[string]
identifier[notebook_apps] = identifier[dxpy] . identifier[find_apps] ( identifier[name] = identifier[NOTEBOOK_APP] , identifier[all_versions] = keyword[True] )
identifier[versions] =[ identifier[str] ( identifier[dxpy] . identifier... | def get_notebook_app_versions():
"""
Get the valid version numbers of the notebook app.
"""
notebook_apps = dxpy.find_apps(name=NOTEBOOK_APP, all_versions=True)
versions = [str(dxpy.describe(app['id'])['version']) for app in notebook_apps]
return versions |
def model_funcpointers(vk, model):
"""Fill the model with function pointer
model['funcpointers'] = {'pfn_name': 'struct_name'}
"""
model['funcpointers'] = {}
funcs = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'funcpointer']
structs = [x for x in vk['regis... | def function[model_funcpointers, parameter[vk, model]]:
constant[Fill the model with function pointer
model['funcpointers'] = {'pfn_name': 'struct_name'}
]
call[name[model]][constant[funcpointers]] assign[=] dictionary[[], []]
variable[funcs] assign[=] <ast.ListComp object at 0x7da1b086... | keyword[def] identifier[model_funcpointers] ( identifier[vk] , identifier[model] ):
literal[string]
identifier[model] [ literal[string] ]={}
identifier[funcs] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[vk] [ literal[string] ][ literal[string] ][ literal[string] ]
keyw... | def model_funcpointers(vk, model):
"""Fill the model with function pointer
model['funcpointers'] = {'pfn_name': 'struct_name'}
"""
model['funcpointers'] = {}
funcs = [x for x in vk['registry']['types']['type'] if x.get('@category') == 'funcpointer']
structs = [x for x in vk['registry']['types']... |
def posthoc_durbin(a, y_col=None, block_col=None, group_col=None, melted=False, sort=False, p_adjust=None):
'''Pairwise post hoc test for multiple comparisons of rank sums according to
Durbin and Conover for a two-way balanced incomplete block design (BIBD). See
references for additional information [1]_, ... | def function[posthoc_durbin, parameter[a, y_col, block_col, group_col, melted, sort, p_adjust]]:
constant[Pairwise post hoc test for multiple comparisons of rank sums according to
Durbin and Conover for a two-way balanced incomplete block design (BIBD). See
references for additional information [1]_, [2... | keyword[def] identifier[posthoc_durbin] ( identifier[a] , identifier[y_col] = keyword[None] , identifier[block_col] = keyword[None] , identifier[group_col] = keyword[None] , identifier[melted] = keyword[False] , identifier[sort] = keyword[False] , identifier[p_adjust] = keyword[None] ):
literal[string]
k... | def posthoc_durbin(a, y_col=None, block_col=None, group_col=None, melted=False, sort=False, p_adjust=None):
"""Pairwise post hoc test for multiple comparisons of rank sums according to
Durbin and Conover for a two-way balanced incomplete block design (BIBD). See
references for additional information [1]_, [... |
def complexity_entropy_shannon(signal):
"""
Computes the shannon entropy. Copied from the `pyEntropy <https://github.com/nikdon/pyEntropy>`_ repo by tjugo.
Parameters
----------
signal : list or array
List or array of values.
Returns
----------
shannon_entropy : float
... | def function[complexity_entropy_shannon, parameter[signal]]:
constant[
Computes the shannon entropy. Copied from the `pyEntropy <https://github.com/nikdon/pyEntropy>`_ repo by tjugo.
Parameters
----------
signal : list or array
List or array of values.
Returns
----------
s... | keyword[def] identifier[complexity_entropy_shannon] ( identifier[signal] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[signal] , identifier[str] ):
identifier[signal] = identifier[list] ( identifier[signal] )
identifier[signal] = identifier[np] . iden... | def complexity_entropy_shannon(signal):
"""
Computes the shannon entropy. Copied from the `pyEntropy <https://github.com/nikdon/pyEntropy>`_ repo by tjugo.
Parameters
----------
signal : list or array
List or array of values.
Returns
----------
shannon_entropy : float
... |
def readACTIONRECORD(self):
""" Read a SWFActionRecord """
action = None
actionCode = self.readUI8()
if actionCode != 0:
actionLength = self.readUI16() if actionCode >= 0x80 else 0
#print "0x%x"%actionCode, actionLength
action = SWFActionFactory.create... | def function[readACTIONRECORD, parameter[self]]:
constant[ Read a SWFActionRecord ]
variable[action] assign[=] constant[None]
variable[actionCode] assign[=] call[name[self].readUI8, parameter[]]
if compare[name[actionCode] not_equal[!=] constant[0]] begin[:]
variable[acti... | keyword[def] identifier[readACTIONRECORD] ( identifier[self] ):
literal[string]
identifier[action] = keyword[None]
identifier[actionCode] = identifier[self] . identifier[readUI8] ()
keyword[if] identifier[actionCode] != literal[int] :
identifier[actionLength] = iden... | def readACTIONRECORD(self):
""" Read a SWFActionRecord """
action = None
actionCode = self.readUI8()
if actionCode != 0:
actionLength = self.readUI16() if actionCode >= 128 else 0
#print "0x%x"%actionCode, actionLength
action = SWFActionFactory.create(actionCode, actionLength)
... |
def _handle_table_style(self, end_token):
"""Handle style attributes for a table until ``end_token``."""
data = _TagOpenData()
data.context = _TagOpenData.CX_ATTR_READY
while True:
this = self._read()
can_exit = (not data.context & data.CX_QUOTED or
... | def function[_handle_table_style, parameter[self, end_token]]:
constant[Handle style attributes for a table until ``end_token``.]
variable[data] assign[=] call[name[_TagOpenData], parameter[]]
name[data].context assign[=] name[_TagOpenData].CX_ATTR_READY
while constant[True] begin[:]
... | keyword[def] identifier[_handle_table_style] ( identifier[self] , identifier[end_token] ):
literal[string]
identifier[data] = identifier[_TagOpenData] ()
identifier[data] . identifier[context] = identifier[_TagOpenData] . identifier[CX_ATTR_READY]
keyword[while] keyword[True] :
... | def _handle_table_style(self, end_token):
"""Handle style attributes for a table until ``end_token``."""
data = _TagOpenData()
data.context = _TagOpenData.CX_ATTR_READY
while True:
this = self._read()
can_exit = not data.context & data.CX_QUOTED or data.context & data.CX_NOTE_SPACE
... |
def add_options(cls, manager):
"""Register plug-in specific options."""
kw = {}
if flake8.__version__ >= '3.0.0':
kw['parse_from_config'] = True
manager.add_option(
"--known-modules",
action='store',
default="",
help=(
... | def function[add_options, parameter[cls, manager]]:
constant[Register plug-in specific options.]
variable[kw] assign[=] dictionary[[], []]
if compare[name[flake8].__version__ greater_or_equal[>=] constant[3.0.0]] begin[:]
call[name[kw]][constant[parse_from_config]] assign[=] cons... | keyword[def] identifier[add_options] ( identifier[cls] , identifier[manager] ):
literal[string]
identifier[kw] ={}
keyword[if] identifier[flake8] . identifier[__version__] >= literal[string] :
identifier[kw] [ literal[string] ]= keyword[True]
identifier[manager] . i... | def add_options(cls, manager):
"""Register plug-in specific options."""
kw = {}
if flake8.__version__ >= '3.0.0':
kw['parse_from_config'] = True # depends on [control=['if'], data=[]]
manager.add_option('--known-modules', action='store', default='', help='User defined mapping between a project ... |
def while_statement(self):
"""
while_statement: 'while' local_or_expr compound
"""
self._process(Nature.WHILE)
condition = self.logical_or_expr()
compound = self.compound()
return WhileStatement(condition=condition, compound=compound) | def function[while_statement, parameter[self]]:
constant[
while_statement: 'while' local_or_expr compound
]
call[name[self]._process, parameter[name[Nature].WHILE]]
variable[condition] assign[=] call[name[self].logical_or_expr, parameter[]]
variable[compound] assign[=] ca... | keyword[def] identifier[while_statement] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_process] ( identifier[Nature] . identifier[WHILE] )
identifier[condition] = identifier[self] . identifier[logical_or_expr] ()
identifier[compound] = identifier[self] . ide... | def while_statement(self):
"""
while_statement: 'while' local_or_expr compound
"""
self._process(Nature.WHILE)
condition = self.logical_or_expr()
compound = self.compound()
return WhileStatement(condition=condition, compound=compound) |
def _on_key_pressed(self, event):
"""
Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it).
"""
delete_request = event.key() in [QtCore.Qt.Key_Backspace,
QtCore.Qt.Key_Delete]
... | def function[_on_key_pressed, parameter[self, event]]:
constant[
Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it).
]
variable[delete_request] assign[=] compare[call[name[event].key, parameter[]] in list[[<ast.Attrib... | keyword[def] identifier[_on_key_pressed] ( identifier[self] , identifier[event] ):
literal[string]
identifier[delete_request] = identifier[event] . identifier[key] () keyword[in] [ identifier[QtCore] . identifier[Qt] . identifier[Key_Backspace] ,
identifier[QtCore] . identifier[Qt] . ident... | def _on_key_pressed(self, event):
"""
Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it).
"""
delete_request = event.key() in [QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete]
if event.text() or delete_request:
curs... |
def file_exists(original_file):
"""
Check to make sure the original file exists
"""
if original_file.startswith("s3://"):
from filesystem import s3
return s3.file_exists(original_file)
else:
if not os.path.exists(original_file):
return False
if not os.path... | def function[file_exists, parameter[original_file]]:
constant[
Check to make sure the original file exists
]
if call[name[original_file].startswith, parameter[constant[s3://]]] begin[:]
from relative_module[filesystem] import module[s3]
return[call[name[s3].file_exists, parameter... | keyword[def] identifier[file_exists] ( identifier[original_file] ):
literal[string]
keyword[if] identifier[original_file] . identifier[startswith] ( literal[string] ):
keyword[from] identifier[filesystem] keyword[import] identifier[s3]
keyword[return] identifier[s3] . identifier[fil... | def file_exists(original_file):
"""
Check to make sure the original file exists
"""
if original_file.startswith('s3://'):
from filesystem import s3
return s3.file_exists(original_file) # depends on [control=['if'], data=[]]
else:
if not os.path.exists(original_file):
... |
def CreateAllStaticRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
rapid_output_folder,
kfac_celerity=1000.0/3600.... | def function[CreateAllStaticRAPIDFiles, parameter[in_drainage_line, river_id, length_id, slope_id, next_down_id, rapid_output_folder, kfac_celerity, kfac_formula_type, kfac_length_units, lambda_k, x_value, nhdplus, taudem_network_connectivity_tree_file, file_geodatabase]]:
constant[
To generate the static R... | keyword[def] identifier[CreateAllStaticRAPIDFiles] ( identifier[in_drainage_line] ,
identifier[river_id] ,
identifier[length_id] ,
identifier[slope_id] ,
identifier[next_down_id] ,
identifier[rapid_output_folder] ,
identifier[kfac_celerity] = literal[int] / literal[int] ,
identifier[kfac_formula_type] = litera... | def CreateAllStaticRAPIDFiles(in_drainage_line, river_id, length_id, slope_id, next_down_id, rapid_output_folder, kfac_celerity=1000.0 / 3600.0, kfac_formula_type=3, kfac_length_units='km', lambda_k=0.35, x_value=0.3, nhdplus=False, taudem_network_connectivity_tree_file=None, file_geodatabase=None):
"""
To gene... |
def on_recv_rsp(self, rsp_pb):
"""receive response callback function"""
ret_code, msg, conn_info_map = InitConnect.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_init_connect(ret_code, msg, conn_info_map)
return ret_code, msg | def function[on_recv_rsp, parameter[self, rsp_pb]]:
constant[receive response callback function]
<ast.Tuple object at 0x7da1b26aead0> assign[=] call[name[InitConnect].unpack_rsp, parameter[name[rsp_pb]]]
if compare[name[self]._notify_obj is_not constant[None]] begin[:]
call[name[... | keyword[def] identifier[on_recv_rsp] ( identifier[self] , identifier[rsp_pb] ):
literal[string]
identifier[ret_code] , identifier[msg] , identifier[conn_info_map] = identifier[InitConnect] . identifier[unpack_rsp] ( identifier[rsp_pb] )
keyword[if] identifier[self] . identifier[_notify_o... | def on_recv_rsp(self, rsp_pb):
"""receive response callback function"""
(ret_code, msg, conn_info_map) = InitConnect.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_init_connect(ret_code, msg, conn_info_map) # depends on [control=['if'], data=[]]
return (ret_code, ... |
def _serialize_zebra_family_prefix(prefix):
"""
Serializes family and prefix in Zebra format.
"""
if ip.valid_ipv4(prefix):
family = socket.AF_INET # fixup
prefix_addr, prefix_num = prefix.split('/')
return family, struct.pack(
_ZEBRA_FAMILY_IPV4_PREFIX_FMT,
... | def function[_serialize_zebra_family_prefix, parameter[prefix]]:
constant[
Serializes family and prefix in Zebra format.
]
if call[name[ip].valid_ipv4, parameter[name[prefix]]] begin[:]
variable[family] assign[=] name[socket].AF_INET
<ast.Tuple object at 0x7da1b1b... | keyword[def] identifier[_serialize_zebra_family_prefix] ( identifier[prefix] ):
literal[string]
keyword[if] identifier[ip] . identifier[valid_ipv4] ( identifier[prefix] ):
identifier[family] = identifier[socket] . identifier[AF_INET]
identifier[prefix_addr] , identifier[prefix_num] = id... | def _serialize_zebra_family_prefix(prefix):
"""
Serializes family and prefix in Zebra format.
"""
if ip.valid_ipv4(prefix):
family = socket.AF_INET # fixup
(prefix_addr, prefix_num) = prefix.split('/')
return (family, struct.pack(_ZEBRA_FAMILY_IPV4_PREFIX_FMT, family, addrconv.i... |
def watch(self):
"""
Watches directory for changes
"""
wm = pyinotify.WatchManager()
self.notifier = pyinotify.Notifier(wm, default_proc_fun=self.callback)
wm.add_watch(self.directory, pyinotify.ALL_EVENTS)
try:
self.notifier.loop()
except ... | def function[watch, parameter[self]]:
constant[
Watches directory for changes
]
variable[wm] assign[=] call[name[pyinotify].WatchManager, parameter[]]
name[self].notifier assign[=] call[name[pyinotify].Notifier, parameter[name[wm]]]
call[name[wm].add_watch, parameter[... | keyword[def] identifier[watch] ( identifier[self] ):
literal[string]
identifier[wm] = identifier[pyinotify] . identifier[WatchManager] ()
identifier[self] . identifier[notifier] = identifier[pyinotify] . identifier[Notifier] ( identifier[wm] , identifier[default_proc_fun] = identifier[self... | def watch(self):
"""
Watches directory for changes
"""
wm = pyinotify.WatchManager()
self.notifier = pyinotify.Notifier(wm, default_proc_fun=self.callback)
wm.add_watch(self.directory, pyinotify.ALL_EVENTS)
try:
self.notifier.loop() # depends on [control=['try'], data=[]... |
def free(self, kind, name):
"""
Mark a node name as no longer in use.
It could thus be recycled to name a new node.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
self._free[kind].add(index)
assert index <= se... | def function[free, parameter[self, kind, name]]:
constant[
Mark a node name as no longer in use.
It could thus be recycled to name a new node.
]
<ast.Try object at 0x7da18c4ce3e0> | keyword[def] identifier[free] ( identifier[self] , identifier[kind] , identifier[name] ):
literal[string]
keyword[try] :
identifier[params] = identifier[self] . identifier[_parse] ( identifier[name] )
identifier[index] = identifier[int] ( identifier[params] [ literal[strin... | def free(self, kind, name):
"""
Mark a node name as no longer in use.
It could thus be recycled to name a new node.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
self._free[kind].add(index)
assert index <= self._top[kind]
if... |
def add_multiple(self, *users):
"""Add multiple users to the group at once.
Each given user must be a dictionary containing a nickname and either
an email, phone number, or user_id.
:param args users: the users to add
:return: a membership request
:rtype: :class:`Member... | def function[add_multiple, parameter[self]]:
constant[Add multiple users to the group at once.
Each given user must be a dictionary containing a nickname and either
an email, phone number, or user_id.
:param args users: the users to add
:return: a membership request
:rt... | keyword[def] identifier[add_multiple] ( identifier[self] ,* identifier[users] ):
literal[string]
identifier[guid] = identifier[uuid] . identifier[uuid4] ()
keyword[for] identifier[i] , identifier[user_] keyword[in] identifier[enumerate] ( identifier[users] ):
identifier[use... | def add_multiple(self, *users):
"""Add multiple users to the group at once.
Each given user must be a dictionary containing a nickname and either
an email, phone number, or user_id.
:param args users: the users to add
:return: a membership request
:rtype: :class:`Membership... |
def impact_table_extractor(impact_report, component_metadata):
"""Extracting impact summary of the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component... | def function[impact_table_extractor, parameter[impact_report, component_metadata]]:
constant[Extracting impact summary of the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.Imp... | keyword[def] identifier[impact_table_extractor] ( identifier[impact_report] , identifier[component_metadata] ):
literal[string]
identifier[context] ={}
identifier[extra_args] = identifier[component_metadata] . identifier[extra_args]
identifier[components_list] = identifier[resolve_from_dictiona... | def impact_table_extractor(impact_report, component_metadata):
"""Extracting impact summary of the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component... |
def sort(self, field, direction="asc"):
"""
Adds sort criteria.
"""
if not isinstance(field, basestring):
raise ValueError("Field should be a string")
if direction not in ["asc", "desc"]:
raise ValueError("Sort direction should be `asc` or `desc`")
... | def function[sort, parameter[self, field, direction]]:
constant[
Adds sort criteria.
]
if <ast.UnaryOp object at 0x7da204622aa0> begin[:]
<ast.Raise object at 0x7da204623a90>
if compare[name[direction] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object at 0x7... | keyword[def] identifier[sort] ( identifier[self] , identifier[field] , identifier[direction] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[field] , identifier[basestring] ):
keyword[raise] identifier[ValueError] ( literal[string] )... | def sort(self, field, direction='asc'):
"""
Adds sort criteria.
"""
if not isinstance(field, basestring):
raise ValueError('Field should be a string') # depends on [control=['if'], data=[]]
if direction not in ['asc', 'desc']:
raise ValueError('Sort direction should be `asc`... |
def ias60(msg):
"""Indicated airspeed
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: indicated airspeed in knots
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ias = bin2int(d[13:23]) # kts
return ias | def function[ias60, parameter[msg]]:
constant[Indicated airspeed
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: indicated airspeed in knots
]
variable[d] assign[=] call[name[hex2bin], parameter[call[name[data], parameter[name[msg]]]]]
... | keyword[def] identifier[ias60] ( identifier[msg] ):
literal[string]
identifier[d] = identifier[hex2bin] ( identifier[data] ( identifier[msg] ))
keyword[if] identifier[d] [ literal[int] ]== literal[string] :
keyword[return] keyword[None]
identifier[ias] = identifier[bin2int] ( identi... | def ias60(msg):
"""Indicated airspeed
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: indicated airspeed in knots
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None # depends on [control=['if'], data=[]]
ias = bin2int(d[13:23]) #... |
def _parse_email(self, val):
"""
The function for parsing the vcard email addresses.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
... | def function[_parse_email, parameter[self, val]]:
constant[
The function for parsing the vcard email addresses.
Args:
val (:obj:`list`): The value to parse.
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da20c990880>, <ast.Constant object at 0x7da20... | keyword[def] identifier[_parse_email] ( identifier[self] , identifier[val] ):
literal[string]
identifier[ret] ={
literal[string] : keyword[None] ,
literal[string] : keyword[None]
}
keyword[try] :
identifier[ret] [ literal[string] ]= identifier[val... | def _parse_email(self, val):
"""
The function for parsing the vcard email addresses.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {'type': None, 'value': None}
try:
ret['type'] = val[1]['type'] # depends on [control=['try'], data=[]]
except (KeyErr... |
def draw_graph( g, fmt='svg', prg='dot', options={} ):
"""
Draw an RDF graph as an image
"""
# Convert RDF to Graphviz
buf = StringIO()
rdf2dot( g, buf, options )
gv_options = options.get('graphviz',[])
if fmt == 'png':
gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
meta... | def function[draw_graph, parameter[g, fmt, prg, options]]:
constant[
Draw an RDF graph as an image
]
variable[buf] assign[=] call[name[StringIO], parameter[]]
call[name[rdf2dot], parameter[name[g], name[buf], name[options]]]
variable[gv_options] assign[=] call[name[options].get, ... | keyword[def] identifier[draw_graph] ( identifier[g] , identifier[fmt] = literal[string] , identifier[prg] = literal[string] , identifier[options] ={}):
literal[string]
identifier[buf] = identifier[StringIO] ()
identifier[rdf2dot] ( identifier[g] , identifier[buf] , identifier[options] )
ide... | def draw_graph(g, fmt='svg', prg='dot', options={}):
"""
Draw an RDF graph as an image
"""
# Convert RDF to Graphviz
buf = StringIO()
rdf2dot(g, buf, options)
gv_options = options.get('graphviz', [])
if fmt == 'png':
gv_options += ['-Gdpi=220', '-Gsize=25,10!']
metadata =... |
def get_access_logs(config):
"""
Parse config for access_log directives
:return: iterator over ('path', 'format name') tuple of found directives
"""
access_log = Literal("access_log") + ZeroOrMore(parameter) + semicolon
access_log.ignore(pythonStyleComment)
for directive in access_log.searc... | def function[get_access_logs, parameter[config]]:
constant[
Parse config for access_log directives
:return: iterator over ('path', 'format name') tuple of found directives
]
variable[access_log] assign[=] binary_operation[binary_operation[call[name[Literal], parameter[constant[access_log]]] ... | keyword[def] identifier[get_access_logs] ( identifier[config] ):
literal[string]
identifier[access_log] = identifier[Literal] ( literal[string] )+ identifier[ZeroOrMore] ( identifier[parameter] )+ identifier[semicolon]
identifier[access_log] . identifier[ignore] ( identifier[pythonStyleComment] )
... | def get_access_logs(config):
"""
Parse config for access_log directives
:return: iterator over ('path', 'format name') tuple of found directives
"""
access_log = Literal('access_log') + ZeroOrMore(parameter) + semicolon
access_log.ignore(pythonStyleComment)
for directive in access_log.search... |
def addworkdays(self, date, offset):
"""
Add work days to a given date, ignoring holidays.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a work date. An offset of 1
represents the next work date, rega... | def function[addworkdays, parameter[self, date, offset]]:
constant[
Add work days to a given date, ignoring holidays.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a work date. An offset of 1
represents the ... | keyword[def] identifier[addworkdays] ( identifier[self] , identifier[date] , identifier[offset] ):
literal[string]
identifier[date] = identifier[parsefun] ( identifier[date] )
keyword[if] identifier[offset] == literal[int] :
keyword[return] identifier[date]
... | def addworkdays(self, date, offset):
"""
Add work days to a given date, ignoring holidays.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a work date. An offset of 1
represents the next work date, regardless of d... |
def dumpDictHdf5(RV,o):
""" Dump a dictionary where each page is a list or an array """
for key in list(RV.keys()):
o.create_dataset(name=key,data=SP.array(RV[key]),chunks=True,compression='gzip') | def function[dumpDictHdf5, parameter[RV, o]]:
constant[ Dump a dictionary where each page is a list or an array ]
for taget[name[key]] in starred[call[name[list], parameter[call[name[RV].keys, parameter[]]]]] begin[:]
call[name[o].create_dataset, parameter[]] | keyword[def] identifier[dumpDictHdf5] ( identifier[RV] , identifier[o] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[RV] . identifier[keys] ()):
identifier[o] . identifier[create_dataset] ( identifier[name] = identifier[key] , identifier[data] = ident... | def dumpDictHdf5(RV, o):
""" Dump a dictionary where each page is a list or an array """
for key in list(RV.keys()):
o.create_dataset(name=key, data=SP.array(RV[key]), chunks=True, compression='gzip') # depends on [control=['for'], data=['key']] |
def get_headers(self, instant):
"""
Build the list of headers needed in order to perform S3 operations.
"""
headers = {'x-amz-date': _auth_v4.makeAMZDate(instant)}
if self.body_producer is None:
data = self.data
if data is None:
data = b""
... | def function[get_headers, parameter[self, instant]]:
constant[
Build the list of headers needed in order to perform S3 operations.
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da18bc712d0>], [<ast.Call object at 0x7da18bc72b00>]]
if compare[name[self].body... | keyword[def] identifier[get_headers] ( identifier[self] , identifier[instant] ):
literal[string]
identifier[headers] ={ literal[string] : identifier[_auth_v4] . identifier[makeAMZDate] ( identifier[instant] )}
keyword[if] identifier[self] . identifier[body_producer] keyword[is] keyword[... | def get_headers(self, instant):
"""
Build the list of headers needed in order to perform S3 operations.
"""
headers = {'x-amz-date': _auth_v4.makeAMZDate(instant)}
if self.body_producer is None:
data = self.data
if data is None:
data = b'' # depends on [control=[... |
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
authstr = 'Basic ' + to_native_string(
b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
)
return authstr | def function[_basic_auth_str, parameter[username, password]]:
constant[Returns a Basic Auth string.]
variable[authstr] assign[=] binary_operation[constant[Basic ] + call[name[to_native_string], parameter[call[call[name[b64encode], parameter[call[binary_operation[constant[%s:%s] <ast.Mod object at 0x7da2... | keyword[def] identifier[_basic_auth_str] ( identifier[username] , identifier[password] ):
literal[string]
identifier[authstr] = literal[string] + identifier[to_native_string] (
identifier[b64encode] (( literal[string] %( identifier[username] , identifier[password] )). identifier[encode] ( literal[str... | def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
authstr = 'Basic ' + to_native_string(b64encode(('%s:%s' % (username, password)).encode('latin1')).strip())
return authstr |
def update(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Add a user to a team.'''
user = get_object_or_404(User, pk=pk)
team = self.check_team_permissions(
request, parent_lookup_seedteam,
pare... | def function[update, parameter[self, request, pk, parent_lookup_seedteam, parent_lookup_seedteam__organization]]:
constant[Add a user to a team.]
variable[user] assign[=] call[name[get_object_or_404], parameter[name[User]]]
variable[team] assign[=] call[name[self].check_team_permissions, paramet... | keyword[def] identifier[update] (
identifier[self] , identifier[request] , identifier[pk] = keyword[None] , identifier[parent_lookup_seedteam] = keyword[None] ,
identifier[parent_lookup_seedteam__organization] = keyword[None] ):
literal[string]
identifier[user] = identifier[get_object_or_404] ( i... | def update(self, request, pk=None, parent_lookup_seedteam=None, parent_lookup_seedteam__organization=None):
"""Add a user to a team."""
user = get_object_or_404(User, pk=pk)
team = self.check_team_permissions(request, parent_lookup_seedteam, parent_lookup_seedteam__organization)
team.users.add(user)
... |
def restore_geometry_on_layout_change(self, value):
"""
Setter for **self.__restore_geometry_on_layout_change** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is ... | def function[restore_geometry_on_layout_change, parameter[self, value]]:
constant[
Setter for **self.__restore_geometry_on_layout_change** attribute.
:param value: Attribute value.
:type value: bool
]
if compare[name[value] is_not constant[None]] begin[:]
assert[... | keyword[def] identifier[restore_geometry_on_layout_change] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[bool] , liter... | def restore_geometry_on_layout_change(self, value):
"""
Setter for **self.__restore_geometry_on_layout_change** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".... |
def fit(self, Z, classes=None):
"""Fit the model according to the given training data.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
classes : iterable
The set of available classes
Ret... | def function[fit, parameter[self, Z, classes]]:
constant[Fit the model according to the given training data.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
classes : iterable
The set of availabl... | keyword[def] identifier[fit] ( identifier[self] , identifier[Z] , identifier[classes] = keyword[None] ):
literal[string]
identifier[check_rdd] ( identifier[Z] ,{ literal[string] :( identifier[sp] . identifier[spmatrix] , identifier[np] . identifier[ndarray] )})
identifier[self] . identifie... | def fit(self, Z, classes=None):
"""Fit the model according to the given training data.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
classes : iterable
The set of available classes
Returns... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.