code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
node.set_attr(key, value) | def call_set_attr(node: Node, key: str, value) | Calls node setter | 8.711303 | 5.010325 | 1.73867 |
for xml_node in node.xml_node.children:
child = render(xml_node, **child_args)
node.add_child(child) | def render_children(node: Node, **child_args) | Render node children | 4.749544 | 3.46482 | 1.370791 |
columns = set()
for values in self._parts:
for value in values._parts:
columns.add(value.column_name)
return sorted(columns) | def all_columns(self) | Return list of all columns. | 5.203025 | 4.416999 | 1.177955 |
while fn is not None:
if hasattr(fn, '_schema_annotation'):
return fn._schema_annotation
fn = getattr(fn, 'im_func', fn)
closure = getattr(fn, '__closure__', None)
fn = closure[0].cell_contents if closure is not None else None
retu... | def get_annotation(cls, fn) | Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
... | 3.256061 | 2.683458 | 1.213382 |
# We allow additional properties because the data this will validate
# may also include kwargs passed by decorators on the handler method.
schema = {'additionalProperties': True,
'definitions': self.resolve('#/definitions'),
'properties': {},
... | def _create_request_schema(self, params, required) | Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema... | 7.026796 | 7.058224 | 0.995547 |
if note_id != 1:
raise NotFoundError('Note does not exist')
new_note = note.copy()
if body is not None:
new_note['body'] = body
if done is not None:
new_note['done'] = done
return new_note | def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note | Update an existing note. | 2.594123 | 2.437672 | 1.064181 |
from google.appengine.api.taskqueue import Task
task_args = self.get_task_args().copy()
payload = None
if 'payload' in task_args:
payload = task_args.pop('payload')
kwargs = {
'method': METHOD_TYPE,
'payload': json.dumps(payload)
... | def to_task(self) | Return a task object representing this message. | 3.729256 | 3.379547 | 1.103478 |
from google.appengine.api.taskqueue import Queue
task = self.to_task()
Queue(name=self.get_queue()).add(task) | def insert(self) | Insert the pull task into the requested queue, 'default' if non
given. | 6.192315 | 4.902946 | 1.262978 |
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
return options | def to_dict(self) | Return this message as a dict suitable for json encoding. | 5.983888 | 5.036451 | 1.188116 |
id = self._options.get('id')
if id:
return id
id = uuid.uuid4().hex
self.update_options(id=id)
return id | def _get_id(self) | If this message has no id, generate one. | 4.010133 | 3.137944 | 1.277949 |
message_options = message.copy()
# JSON don't like datetimes.
eta = message_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
message_options['task_args']['eta'] = datetime.fromtimestamp(eta)
return Message(**messag... | def from_dict(cls, message) | Return an message from a dict output by Async.to_dict. | 5.702522 | 4.986753 | 1.143534 |
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if not 'countdown' in task_args:
task_args['countdown'] = self.frequency
... | def to_task(self) | Return a task object representing this MessageProcessor job. | 4.860744 | 4.33353 | 1.121659 |
current_batch = memcache.get(self.group_key)
if not current_batch:
memcache.add(self.group_key, 1)
current_batch = 1
return current_batch | def current_batch(self) | Return the batch id for the tag.
:return: :class: `int` current batch id | 3.740505 | 4.239516 | 0.882295 |
if self._fetched:
return
start = time.time()
loaded_messages = self.queue.lease_tasks_by_tag(
self.duration, self.size, tag=self.tag, deadline=self.deadline)
# If we are within 0.1 sec of our deadline and no messages were
# returned, then we ar... | def fetch_messages(self) | Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages. | 5.631218 | 5.339721 | 1.05459 |
if not self._messages:
if self.auto_delete:
self.delete_messages()
raise StopIteration
message = self._messages.pop(0)
self._processed_messages.append(message)
return json.loads(message.payload) | def next(self) | Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration. | 3.739809 | 2.669783 | 1.400792 |
messages = self._processed_messages
if not only_processed:
messages += self._messages
if messages:
try:
self.queue.delete_tasks(messages)
except Exception:
logging.exception("Error deleting messages")
r... | def delete_messages(self, only_processed=True) | Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted. | 4.737159 | 5.262283 | 0.90021 |
copied = types.FunctionType(
func.__code__, func.__globals__, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
copied = functools.update_wrapper(copied, func)
copied.__kwdefaults__ = func.__kwdefaults__
return copied | def copy_func(func: Callable) -> Callable | Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function. | 2.080627 | 2.523115 | 0.824626 |
if signature is None:
# Check if the function already parsed the signature
signature = getattr(func, '_doctor_signature', None)
# Otherwise parse the signature
if signature is None:
signature = inspect.signature(func)
# Check if a `req_obj_type` was provided for... | def get_params_from_func(func: Callable, signature: Signature=None) -> Params | Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters. | 4.49203 | 4.505933 | 0.996914 |
# If we've already added param annotations to this function get the
# values from the logic, otherwise we need to inspect it.
if hasattr(logic, '_doctor_signature'):
sig = logic._doctor_signature
doctor_params = logic._doctor_params
else:
sig = inspect.signature(logic)
... | def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable | Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter an... | 2.959218 | 2.957075 | 1.000725 |
if namespace is None:
namespace = {}
module_filename = os.path.abspath(module_filename)
namespace['__file__'] = module_filename
module_dir = os.path.dirname(module_filename)
old_cwd = os.getcwd()
old_sys_path = sys.path[:]
try:
os.chdir(module_dir)
sys.path.appen... | def get_module_attr(module_filename, module_attr, namespace=None) | Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sp... | 1.735152 | 1.934997 | 0.896721 |
if prepare_docstring is None:
raise ImportError('sphinx must be installed to use this function.')
if not isinstance(docstring, str):
return []
lines = []
for line in prepare_docstring(docstring):
if DESCRIPTION_END_RE.match(line):
break
lines.append(line... | def get_description_lines(docstring) | Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list | 3.538392 | 3.942253 | 0.897556 |
s = str(s).strip()
s = ''.join([w.title() for w in re.split(r'\W+|_', s)])
return re.sub(r'[^\w|_]', '', s) | def get_valid_class_name(s: str) -> str | Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string... | 4.565706 | 3.972219 | 1.14941 |
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
execution_context = _ExecutionContext(async)
local_context._executing_async_context = execution_context
return execution_context | def execution_context_from_async(async) | Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier. | 4.109214 | 3.922176 | 1.047687 |
return self._cli.get_session(self._new_sessions(), command_mode, self._logger) | def get_cli_service(self, command_mode) | Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager | 13.162377 | 13.957798 | 0.943012 |
# getting symmetry datasets for both crystals
cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
cryst_b = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_b), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
samecell = np.allcl... | def check_crystal_equivalence(crystal_a, crystal_b) | Function that identifies whether two crystals are equivalent | 2.666692 | 2.67846 | 0.995606 |
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info)
info = 'Line {0} in "{1}"'.forma... | def add_view_info(self, view_info: ViewInfo) | Adds view information to error message | 3.855979 | 3.250039 | 1.186441 |
'''Adds "header: message" line to error message'''
current_message = self.args[0]
message = current_message + self._format_info(header, message)
self.args = (message,) + self.args[1:] | def add_info(self, header, message) | Adds "header: message" line to error message | 4.981882 | 3.81111 | 1.3072 |
'''Adds cause error to error message'''
self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error)) | def add_cause(self, error: Exception) | Adds cause error to error message | 8.384279 | 5.137393 | 1.63201 |
async_options = json.loads(request_body)
async = async_from_options(async_options)
_log_task_info(headers,
extra_task_info=async.get_options().get('_extra_task_info'))
logging.info(async._function_path)
with context.execution_context_from_async(async):
run_job()
... | def process_async_task(headers, request_body) | Process an Async task and execute the requested function. | 7.429008 | 7.102493 | 1.045972 |
ran_at = time.time()
task_eta = float(headers.get('X-Appengine-Tasketa', 0.0))
task_info = {
'retry_count': headers.get('X-Appengine-Taskretrycount', ''),
'execution_count': headers.get('X-Appengine-Taskexecutioncount', ''),
'task_eta': task_eta,
'ran': ran_at,
'... | def _log_task_info(headers, extra_task_info=None) | Processes the header from task requests to log analytical data. | 2.88796 | 2.853771 | 1.01198 |
url = UrlParser.parse_url(path)
required_keys = [UrlParser.FILENAME, UrlParser.HOSTNAME, UrlParser.SCHEME]
if not url or not all(key in url for key in required_keys):
raise Exception(self.__class__.__name__, "Path is wrong or empty")
self.load_firmware_flow.execut... | def load_firmware(self, path, vrf_management_name=None) | Update firmware version on device by loading provided image, performs following steps:
1. Copy bin file from remote tftp server.
2. Clear in run config boot system section.
3. Set downloaded bin file as boot file and then reboot device.
4. Check if firmware was successfu... | 6.116242 | 5.869434 | 1.04205 |
if not ports:
return []
return [tuple(port_pair.split("::")) for port_pair in ports.strip(";").split(";")] | def _parse_ports(self, ports) | Parse ports string into the list
:param str ports:
:rtype: list[tuple[str, str]] | 6.625718 | 4.898314 | 1.352653 |
ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | def add_trunk_ports(self) | SDN Controller enable trunk ports
:rtype: list[tuple[str, str]] | 13.932024 | 11.363631 | 1.226019 |
ports = self.attributes.get("{}Disable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | def remove_trunk_ports(self) | SDN Controller disable trunk ports
:rtype: list[tuple[str, str]] | 15.488256 | 12.565025 | 1.232648 |
import os
from furious.context import get_current_async
async = get_current_async()
async_exception = async.result.payload
exc_info = async_exception.traceback
logging.info('async job blew up, exception info: %r', exc_info)
retries = int(os.environ['HTTP_X_APPENGINE_TASKRETRYCOUNT'])... | def handle_an_error() | Will be run if the async task raises an unhandled exception. | 6.846241 | 6.329746 | 1.081598 |
result = {}
for resource_prefix, resources in autoload_resource.iteritems():
max_free_index = max(map(int, resources)) + 1 or 1
for index, sub_resources in resources.iteritems():
if not index or index == -1:
index = max_free_index
... | def _validate_build_resource_structure(autoload_resource) | Validate resource structure
:param dict autoload_resource:
:return correct autoload resource structure
:rtype: dict | 2.512262 | 2.479456 | 1.013231 |
self._autoload_details.attributes.extend([AutoLoadAttribute(relative_address=relative_path,
attribute_name=attribute_name,
attribute_value=attribute_value)
... | def _build_autoload_details(self, autoload_data, relative_path="") | Build autoload details
:param autoload_data: dict:
:param relative_path: str: full relative path of current autoload resource | 3.168127 | 3.103344 | 1.020875 |
self.attr_setter(self, key, value) | def set_attr(self, key: str, value) | Sets node attribute. Can be customized by attr_setter property | 13.851555 | 4.862079 | 2.848896 |
binding.add_error_info = lambda error: error.add_view_info(self._xml_node.view_info)
self._bindings.append(binding) | def add_binding(self, binding: Binding) | Stores binding | 10.74502 | 9.398614 | 1.143256 |
self.destroy_children()
self.destroy_bindings()
if self.on_destroy:
self.on_destroy(self) | def destroy(self) | Destroys node | 4.117211 | 4.066704 | 1.01242 |
self._value = self._setter(self._node, value, self._value) if self._setter else value | def set(self, value) | Sets value | 8.88496 | 9.368427 | 0.948394 |
return Property(self.name, self._setter, node) | def new(self, node: Node) | Creates property for node | 32.560982 | 14.062435 | 2.315458 |
# reshape
if len(r.shape) == 2:
idx = (np.tri(N=r.shape[0], k=-1) == 1)
r = r[idx]
pval = pval[idx]
# indicies for the three groups
i1 = (pval >= plim)
i2 = (pval < plim) & (np.abs(r) > rlim)
i3 = (pval < plim) & (np.abs(r) <= rlim)
# plot paramters
absmax ... | def corr_vs_pval(r, pval, plim=0.01, rlim=0.4, dpi=96) | Histogram for correlation coefficients and its p-values (colored)
Parameters:
-----------
r : np.ndarray
Correlation coefficient matrix.
The upper triangular elements are extracted if a NxN is provided.
Otherwise provide a plain vector.
pval : np.ndarray
NxN matrix with... | 2.805286 | 2.760824 | 1.016105 |
return cls(address=context.resource.address,
family=context.resource.family,
shell_type=shell_type,
shell_name=shell_name,
fullname=context.resource.fullname,
attributes=dict(context.resource.attributes),
... | def from_context(cls, context, shell_type=None, shell_name=None) | Create an instance of TrafficGeneratorVBladeResource from the given context
:param cloudshell.shell.core.driver_context.ResourceCommandContext context:
:param str shell_type: shell type
:param str shell_name: shell name
:rtype: TrafficGeneratorVChassisResource | 3.109868 | 3.040461 | 1.022828 |
if user is not None:
if not user.id:
return None
d['user'] = user
if status is not None:
d['status'] = status | def update_filter_dict(d, user, status) | Helper. Updates filter dict for a queryset.
:param dict d:
:param User|None user:
:param int|None status:
:return: | 3.064247 | 4.117101 | 0.744273 |
return get_model_class_from_string(MODEL_FLAG).get_flags_for_types(
mdl_classes, user=user, status=status, allow_empty=allow_empty) | def get_flags_for_types(cls, mdl_classes, user=None, status=None, allow_empty=True) | Returns a dictionary with flag objects associated with the given model classes (types).
The dictionary is indexed by model classes.
Each dict entry contains a list of associated flag objects.
:param list mdl_classes:
:param User user:
:param int status:
:param bool allow... | 3.754662 | 4.672013 | 0.80365 |
return get_model_class_from_string(MODEL_FLAG).get_flags_for_objects(objects_list, user=user, status=status) | def get_flags_for_objects(cls, objects_list, user=None, status=None) | Returns a dictionary with flag objects associated with the given model objects.
The dictionary is indexed by objects IDs.
Each dict entry contains a list of associated flag objects.
:param list, QuerySet objects_list:
:param User user:
:param int status:
:rtype: dict | 4.778737 | 5.841902 | 0.81801 |
filter_kwargs = {}
update_filter_dict(filter_kwargs, user, status)
return self.flags.filter(**filter_kwargs).all() | def get_flags(self, user=None, status=None) | Returns flags for the object optionally filtered by status.
:param User user: Optional user filter
:param int status: Optional status filter
:rtype: QuerySet | 4.746035 | 5.898697 | 0.80459 |
if not user.id:
return None
init_kwargs = {
'user': user,
'linked_object': self,
}
if note is not None:
init_kwargs['note'] = note
if status is not None:
init_kwargs['status'] = status
flag = get_flag_... | def set_flag(self, user, note=None, status=None) | Flags the object.
:param User user:
:param str note: User-defined note for this flag.
:param int status: Optional status integer (the meaning is defined by a developer).
:return: | 2.929861 | 3.149738 | 0.930192 |
filter_kwargs = {
'content_type': ContentType.objects.get_for_model(self),
'object_id': self.id
}
update_filter_dict(filter_kwargs, user, status)
get_flag_model().objects.filter(**filter_kwargs).delete() | def remove_flag(self, user=None, status=None) | Removes flag(s) from the object.
:param User user: Optional user filter
:param int status: Optional status filter
:return: | 2.87939 | 3.321898 | 0.866791 |
filter_kwargs = {
'content_type': ContentType.objects.get_for_model(self),
'object_id': self.id,
}
update_filter_dict(filter_kwargs, user, status)
return self.flags.filter(**filter_kwargs).count() | def is_flagged(self, user=None, status=None) | Returns boolean whether the objects is flagged by a user.
:param User user: Optional user filter
:param int status: Optional status filter
:return: | 2.896855 | 3.29957 | 0.877949 |
new_backend = BACKENDS.get(database.lower())
if not new_backend:
raise Exception('Backend {} is not supported.'.format(database))
global BACKEND # pylint: disable=global-statement
BACKEND = new_backend | def set_backend(database) | Configure used database, so sqlpuzzle can generate queries which are needed.
For now there is only support of MySQL and PostgreSQL. | 2.989148 | 2.80548 | 1.065468 |
api_response = 'Online'
result = 'Health check on resource {}'.format(self._resource_name)
try:
health_check_flow = RunCommandFlow(self.cli_handler, self._logger)
health_check_flow.execute_flow()
result += ' passed.'
except Exception as e:
... | def health_check(self) | Verify that device is accessible over CLI by sending ENTER for cli session | 5.124693 | 4.761517 | 1.076273 |
from sqlpuzzle._common.utils import force_text
value = force_text(value)
parts = re.split(r'{quote}([^{quote}]+){quote}|\.'.format(quote=cls.reference_quote), value)
parts = ('{quote}{i}{quote}'.format(quote=cls.reference_quote, i=i) if i != '*' else i for i in parts if i)
... | def reference(cls, value) | Convert as reference on column.
table => "table"
table.column => "table"."column"
db.table.column => "db"."table"."column"
table."col.umn" => "table"."col.umn"
"table"."col.umn" => "table"."col.umn" | 4.496825 | 4.624418 | 0.972409 |
# Try to pop the options off whatever they passed in.
if isinstance(reference, basestring):
# This is an object path name in str form.
import re
if not re.match(r'^[^\d\W]([a-zA-Z._]|((?<!\.)\d))+$', reference):
raise errors.BadObjectPathError(
'Invalid r... | def reference_to_path(reference) | Convert a reference to a Python object to a string path. | 4.345597 | 4.248584 | 1.022834 |
# By default JSON decodes strings as unicode. The Python __import__ does
# not like that choice. So we'll just cast all function paths to a string.
# NOTE: that there is no corresponding unit test for the classmethod
# version of this problem. It only impacts importing modules.
path = str(pat... | def path_to_reference(path) | Convert an object path reference to a reference. | 3.718243 | 3.642852 | 1.020696 |
from furious.async import Async
if not callbacks:
return
encoded_callbacks = {}
for event, callback in callbacks.iteritems():
if callable(callback):
callback, _ = get_function_path_and_options(callback)
elif isinstance(callback, Async):
callback = ... | def encode_callbacks(callbacks) | Encode callbacks to as a dict suitable for JSON encoding. | 4.280456 | 3.903448 | 1.096583 |
from furious.async import Async
callbacks = {}
for event, callback in encoded_callbacks.iteritems():
if isinstance(callback, dict):
async_type = Async
if '_type' in callback:
async_type = path_to_reference(callback['_type'])
callback = async_... | def decode_callbacks(encoded_callbacks) | Decode the callbacks to an executable form. | 3.4444 | 3.343328 | 1.030231 |
if current is not None:
stack = stack + [current]
if len(stack) > 1:
prefix = os.path.commonprefix(stack)
if prefix.endswith('/'):
prefix = prefix[:-1]
stack = [scope[len(prefix):] for scope in stack]
return ' => '.join(sta... | def _format_stack(self, stack, current=None) | Prettifies a scope stack for use in error messages.
:param list(str) stack: List of scopes.
:param str current: The current scope. If specified, will be appended
onto the stack before formatting.
:returns: str | 3.10791 | 3.133924 | 0.991699 |
try:
# This logic is basically the RefResolver's resolve function, but
# updated to support fragments of dynamic documents. The jsonschema
# module supports passing documents when resolving fragments, but
# it doesn't expose that capability in the resolve... | def resolve(self, ref, document=None) | Resolve a fragment within the schema.
If the resolved value contains a $ref, it will attempt to resolve that
as well, until it gets something that is not a reference. Circular
references will raise a SchemaError.
:param str ref: URI to resolve.
:param dict document: Optional sc... | 4.704074 | 4.490754 | 1.047502 |
if uri.startswith('file://'):
try:
path = uri[7:]
with open(path, 'r') as schema_file:
result = yaml.load(schema_file)
if self.cache_remote:
self.store[uri] = result
return result
... | def resolve_remote(self, uri) | Add support to load YAML files.
This will attempt to load a YAML file first, and then go back to the
default behavior.
:param str uri: the URI to resolve
:returns: the retrieved document | 3.247119 | 3.252033 | 0.998489 |
schema = schema if schema is not None else self.schema
return jsonschema.Draft4Validator(
schema, resolver=self.resolver,
format_checker=jsonschema.draft4_format_checker) | def get_validator(self, schema=None) | Get a jsonschema validator.
:param dict schema: A custom schema to validate against.
:returns: an instance of jsonschema Draft4Validator. | 2.87979 | 3.269221 | 0.88088 |
_, resolved = self.resolver.resolve(ref, document=document)
return resolved | def resolve(self, ref, document=None) | Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:retu... | 6.47753 | 6.733629 | 0.961967 |
if self._resolver is not None:
return self._resolver
if self._schema_path is not None:
# the documentation for ref resolving
# https://github.com/Julian/jsonschema/issues/98
# https://python-jsonschema.readthedocs.org/en/latest/references/
... | def resolver(self) | jsonschema RefResolver object for the base schema. | 3.720131 | 3.153454 | 1.1797 |
try:
validator.validate(value)
except Exception as e:
logging.debug(e, exc_info=e)
if isinstance(e, DoctorError):
raise
else:
# Gather all the validation errors
validation_errors = sorted(
... | def validate(self, value, validator) | Validates and returns the value.
If the value does not validate against the schema, SchemaValidationError
will be raised.
:param value: A value to validate (usually a dict).
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().... | 3.662228 | 3.660855 | 1.000375 |
value = parse_json(json_value)
return self.validate(value, validator) | def validate_json(self, json_value, validator) | Validates and returns the parsed JSON string.
If the value is not valid JSON, ParseError will be raised. If it is
valid JSON, but does not validate against the schema,
SchemaValidationError will be raised.
:param str json_value: JSON value.
:param validator: An instance of a js... | 5.713361 | 11.137897 | 0.512966 |
schema_filepath = os.path.abspath(schema_filepath)
try:
with open(schema_filepath, 'r') as schema_file:
schema = yaml.load(schema_file.read())
except Exception:
msg = 'Error loading schema file {}'.format(schema_filepath)
logging.excep... | def from_file(cls, schema_filepath, *args, **kwargs) | Create an instance from a YAML or JSON schema file.
Any additional args or kwargs will be passed on when constructing the
new schema instance (useful for subclasses).
:param str schema_filepath: Path to the schema file.
:returns: an instance of the class.
:raises SchemaLoadingE... | 2.184869 | 2.397162 | 0.91144 |
responses = []
if isinstance(custom_command, str):
commands = [custom_command]
elif isinstance(custom_command, tuple):
commands = list(custom_command)
else:
commands = custom_command
if is_config:
mode = self._cli_handler... | def execute_flow(self, custom_command="", is_config=False) | Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output | 2.929566 | 2.829466 | 1.035378 |
return self.run_command_flow.execute_flow(custom_command=custom_command, is_config=True) | def run_custom_config_command(self, custom_command) | Execute custom command in configuration mode on device
:param custom_command: command
:return: result of command execution | 8.50456 | 11.437228 | 0.743586 |
'''
Parses a url like this rethinkdb://server1:port,server2:port/database/table
Returns:
tuple `(['server1:port', 'server2:port'], database, table)`
`table` and `database` may be None
Raises:
ValueError if url cannot be parsed as a rethinkdb url
There is some precedent for... | def parse_rethinkdb_url(s) | Parses a url like this rethinkdb://server1:port,server2:port/database/table
Returns:
tuple `(['server1:port', 'server2:port'], database, table)`
`table` and `database` may be None
Raises:
ValueError if url cannot be parsed as a rethinkdb url
There is some precedent for this kind o... | 4.950904 | 1.713267 | 2.889745 |
_type = options.pop('_type', 'furious.async.Async')
_type = path_to_reference(_type)
return _type.from_dict(options) | def async_from_options(options) | Deserialize an Async or Async subclass from an options dict. | 10.365721 | 7.388123 | 1.403025 |
options = copy.deepcopy(async._options)
options['_type'] = reference_to_path(async.__class__)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
callbacks = async._options.get('callbacks')
... | def encode_async_options(async) | Encode Async options for JSON encoding. | 3.622284 | 3.542919 | 1.022401 |
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = datetime.fromtimestamp(eta)
# If there are callbacks, reconstitute them.
callb... | def decode_async_options(options) | Decode Async options from JSON decoding. | 3.636681 | 3.545109 | 1.02583 |
_check_options(options)
def real_decorator(function):
function._async_options = options
@wraps(function)
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
return real_decorator | def defaults(**options) | Set default Async options on the function decorated.
Note: you must pass the decorated function by reference, not as a
"path.string.to.function" for this to have any effect. | 3.493774 | 3.328447 | 1.049671 |
self._prepare_persistence_engine()
return self._persistence_engine.store_async_result(
self.id, self.result) | def _persist_result(self) | Store this Async's result in persistent storage. | 11.584138 | 7.350447 | 1.575977 |
from furious.context import get_current_async
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0)
max_depth = recursion_options.get('max', MAX_DEPTH)
try:
executing_async = get_current_async()
... | def _initialize_recursion_depth(self) | Ensure recursion info is initialized, if not, initialize it. | 4.745171 | 4.518474 | 1.050171 |
from furious.async import MAX_DEPTH
recursion_options = self._options.get('_recursion', {})
max_depth = recursion_options.get('max', MAX_DEPTH)
# Check if recursion check has been disabled, then check depth.
if (max_depth != DISABLE_RECURSION_CHECK and
... | def check_recursion_depth(self) | Check recursion depth, raise AsyncRecursionError if too deep. | 6.51446 | 5.334589 | 1.221174 |
target_path, options = get_function_path_and_options(target)
assert isinstance(args, (tuple, list)) or args is None
assert isinstance(kwargs, dict) or kwargs is None
if options:
self.update_options(**options)
self._options['job'] = (target_path, args, kwar... | def _update_job(self, target, args, kwargs) | Specify the function this async job is to execute when run. | 4.006541 | 3.790359 | 1.057035 |
if self._execution_context:
raise errors.AlreadyInContextError
self._execution_context = execution_context | def set_execution_context(self, execution_context) | Set the ExecutionContext this async is executing under. | 5.917563 | 5.04539 | 1.172865 |
_check_options(options)
if 'persistence_engine' in options:
options['persistence_engine'] = reference_to_path(
options['persistence_engine'])
if 'id' in options:
self._id = options['id']
self._options.update(options) | def update_options(self, **options) | Safely update this async job's configuration options. | 4.845765 | 4.11028 | 1.178938 |
from google.appengine.api.taskqueue import Task
from google.appengine.api.taskqueue import TaskRetryOptions
self._increment_recursion_level()
self.check_recursion_depth()
url = "%s/%s" % (ASYNC_ENDPOINT, self.function_path)
kwargs = {
'url': url,
... | def to_task(self) | Return a task object representing this async job. | 3.430563 | 3.251642 | 1.055025 |
from google.appengine.api import taskqueue
task = self.to_task()
queue = taskqueue.Queue(name=self.get_queue())
retry_transient = self._options.get('retry_transient_errors', True)
retry_delay = self._options.get('retry_delay', RETRY_SLEEP_SECS)
add = queue.add
... | def start(self, transactional=False, async=False, rpc=None) | Insert the task into the requested queue, 'default' if non given.
If a TransientError is hit the task will re-insert the task. If a
TaskAlreadyExistsError or TombstonedTaskError is hit the task will
silently fail.
If the async flag is set, then the add will be done asynchronously and
... | 3.729162 | 3.377157 | 1.104231 |
async_options = decode_async_options(async)
target, args, kwargs = async_options.pop('job')
return cls(target, args, kwargs, **async_options) | def from_dict(cls, async) | Return an async job from a dict output by Async.to_dict. | 6.064934 | 5.072194 | 1.195722 |
if self._persistence_engine:
return
persistence_engine = self._options.get('persistence_engine')
if persistence_engine:
self._persistence_engine = path_to_reference(persistence_engine)
return
from furious.config import get_default_persistenc... | def _prepare_persistence_engine(self) | Load the specified persistence engine, or the default if none is
set. | 3.433347 | 2.91464 | 1.177966 |
from furious.context import get_current_context
context_id = self._options.get('context_id')
if context_id:
return context_id
try:
context = get_current_context()
except errors.NotInContextError:
context = None
self.upd... | def _get_context_id(self) | If this async is in a context set the context id. | 3.108413 | 2.707079 | 1.148254 |
parent_id = self._options.get('parent_id')
if parent_id:
return parent_id
from furious.context import get_current_async
try:
async = get_current_async()
except errors.NotInContextError:
async = None
if async:
par... | def _get_parent_id(self) | If this async is in within another async set that async id as the
parent. | 3.869545 | 3.304228 | 1.171089 |
full_id = ""
if self.parent_id:
full_id = ":".join([self.parent_id, self.id])
else:
full_id = self.id
if self.context_id:
full_id = "|".join([full_id, self.context_id])
return full_id | def full_id(self) | Return the full_id for this Async. Consists of the parent id, id and
context id. | 2.493703 | 2.040396 | 1.222166 |
# Update the recursion info. This is done so that if an async created
# outside an executing context, or one previously created is later
# loaded from storage, that the "current" setting is correctly set.
self._initialize_recursion_depth()
recursion_options = self._opt... | def _increment_recursion_level(self) | Increment current_depth based on either defaults or the enclosing
Async. | 8.038079 | 7.487396 | 1.073548 |
if not self._context_id:
self._context_id = self._get_context_id()
self.update_options(context_id=self._context_id)
return self._context_id | def context_id(self) | Return this Async's Context Id if it exists. | 3.175836 | 2.795728 | 1.13596 |
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": self.payload.error,
"args": self.payload.args,
"traceback": traceback.format_exception(*self.payload.traceback)
} | def _payload_to_dict(self) | When an error status the payload is holding an AsyncException that
is converted to a serializable dict. | 4.090197 | 3.085994 | 1.325407 |
return HTTPMethod('put', func, allowed_exceptions=allowed_exceptions,
title=title, req_obj_type=req_obj_type) | def put(func: Callable, allowed_exceptions: List = None,
title: str = None, req_obj_type: Callable = None) -> HTTPMethod | Returns a HTTPMethod instance to create a PUT route.
:see: :class:`~doctor.routing.HTTPMethod` | 2.379352 | 2.954007 | 0.805466 |
@functools.wraps(logic)
def fn(handler, *args, **kwargs):
if before is not None and callable(before):
before()
result = handle_http(handler, args, kwargs, logic)
if after is not None and callable(after):
after(result)
return result
return fn | def create_http_method(logic: Callable, http_method: str,
handle_http: Callable, before: Callable = None,
after: Callable = None) -> Callable | Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with the
parsed and validated parameters.
:param str http_method: HTTP method this will handle.
:param handle_http: The HTTP handler function that should be
used to wrap the logi... | 2.681441 | 2.879835 | 0.931109 |
if route.handler_name is not None:
return route.handler_name
if any(m for m in route.methods if m.method.lower() == 'post'):
# A list endpoint
if route.heading != 'API':
return '{}ListHandler'.format(get_valid_class_name(route.heading))
return '{}ListHandler'.for... | def get_handler_name(route: Route, logic: Callable) -> str | Gets the handler name.
:param route: A Route instance.
:param logic: The logic function.
:returns: A handler class name. | 2.984488 | 2.859439 | 1.043732 |
created_routes = []
all_handler_names = []
for r in routes:
handler = None
if r.base_handler_class is not None:
base_handler_class = r.base_handler_class
else:
base_handler_class = default_base_handler_class
# Define the handler name. To prevent... | def create_routes(routes: Tuple[HTTPMethod], handle_http: Callable,
default_base_handler_class: Any) -> List[Tuple[str, Any]] | Creates handler routes from the provided routes.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param default_base_handler_class: The d... | 3.605057 | 3.673442 | 0.981384 |
parser_options = ParserOptions(options)
parser_input = ParserInput(args, kwds)
parser = Parser(parser_options, parser_input)
parser.parse()
return parser.output_data | def parse_args(options={}, *args, **kwds) | Parser of arguments.
dict options {
int min_items: Min of required items to fold one tuple. (default: 1)
int max_items: Count of items in one tuple. Last `max_items-min_items`
items is by default set to None. (default: 1)
bool allow_dict: Flag allowing dictionary as first (and o... | 3.987707 | 6.140043 | 0.649459 |
from random import random
from furious.async import Async
number = random()
logging.info('Generating a number... %s', number)
if number > 0.25:
logging.info('Continuing to do stuff.')
return Async(target=simple_state_machine)
return number | def simple_state_machine() | Pick a number, if it is more than some cuttoff continue the chain. | 8.109401 | 6.643845 | 1.220589 |
if attrs is not None:
def parts():
for key, value in sorted(attrs.items()):
if value is None:
continue
if value is True:
yield '%s' % (key, )
continue
if key == 'class' and isinstance... | def render_attrs(attrs) | Render HTML attributes, or return '' if no attributes needs to be rendered. | 2.352673 | 2.305979 | 1.020249 |
store_async_marker(async.id, async.result.status if async.result else -1)
logging.debug("Async check completion for: %s", async.context_id)
current_queue = _get_current_queue()
from furious.async import Async
logging.debug("Completion Check queue:%s", current_queue)
Async(_completion_chec... | def context_completion_checker(async) | Persist async marker and async the completion check | 7.565926 | 6.62751 | 1.141594 |
if not context_id:
logging.debug("Context for async %s does not exist", async_id)
return
context = FuriousContext.from_id(context_id)
marker = FuriousCompletionMarker.get_by_id(context_id)
if marker and marker.complete:
logging.info("Context %s already complete" % context... | def _completion_checker(async_id, context_id) | Check if all Async jobs within a Context have been run. | 4.054588 | 3.887276 | 1.043041 |
shuffle(task_ids)
has_errors = False
for index in xrange(0, len(task_ids), offset):
keys = [ndb.Key(FuriousAsyncMarker, id)
for id in task_ids[index:index + offset]]
markers = ndb.get_multi(keys)
if not all(markers):
logging.debug("Not all Async's... | def _check_markers(task_ids, offset=10) | Returns a flag for markers being found for the task_ids. If all task ids
have markers True will be returned. Otherwise it will return False as soon
as a None result is hit. | 5.819708 | 5.654021 | 1.029304 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.