code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def currentProfile(self):
"""
Returns the currently selected profile from the system.
:return <XViewProfile>
"""
index = self._profileCombo.currentIndex()
if 0 <= index and index < len(self._profiles):
return self._profiles[index]
... | def function[currentProfile, parameter[self]]:
constant[
Returns the currently selected profile from the system.
:return <XViewProfile>
]
variable[index] assign[=] call[name[self]._profileCombo.currentIndex, parameter[]]
if <ast.BoolOp object at 0x7da1b24693c... | keyword[def] identifier[currentProfile] ( identifier[self] ):
literal[string]
identifier[index] = identifier[self] . identifier[_profileCombo] . identifier[currentIndex] ()
keyword[if] literal[int] <= identifier[index] keyword[and] identifier[index] < identifier[len] ( identifier[self]... | def currentProfile(self):
"""
Returns the currently selected profile from the system.
:return <XViewProfile>
"""
index = self._profileCombo.currentIndex()
if 0 <= index and index < len(self._profiles):
return self._profiles[index] # depends on [control=['if'], d... |
def verify_secret(self, form_instance, secret):
"""Verifies an IPN payment over SSL using EWP."""
warn_untested()
if not check_secret(form_instance, secret):
self.set_flag("Invalid secret. (%s)") % secret
self.save() | def function[verify_secret, parameter[self, form_instance, secret]]:
constant[Verifies an IPN payment over SSL using EWP.]
call[name[warn_untested], parameter[]]
if <ast.UnaryOp object at 0x7da2047ea890> begin[:]
binary_operation[call[name[self].set_flag, parameter[constant[Inval... | keyword[def] identifier[verify_secret] ( identifier[self] , identifier[form_instance] , identifier[secret] ):
literal[string]
identifier[warn_untested] ()
keyword[if] keyword[not] identifier[check_secret] ( identifier[form_instance] , identifier[secret] ):
identifier[self] .... | def verify_secret(self, form_instance, secret):
"""Verifies an IPN payment over SSL using EWP."""
warn_untested()
if not check_secret(form_instance, secret):
self.set_flag('Invalid secret. (%s)') % secret # depends on [control=['if'], data=[]]
self.save() |
def expression(value):
"""Create an SPL expression.
Args:
value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value.
Returns:
Expression: SPL expression from `value`.... | def function[expression, parameter[value]]:
constant[Create an SPL expression.
Args:
value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value.
Returns:
Expression: S... | keyword[def] identifier[expression] ( identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[Expression] ):
keyword[return] identifier[Expression] ( identifier[value] . identifier[_type] , identifier[value] . identif... | def expression(value):
"""Create an SPL expression.
Args:
value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value.
Returns:
Expression: SPL expression from `value`.
... |
def subdomain_row_factory(cls, cursor, row):
"""
Dict row factory for subdomains
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | def function[subdomain_row_factory, parameter[cls, cursor, row]]:
constant[
Dict row factory for subdomains
]
variable[d] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b180f010>, <ast.Name object at 0x7da1b180d0c0>]]] in starred[call[name[enumerate], par... | keyword[def] identifier[subdomain_row_factory] ( identifier[cls] , identifier[cursor] , identifier[row] ):
literal[string]
identifier[d] ={}
keyword[for] identifier[idx] , identifier[col] keyword[in] identifier[enumerate] ( identifier[cursor] . identifier[description] ):
id... | def subdomain_row_factory(cls, cursor, row):
"""
Dict row factory for subdomains
"""
d = {}
for (idx, col) in enumerate(cursor.description):
d[col[0]] = row[idx] # depends on [control=['for'], data=[]]
return d |
def from_file(cls, name: str, mod_path: Tuple[str] = (".",),
description: str = None) -> "DataModel":
"""Initialize the data model from a file with YANG library data.
Args:
name: Name of a file with YANG library data.
mod_path: Tuple of directories where to loo... | def function[from_file, parameter[cls, name, mod_path, description]]:
constant[Initialize the data model from a file with YANG library data.
Args:
name: Name of a file with YANG library data.
mod_path: Tuple of directories where to look for YANG modules.
description:... | keyword[def] identifier[from_file] ( identifier[cls] , identifier[name] : identifier[str] , identifier[mod_path] : identifier[Tuple] [ identifier[str] ]=( literal[string] ,),
identifier[description] : identifier[str] = keyword[None] )-> literal[string] :
literal[string]
keyword[with] identifier[o... | def from_file(cls, name: str, mod_path: Tuple[str]=('.',), description: str=None) -> 'DataModel':
"""Initialize the data model from a file with YANG library data.
Args:
name: Name of a file with YANG library data.
mod_path: Tuple of directories where to look for YANG modules.
... |
def run(self, batch=True, interruptible=None, inplace=True):
"""
Run task
:param batch if False batching will be disabled.
:param interruptible: If true interruptible instance
will be used.
:param inplace Apply action on the current object or return a new one.
:re... | def function[run, parameter[self, batch, interruptible, inplace]]:
constant[
Run task
:param batch if False batching will be disabled.
:param interruptible: If true interruptible instance
will be used.
:param inplace Apply action on the current object or return a new one.... | keyword[def] identifier[run] ( identifier[self] , identifier[batch] = keyword[True] , identifier[interruptible] = keyword[None] , identifier[inplace] = keyword[True] ):
literal[string]
identifier[params] ={}
keyword[if] keyword[not] identifier[batch] :
identifier[params] [ l... | def run(self, batch=True, interruptible=None, inplace=True):
"""
Run task
:param batch if False batching will be disabled.
:param interruptible: If true interruptible instance
will be used.
:param inplace Apply action on the current object or return a new one.
:return... |
def _ReadLine(self, text_file_object, max_len=None, depth=0):
"""Reads a line from a text file.
Args:
text_file_object (dfvfs.TextFile): text file.
max_len (Optional[int]): maximum number of bytes a single line can take,
where None means all remaining bytes should be read.
depth (Op... | def function[_ReadLine, parameter[self, text_file_object, max_len, depth]]:
constant[Reads a line from a text file.
Args:
text_file_object (dfvfs.TextFile): text file.
max_len (Optional[int]): maximum number of bytes a single line can take,
where None means all remaining bytes should ... | keyword[def] identifier[_ReadLine] ( identifier[self] , identifier[text_file_object] , identifier[max_len] = keyword[None] , identifier[depth] = literal[int] ):
literal[string]
identifier[line] = identifier[text_file_object] . identifier[readline] ( identifier[size] = identifier[max_len] )
keyword[if... | def _ReadLine(self, text_file_object, max_len=None, depth=0):
"""Reads a line from a text file.
Args:
text_file_object (dfvfs.TextFile): text file.
max_len (Optional[int]): maximum number of bytes a single line can take,
where None means all remaining bytes should be read.
depth (Op... |
def addChildJobFn(self, fn, *args, **kwargs):
"""
Adds a job function as a child job. See :class:`toil.job.JobFunctionWrappingJob`
for a definition of a job function.
:param fn: Job function to be run as a child job with ``*args`` and ``**kwargs`` as \
arguments to this function... | def function[addChildJobFn, parameter[self, fn]]:
constant[
Adds a job function as a child job. See :class:`toil.job.JobFunctionWrappingJob`
for a definition of a job function.
:param fn: Job function to be run as a child job with ``*args`` and ``**kwargs`` as arguments to this ... | keyword[def] identifier[addChildJobFn] ( identifier[self] , identifier[fn] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[PromisedRequirement] . identifier[convertPromises] ( identifier[kwargs] ):
keyword[return] identifier[self] . identifier[add... | def addChildJobFn(self, fn, *args, **kwargs):
"""
Adds a job function as a child job. See :class:`toil.job.JobFunctionWrappingJob`
for a definition of a job function.
:param fn: Job function to be run as a child job with ``*args`` and ``**kwargs`` as arguments to this function. See ... |
def load(cls, path):
"""
Load a recursive SOM from a JSON file.
You can use this function to load weights of other SOMs.
If there are no context weights, they will be set to 0.
Parameters
----------
path : str
The path to the JSON file.
Retu... | def function[load, parameter[cls, path]]:
constant[
Load a recursive SOM from a JSON file.
You can use this function to load weights of other SOMs.
If there are no context weights, they will be set to 0.
Parameters
----------
path : str
The path to t... | keyword[def] identifier[load] ( identifier[cls] , identifier[path] ):
literal[string]
identifier[data] = identifier[json] . identifier[load] ( identifier[open] ( identifier[path] ))
identifier[weights] = identifier[data] [ literal[string] ]
identifier[weights] = identifier[np] . ... | def load(cls, path):
"""
Load a recursive SOM from a JSON file.
You can use this function to load weights of other SOMs.
If there are no context weights, they will be set to 0.
Parameters
----------
path : str
The path to the JSON file.
Returns
... |
def get_context_data(self,**kwargs):
''' Add the list of names for the given guest list '''
event = Event.objects.filter(id=self.kwargs.get('event_id')).first()
if self.kwargs.get('event_id') and not self.object.appliesToEvent(event):
raise Http404(_('Invalid event.'))
... | def function[get_context_data, parameter[self]]:
constant[ Add the list of names for the given guest list ]
variable[event] assign[=] call[call[name[Event].objects.filter, parameter[]].first, parameter[]]
if <ast.BoolOp object at 0x7da18dc9a890> begin[:]
<ast.Raise object at 0x7da1b13909... | keyword[def] identifier[get_context_data] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[event] = identifier[Event] . identifier[objects] . identifier[filter] ( identifier[id] = identifier[self] . identifier[kwargs] . identifier[get] ( literal[string] )). identifier[first... | def get_context_data(self, **kwargs):
""" Add the list of names for the given guest list """
event = Event.objects.filter(id=self.kwargs.get('event_id')).first()
if self.kwargs.get('event_id') and (not self.object.appliesToEvent(event)):
raise Http404(_('Invalid event.')) # depends on [control=['if... |
def tyn_calus(target, VA, VB, sigma_A, sigma_B, temperature='pore.temperature',
viscosity='pore.viscosity'):
r"""
Uses Tyn_Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
----------
targ... | def function[tyn_calus, parameter[target, VA, VB, sigma_A, sigma_B, temperature, viscosity]]:
constant[
Uses Tyn_Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
----------
target : OpenPNM Object
... | keyword[def] identifier[tyn_calus] ( identifier[target] , identifier[VA] , identifier[VB] , identifier[sigma_A] , identifier[sigma_B] , identifier[temperature] = literal[string] ,
identifier[viscosity] = literal[string] ):
literal[string]
identifier[T] = identifier[target] [ identifier[temperature] ]
... | def tyn_calus(target, VA, VB, sigma_A, sigma_B, temperature='pore.temperature', viscosity='pore.viscosity'):
"""
Uses Tyn_Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
----------
target : OpenPNM Ob... |
def create_subscription(
self,
name,
topic,
push_config=None,
ack_deadline_seconds=None,
retain_acked_messages=None,
message_retention_duration=None,
labels=None,
enable_message_ordering=None,
expiration_policy=None,
retry=google.ap... | def function[create_subscription, parameter[self, name, topic, push_config, ack_deadline_seconds, retain_acked_messages, message_retention_duration, labels, enable_message_ordering, expiration_policy, retry, timeout, metadata]]:
constant[
Creates a subscription to a given topic. See the resource name ru... | keyword[def] identifier[create_subscription] (
identifier[self] ,
identifier[name] ,
identifier[topic] ,
identifier[push_config] = keyword[None] ,
identifier[ack_deadline_seconds] = keyword[None] ,
identifier[retain_acked_messages] = keyword[None] ,
identifier[message_retention_duration] = keyword[None] ,
ide... | def create_subscription(self, name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None, enable_message_ordering=None, expiration_policy=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata... |
def add_indent_lines(prefix, s):
"""
:param str prefix:
:param str s:
:return: s with prefix indent added to all lines
:rtype: str
"""
if not s:
return prefix
prefix_len = str_visible_len(prefix)
lines = s.splitlines(True)
return "".join([prefix + lines[0]] + [" " * prefi... | def function[add_indent_lines, parameter[prefix, s]]:
constant[
:param str prefix:
:param str s:
:return: s with prefix indent added to all lines
:rtype: str
]
if <ast.UnaryOp object at 0x7da1b23d1c60> begin[:]
return[name[prefix]]
variable[prefix_len] assign[=] call[... | keyword[def] identifier[add_indent_lines] ( identifier[prefix] , identifier[s] ):
literal[string]
keyword[if] keyword[not] identifier[s] :
keyword[return] identifier[prefix]
identifier[prefix_len] = identifier[str_visible_len] ( identifier[prefix] )
identifier[lines] = identifier[s] ... | def add_indent_lines(prefix, s):
"""
:param str prefix:
:param str s:
:return: s with prefix indent added to all lines
:rtype: str
"""
if not s:
return prefix # depends on [control=['if'], data=[]]
prefix_len = str_visible_len(prefix)
lines = s.splitlines(True)
return ''... |
def action_fluent_variables(self) -> FluentParamsList:
'''Returns the instantiated action fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
'''
fluents ... | def function[action_fluent_variables, parameter[self]]:
constant[Returns the instantiated action fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
]
var... | keyword[def] identifier[action_fluent_variables] ( identifier[self] )-> identifier[FluentParamsList] :
literal[string]
identifier[fluents] = identifier[self] . identifier[domain] . identifier[action_fluents]
identifier[ordering] = identifier[self] . identifier[domain] . identifier[action_... | def action_fluent_variables(self) -> FluentParamsList:
"""Returns the instantiated action fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
"""
fluents = self.d... |
def is_deterministic(self):
"""Tests whether machine is deterministic."""
# naive quadratic algorithm
patterns = [t.lhs for t in self.transitions] + list(self.accept_configs)
for i, t1 in enumerate(patterns):
for t2 in patterns[:i]:
match = True
... | def function[is_deterministic, parameter[self]]:
constant[Tests whether machine is deterministic.]
variable[patterns] assign[=] binary_operation[<ast.ListComp object at 0x7da18f812b00> + call[name[list], parameter[name[self].accept_configs]]]
for taget[tuple[[<ast.Name object at 0x7da18f812fe0>,... | keyword[def] identifier[is_deterministic] ( identifier[self] ):
literal[string]
identifier[patterns] =[ identifier[t] . identifier[lhs] keyword[for] identifier[t] keyword[in] identifier[self] . identifier[transitions] ]+ identifier[list] ( identifier[self] . identifier[accept_configs] ... | def is_deterministic(self):
"""Tests whether machine is deterministic."""
# naive quadratic algorithm
patterns = [t.lhs for t in self.transitions] + list(self.accept_configs)
for (i, t1) in enumerate(patterns):
for t2 in patterns[:i]:
match = True
for (in1, in2) in zip(t1... |
def start_waiting(self):
"""
Show waiting progress bar until done_waiting is called.
Only has an effect if we are in waiting state.
"""
if not self.waiting:
self.waiting = True
wait_msg = "Waiting for project to become ready for {}".format(self.msg_verb)
... | def function[start_waiting, parameter[self]]:
constant[
Show waiting progress bar until done_waiting is called.
Only has an effect if we are in waiting state.
]
if <ast.UnaryOp object at 0x7da1b1a5cbb0> begin[:]
name[self].waiting assign[=] constant[True]
... | keyword[def] identifier[start_waiting] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[waiting] :
identifier[self] . identifier[waiting] = keyword[True]
identifier[wait_msg] = literal[string] . identifier[format] ( identifier... | def start_waiting(self):
"""
Show waiting progress bar until done_waiting is called.
Only has an effect if we are in waiting state.
"""
if not self.waiting:
self.waiting = True
wait_msg = 'Waiting for project to become ready for {}'.format(self.msg_verb)
self.prog... |
def get_user(self, user_id):
"""Get a user by its ID.
Args:
user_id (~hangups.user.UserID): The ID of the user.
Raises:
KeyError: If no such user is known.
Returns:
:class:`~hangups.user.User` with the given ID.
"""
try:
... | def function[get_user, parameter[self, user_id]]:
constant[Get a user by its ID.
Args:
user_id (~hangups.user.UserID): The ID of the user.
Raises:
KeyError: If no such user is known.
Returns:
:class:`~hangups.user.User` with the given ID.
]
... | keyword[def] identifier[get_user] ( identifier[self] , identifier[user_id] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_user_dict] [ identifier[user_id] ]
keyword[except] identifier[KeyError] :
identifier[logger] . identifier[... | def get_user(self, user_id):
"""Get a user by its ID.
Args:
user_id (~hangups.user.UserID): The ID of the user.
Raises:
KeyError: If no such user is known.
Returns:
:class:`~hangups.user.User` with the given ID.
"""
try:
return self.... |
def get_file_hash(fpath, blocksize=65536, hasher=None, stride=1,
hexdigest=False):
r"""
For better hashes use hasher=hashlib.sha256, and keep stride=1
Args:
fpath (str): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
hasher (None): defau... | def function[get_file_hash, parameter[fpath, blocksize, hasher, stride, hexdigest]]:
constant[
For better hashes use hasher=hashlib.sha256, and keep stride=1
Args:
fpath (str): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
hasher (None): defaults to ... | keyword[def] identifier[get_file_hash] ( identifier[fpath] , identifier[blocksize] = literal[int] , identifier[hasher] = keyword[None] , identifier[stride] = literal[int] ,
identifier[hexdigest] = keyword[False] ):
literal[string]
keyword[if] identifier[hasher] keyword[is] keyword[None] :
iden... | def get_file_hash(fpath, blocksize=65536, hasher=None, stride=1, hexdigest=False):
"""
For better hashes use hasher=hashlib.sha256, and keep stride=1
Args:
fpath (str): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
hasher (None): defaults to sha1 for fas... |
def get_state(self):
"""
Return the sampler and step methods current state in order to
restart sampling at a later time.
"""
self.step_methods = set()
for s in self.stochastics:
self.step_methods |= set(self.step_method_dict[s])
state = Sampler.get_s... | def function[get_state, parameter[self]]:
constant[
Return the sampler and step methods current state in order to
restart sampling at a later time.
]
name[self].step_methods assign[=] call[name[set], parameter[]]
for taget[name[s]] in starred[name[self].stochastics] begin... | keyword[def] identifier[get_state] ( identifier[self] ):
literal[string]
identifier[self] . identifier[step_methods] = identifier[set] ()
keyword[for] identifier[s] keyword[in] identifier[self] . identifier[stochastics] :
identifier[self] . identifier[step_methods] |= iden... | def get_state(self):
"""
Return the sampler and step methods current state in order to
restart sampling at a later time.
"""
self.step_methods = set()
for s in self.stochastics:
self.step_methods |= set(self.step_method_dict[s]) # depends on [control=['for'], data=['s']]
... |
def _validate_date_like_dtype(dtype):
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The d... | def function[_validate_date_like_dtype, parameter[dtype]]:
constant[
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-lik... | keyword[def] identifier[_validate_date_like_dtype] ( identifier[dtype] ):
literal[string]
keyword[try] :
identifier[typ] = identifier[np] . identifier[datetime_data] ( identifier[dtype] )[ literal[int] ]
keyword[except] identifier[ValueError] keyword[as] identifier[e] :
keyword[r... | def _validate_date_like_dtype(dtype):
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The d... |
def text(self, etype, value, tb, tb_offset=None, context=5):
"""Return formatted traceback.
Subclasses may override this if they add extra arguments.
"""
tb_list = self.structured_traceback(etype, value, tb,
tb_offset, context)
return ... | def function[text, parameter[self, etype, value, tb, tb_offset, context]]:
constant[Return formatted traceback.
Subclasses may override this if they add extra arguments.
]
variable[tb_list] assign[=] call[name[self].structured_traceback, parameter[name[etype], name[value], name[tb], nam... | keyword[def] identifier[text] ( identifier[self] , identifier[etype] , identifier[value] , identifier[tb] , identifier[tb_offset] = keyword[None] , identifier[context] = literal[int] ):
literal[string]
identifier[tb_list] = identifier[self] . identifier[structured_traceback] ( identifier[etype] , i... | def text(self, etype, value, tb, tb_offset=None, context=5):
"""Return formatted traceback.
Subclasses may override this if they add extra arguments.
"""
tb_list = self.structured_traceback(etype, value, tb, tb_offset, context)
return self.stb2text(tb_list) |
def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version ... | def function[_validate_timeout, parameter[cls, value, name]]:
constant[ Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The va... | keyword[def] identifier[_validate_timeout] ( identifier[cls] , identifier[value] , identifier[name] ):
literal[string]
keyword[if] identifier[value] keyword[is] identifier[_Default] :
keyword[return] identifier[cls] . identifier[DEFAULT_TIMEOUT]
keyword[if] identifier[v... | def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of t... |
def is_child_of_vault(self, id_, vault_id):
"""Tests if a vault is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if the ``id`` is a child of
``vault_id,`` ``false`` otherwi... | def function[is_child_of_vault, parameter[self, id_, vault_id]]:
constant[Tests if a vault is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if the ``id`` is a child of
``vau... | keyword[def] identifier[is_child_of_vault] ( identifier[self] , identifier[id_] , identifier[vault_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . ident... | def is_child_of_vault(self, id_, vault_id):
"""Tests if a vault is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if the ``id`` is a child of
``vault_id,`` ``false`` otherwise
... |
def random_box(molecules, total=None, proportions=None, size=[1.,1.,1.], maxtries=100):
'''Create a System made of a series of random molecules.
Parameters:
total:
molecules:
proportions:
'''
# Setup proportions to be right
if proportions is None:
proportions = np.... | def function[random_box, parameter[molecules, total, proportions, size, maxtries]]:
constant[Create a System made of a series of random molecules.
Parameters:
total:
molecules:
proportions:
]
if compare[name[proportions] is constant[None]] begin[:]
variable[... | keyword[def] identifier[random_box] ( identifier[molecules] , identifier[total] = keyword[None] , identifier[proportions] = keyword[None] , identifier[size] =[ literal[int] , literal[int] , literal[int] ], identifier[maxtries] = literal[int] ):
literal[string]
keyword[if] identifier[proportions] ke... | def random_box(molecules, total=None, proportions=None, size=[1.0, 1.0, 1.0], maxtries=100):
"""Create a System made of a series of random molecules.
Parameters:
total:
molecules:
proportions:
"""
# Setup proportions to be right
if proportions is None:
proportions = np.... |
def find_min_required(path):
"""Inspect terraform files and find minimum version."""
found_min_required = ''
for filename in glob.glob(os.path.join(path, '*.tf')):
with open(filename, 'r') as stream:
tf_config = hcl.load(stream)
if tf_config.get('terraform', {}).get('required... | def function[find_min_required, parameter[path]]:
constant[Inspect terraform files and find minimum version.]
variable[found_min_required] assign[=] constant[]
for taget[name[filename]] in starred[call[name[glob].glob, parameter[call[name[os].path.join, parameter[name[path], constant[*.tf]]]]]] ... | keyword[def] identifier[find_min_required] ( identifier[path] ):
literal[string]
identifier[found_min_required] = literal[string]
keyword[for] identifier[filename] keyword[in] identifier[glob] . identifier[glob] ( identifier[os] . identifier[path] . identifier[join] ( identifier[path] , literal[st... | def find_min_required(path):
"""Inspect terraform files and find minimum version."""
found_min_required = ''
for filename in glob.glob(os.path.join(path, '*.tf')):
with open(filename, 'r') as stream:
tf_config = hcl.load(stream)
if tf_config.get('terraform', {}).get('required... |
def put(self, metrics):
"""
Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric
"""
if type(metrics) == list:
for metric in metrics:
self.c.put_metric_data(**metric)
else:
self.c.put_metric_... | def function[put, parameter[self, metrics]]:
constant[
Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric
]
if compare[call[name[type], parameter[name[metrics]]] equal[==] name[list]] begin[:]
for taget[name[metric]] in s... | keyword[def] identifier[put] ( identifier[self] , identifier[metrics] ):
literal[string]
keyword[if] identifier[type] ( identifier[metrics] )== identifier[list] :
keyword[for] identifier[metric] keyword[in] identifier[metrics] :
identifier[self] . identifier[c] . i... | def put(self, metrics):
"""
Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric
"""
if type(metrics) == list:
for metric in metrics:
self.c.put_metric_data(**metric) # depends on [control=['for'], data=['metric']] # depends ... |
def delete(self, CorpNum, MgtKeyType, MgtKey, UserID=None):
""" 삭제
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
UserID : 팝빌 회원아이디
return
처리결과. consist of cod... | def function[delete, parameter[self, CorpNum, MgtKeyType, MgtKey, UserID]]:
constant[ 삭제
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
UserID : 팝빌 회원아이디
return
... | keyword[def] identifier[delete] ( identifier[self] , identifier[CorpNum] , identifier[MgtKeyType] , identifier[MgtKey] , identifier[UserID] = keyword[None] ):
literal[string]
keyword[if] identifier[MgtKeyType] keyword[not] keyword[in] identifier[self] . identifier[__MgtKeyTypes] :
... | def delete(self, CorpNum, MgtKeyType, MgtKey, UserID=None):
""" 삭제
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
UserID : 팝빌 회원아이디
return
처리결과. consist of code an... |
def to_int(b:Any)->Union[int,List[int]]:
"Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible"
if is_listy(b): return [to_int(x) for x in b]
else: return int(b) | def function[to_int, parameter[b]]:
constant[Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible]
if call[name[is_listy], parameter[name[b]]] begin[:]
return[<ast.ListComp object at 0x7da1b1dd8820>] | keyword[def] identifier[to_int] ( identifier[b] : identifier[Any] )-> identifier[Union] [ identifier[int] , identifier[List] [ identifier[int] ]]:
literal[string]
keyword[if] identifier[is_listy] ( identifier[b] ): keyword[return] [ identifier[to_int] ( identifier[x] ) keyword[for] identifier[x] keyword... | def to_int(b: Any) -> Union[int, List[int]]:
"""Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible"""
if is_listy(b):
return [to_int(x) for x in b] # depends on [control=['if'], data=[]]
else:
return int(b) |
def filter_directories(self):
"""Filter the directories to show"""
index = self.get_index('.spyproject')
if index is not None:
self.setRowHidden(index.row(), index.parent(), True) | def function[filter_directories, parameter[self]]:
constant[Filter the directories to show]
variable[index] assign[=] call[name[self].get_index, parameter[constant[.spyproject]]]
if compare[name[index] is_not constant[None]] begin[:]
call[name[self].setRowHidden, parameter[call[n... | keyword[def] identifier[filter_directories] ( identifier[self] ):
literal[string]
identifier[index] = identifier[self] . identifier[get_index] ( literal[string] )
keyword[if] identifier[index] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[setRo... | def filter_directories(self):
"""Filter the directories to show"""
index = self.get_index('.spyproject')
if index is not None:
self.setRowHidden(index.row(), index.parent(), True) # depends on [control=['if'], data=['index']] |
def create_vars_from_data(self, dataset, split="train"):
"""
Create vars given a dataset and set test values.
Useful when dataset is already defined.
"""
from deepy.core.neural_var import NeuralVariable
vars = []
if split == "valid":
data_split = datas... | def function[create_vars_from_data, parameter[self, dataset, split]]:
constant[
Create vars given a dataset and set test values.
Useful when dataset is already defined.
]
from relative_module[deepy.core.neural_var] import module[NeuralVariable]
variable[vars] assign[=] list[[... | keyword[def] identifier[create_vars_from_data] ( identifier[self] , identifier[dataset] , identifier[split] = literal[string] ):
literal[string]
keyword[from] identifier[deepy] . identifier[core] . identifier[neural_var] keyword[import] identifier[NeuralVariable]
identifier[vars] =[]
... | def create_vars_from_data(self, dataset, split='train'):
"""
Create vars given a dataset and set test values.
Useful when dataset is already defined.
"""
from deepy.core.neural_var import NeuralVariable
vars = []
if split == 'valid':
data_split = dataset.valid_set() # de... |
def from_dict(data, ctx):
"""
Instantiate a new OrderBook from a dict (generally from loading a JSON
response). The data used to instantiate the OrderBook is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately.
"""
data =... | def function[from_dict, parameter[data, ctx]]:
constant[
Instantiate a new OrderBook from a dict (generally from loading a JSON
response). The data used to instantiate the OrderBook is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately.
... | keyword[def] identifier[from_dict] ( identifier[data] , identifier[ctx] ):
literal[string]
identifier[data] = identifier[data] . identifier[copy] ()
keyword[if] identifier[data] . identifier[get] ( literal[string] ) keyword[is] keyword[not] keyword[None] :
identifier[data... | def from_dict(data, ctx):
"""
Instantiate a new OrderBook from a dict (generally from loading a JSON
response). The data used to instantiate the OrderBook is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately.
"""
data = data.cop... |
def tradeStatus(self, trade_id):
"""Return trade status.
:params trade_id: Trade id.
"""
method = 'GET'
url = 'trade/status'
if not isinstance(trade_id, (list, tuple)):
trade_id = (trade_id,)
trade_id = (str(i) for i in trade_id)
params = {'t... | def function[tradeStatus, parameter[self, trade_id]]:
constant[Return trade status.
:params trade_id: Trade id.
]
variable[method] assign[=] constant[GET]
variable[url] assign[=] constant[trade/status]
if <ast.UnaryOp object at 0x7da1b014e410> begin[:]
va... | keyword[def] identifier[tradeStatus] ( identifier[self] , identifier[trade_id] ):
literal[string]
identifier[method] = literal[string]
identifier[url] = literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[trade_id] ,( identifier[list] , identifier[tup... | def tradeStatus(self, trade_id):
"""Return trade status.
:params trade_id: Trade id.
"""
method = 'GET'
url = 'trade/status'
if not isinstance(trade_id, (list, tuple)):
trade_id = (trade_id,) # depends on [control=['if'], data=[]]
trade_id = (str(i) for i in trade_id)
p... |
def get_users(self, course):
""" Returns a sorted list of users """
users = OrderedDict(sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course)).items()),
key=lambda k: k[1][0] if k[1] is not None else ""))
return users | def function[get_users, parameter[self, course]]:
constant[ Returns a sorted list of users ]
variable[users] assign[=] call[name[OrderedDict], parameter[call[name[sorted], parameter[call[name[list], parameter[call[call[name[self].user_manager.get_users_info, parameter[call[name[self].user_manager.get_co... | keyword[def] identifier[get_users] ( identifier[self] , identifier[course] ):
literal[string]
identifier[users] = identifier[OrderedDict] ( identifier[sorted] ( identifier[list] ( identifier[self] . identifier[user_manager] . identifier[get_users_info] ( identifier[self] . identifier[user_manager] ... | def get_users(self, course):
""" Returns a sorted list of users """
users = OrderedDict(sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course)).items()), key=lambda k: k[1][0] if k[1] is not None else ''))
return users |
def get_upload_form(self):
"""Construct form for accepting file upload."""
return self.form_class(self.request.POST, self.request.FILES) | def function[get_upload_form, parameter[self]]:
constant[Construct form for accepting file upload.]
return[call[name[self].form_class, parameter[name[self].request.POST, name[self].request.FILES]]] | keyword[def] identifier[get_upload_form] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[form_class] ( identifier[self] . identifier[request] . identifier[POST] , identifier[self] . identifier[request] . identifier[FILES] ) | def get_upload_form(self):
"""Construct form for accepting file upload."""
return self.form_class(self.request.POST, self.request.FILES) |
def system_find_affiliates(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findAffiliates API method.
"""
return DXHTTPRequest('/system/findAffiliates', input_params, always_retry=always_retry, **kwargs) | def function[system_find_affiliates, parameter[input_params, always_retry]]:
constant[
Invokes the /system/findAffiliates API method.
]
return[call[name[DXHTTPRequest], parameter[constant[/system/findAffiliates], name[input_params]]]] | keyword[def] identifier[system_find_affiliates] ( identifier[input_params] ={}, identifier[always_retry] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[DXHTTPRequest] ( literal[string] , identifier[input_params] , identifier[always_retry] = identifier[always_retry] ,*... | def system_find_affiliates(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findAffiliates API method.
"""
return DXHTTPRequest('/system/findAffiliates', input_params, always_retry=always_retry, **kwargs) |
def pullup(self, pin, enabled):
"""Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor.
"""
self._validate_channel(pin)
if enabled:
self.gppu[int(pin/8)] |= 1 << (int(pin%8))
else:
self.gpp... | def function[pullup, parameter[self, pin, enabled]]:
constant[Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor.
]
call[name[self]._validate_channel, parameter[name[pin]]]
if name[enabled] begin[:]
<ast.AugAssig... | keyword[def] identifier[pullup] ( identifier[self] , identifier[pin] , identifier[enabled] ):
literal[string]
identifier[self] . identifier[_validate_channel] ( identifier[pin] )
keyword[if] identifier[enabled] :
identifier[self] . identifier[gppu] [ identifier[int] ( identif... | def pullup(self, pin, enabled):
"""Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor.
"""
self._validate_channel(pin)
if enabled:
self.gppu[int(pin / 8)] |= 1 << int(pin % 8) # depends on [control=['if'], data=[]]
else... |
def almost_equal(f: DataFrame, g: DataFrame) -> bool:
"""
Return ``True`` if and only if the given DataFrames are equal after
sorting their columns names, sorting their values, and
reseting their indices.
"""
if f.empty or g.empty:
return f.equals(g)
else:
# Put in canonical ... | def function[almost_equal, parameter[f, g]]:
constant[
Return ``True`` if and only if the given DataFrames are equal after
sorting their columns names, sorting their values, and
reseting their indices.
]
if <ast.BoolOp object at 0x7da20c6a80a0> begin[:]
return[call[name[f].equals... | keyword[def] identifier[almost_equal] ( identifier[f] : identifier[DataFrame] , identifier[g] : identifier[DataFrame] )-> identifier[bool] :
literal[string]
keyword[if] identifier[f] . identifier[empty] keyword[or] identifier[g] . identifier[empty] :
keyword[return] identifier[f] . identifier[... | def almost_equal(f: DataFrame, g: DataFrame) -> bool:
"""
Return ``True`` if and only if the given DataFrames are equal after
sorting their columns names, sorting their values, and
reseting their indices.
"""
if f.empty or g.empty:
return f.equals(g) # depends on [control=['if'], data=[... |
def get_ticker_price(self, ticker,
startDate=None, endDate=None,
fmt='json', frequency='daily'):
"""By default, return latest EOD Composite Price for a stock ticker.
On average, each feed contains 3 data sources.
Supported tickers + Avail... | def function[get_ticker_price, parameter[self, ticker, startDate, endDate, fmt, frequency]]:
constant[By default, return latest EOD Composite Price for a stock ticker.
On average, each feed contains 3 data sources.
Supported tickers + Available Day Ranges are here:
https://ap... | keyword[def] identifier[get_ticker_price] ( identifier[self] , identifier[ticker] ,
identifier[startDate] = keyword[None] , identifier[endDate] = keyword[None] ,
identifier[fmt] = literal[string] , identifier[frequency] = literal[string] ):
literal[string]
identifier[url] = identifier[self] . ide... | def get_ticker_price(self, ticker, startDate=None, endDate=None, fmt='json', frequency='daily'):
"""By default, return latest EOD Composite Price for a stock ticker.
On average, each feed contains 3 data sources.
Supported tickers + Available Day Ranges are here:
https://apimedia... |
def user_preference_form_builder(instance, preferences=[], **kwargs):
"""
A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)`
:param user: a :py:class:`django.contrib.auth.models.User` instance
"""
return preference_form_builder(
UserPreferenceForm,
... | def function[user_preference_form_builder, parameter[instance, preferences]]:
constant[
A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)`
:param user: a :py:class:`django.contrib.auth.models.User` instance
]
return[call[name[preference_form_builder], parame... | keyword[def] identifier[user_preference_form_builder] ( identifier[instance] , identifier[preferences] =[],** identifier[kwargs] ):
literal[string]
keyword[return] identifier[preference_form_builder] (
identifier[UserPreferenceForm] ,
identifier[preferences] ,
identifier[model] ={ literal[s... | def user_preference_form_builder(instance, preferences=[], **kwargs):
"""
A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)`
:param user: a :py:class:`django.contrib.auth.models.User` instance
"""
return preference_form_builder(UserPreferenceForm, preferences, m... |
def get_spider_stats(self):
'''
Gather spider based stats
'''
self.logger.debug("Gathering spider stats")
the_dict = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys('stats:crawler:*:*:*')
for key in keys:
# we ... | def function[get_spider_stats, parameter[self]]:
constant[
Gather spider based stats
]
call[name[self].logger.debug, parameter[constant[Gathering spider stats]]]
variable[the_dict] assign[=] dictionary[[], []]
variable[spider_set] assign[=] call[name[set], parameter[]]
... | keyword[def] identifier[get_spider_stats] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
identifier[the_dict] ={}
identifier[spider_set] = identifier[set] ()
identifier[total_spider_count] = literal[int]... | def get_spider_stats(self):
"""
Gather spider based stats
"""
self.logger.debug('Gathering spider stats')
the_dict = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys('stats:crawler:*:*:*')
for key in keys:
# we only care about the spider
... |
def set_user_project_permission(self, project_id, user_id, auth_role):
"""
Send PUT request to /projects/{project_id}/permissions/{user_id/ with auth_role value.
:param project_id: str uuid of the project
:param user_id: str uuid of the user
:param auth_role: str project role eg ... | def function[set_user_project_permission, parameter[self, project_id, user_id, auth_role]]:
constant[
Send PUT request to /projects/{project_id}/permissions/{user_id/ with auth_role value.
:param project_id: str uuid of the project
:param user_id: str uuid of the user
:param auth... | keyword[def] identifier[set_user_project_permission] ( identifier[self] , identifier[project_id] , identifier[user_id] , identifier[auth_role] ):
literal[string]
identifier[put_data] ={
literal[string] : identifier[auth_role]
}
keyword[return] identifier[self] . identifi... | def set_user_project_permission(self, project_id, user_id, auth_role):
"""
Send PUT request to /projects/{project_id}/permissions/{user_id/ with auth_role value.
:param project_id: str uuid of the project
:param user_id: str uuid of the user
:param auth_role: str project role eg 'pro... |
def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
... | def function[redirect, parameter[url, code]]:
constant[ Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. ]
if <ast.UnaryOp object at 0x7da20e956770> begin[:]
variable[code] assign[=] <ast.IfExp object at 0x7da20e956c20>
variable[r... | keyword[def] identifier[redirect] ( identifier[url] , identifier[code] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[code] :
identifier[code] = literal[int] keyword[if] identifier[request] . identifier[get] ( literal[string] )== literal[string] keyword[else] literal[... | def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == 'HTTP/1.1' else 302 # depends on [control=['if'], data=[]]
res = response.copy(cls=HTTPResponse)
... |
def get_issue_generator(self, user_id, project_id, project_name):
"""
Approach:
1. Get user ID from bugwarriorrc file
2. Get list of tickets from /user-tasks for a given project
3. For each ticket/task returned from #2, get ticket/task info and
check if logged-in user... | def function[get_issue_generator, parameter[self, user_id, project_id, project_name]]:
constant[
Approach:
1. Get user ID from bugwarriorrc file
2. Get list of tickets from /user-tasks for a given project
3. For each ticket/task returned from #2, get ticket/task info and
... | keyword[def] identifier[get_issue_generator] ( identifier[self] , identifier[user_id] , identifier[project_id] , identifier[project_name] ):
literal[string]
identifier[user_tasks_data] = identifier[self] . identifier[call_api] (
literal[string] + identifier[six] . identifier[text_type] ( ... | def get_issue_generator(self, user_id, project_id, project_name):
"""
Approach:
1. Get user ID from bugwarriorrc file
2. Get list of tickets from /user-tasks for a given project
3. For each ticket/task returned from #2, get ticket/task info and
check if logged-in user is ... |
def createMenu(self, parent):
"""
Creates a new menu for the inputed parent item.
:param parent | <QMenu>
"""
menu = QtGui.QMenu(parent)
menu.setTitle('&View')
act = menu.addAction('&Lock/Unlock Layout')
act.setIcon(QtGui.QIcon(projexui.reso... | def function[createMenu, parameter[self, parent]]:
constant[
Creates a new menu for the inputed parent item.
:param parent | <QMenu>
]
variable[menu] assign[=] call[name[QtGui].QMenu, parameter[name[parent]]]
call[name[menu].setTitle, parameter[constant[&Vie... | keyword[def] identifier[createMenu] ( identifier[self] , identifier[parent] ):
literal[string]
identifier[menu] = identifier[QtGui] . identifier[QMenu] ( identifier[parent] )
identifier[menu] . identifier[setTitle] ( literal[string] )
identifier[act] = identifier[menu] . identifi... | def createMenu(self, parent):
"""
Creates a new menu for the inputed parent item.
:param parent | <QMenu>
"""
menu = QtGui.QMenu(parent)
menu.setTitle('&View')
act = menu.addAction('&Lock/Unlock Layout')
act.setIcon(QtGui.QIcon(projexui.resources.find('img/view/... |
def get_infobox(ptree, boxterm="box"):
"""
Returns parse tree template with title containing <boxterm> as dict:
<box> = {<name>: <value>, ...}
If simple transform fails, attempts more general assembly:
<box> = {'boxes': [{<title>: <parts>}, ...],
'count': <len(boxes)>}
... | def function[get_infobox, parameter[ptree, boxterm]]:
constant[
Returns parse tree template with title containing <boxterm> as dict:
<box> = {<name>: <value>, ...}
If simple transform fails, attempts more general assembly:
<box> = {'boxes': [{<title>: <parts>}, ...],
... | keyword[def] identifier[get_infobox] ( identifier[ptree] , identifier[boxterm] = literal[string] ):
literal[string]
identifier[boxes] =[]
keyword[for] identifier[item] keyword[in] identifier[lxml] . identifier[etree] . identifier[fromstring] ( identifier[ptree] ). identifier[xpath] ( literal[string... | def get_infobox(ptree, boxterm='box'):
"""
Returns parse tree template with title containing <boxterm> as dict:
<box> = {<name>: <value>, ...}
If simple transform fails, attempts more general assembly:
<box> = {'boxes': [{<title>: <parts>}, ...],
'count': <len(boxes)>}
... |
async def revoke(self, user_id, *permissions):
" 取消用户(user_id)的权限(permission) "
prefix = f"{self._prefix_perm}/{user_id}/"
perm_names = [str(p) for p in permissions]
checkings = [
KV.delete.txn(prefix + p, b'\0', prev_kv=True) for p in perm_names
]
s... | <ast.AsyncFunctionDef object at 0x7da1b164fe20> | keyword[async] keyword[def] identifier[revoke] ( identifier[self] , identifier[user_id] ,* identifier[permissions] ):
literal[string]
identifier[prefix] = literal[string]
identifier[perm_names] =[ identifier[str] ( identifier[p] ) keyword[for] identifier[p] keyword[in] identifier[pe... | async def revoke(self, user_id, *permissions):
""" 取消用户(user_id)的权限(permission) """
prefix = f'{self._prefix_perm}/{user_id}/'
perm_names = [str(p) for p in permissions]
checkings = [KV.delete.txn(prefix + p, b'\x00', prev_kv=True) for p in perm_names]
(success, response) = await self._client.txn(co... |
def config(ctx):
"""Show access token and other configuration settings.
The access token and command verbosity level can be set on the
command line, as environment variables, and in mapbox.ini config
files.
"""
ctx.default_map = ctx.obj['cfg']
click.echo("CLI:")
click.echo("access-token... | def function[config, parameter[ctx]]:
constant[Show access token and other configuration settings.
The access token and command verbosity level can be set on the
command line, as environment variables, and in mapbox.ini config
files.
]
name[ctx].default_map assign[=] call[name[ctx].obj]... | keyword[def] identifier[config] ( identifier[ctx] ):
literal[string]
identifier[ctx] . identifier[default_map] = identifier[ctx] . identifier[obj] [ literal[string] ]
identifier[click] . identifier[echo] ( literal[string] )
identifier[click] . identifier[echo] ( literal[string] . identifier[forma... | def config(ctx):
"""Show access token and other configuration settings.
The access token and command verbosity level can be set on the
command line, as environment variables, and in mapbox.ini config
files.
"""
ctx.default_map = ctx.obj['cfg']
click.echo('CLI:')
click.echo('access-token... |
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
... | def function[start, parameter[self]]:
constant[Start thread.]
if <ast.UnaryOp object at 0x7da1b28f42b0> begin[:]
call[name[logging].info, parameter[constant[Starting asterisk mbox thread]]]
<ast.Try object at 0x7da1b28f55d0>
name[self]._thread assign[=] call[name[... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_thread] :
identifier[logging] . identifier[info] ( literal[string] )
keyword[try] :
keyword[while] keyword[True] :
... | def start(self):
"""Start thread."""
if not self._thread:
logging.info('Starting asterisk mbox thread')
# Ensure signal queue is empty
try:
while True:
self.signal.get(False) # depends on [control=['while'], data=[]] # depends on [control=['try'], data=[]]
... |
def parse(cls, resource, parent=None, _with_children=False):
""" Parse a resource
:param resource: Element rerpresenting a work
:param type: basestring, etree._Element
:param parent: Parent of the object
:type parent: XmlCtsTextgroupMetadata
:param _cls_dict: Dictionary ... | def function[parse, parameter[cls, resource, parent, _with_children]]:
constant[ Parse a resource
:param resource: Element rerpresenting a work
:param type: basestring, etree._Element
:param parent: Parent of the object
:type parent: XmlCtsTextgroupMetadata
:param _cls_d... | keyword[def] identifier[parse] ( identifier[cls] , identifier[resource] , identifier[parent] = keyword[None] , identifier[_with_children] = keyword[False] ):
literal[string]
identifier[xml] = identifier[xmlparser] ( identifier[resource] )
identifier[o] = identifier[cls] ( identifier[urn] =... | def parse(cls, resource, parent=None, _with_children=False):
""" Parse a resource
:param resource: Element rerpresenting a work
:param type: basestring, etree._Element
:param parent: Parent of the object
:type parent: XmlCtsTextgroupMetadata
:param _cls_dict: Dictionary of c... |
def _get_related_exporter(self, related_obj, column):
"""
returns an SqlaOdsExporter for the given related object and stores it in
the column object as a cache
"""
result = column.get('sqla_ods_exporter')
if result is None:
result = column['sqla_ods_exporter']... | def function[_get_related_exporter, parameter[self, related_obj, column]]:
constant[
returns an SqlaOdsExporter for the given related object and stores it in
the column object as a cache
]
variable[result] assign[=] call[name[column].get, parameter[constant[sqla_ods_exporter]]]
... | keyword[def] identifier[_get_related_exporter] ( identifier[self] , identifier[related_obj] , identifier[column] ):
literal[string]
identifier[result] = identifier[column] . identifier[get] ( literal[string] )
keyword[if] identifier[result] keyword[is] keyword[None] :
ident... | def _get_related_exporter(self, related_obj, column):
"""
returns an SqlaOdsExporter for the given related object and stores it in
the column object as a cache
"""
result = column.get('sqla_ods_exporter')
if result is None:
result = column['sqla_ods_exporter'] = SqlaOdsExport... |
def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.value) | def function[copy, parameter[self, props, value]]:
constant[
Copy the Overlay possibly overriding props.
]
return[call[name[Overlay], parameter[name[self].text, tuple[[<ast.Attribute object at 0x7da1b15a16f0>, <ast.Attribute object at 0x7da1b15a2380>]]]]] | keyword[def] identifier[copy] ( identifier[self] , identifier[props] = keyword[None] , identifier[value] = keyword[None] ):
literal[string]
keyword[return] identifier[Overlay] ( identifier[self] . identifier[text] ,
( identifier[self] . identifier[start] , identifier[self] . identifier[en... | def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text, (self.start, self.end), props=props or self.props, value=value or self.value) |
def get_version(path):
"""Return the project version from VERSION file."""
with open(os.path.join(path, 'VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
return version.strip() | def function[get_version, parameter[path]]:
constant[Return the project version from VERSION file.]
with call[name[open], parameter[call[name[os].path.join, parameter[name[path], constant[VERSION]]], constant[rb]]] begin[:]
variable[version] assign[=] call[call[call[name[f].read, paramet... | keyword[def] identifier[get_version] ( identifier[path] ):
literal[string]
keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[path] , literal[string] ), literal[string] ) keyword[as] identifier[f] :
identifier[version] = identifier[f] . identifier... | def get_version(path):
"""Return the project version from VERSION file."""
with open(os.path.join(path, 'VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip() # depends on [control=['with'], data=['f']]
return version.strip() |
def flush(self):
"""
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
"""
i = 0
while self._frame_data.is_dirty and i < 10:
i += 1
time.sleep(0.1) | def function[flush, parameter[self]]:
constant[
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
]
variable[i] assign[=] constant[0]
while <ast.BoolOp object at 0x7da1b0cf69e0> begin[:]
<ast.AugAssign object at 0x7da1b0cf6... | keyword[def] identifier[flush] ( identifier[self] ):
literal[string]
identifier[i] = literal[int]
keyword[while] identifier[self] . identifier[_frame_data] . identifier[is_dirty] keyword[and] identifier[i] < literal[int] :
identifier[i] += literal[int]
identi... | def flush(self):
"""
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
"""
i = 0
while self._frame_data.is_dirty and i < 10:
i += 1
time.sleep(0.1) # depends on [control=['while'], data=[]] |
async def handle_request(self, channel: Channel, body, envelope,
properties, futurize=True):
"""
the 'futurize' param is simply because aioamqp doesnt send another job until
this method returns (completes), so we ensure the future of
ourselves and return im... | <ast.AsyncFunctionDef object at 0x7da1b26ae470> | keyword[async] keyword[def] identifier[handle_request] ( identifier[self] , identifier[channel] : identifier[Channel] , identifier[body] , identifier[envelope] ,
identifier[properties] , identifier[futurize] = keyword[True] ):
literal[string]
keyword[if] identifier[futurize] :
ident... | async def handle_request(self, channel: Channel, body, envelope, properties, futurize=True):
"""
the 'futurize' param is simply because aioamqp doesnt send another job until
this method returns (completes), so we ensure the future of
ourselves and return immediately so we can handle many r... |
def threshold(self, front_thresh=0.0, rear_thresh=100.0):
"""Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
... | def function[threshold, parameter[self, front_thresh, rear_thresh]]:
constant[Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_... | keyword[def] identifier[threshold] ( identifier[self] , identifier[front_thresh] = literal[int] , identifier[rear_thresh] = literal[int] ):
literal[string]
identifier[data] = identifier[np] . identifier[copy] ( identifier[self] . identifier[_data] )
identifier[data] [ identifier[data] < id... | def threshold(self, front_thresh=0.0, rear_thresh=100.0):
"""Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
... |
def hv_mv_station_load(network):
"""
Checks for over-loading of HV/MV station.
Parameters
----------
network : :class:`~.grid.network.Network`
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded HV/MV stations, their apparent power
at ... | def function[hv_mv_station_load, parameter[network]]:
constant[
Checks for over-loading of HV/MV station.
Parameters
----------
network : :class:`~.grid.network.Network`
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded HV/MV stations, t... | keyword[def] identifier[hv_mv_station_load] ( identifier[network] ):
literal[string]
identifier[crit_stations] = identifier[pd] . identifier[DataFrame] ()
identifier[crit_stations] = identifier[_station_load] ( identifier[network] , identifier[network] . identifier[mv_grid] . identifier[station] ,
... | def hv_mv_station_load(network):
"""
Checks for over-loading of HV/MV station.
Parameters
----------
network : :class:`~.grid.network.Network`
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded HV/MV stations, their apparent power
at ... |
def get_internet_gateway(vpc, **conn):
"""Gets the Internet Gateway details about a VPC"""
result = {}
ig_result = describe_internet_gateways(Filters=[{"Name": "attachment.vpc-id", "Values": [vpc["id"]]}], **conn)
if ig_result:
# Only 1 IG can be attached to a VPC:
result.update({
... | def function[get_internet_gateway, parameter[vpc]]:
constant[Gets the Internet Gateway details about a VPC]
variable[result] assign[=] dictionary[[], []]
variable[ig_result] assign[=] call[name[describe_internet_gateways], parameter[]]
if name[ig_result] begin[:]
call[nam... | keyword[def] identifier[get_internet_gateway] ( identifier[vpc] ,** identifier[conn] ):
literal[string]
identifier[result] ={}
identifier[ig_result] = identifier[describe_internet_gateways] ( identifier[Filters] =[{ literal[string] : literal[string] , literal[string] :[ identifier[vpc] [ literal[strin... | def get_internet_gateway(vpc, **conn):
"""Gets the Internet Gateway details about a VPC"""
result = {}
ig_result = describe_internet_gateways(Filters=[{'Name': 'attachment.vpc-id', 'Values': [vpc['id']]}], **conn)
if ig_result:
# Only 1 IG can be attached to a VPC:
result.update({'State'... |
def wait_for_deps(self, conf, images):
"""Wait for all our dependencies"""
from harpoon.option_spec.image_objs import WaitCondition
api = conf.harpoon.docker_context_maker().api
waited = set()
last_attempt = {}
dependencies = set(dep for dep, _ in conf.dependency_images(... | def function[wait_for_deps, parameter[self, conf, images]]:
constant[Wait for all our dependencies]
from relative_module[harpoon.option_spec.image_objs] import module[WaitCondition]
variable[api] assign[=] call[name[conf].harpoon.docker_context_maker, parameter[]].api
variable[waited] assign... | keyword[def] identifier[wait_for_deps] ( identifier[self] , identifier[conf] , identifier[images] ):
literal[string]
keyword[from] identifier[harpoon] . identifier[option_spec] . identifier[image_objs] keyword[import] identifier[WaitCondition]
identifier[api] = identifier[conf] . ident... | def wait_for_deps(self, conf, images):
"""Wait for all our dependencies"""
from harpoon.option_spec.image_objs import WaitCondition
api = conf.harpoon.docker_context_maker().api
waited = set()
last_attempt = {}
dependencies = set((dep for (dep, _) in conf.dependency_images()))
# Wait conditi... |
def cli():
"""Run the command line interface."""
args = docopt.docopt(__doc__, version=__VERSION__)
secure = args['--secure']
numberofwords = int(args['<numberofwords>'])
dictpath = args['--dict']
if dictpath is not None:
dictfile = open(dictpath)
else:
dictfile = load_strea... | def function[cli, parameter[]]:
constant[Run the command line interface.]
variable[args] assign[=] call[name[docopt].docopt, parameter[name[__doc__]]]
variable[secure] assign[=] call[name[args]][constant[--secure]]
variable[numberofwords] assign[=] call[name[int], parameter[call[name[arg... | keyword[def] identifier[cli] ():
literal[string]
identifier[args] = identifier[docopt] . identifier[docopt] ( identifier[__doc__] , identifier[version] = identifier[__VERSION__] )
identifier[secure] = identifier[args] [ literal[string] ]
identifier[numberofwords] = identifier[int] ( identifier[ar... | def cli():
"""Run the command line interface."""
args = docopt.docopt(__doc__, version=__VERSION__)
secure = args['--secure']
numberofwords = int(args['<numberofwords>'])
dictpath = args['--dict']
if dictpath is not None:
dictfile = open(dictpath) # depends on [control=['if'], data=['di... |
def set_cpus(self, cpus=0):
"""
Add --cpus options to specify how many threads to use.
"""
from multiprocessing import cpu_count
max_cpus = cpu_count()
if not 0 < cpus < max_cpus:
cpus = max_cpus
self.add_option("--cpus", default=cpus, type="int",
... | def function[set_cpus, parameter[self, cpus]]:
constant[
Add --cpus options to specify how many threads to use.
]
from relative_module[multiprocessing] import module[cpu_count]
variable[max_cpus] assign[=] call[name[cpu_count], parameter[]]
if <ast.UnaryOp object at 0x7da207f... | keyword[def] identifier[set_cpus] ( identifier[self] , identifier[cpus] = literal[int] ):
literal[string]
keyword[from] identifier[multiprocessing] keyword[import] identifier[cpu_count]
identifier[max_cpus] = identifier[cpu_count] ()
keyword[if] keyword[not] literal[int] < ... | def set_cpus(self, cpus=0):
"""
Add --cpus options to specify how many threads to use.
"""
from multiprocessing import cpu_count
max_cpus = cpu_count()
if not 0 < cpus < max_cpus:
cpus = max_cpus # depends on [control=['if'], data=[]]
self.add_option('--cpus', default=cpus, ... |
def qualified_name_import(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
parts = qualified_name(cls).split('.')
return "from {} import {}".format('.'.join(parts[:-1]), parts[-1]) | def function[qualified_name_import, parameter[cls]]:
constant[Full name of a class, including the module. Like qualified_class_name, but when you already have a class ]
variable[parts] assign[=] call[call[name[qualified_name], parameter[name[cls]]].split, parameter[constant[.]]]
return[call[constant... | keyword[def] identifier[qualified_name_import] ( identifier[cls] ):
literal[string]
identifier[parts] = identifier[qualified_name] ( identifier[cls] ). identifier[split] ( literal[string] )
keyword[return] literal[string] . identifier[format] ( literal[string] . identifier[join] ( identifier[parts]... | def qualified_name_import(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
parts = qualified_name(cls).split('.')
return 'from {} import {}'.format('.'.join(parts[:-1]), parts[-1]) |
def distribute(self, f, n):
"""Distribute the computations amongst the multiprocessing pools
Parameters
----------
f : function
Function to be distributed to the processors
n : int
The values in range(0,n) will be passed as arguments to the
function... | def function[distribute, parameter[self, f, n]]:
constant[Distribute the computations amongst the multiprocessing pools
Parameters
----------
f : function
Function to be distributed to the processors
n : int
The values in range(0,n) will be passed as argument... | keyword[def] identifier[distribute] ( identifier[self] , identifier[f] , identifier[n] ):
literal[string]
keyword[if] identifier[self] . identifier[pool] keyword[is] keyword[None] :
keyword[return] [ identifier[f] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifi... | def distribute(self, f, n):
"""Distribute the computations amongst the multiprocessing pools
Parameters
----------
f : function
Function to be distributed to the processors
n : int
The values in range(0,n) will be passed as arguments to the
function f.
... |
def on_portal(self, *args):
"""Set my ``name`` and instantiate my ``mirrormap`` as soon as I have
the properties I need to do so.
"""
if not (
self.board and
self.origin and
self.destination and
self.origin.name in self.boa... | def function[on_portal, parameter[self]]:
constant[Set my ``name`` and instantiate my ``mirrormap`` as soon as I have
the properties I need to do so.
]
if <ast.UnaryOp object at 0x7da1b0b80ee0> begin[:]
call[name[Clock].schedule_once, parameter[name[self].on_portal, cons... | keyword[def] identifier[on_portal] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] keyword[not] (
identifier[self] . identifier[board] keyword[and]
identifier[self] . identifier[origin] keyword[and]
identifier[self] . identifier[destination] ke... | def on_portal(self, *args):
"""Set my ``name`` and instantiate my ``mirrormap`` as soon as I have
the properties I need to do so.
"""
if not (self.board and self.origin and self.destination and (self.origin.name in self.board.character.portal) and (self.destination.name in self.board.character.... |
def fft_transpose_numpy(vec):
"""
Perform a numpy transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array.
"""
N1, N2 = splay(vec)
... | def function[fft_transpose_numpy, parameter[vec]]:
constant[
Perform a numpy transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array.
... | keyword[def] identifier[fft_transpose_numpy] ( identifier[vec] ):
literal[string]
identifier[N1] , identifier[N2] = identifier[splay] ( identifier[vec] )
keyword[return] identifier[pycbc] . identifier[types] . identifier[Array] ( identifier[vec] . identifier[data] . identifier[copy] (). identifier[re... | def fft_transpose_numpy(vec):
"""
Perform a numpy transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array.
"""
(N1, N2) = splay(vec)... |
def rec_edit(self, zone, record_type, record_id, name, content, ttl=1, service_mode=None, priority=None,
service=None, service_name=None, protocol=None, weight=None, port=None, target=None):
"""
Edit a DNS record for the given zone.
:param zone: domain name
:type zone: s... | def function[rec_edit, parameter[self, zone, record_type, record_id, name, content, ttl, service_mode, priority, service, service_name, protocol, weight, port, target]]:
constant[
Edit a DNS record for the given zone.
:param zone: domain name
:type zone: str
:param record_type: T... | keyword[def] identifier[rec_edit] ( identifier[self] , identifier[zone] , identifier[record_type] , identifier[record_id] , identifier[name] , identifier[content] , identifier[ttl] = literal[int] , identifier[service_mode] = keyword[None] , identifier[priority] = keyword[None] ,
identifier[service] = keyword[None] ,... | def rec_edit(self, zone, record_type, record_id, name, content, ttl=1, service_mode=None, priority=None, service=None, service_name=None, protocol=None, weight=None, port=None, target=None):
"""
Edit a DNS record for the given zone.
:param zone: domain name
:type zone: str
:param rec... |
def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(
encoding=serializ... | def function[ed25519_private_key_to_string, parameter[key]]:
constant[Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
]
return[call[call[name[base64].b64encode... | keyword[def] identifier[ed25519_private_key_to_string] ( identifier[key] ):
literal[string]
keyword[return] identifier[base64] . identifier[b64encode] ( identifier[key] . identifier[private_bytes] (
identifier[encoding] = identifier[serialization] . identifier[Encoding] . identifier[Raw] ,
ident... | def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(encoding=serialization.Enc... |
def feed_forward(self, input_data, prediction=False):
"""Propagate forward through the layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
prediction : bool, optional
Whether to use prediction model. Only relevant when using
... | def function[feed_forward, parameter[self, input_data, prediction]]:
constant[Propagate forward through the layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
prediction : bool, optional
Whether to use prediction model. Only ... | keyword[def] identifier[feed_forward] ( identifier[self] , identifier[input_data] , identifier[prediction] = keyword[False] ):
literal[string]
keyword[if] identifier[input_data] . identifier[shape] [ literal[int] ]!= identifier[self] . identifier[W] . identifier[shape] [ literal[int] ]:
... | def feed_forward(self, input_data, prediction=False):
"""Propagate forward through the layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
prediction : bool, optional
Whether to use prediction model. Only relevant when using
... |
def delete_lbaas_port(self, lb_id):
"""send vm down event and delete db.
:param lb_id: vip id for v1 and lbaas_id for v2
"""
lb_id = lb_id.replace('-', '')
req = dict(instance_id=lb_id)
instances = self.get_vms_for_this_req(**req)
for vm in instances:
... | def function[delete_lbaas_port, parameter[self, lb_id]]:
constant[send vm down event and delete db.
:param lb_id: vip id for v1 and lbaas_id for v2
]
variable[lb_id] assign[=] call[name[lb_id].replace, parameter[constant[-], constant[]]]
variable[req] assign[=] call[name[dict], ... | keyword[def] identifier[delete_lbaas_port] ( identifier[self] , identifier[lb_id] ):
literal[string]
identifier[lb_id] = identifier[lb_id] . identifier[replace] ( literal[string] , literal[string] )
identifier[req] = identifier[dict] ( identifier[instance_id] = identifier[lb_id] )
... | def delete_lbaas_port(self, lb_id):
"""send vm down event and delete db.
:param lb_id: vip id for v1 and lbaas_id for v2
"""
lb_id = lb_id.replace('-', '')
req = dict(instance_id=lb_id)
instances = self.get_vms_for_this_req(**req)
for vm in instances:
LOG.info('deleting lbaa... |
def add_block(self, name):
""" Adds a new block to the AST.
`name`
Block name.
* Raises a ``ValueError`` exception if `name` is invalid or
an existing block name matches value provided for `name`.
"""
if not self.RE_NAME.match(name):
... | def function[add_block, parameter[self, name]]:
constant[ Adds a new block to the AST.
`name`
Block name.
* Raises a ``ValueError`` exception if `name` is invalid or
an existing block name matches value provided for `name`.
]
if <ast.Un... | keyword[def] identifier[add_block] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[RE_NAME] . identifier[match] ( identifier[name] ):
keyword[raise] identifier[ValueError] ( literal[string]
. identifier[fo... | def add_block(self, name):
""" Adds a new block to the AST.
`name`
Block name.
* Raises a ``ValueError`` exception if `name` is invalid or
an existing block name matches value provided for `name`.
"""
if not self.RE_NAME.match(name):
ra... |
def recover_cfg_all(self, entries, symbols=None, callback=None, arch_mode=None):
"""Recover CFG for all functions from an entry point and/or symbol table.
Args:
entries (list): A list of function addresses' to start the CFG recovery process.
symbols (dict): Symbol table.
... | def function[recover_cfg_all, parameter[self, entries, symbols, callback, arch_mode]]:
constant[Recover CFG for all functions from an entry point and/or symbol table.
Args:
entries (list): A list of function addresses' to start the CFG recovery process.
symbols (dict): Symbol ta... | keyword[def] identifier[recover_cfg_all] ( identifier[self] , identifier[entries] , identifier[symbols] = keyword[None] , identifier[callback] = keyword[None] , identifier[arch_mode] = keyword[None] ):
literal[string]
keyword[if] identifier[arch_mode] keyword[is] keyword[None] :
... | def recover_cfg_all(self, entries, symbols=None, callback=None, arch_mode=None):
"""Recover CFG for all functions from an entry point and/or symbol table.
Args:
entries (list): A list of function addresses' to start the CFG recovery process.
symbols (dict): Symbol table.
... |
def search_project_root():
"""
Search your Django project root.
returns:
- path:string Django project root path
"""
while True:
current = os.getcwd()
if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file():
... | def function[search_project_root, parameter[]]:
constant[
Search your Django project root.
returns:
- path:string Django project root path
]
while constant[True] begin[:]
variable[current] assign[=] call[name[os].getcwd, parameter[]]
... | keyword[def] identifier[search_project_root] ():
literal[string]
keyword[while] keyword[True] :
identifier[current] = identifier[os] . identifier[getcwd] ()
keyword[if] identifier[pathlib] . identifier[Path] ( literal[string] ). identifier[is_file] () keyword[or] ide... | def search_project_root():
"""
Search your Django project root.
returns:
- path:string Django project root path
"""
while True:
current = os.getcwd()
if pathlib.Path('Miragefile.py').is_file() or pathlib.Path('Miragefile').is_file():
return curre... |
def _get_setting(self, key, default_value=None, value_type=str):
"""Get the setting stored at the given key.
Args:
key (str): the setting key
default_value (str, optional): The default value, if none is
found. Defaults to None.
value_type (function, o... | def function[_get_setting, parameter[self, key, default_value, value_type]]:
constant[Get the setting stored at the given key.
Args:
key (str): the setting key
default_value (str, optional): The default value, if none is
found. Defaults to None.
value... | keyword[def] identifier[_get_setting] ( identifier[self] , identifier[key] , identifier[default_value] = keyword[None] , identifier[value_type] = identifier[str] ):
literal[string]
keyword[try] :
identifier[state_entry] = identifier[self] . identifier[_state_view] . identifier[get] (
... | def _get_setting(self, key, default_value=None, value_type=str):
"""Get the setting stored at the given key.
Args:
key (str): the setting key
default_value (str, optional): The default value, if none is
found. Defaults to None.
value_type (function, optio... |
def set_cursor_pos_callback(window, cbfun):
"""
Sets the cursor position callback.
Wrapper for:
GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_... | def function[set_cursor_pos_callback, parameter[window, cbfun]]:
constant[
Sets the cursor position callback.
Wrapper for:
GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
]
variable[window_addr] assign[=] call[name[ctypes].cast, parameter[call[... | keyword[def] identifier[set_cursor_pos_callback] ( identifier[window] , identifier[cbfun] ):
literal[string]
identifier[window_addr] = identifier[ctypes] . identifier[cast] ( identifier[ctypes] . identifier[pointer] ( identifier[window] ),
identifier[ctypes] . identifier[POINTER] ( identifier[ctypes] ... | def set_cursor_pos_callback(window, cbfun):
"""
Sets the cursor position callback.
Wrapper for:
GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if w... |
def get_example_features(example):
"""Returns the non-sequence features from the provided example."""
return (example.features.feature if isinstance(example, tf.train.Example)
else example.context.feature) | def function[get_example_features, parameter[example]]:
constant[Returns the non-sequence features from the provided example.]
return[<ast.IfExp object at 0x7da1b1f9bf70>] | keyword[def] identifier[get_example_features] ( identifier[example] ):
literal[string]
keyword[return] ( identifier[example] . identifier[features] . identifier[feature] keyword[if] identifier[isinstance] ( identifier[example] , identifier[tf] . identifier[train] . identifier[Example] )
keyword[else] ide... | def get_example_features(example):
"""Returns the non-sequence features from the provided example."""
return example.features.feature if isinstance(example, tf.train.Example) else example.context.feature |
def rename(self, old_fieldname, new_fieldname):
"""
Renames a specific field, and preserves the underlying order.
"""
if old_fieldname not in self:
raise Exception("DataTable does not have field `%s`" %
old_fieldname)
if not isinstance(new... | def function[rename, parameter[self, old_fieldname, new_fieldname]]:
constant[
Renames a specific field, and preserves the underlying order.
]
if compare[name[old_fieldname] <ast.NotIn object at 0x7da2590d7190> name[self]] begin[:]
<ast.Raise object at 0x7da1b13fb0a0>
if ... | keyword[def] identifier[rename] ( identifier[self] , identifier[old_fieldname] , identifier[new_fieldname] ):
literal[string]
keyword[if] identifier[old_fieldname] keyword[not] keyword[in] identifier[self] :
keyword[raise] identifier[Exception] ( literal[string] %
ide... | def rename(self, old_fieldname, new_fieldname):
"""
Renames a specific field, and preserves the underlying order.
"""
if old_fieldname not in self:
raise Exception('DataTable does not have field `%s`' % old_fieldname) # depends on [control=['if'], data=['old_fieldname']]
if not isin... |
def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
self.services.clear()
self.services = None
self._future_value = None
super(AggregateDependency, self).clear() | def function[clear, parameter[self]]:
constant[
Cleans up the manager. The manager can't be used after this method has
been called
]
call[name[self].services.clear, parameter[]]
name[self].services assign[=] constant[None]
name[self]._future_value assign[=] consta... | keyword[def] identifier[clear] ( identifier[self] ):
literal[string]
identifier[self] . identifier[services] . identifier[clear] ()
identifier[self] . identifier[services] = keyword[None]
identifier[self] . identifier[_future_value] = keyword[None]
identifier[super] ( i... | def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
self.services.clear()
self.services = None
self._future_value = None
super(AggregateDependency, self).clear() |
def previous_workday(dt):
"""
returns previous weekday used for observances
"""
dt -= timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt -= timedelta(days=1)
return dt | def function[previous_workday, parameter[dt]]:
constant[
returns previous weekday used for observances
]
<ast.AugAssign object at 0x7da1b2344490>
while compare[call[name[dt].weekday, parameter[]] greater[>] constant[4]] begin[:]
<ast.AugAssign object at 0x7da1b2345e40>
return[nam... | keyword[def] identifier[previous_workday] ( identifier[dt] ):
literal[string]
identifier[dt] -= identifier[timedelta] ( identifier[days] = literal[int] )
keyword[while] identifier[dt] . identifier[weekday] ()> literal[int] :
identifier[dt] -= identifier[timedelta] ( identifier[days] = l... | def previous_workday(dt):
"""
returns previous weekday used for observances
"""
dt -= timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt -= timedelta(days=1) # depends on [control=['while'], data=[]]
return dt |
def _get_grid_files(self):
"""Get the files holding grid data for an aospy object."""
grid_file_paths = self.grid_file_paths
datasets = []
if isinstance(grid_file_paths, str):
grid_file_paths = [grid_file_paths]
for path in grid_file_paths:
try:
... | def function[_get_grid_files, parameter[self]]:
constant[Get the files holding grid data for an aospy object.]
variable[grid_file_paths] assign[=] name[self].grid_file_paths
variable[datasets] assign[=] list[[]]
if call[name[isinstance], parameter[name[grid_file_paths], name[str]]] begin... | keyword[def] identifier[_get_grid_files] ( identifier[self] ):
literal[string]
identifier[grid_file_paths] = identifier[self] . identifier[grid_file_paths]
identifier[datasets] =[]
keyword[if] identifier[isinstance] ( identifier[grid_file_paths] , identifier[str] ):
... | def _get_grid_files(self):
"""Get the files holding grid data for an aospy object."""
grid_file_paths = self.grid_file_paths
datasets = []
if isinstance(grid_file_paths, str):
grid_file_paths = [grid_file_paths] # depends on [control=['if'], data=[]]
for path in grid_file_paths:
try... |
def password_dialog(self, title="Enter password", message="Enter password", **kwargs):
"""
Show a password input dialog
Usage: C{dialog.password_dialog(title="Enter password", message="Enter password")}
@param title: window title for the dialog
@param message: m... | def function[password_dialog, parameter[self, title, message]]:
constant[
Show a password input dialog
Usage: C{dialog.password_dialog(title="Enter password", message="Enter password")}
@param title: window title for the dialog
@param message: message displayed ... | keyword[def] identifier[password_dialog] ( identifier[self] , identifier[title] = literal[string] , identifier[message] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_run_zenity] ( identifier[title] ,[ literal[string] , literal[string] , ... | def password_dialog(self, title='Enter password', message='Enter password', **kwargs):
"""
Show a password input dialog
Usage: C{dialog.password_dialog(title="Enter password", message="Enter password")}
@param title: window title for the dialog
@param message: messa... |
def get_reserved_space(self):
"""Get the number of lines to reserve for the completion menu."""
reserved_space_ratio = .45
max_reserved_space = 8
_, height = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) | def function[get_reserved_space, parameter[self]]:
constant[Get the number of lines to reserve for the completion menu.]
variable[reserved_space_ratio] assign[=] constant[0.45]
variable[max_reserved_space] assign[=] constant[8]
<ast.Tuple object at 0x7da18bc71e40> assign[=] call[name[cli... | keyword[def] identifier[get_reserved_space] ( identifier[self] ):
literal[string]
identifier[reserved_space_ratio] = literal[int]
identifier[max_reserved_space] = literal[int]
identifier[_] , identifier[height] = identifier[click] . identifier[get_terminal_size] ()
keyw... | def get_reserved_space(self):
"""Get the number of lines to reserve for the completion menu."""
reserved_space_ratio = 0.45
max_reserved_space = 8
(_, height) = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) |
def set(self, x, y, z):
"""Set x, y, and z components.
Also return self.
"""
self.x = x
self.y = y
self.z = z
return self | def function[set, parameter[self, x, y, z]]:
constant[Set x, y, and z components.
Also return self.
]
name[self].x assign[=] name[x]
name[self].y assign[=] name[y]
name[self].z assign[=] name[z]
return[name[self]] | keyword[def] identifier[set] ( identifier[self] , identifier[x] , identifier[y] , identifier[z] ):
literal[string]
identifier[self] . identifier[x] = identifier[x]
identifier[self] . identifier[y] = identifier[y]
identifier[self] . identifier[z] = identifier[z]
keywor... | def set(self, x, y, z):
"""Set x, y, and z components.
Also return self.
"""
self.x = x
self.y = y
self.z = z
return self |
def _send(self, msg):
"""
Raw send to the given connection ID at the given uuid, mostly used
internally.
"""
uuid = self.m2req.sender
conn_id = self.m2req.conn_id
header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id))
zmq_message = header + ' ' +... | def function[_send, parameter[self, msg]]:
constant[
Raw send to the given connection ID at the given uuid, mostly used
internally.
]
variable[uuid] assign[=] name[self].m2req.sender
variable[conn_id] assign[=] name[self].m2req.conn_id
variable[header] assign[=] ... | keyword[def] identifier[_send] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[uuid] = identifier[self] . identifier[m2req] . identifier[sender]
identifier[conn_id] = identifier[self] . identifier[m2req] . identifier[conn_id]
identifier[header] = literal[stri... | def _send(self, msg):
"""
Raw send to the given connection ID at the given uuid, mostly used
internally.
"""
uuid = self.m2req.sender
conn_id = self.m2req.conn_id
header = '%s %d:%s,' % (uuid, len(str(conn_id)), str(conn_id))
zmq_message = header + ' ' + msg
self.stream.... |
def build_vcf_parts(feature, genome_2bit, info=None):
"""Convert BedPe feature information into VCF part representation.
Each feature will have two VCF lines for each side of the breakpoint.
"""
base1 = genome_2bit[feature.chrom1].get(
feature.start1, feature.start1 + 1).upper()
id1 = "hydr... | def function[build_vcf_parts, parameter[feature, genome_2bit, info]]:
constant[Convert BedPe feature information into VCF part representation.
Each feature will have two VCF lines for each side of the breakpoint.
]
variable[base1] assign[=] call[call[call[name[genome_2bit]][name[feature].chrom1... | keyword[def] identifier[build_vcf_parts] ( identifier[feature] , identifier[genome_2bit] , identifier[info] = keyword[None] ):
literal[string]
identifier[base1] = identifier[genome_2bit] [ identifier[feature] . identifier[chrom1] ]. identifier[get] (
identifier[feature] . identifier[start1] , identifi... | def build_vcf_parts(feature, genome_2bit, info=None):
"""Convert BedPe feature information into VCF part representation.
Each feature will have two VCF lines for each side of the breakpoint.
"""
base1 = genome_2bit[feature.chrom1].get(feature.start1, feature.start1 + 1).upper()
id1 = 'hydra{0}a'.fo... |
def build_fake_input_fns(batch_size):
"""Builds fake data for unit testing."""
num_words = 1000
vocabulary = [str(i) for i in range(num_words)]
random_sample = np.random.randint(
10, size=(batch_size, num_words)).astype(np.float32)
def train_input_fn():
dataset = tf.data.Dataset.from_tensor_slices... | def function[build_fake_input_fns, parameter[batch_size]]:
constant[Builds fake data for unit testing.]
variable[num_words] assign[=] constant[1000]
variable[vocabulary] assign[=] <ast.ListComp object at 0x7da1b02c9330>
variable[random_sample] assign[=] call[call[name[np].random.randint,... | keyword[def] identifier[build_fake_input_fns] ( identifier[batch_size] ):
literal[string]
identifier[num_words] = literal[int]
identifier[vocabulary] =[ identifier[str] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[num_words] )]
identifier[random_sample] = i... | def build_fake_input_fns(batch_size):
"""Builds fake data for unit testing."""
num_words = 1000
vocabulary = [str(i) for i in range(num_words)]
random_sample = np.random.randint(10, size=(batch_size, num_words)).astype(np.float32)
def train_input_fn():
dataset = tf.data.Dataset.from_tensor_... |
def handle_relative(self, event):
"""Relative mouse movement."""
delta_x, delta_y = self._get_relative(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if de... | def function[handle_relative, parameter[self, event]]:
constant[Relative mouse movement.]
<ast.Tuple object at 0x7da1b088cf70> assign[=] call[name[self]._get_relative, parameter[name[event]]]
if name[delta_x] begin[:]
call[name[self].events.append, parameter[call[name[self].emula... | keyword[def] identifier[handle_relative] ( identifier[self] , identifier[event] ):
literal[string]
identifier[delta_x] , identifier[delta_y] = identifier[self] . identifier[_get_relative] ( identifier[event] )
keyword[if] identifier[delta_x] :
identifier[self] . identifier[ev... | def handle_relative(self, event):
"""Relative mouse movement."""
(delta_x, delta_y) = self._get_relative(event)
if delta_x:
self.events.append(self.emulate_rel(0, delta_x, self.timeval)) # depends on [control=['if'], data=[]]
if delta_y:
self.events.append(self.emulate_rel(1, delta_y, s... |
def get_rarity_info(self, rarity: str):
"""Returns card info from constants
Parameters
---------
rarity: str
A rarity name
Returns None or Constants
"""
for c in self.constants.rarities:
if c.name == rarity:
return c | def function[get_rarity_info, parameter[self, rarity]]:
constant[Returns card info from constants
Parameters
---------
rarity: str
A rarity name
Returns None or Constants
]
for taget[name[c]] in starred[name[self].constants.rarities] begin[:]
... | keyword[def] identifier[get_rarity_info] ( identifier[self] , identifier[rarity] : identifier[str] ):
literal[string]
keyword[for] identifier[c] keyword[in] identifier[self] . identifier[constants] . identifier[rarities] :
keyword[if] identifier[c] . identifier[name] == identifier[... | def get_rarity_info(self, rarity: str):
"""Returns card info from constants
Parameters
---------
rarity: str
A rarity name
Returns None or Constants
"""
for c in self.constants.rarities:
if c.name == rarity:
return c # depends on [contro... |
def get_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] | def function[get_tags, parameter[self, tagtype]]:
constant[ Get all tags of a type ]
return[<ast.ListComp object at 0x7da1b1131c60>] | keyword[def] identifier[get_tags] ( identifier[self] , identifier[tagtype] ):
literal[string]
keyword[return] [ identifier[t] keyword[for] identifier[t] keyword[in] identifier[self] . identifier[__tags] keyword[if] identifier[t] . identifier[tagtype] == identifier[tagtype] ] | def get_tags(self, tagtype):
""" Get all tags of a type """
return [t for t in self.__tags if t.tagtype == tagtype] |
def _read_addr_resolve(self, length, htype):
"""Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address
"""
if htype == 1: # Ether... | def function[_read_addr_resolve, parameter[self, length, htype]]:
constant[Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address
]
... | keyword[def] identifier[_read_addr_resolve] ( identifier[self] , identifier[length] , identifier[htype] ):
literal[string]
keyword[if] identifier[htype] == literal[int] :
identifier[_byte] = identifier[self] . identifier[_read_fileng] ( literal[int] )
identifier[_addr] = ... | def _read_addr_resolve(self, length, htype):
"""Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address
"""
if htype == 1: # Ethernet
... |
def discrete(self, vertices, scale=1.0):
"""
Discretize the arc entity into line sections.
Parameters
------------
vertices : (n, dimension) float
Points in space
scale : float
Size of overall scene for numerical comparisons
Returns
... | def function[discrete, parameter[self, vertices, scale]]:
constant[
Discretize the arc entity into line sections.
Parameters
------------
vertices : (n, dimension) float
Points in space
scale : float
Size of overall scene for numerical comparisons... | keyword[def] identifier[discrete] ( identifier[self] , identifier[vertices] , identifier[scale] = literal[int] ):
literal[string]
identifier[discrete] = identifier[discretize_arc] ( identifier[vertices] [ identifier[self] . identifier[points] ],
identifier[close] = identifier[self] . ident... | def discrete(self, vertices, scale=1.0):
"""
Discretize the arc entity into line sections.
Parameters
------------
vertices : (n, dimension) float
Points in space
scale : float
Size of overall scene for numerical comparisons
Returns
-... |
def serialize_training_step(features, model_fn, batch_dim, num_splits):
"""Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary ... | def function[serialize_training_step, parameter[features, model_fn, batch_dim, num_splits]]:
constant[Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microb... | keyword[def] identifier[serialize_training_step] ( identifier[features] , identifier[model_fn] , identifier[batch_dim] , identifier[num_splits] ):
literal[string]
keyword[for] identifier[v] keyword[in] identifier[features] . identifier[values] ():
identifier[mesh] = identifier[v] . identifier[mesh]
... | def serialize_training_step(features, model_fn, batch_dim, num_splits):
"""Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionar... |
def python_lib_rpm_dirs(self):
"""Both arch and non-arch site-packages directories."""
libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir]
def append_rpm(path):
return os.path.join(path, 'rpm')
return map(append_rpm, libs) | def function[python_lib_rpm_dirs, parameter[self]]:
constant[Both arch and non-arch site-packages directories.]
variable[libs] assign[=] list[[<ast.Attribute object at 0x7da1b04d98a0>, <ast.Attribute object at 0x7da1b04da500>]]
def function[append_rpm, parameter[path]]:
return[call[name[... | keyword[def] identifier[python_lib_rpm_dirs] ( identifier[self] ):
literal[string]
identifier[libs] =[ identifier[self] . identifier[python_lib_arch_dir] , identifier[self] . identifier[python_lib_non_arch_dir] ]
keyword[def] identifier[append_rpm] ( identifier[path] ):
keyw... | def python_lib_rpm_dirs(self):
"""Both arch and non-arch site-packages directories."""
libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir]
def append_rpm(path):
return os.path.join(path, 'rpm')
return map(append_rpm, libs) |
def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] | def function[metrics, parameter[self]]:
constant[ Set of metrics for this model ]
from relative_module[vel.metrics.loss_metric] import module[Loss]
from relative_module[vel.metrics.accuracy] import module[Accuracy]
return[list[[<ast.Call object at 0x7da1b1603370>, <ast.Call object at 0x7da1b1603250>... | keyword[def] identifier[metrics] ( identifier[self] ):
literal[string]
keyword[from] identifier[vel] . identifier[metrics] . identifier[loss_metric] keyword[import] identifier[Loss]
keyword[from] identifier[vel] . identifier[metrics] . identifier[accuracy] keyword[import] identifier... | def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] |
def add_mongo_config_with_uri(app, connection_string_uri,
database_name, collection_name):
"""
Configure PyMongo with a MongoDB connection string.
:param app: Flask application
:param connection_string_uri: MongoDB connection string
:param database_name: Sacred databas... | def function[add_mongo_config_with_uri, parameter[app, connection_string_uri, database_name, collection_name]]:
constant[
Configure PyMongo with a MongoDB connection string.
:param app: Flask application
:param connection_string_uri: MongoDB connection string
:param database_name: Sacred databa... | keyword[def] identifier[add_mongo_config_with_uri] ( identifier[app] , identifier[connection_string_uri] ,
identifier[database_name] , identifier[collection_name] ):
literal[string]
identifier[app] . identifier[config] [ literal[string] ]= identifier[PyMongoDataAccess] . identifier[build_data_access_with_... | def add_mongo_config_with_uri(app, connection_string_uri, database_name, collection_name):
"""
Configure PyMongo with a MongoDB connection string.
:param app: Flask application
:param connection_string_uri: MongoDB connection string
:param database_name: Sacred database name
:param collection_n... |
def visitTripleConstraint(self, ctx: ShExDocParser.TripleConstraintContext):
""" tripleConstraint: senseFlags? predicate inlineShapeExpression cardinality? annotation* semanticActions """
# This exists because of the predicate within annotation - if we default to visitchildren, we intercept both
... | def function[visitTripleConstraint, parameter[self, ctx]]:
constant[ tripleConstraint: senseFlags? predicate inlineShapeExpression cardinality? annotation* semanticActions ]
if call[name[ctx].senseFlags, parameter[]] begin[:]
call[name[self].visit, parameter[call[name[ctx].senseFlags, pa... | keyword[def] identifier[visitTripleConstraint] ( identifier[self] , identifier[ctx] : identifier[ShExDocParser] . identifier[TripleConstraintContext] ):
literal[string]
keyword[if] identifier[ctx] . identifier[senseFlags] ():
identifier[self] . identifier[visit] ( id... | def visitTripleConstraint(self, ctx: ShExDocParser.TripleConstraintContext):
""" tripleConstraint: senseFlags? predicate inlineShapeExpression cardinality? annotation* semanticActions """
# This exists because of the predicate within annotation - if we default to visitchildren, we intercept both
# predicate... |
def get_window_pos(window):
"""
Retrieves the position of the client area of the specified window.
Wrapper for:
void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos =... | def function[get_window_pos, parameter[window]]:
constant[
Retrieves the position of the client area of the specified window.
Wrapper for:
void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
]
variable[xpos_value] assign[=] call[name[ctypes].c_int, parameter[constant[0]... | keyword[def] identifier[get_window_pos] ( identifier[window] ):
literal[string]
identifier[xpos_value] = identifier[ctypes] . identifier[c_int] ( literal[int] )
identifier[xpos] = identifier[ctypes] . identifier[pointer] ( identifier[xpos_value] )
identifier[ypos_value] = identifier[ctypes] . ide... | def get_window_pos(window):
"""
Retrieves the position of the client area of the specified window.
Wrapper for:
void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos =... |
def _setup_locale(self, locale: str = locales.DEFAULT_LOCALE) -> None:
"""Set up locale after pre-check.
:param str locale: Locale
:raises UnsupportedLocale: When locale is not supported.
:return: Nothing.
"""
if not locale:
locale = locales.DEFAULT_LOCALE
... | def function[_setup_locale, parameter[self, locale]]:
constant[Set up locale after pre-check.
:param str locale: Locale
:raises UnsupportedLocale: When locale is not supported.
:return: Nothing.
]
if <ast.UnaryOp object at 0x7da20e9b2020> begin[:]
variabl... | keyword[def] identifier[_setup_locale] ( identifier[self] , identifier[locale] : identifier[str] = identifier[locales] . identifier[DEFAULT_LOCALE] )-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[locale] :
identifier[locale] = identifier[locales] . identifier[... | def _setup_locale(self, locale: str=locales.DEFAULT_LOCALE) -> None:
"""Set up locale after pre-check.
:param str locale: Locale
:raises UnsupportedLocale: When locale is not supported.
:return: Nothing.
"""
if not locale:
locale = locales.DEFAULT_LOCALE # depends on [c... |
def get_parameter_dd(self, parameter):
"""
This method returns parameters as nested dicts in case of decision
diagram parameter.
"""
dag = defaultdict(list)
dag_elem = parameter.find('DAG')
node = dag_elem.find('Node')
root = node.get('var')
def g... | def function[get_parameter_dd, parameter[self, parameter]]:
constant[
This method returns parameters as nested dicts in case of decision
diagram parameter.
]
variable[dag] assign[=] call[name[defaultdict], parameter[name[list]]]
variable[dag_elem] assign[=] call[name[para... | keyword[def] identifier[get_parameter_dd] ( identifier[self] , identifier[parameter] ):
literal[string]
identifier[dag] = identifier[defaultdict] ( identifier[list] )
identifier[dag_elem] = identifier[parameter] . identifier[find] ( literal[string] )
identifier[node] = identifier[... | def get_parameter_dd(self, parameter):
"""
This method returns parameters as nested dicts in case of decision
diagram parameter.
"""
dag = defaultdict(list)
dag_elem = parameter.find('DAG')
node = dag_elem.find('Node')
root = node.get('var')
def get_param(node):
... |
def _configMailer(self):
""" Config Mailer Class """
self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT)
self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) | def function[_configMailer, parameter[self]]:
constant[ Config Mailer Class ]
name[self]._MAILER assign[=] call[name[Mailer], parameter[name[self].MAILER_HOST, name[self].MAILER_PORT]]
call[name[self]._MAILER.login, parameter[name[self].MAILER_USER, name[self].MAILER_PWD]] | keyword[def] identifier[_configMailer] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_MAILER] = identifier[Mailer] ( identifier[self] . identifier[MAILER_HOST] , identifier[self] . identifier[MAILER_PORT] )
identifier[self] . identifier[_MAILER] . identifier[login] ( ... | def _configMailer(self):
""" Config Mailer Class """
self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT)
self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) |
def select(self, attr, default=None):
"""
Select a given attribute (or chain or attributes) from the objects within the
list.
Args:
attr (str): attributes to be selected (with initial `.` omitted)
default (any): value to return if given element in list doesn't co... | def function[select, parameter[self, attr, default]]:
constant[
Select a given attribute (or chain or attributes) from the objects within the
list.
Args:
attr (str): attributes to be selected (with initial `.` omitted)
default (any): value to return if given elem... | keyword[def] identifier[select] ( identifier[self] , identifier[attr] , identifier[default] = keyword[None] ):
literal[string]
keyword[return] identifier[List] ([ identifier[_select] ( identifier[item] , identifier[attr] , identifier[default] ) keyword[for] identifier[item] keyword[in] identifi... | def select(self, attr, default=None):
"""
Select a given attribute (or chain or attributes) from the objects within the
list.
Args:
attr (str): attributes to be selected (with initial `.` omitted)
default (any): value to return if given element in list doesn't contai... |
def plugin_info(self):
"""
Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations.
:rtype: yagocd.resources.plugin_info.PluginInfoManager
"""
if self._plugin_info_manager is None:
self._plugin_info_manager = Plugin... | def function[plugin_info, parameter[self]]:
constant[
Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations.
:rtype: yagocd.resources.plugin_info.PluginInfoManager
]
if compare[name[self]._plugin_info_manager is constant[None... | keyword[def] identifier[plugin_info] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_plugin_info_manager] keyword[is] keyword[None] :
identifier[self] . identifier[_plugin_info_manager] = identifier[PluginInfoManager] ( identifier[session] = identifi... | def plugin_info(self):
"""
Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations.
:rtype: yagocd.resources.plugin_info.PluginInfoManager
"""
if self._plugin_info_manager is None:
self._plugin_info_manager = PluginInfoManager(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.