code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
current = None if marker: current = marker.key.get() if not current: return False if current and current.complete: return False current.complete = True current.has_errors = has_errors current.put() # Kick off completion tasks. _insert_post_complete_...
def _mark_context_complete(marker, context, has_errors)
Transactionally 'complete' the context.
4.750392
4.422376
1.074172
logging.debug("Context %s is complete.", context.id) # Async event handlers context.exec_event_handler('complete', transactional=True) # Insert cleanup tasks try: # TODO: If tracking results we may not want to auto cleanup and instead # wait until the results have been access...
def _insert_post_complete_tasks(context)
Insert the event's asyncs and cleanup tasks.
13.368054
12.2687
1.089606
logging.debug("Cleanup %d markers for Context %s", len(task_ids), context_id) # TODO: Handle exceptions and retries here. delete_entities = [ndb.Key(FuriousAsyncMarker, id) for id in task_ids] delete_entities.append(ndb.Key(FuriousCompletionMarker, context_id)) ndb.delete_m...
def _cleanup_markers(context_id, task_ids)
Delete the FuriousAsyncMarker entities corresponding to ids.
4.857139
3.640364
1.334245
logging.debug("Attempting to store Context %s.", context.id) entity = FuriousContext.from_context(context) # TODO: Handle exceptions and retries here. marker = FuriousCompletionMarker(id=context.id) key, _ = ndb.put_multi((entity, marker)) logging.debug("Stored Context with key: %s.", k...
def store_context(context)
Persist a furious.context.Context object to the datastore by loading it into a FuriousContext ndb.Model.
7.735741
5.224927
1.480545
logging.debug("Storing result for %s", async_id) key = FuriousAsyncMarker( id=async_id, result=json.dumps(async_result.to_dict()), status=async_result.status).put() logging.debug("Setting Async result %s using marker: %s.", async_result, key)
def store_async_result(async_id, async_result)
Persist the Async's result to the datastore.
7.272419
6.48975
1.120601
logging.debug("Attempting to mark Async %s complete.", async_id) # QUESTION: Do we trust if the marker had a flag result to just trust it? marker = FuriousAsyncMarker.get_by_id(async_id) if marker: logging.debug("Marker already exists for %s.", async_id) return # TODO: Handl...
def store_async_marker(async_id, status)
Persist a marker indicating the Async ran to the datastore.
7.071164
6.485564
1.090293
for futures in iget_batches(context.task_ids, batch_size=batch_size): for key, future in futures: task = future.get_result() if task_cache is not None: task_cache[key.id()] = task yield key.id(), task
def iter_context_results(context, batch_size=10, task_cache=None)
Yield out the results found on the markers for the context task ids.
4.459934
4.185818
1.065487
make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id) for keys in i_batch(imap(make_key, task_ids), batch_size): yield izip(keys, ndb.get_multi_async(keys))
def iget_batches(task_ids, batch_size=10)
Yield out a map of the keys and futures in batches of the batch size passed in.
8.099465
6.709842
1.207102
for items_batch in iter(lambda: tuple(islice(items, size)), tuple()): yield items_batch
def i_batch(items, size)
Generator that iteratively batches items to a max size and consumes the items as each batch is yielded.
4.13061
6.470068
0.638418
return cls(id=context.id, context=context.to_dict())
def from_context(cls, context)
Create a `cls` entity from a context.
6.976337
5.48001
1.273052
from furious.context import Context # TODO: Handle exceptions and retries here. entity = cls.get_by_id(id) if not entity: raise FuriousContextNotFoundError( "Context entity not found for: {}".format(id)) return Context.from_dict(entity.conte...
def from_id(cls, id)
Load a `cls` entity and instantiate the Context it stores.
6.940289
5.317805
1.305104
for key, task in self._tasks: if not (task and task.result): yield key, None else: yield key, json.loads(task.result)["payload"]
def items(self)
Yield the async reuslts for the context.
6.655774
4.978356
1.336942
for _, task in self._tasks: if not (task and task.result): yield None else: yield json.loads(task.result)["payload"]
def values(self)
Yield the async reuslt values for the context.
8.850111
6.540052
1.353217
from aiidalab_widgets_base import aiida_visualizers try: visualizer = getattr(aiida_visualizers, AIIDA_VISUALIZER_MAPPING[obj.type]) display(visualizer(obj, downloadable=downloadable), **kwargs) except KeyError: display(obj, **kwargs)
def aiidalab_display(obj, downloadable=True, **kwargs)
Display AiiDA data types in Jupyter notebooks. :param downloadable: If True, add link/button to download content of displayed AiiDA object. Defers to IPython.display.display for any objects it does not recognize.
3.728847
3.979176
0.93709
with self._setup_ssh_out: clear_output() self._ssh_keygen() #temporary passwords password = self.__password proxy_password = self.__proxy_password # step 1: if hostname is not provided - do not do anything if self.hos...
def on_setup_ssh(self, b)
ATTENTION: modifying the order of operations in this function can lead to unexpected problems
5.826378
5.74333
1.01446
passwd = copy(self._inp_password.value) self._inp_password.value = '' return passwd
def __password(self)
Returning the password and immediately destroying it
9.051995
6.573463
1.377051
passwd = copy(self._inp_proxy_password.value) self._inp_proxy_password.value = '' return passwd
def __proxy_password(self)
Returning the password and immediately destroying it
7.108861
5.385551
1.319988
if len(self._inp_username.value.strip()) == 0: # if username provided by user if not self.hostname is None: config = parse_sshconfig(self.hostname) if 'user' in config: # if username is present in the config file return config['user'] ...
def username(self)
Loking for username in user's input and config file
5.044581
4.470642
1.12838
print("Configuring '{}'".format(self.name)) sshcfg = parse_sshconfig(self.hostname) authparams = { 'compress': True, 'gss_auth': False, 'gss_deleg_creds': False, 'gss_host': self.hostname, 'gss_kex': False, 'key_pol...
def _configure_computer(self)
create DbAuthInfo
3.544153
3.37693
1.049519
setup( name='pyviews', version=_get_version(), description='Base package for xml views', long_description=_get_long_description(), long_description_content_type='text/markdown', url='https://github.com/eumis/pyviews', author='eumis(Eugen Misievich)', ...
def setup_package()
Package setup
3.063882
3.054047
1.00322
m = a == p # matches (a=1, p=1) and (a=0, p=0) f = np.logical_not(m) # xor (a=1, p=0) and (a=0, p=1) tp = np.sum(np.logical_and(m, a)) # 11 tn = np.sum(np.logical_and(m, np.logical_not(a))) # 00 fn = np.sum(np.logical_and(f, a)) # 10 fp = np.sum(np.logical_and(f, p)) # 01 return n...
def confusion(a, p)
Confusion Matrix - confusion matrix, error matrix, matching matrix (unsupervised) - is a special case: 2x2 contingency table (xtab, RxC table) - both dimensions are variables with the same classes/labels, i.e. actual and predicted variables are binary [0,1] Parameters: ----------- a : nd...
2.048387
2.100846
0.97503
''' Retrieves a document from the database, by primary key. ''' if pk is None: return None d = rr.table(cls.table).get(pk).run() if d is None: return None doc = cls(rr, d) return doc
def load(cls, rr, pk)
Retrieves a document from the database, by primary key.
3.749784
2.86313
1.30968
''' Creates the table if it doesn't exist. ''' dbs = rr.db_list().run() if not rr.dbname in dbs: logging.info('creating rethinkdb database %s', repr(rr.dbname)) rr.db_create(rr.dbname).run() tables = rr.table_list().run() if not cls.table i...
def table_ensure(cls, rr)
Creates the table if it doesn't exist.
3.060042
2.852993
1.072573
''' Name of the primary key field as retrieved from rethinkdb table metadata, 'id' by default. Should not be overridden. Override `table_create` if you want to use a nonstandard field as the primary key. ''' if not self._pk: try: pk = s...
def pk_field(self)
Name of the primary key field as retrieved from rethinkdb table metadata, 'id' by default. Should not be overridden. Override `table_create` if you want to use a nonstandard field as the primary key.
5.40376
2.641992
2.045336
''' Persist changes to rethinkdb. Updates only the fields that have changed. Performs insert rather than update if the document has no primary key or if the primary key is absent from the database. If there have been any changes to nested fields, updates the first level ...
def save(self)
Persist changes to rethinkdb. Updates only the fields that have changed. Performs insert rather than update if the document has no primary key or if the primary key is absent from the database. If there have been any changes to nested fields, updates the first level attribute. For examp...
3.557307
2.213706
1.606947
''' Refresh the document from the database. ''' d = self.rr.table(self.table).get(self.pk_value).run() if d is None: raise KeyError for k in d: dict.__setitem__( self, k, watch(d[k], callback=self._updated, field=k))
def refresh(self)
Refresh the document from the database.
7.860773
6.103013
1.288015
self._setup_parser() try: self._view_name = view_name self._parser.ParseFile(xml_file) except ExpatError as error: # pylint: disable=E1101 raise XmlError(errors.messages[error.code], ViewInfo(view_name, error.lineno)) root = self....
def parse(self, xml_file, view_name=None) -> XmlNode
Parses xml file with xml_path and returns XmlNode
4.3946
4.537167
0.968578
# transpose if axis<>0 if axis is not 0: x = x.T # read dimensions and allocate variables _, c = x.shape pairs = [] # compute each (i,j)-th correlation for i in range(0, c): for j in range(i + 1, c): _, p = scipy.stats.pearsonr(x[:, i], x[:, j]) ...
def find_unrelated(x, plim=0.1, axis=0)
Find indicies of insignificant un-/correlated variables Example: -------- i, j = find_unrelated(x, plim, rlim)
4.304252
4.603862
0.934922
if request is None or request == "": raise Exception(self.__class__.__name__, "request is None or empty") holder = JsonRequestDeserializer(jsonpickle.decode(request)) if not holder or not hasattr(holder, "driverRequest"): raise Exception(self.__class__.__name_...
def apply_connectivity_changes(self, request)
Handle apply connectivity changes request json, trigger add or remove vlan methods, get responce from them and create json response :param request: json with all required action to configure or remove vlans from certain port :return Serialized DriverResponseRoot to json :rtype json
2.680677
2.510162
1.06793
is_fail = False fail_attribute = "" for class_attribute in self.APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST: if type(class_attribute) is tuple: if not hasattr(action, class_attribute[0]): is_fail = True fa...
def _validate_request_action(self, action)
Validate action from the request json, according to APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST
3.0078
2.14606
1.401545
result = set() for splitted_vlan in vlan_str.split(","): if "-" not in splitted_vlan: if validate_vlan_number(splitted_vlan): result.add(int(splitted_vlan)) else: raise Exception(self.__class__.__name__, "Wrong...
def _get_vlan_list(self, vlan_str)
Get VLAN list from input string :param vlan_str: :return list of VLANs or Exception
2.067935
2.032264
1.017553
try: action_result = self.add_vlan_flow.execute_flow(vlan_range=vlan_id, port_mode=port_mode, port_name=full_name, ...
def add_vlan(self, vlan_id, full_name, port_mode, qnq, c_tag)
Run flow to add VLAN(s) to interface :param vlan_id: Already validated number of VLAN(s) :param full_name: Full interface name. Example: 2950/Chassis 0/FastEthernet0-23 :param port_mode: port mode type. Should be trunk or access :param qnq: :param c_tag:
2.947885
2.908466
1.013553
try: action_result = self.remove_vlan_flow.execute_flow(vlan_range=vlan_id, port_name=full_name, port_mode=port_mode) self.result[current_thread().name...
def remove_vlan(self, vlan_id, full_name, port_mode)
Run flow to remove VLAN(s) from interface :param vlan_id: Already validated number of VLAN(s) :param full_name: Full interface name. Example: 2950/Chassis 0/FastEthernet0-23 :param port_mode: port mode type. Should be trunk or access
3.403851
3.483019
0.97727
'''Process view and return root Node''' try: root_xml = get_view_root(view_name) return render(root_xml, **args) except CoreError as error: error.add_view_info(ViewInfo(view_name, None)) raise except: info = exc_info() error = ViewError('Unknown error occu...
def render_view(view_name, **args)
Process view and return root Node
5.032316
4.320965
1.164628
'''Parses xml file and return root XmlNode''' try: path = join(deps.views_folder, '{0}.{1}'.format(view_name, deps.view_ext)) parser = Parser() if path not in _XML_CACHE: with open(path, 'rb') as xml_file: _XML_CACHE[path] = parser.parse(xml_file, view_name) ...
def get_view_root(view_name: str) -> XmlNode
Parses xml file and return root XmlNode
3.563784
3.406225
1.046256
node.node_globals[key] = import_path(path)
def import_global(node: Node, key: str, path: Any)
Import passed module, class, function full name and stores it to node's globals
12.81716
7.216194
1.776166
value = get_current_scope().container.get(inject_key) set_global(node, global_key, value)
def inject_global(node: Node, global_key: str, inject_key: Any)
Resolves passed dependency and stores it to node's globals
6.644731
4.643226
1.431059
node.node_globals[key] = value
def set_global(node: Node, key: str, value: Any)
Adds passed value to node's globals
18.52063
8.895158
2.082102
value = _to_list(value) if not value or not isinstance(value[-1], dict): value.append({}) args = value[0:-1] kwargs = value[-1] node.__dict__[key](*args, **kwargs)
def call(node: Node, key: str, value: Any)
Calls node or node instance method
4.693868
3.809445
1.232166
# Need to store a list of route, view_class, and annotations by a # section key so that all methods of a resource are kept together in # the documentation. The key of the section will be the heading that # the route documentation goes under. section_map = defaultdict(li...
def iter_annotations(self)
Yield a tuple for each Flask handler containing annotated methods. Each tuple contains a heading, routing rule, the view class associated with the rule, and the annotations for the methods in that class.
3.875367
3.44604
1.124586
headers = self._get_headers(rule, annotation) example_values = self._get_example_values(rule, annotation) # If any of the example values for DELETE/GET HTTP methods are dicts # or lists, we will need to json dump them before building the rule, # otherwise the query strin...
def request(self, rule, view_class, annotation)
Make a request against the app. This attempts to use the schema to replace any url params in the path pattern. If there are any unused parameters in the schema, after substituting the ones in the path, they will be sent as query string parameters or form parameters. The substituted valu...
3.037574
2.748793
1.105057
if key not in self._callbacks: self._add_key(key) self._callbacks[key].append(callback)
def observe(self, key: str, callback: Callable[[Any, Any], None])
Subscribes to key changes
4.201922
3.705147
1.134077
try: self._callbacks[key].remove(callback) except (KeyError, ValueError): pass
def release(self, key: str, callback: Callable[[Any, Any], None])
Releases callback from key changes
4.74726
3.497871
1.357186
if key not in self.__dict__ and key not in self._callbacks: raise KeyError('Entity ' + str(self) + 'doesn''t have attribute' + key) super().observe(key, callback)
def observe(self, key, callback: Callable[[Any, Any], None])
Subscribes to key changes
5.977357
5.601152
1.067166
if self._parent == parent: return if self._parent: self._parent.release_all(self._parent_changed) self_values = {key: self._container[key] for key in self._own_keys} self._container = {**parent.to_dictionary(), **self_values} self._parent = parent...
def inherit(self, parent)
Inherit passed dictionary
4.178239
4.232184
0.987254
self._all_callbacks.append(callback)
def observe_all(self, callback: Callable[[str, Any, Any], None])
Subscribes to all keys changes
16.492014
10.79283
1.528053
self._all_callbacks.remove(callback)
def release_all(self, callback: Callable[[str, Any, Any], None])
Releases callback from all keys changes
26.454542
10.203043
2.592809
try: self._own_keys.discard(key) if self._parent and self._parent.has_key(key): self._container[key] = self._parent[key] else: del self._container[key] except KeyError: pass
def remove_key(self, key)
Remove own key, value
3.352691
3.167072
1.058609
if binding_type not in self._rules: self._rules[binding_type] = [] self._rules[binding_type].insert(0, rule)
def add_rule(self, binding_type: str, rule: BindingRule)
Adds new rule
2.927102
2.291044
1.277628
try: rules = self._rules[binding_type] return next(rule for rule in rules if rule.suitable(**args)) except (KeyError, StopIteration): return None
def find_rule(self, binding_type: str, **args)
Finds rule by binding type and args
3.766834
3.069709
1.227098
rule = self.find_rule(binding_type, **args) if rule is None: error = BindingError('Binding rule is not found') error.add_info('Binding type', binding_type) error.add_info('args', args) raise error binding = rule.apply(**args) if bi...
def apply(self, binding_type, **args)
Returns apply function
3.826297
3.865589
0.989835
'''Factory method to create expression target''' root = expression.get_object_tree() if len(root.children) != 1 or not PROPERTY_EXPRESSION_REGEX.fullmatch(expression.code): error = BindingError('Expression should be property expression') error.add_info('Expression', expression.code) ...
def get_expression_target(expression: Expression, expr_vars: InheritedDict) -> BindingTarget
Factory method to create expression target
5.73145
5.246506
1.092432
'''Calles modifier on instance with passed value''' self._modifier(self.inst, self.prop, value)
def on_change(self, value)
Calles modifier on instance with passed value
38.533459
9.594549
4.016182
'''Unsubscribes callback from observable''' self._observable.release(self._key, self._callback) self._observable = None self._key = None self._callback = None
def destroy(self)
Unsubscribes callback from observable
6.160999
4.404534
1.398786
parser = argparse.ArgumentParser(description='Run the Furious Examples.') parser.add_argument('--gae-sdk-path', metavar='S', dest="gae_lib_path", default="/usr/local/google_appengine", help='path to the GAE SDK') parser.add_argument('url', metavar='U', ...
def args()
Add and parse the arguments for the script. url: the url of the example to run gae-sdk-path: this allows a user to point the script to their GAE SDK if it's not in /usr/local/google_appengine.
5.071317
3.290035
1.541418
sys.path.insert(0, options.gae_lib_path) from dev_appserver import fix_sys_path fix_sys_path()
def setup(options)
Grabs the gae_lib_path from the options and inserts it into the first index of the sys.path. Then calls GAE's fix_sys_path to get all the proper GAE paths included. :param options:
3.876988
3.383655
1.145799
from google.appengine.tools import appengine_rpc from google.appengine.tools import appcfg source = 'furious' # use the same user agent that GAE uses in appcfg user_agent = appcfg.GetUserAgent() # Since we're only using the dev server for now we can hard code these # values. This wil...
def run(options)
Run the passed in url of the example using GAE's rpc runner. Uses appengine_rpc.HttpRpcServer to send a request to the url passed in via the options. :param options:
8.357457
7.664205
1.090453
details = self.autoload_flow.execute_flow(self.resource_config.supported_os, self.resource_config.shell_name, self.resource_config.family, self.resource...
def discover(self)
Enable and Disable SNMP communityon the device, Read it's structure and attributes: chassis, modules, submodules, ports, port-channels and power supplies :return: AutoLoadDetails object :rtype: cloudshell.shell.core.driver_context.AutoLoadDetails
8.906771
5.523116
1.612635
querypart = self._queryparts.get(querypart_name) if not querypart: return False if not querypart.is_set: return False if value: return querypart.has(value) return True
def has(self, querypart_name, value=None)
Returns True if `querypart_name` with `value` is set. For example you can check if you already used condition by `sql.has('where')`. If you want to check for more information, for example if that condition also contain ID, you can do this by `sql.has('where', 'id')`.
2.609399
2.829518
0.922206
try: parameters = {} if parameters is None else parameters return eval(self._compiled_code, parameters, {}) except: info = exc_info() error = CompilationError('Error occurred in expression execution', self.code) error.add_cause(info[1]...
def execute(self, parameters: dict = None)
Executes expression with passed parameters and returns result
7.277834
5.929967
1.227297
import random logging.info('In aborting_function') if random.random() < .5: from furious.errors import AbortAndRestart logging.info('Getting ready to restart') # Raise AbortAndRestart like an Exception, and watch the magic happen. raise AbortAndRestart() logging...
def aborting_function()
There is a 50% chance that this function will AbortAndRestart or complete successfully. The 50% chance simply represents a process that will fail half the time and succeed half the time.
10.079
8.686134
1.160355
stu_res = _strip_ansi(state.student_result) return state.to_child(student_result = stu_res)
def strip_ansi(state)
Remove ANSI escape codes from student result.
12.731228
5.850474
2.176102
stu_code = state.student_code # either simple text matching or regex test res = text in stu_code if fixed else re.search(text, stu_code) if not res: _msg = state.build_message(incorrect_msg, fmt_kwargs={ 'text': text }) state.do_test(_msg) return state
def has_code(state, text, incorrect_msg="The checker expected to find `{{text}}` in your command.", fixed=False)
Check whether the student code contains text. This function is a simpler override of the `has_code` function in protowhat, because ``ast_node._get_text()`` is not implemented in the OSH parser Using ``has_code()`` should be a last resort. It is always better to look at the result of code or the side e...
8.046102
8.367794
0.961556
stu_output = state.student_result if strip_ansi: stu_output = _strip_ansi(stu_output) # either simple text matching or regex test res = text in stu_output if fixed else re.search(text, stu_output) if not res: _msg = state.build_message(incorrect_msg, fmt_kwargs={ 'text': text, 'fixe...
def has_output(state, text, incorrect_msg="The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.", fixed=False, strip_ansi=True)
Check whether student output contains specific text. Before you use ``has_output()``, have a look at ``has_expr_output()`` or ``has_expr_error()``; they might be more fit for your use case. Args: state: State instance describing student and solution code. Can be omitted if used with ``Ex()``. ...
5.928535
6.534645
0.907247
expr = "[[ $PWD == '{}' ]]".format(dir) _msg = state.build_message(incorrect_msg, fmt_kwargs={ 'dir': dir }) has_expr_exit_code(state, expr, output="0", incorrect_msg=_msg) return state
def has_cwd(state, dir, incorrect_msg="Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there.")
Check whether the student is in the expected directory. This check is typically used before using ``has_expr_output()`` to make sure the student didn't navigate somewhere else. Args: state: State instance describing student and solution code. Can be omitted if used with ``Ex()``. dir: Dire...
8.851775
11.869939
0.74573
''' Update service status, indicating "up"-ness. Args: status_info (dict): a dictionary representing the status of the service `status_info` must have at least the fields 'role', 'load', and 'ttl'. Some additional fields are populated automatically by th...
def heartbeat(self, status_info)
Update service status, indicating "up"-ness. Args: status_info (dict): a dictionary representing the status of the service `status_info` must have at least the fields 'role', 'load', and 'ttl'. Some additional fields are populated automatically by this method. I...
3.536319
1.730338
2.043716
''' Remove the service with id `id` from the service registry. ''' result = self.rr.table(self.table).get(id).delete().run() if result != { 'deleted':1, 'errors':0,'inserted':0, 'replaced':0,'skipped':0,'unchanged':0}: self.logger.warn(...
def unregister(self, id)
Remove the service with id `id` from the service registry.
5.741213
5.155484
1.113613
''' Look up healthy services in the registry. A service is considered healthy if its 'last_heartbeat' was less than 'ttl' seconds ago Args: role (str, optional): role name Returns: If `role` is supplied, returns list of healthy services for the ...
def healthy_services(self, role=None)
Look up healthy services in the registry. A service is considered healthy if its 'last_heartbeat' was less than 'ttl' seconds ago Args: role (str, optional): role name Returns: If `role` is supplied, returns list of healthy services for the given ro...
4.957202
2.656052
1.86638
if batch_size: new_context = AutoContext(batch_size=batch_size, **options) else: new_context = Context(**options) _local.get_local_context().registry.append(new_context) return new_context
def new(batch_size=None, **options)
Get a new furious context and add it to the registry. If a batch size is specified, use an AutoContext which inserts tasks in batches as they are added to the context.
4.302142
3.166316
1.358722
local_context = _local.get_local_context() if local_context._executing_async: return local_context._executing_async[-1] raise errors.NotInContextError('Not in an _ExecutionContext.')
def get_current_async()
Return a reference to the currently executing Async job object or None if not in an Async job.
8.003547
7.864087
1.017734
local_context = _local.get_local_context() if local_context.registry: return local_context.registry[-1] raise errors.NotInContextError('Not in a Context.')
def get_current_context()
Return a reference to the current Context object.
7.197774
6.225576
1.156162
digest_maker = self._digest_maker() digest_maker.update(self.user_id) digest_maker.update(self._DELIMITER) if action: digest_maker.update(action) digest_maker.update(self._DELIMITER) digest_maker.update(str(self.current_time)) return base...
def generate_token_string(self, action=None)
Generate a hash of the given token contents that can be verified. :param action: A string representing the action that the generated hash is valid for. This string is usually a URL. :returns: A string containing the hash contents of the given `action` and the ...
2.816041
2.91784
0.965112
try: decoded_token_string = base64.urlsafe_b64decode(token_string) except TypeError: raise XSRFTokenMalformed() split_token = decoded_token_string.split(self._DELIMITER) if len(split_token) != 2: raise XSRFTokenMalformed() try: t...
def verify_token_string(self, token_string, action=None, timeout=None, current_time=None)
Generate a hash of the given token contents that can be verified. :param token_string: A string containing the hashed token (generated by `generate_token_string`). :param action: A string containing the action that is being verified. :param timeout: ...
2.634182
2.42482
1.086341
path_parts = path.split("/") return_list = [] if len(path_parts) == 0: #no search string return d else: try: sub_dicts = [d] #BFS, start with root node for i in range(0, len(path_parts)): #BFS new_sub_dicts = [] for s ...
def iterate_dictionary(d, path, squash_single = False)
Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of objects found at all leaf nodes at all trajectories `dict[A][B][C][D]`. It does this using BFS not DFS. The word "leaf" hereby refers to an item at the search path level. That is, upon calling the function it...
3.464568
3.1795
1.089658
return SnmpContextManager(self.enable_flow, self.disable_flow, self._snmp_parameters, self._logger)
def get_snmp_service(self)
Enable/Disable snmp :param snmp_parameters: :return: :rtype: SnmpContextManager
17.593805
8.907119
1.975252
argv = argv or sys.argv arg_parser = argparse.ArgumentParser( prog=os.path.basename(argv[0]), description=( 'doublethink-purge-stale-services: utility to periodically ' 'purge stale entries from the "services" table.')) arg_parser.add_argument( "...
def purge_stale_services(argv=None)
Command-line utility to periodically purge stale entries from the "services" table. It is designed to be used in conjunction with cron.
2.81573
2.73925
1.02792
from google.appengine.api import taskqueue if not tasks: return 0 try: taskqueue.Queue(name=queue).add(tasks, transactional=transactional) return len(tasks) except (taskqueue.BadTaskStateError, taskqueue.TaskAlreadyExistsError, taskqueue.TombstonedT...
def _insert_tasks(tasks, queue, transactional=False, retry_transient_errors=True, retry_delay=RETRY_SLEEP_SECS)
Insert a batch of tasks into the specified queue. If an error occurs during insertion, split the batch and retry until they are successfully inserted. Return the number of successfully inserted tasks.
3.401913
3.373092
1.008544
if transactional: return tasks return [task for task in tasks if not task.was_enqueued]
def _tasks_to_reinsert(tasks, transactional)
Return a list containing the tasks that should be reinserted based on the was_enqueued property and whether the insert is transactional or not.
5.98891
3.424889
1.748644
from itertools import izip_longest if not batch_size: batch_size = DEFAULT_TASK_BATCH_SIZE # Ensure the batch size is under the task api limit. batch_size = min(batch_size, 100) args = [iter(tasks)] * batch_size return ([task for task in group if task] for group in izip_longest(*...
def _task_batcher(tasks, batch_size=None)
Batches large task lists into groups of 100 so that they can all be inserted.
4.00616
3.736065
1.072294
if self._tasks_inserted: raise errors.ContextAlreadyStartedError( "This Context has already had its tasks inserted.") task_map = self._get_tasks_by_queue() # QUESTION: Should the persist happen before or after the task # insertion? I feel like this...
def _handle_tasks_insert(self, batch_size=None)
Convert all Async's into tasks, then insert them into queues.
6.121714
5.701103
1.073777
task_map = {} _checker = None # Ask the persistence engine for an Async to use for checking if the # context is complete. if self._persistence_engine: _checker = self._persistence_engine.context_completion_checker for async in self._tasks: ...
def _get_tasks_by_queue(self)
Return the tasks for this Context, grouped by queue.
6.280751
5.136382
1.222797
# QUESTION: Should we raise an exception if `event` is not in some # known event-type list? self._prepare_persistence_engine() callbacks = self._options.get('callbacks', {}) callbacks[event] = handler self._options['callbacks'] = callbacks
def set_event_handler(self, event, handler)
Add an Async to be run on event.
8.459558
8.298415
1.019418
# QUESTION: Should we raise an exception if `event` is not in some # known event-type list? callbacks = self._options.get('callbacks', {}) handler = callbacks.get(event) if not handler: raise Exception('Handler not defined!!!') handler.start(trans...
def exec_event_handler(self, event, transactional=False)
Execute the Async set to be run on event.
8.061344
7.816359
1.031343
from furious.async import Async from furious.batcher import Message if self._tasks_inserted: raise errors.ContextAlreadyStartedError( "This Context has already had its tasks inserted.") if not isinstance(target, (Async, Message)): target...
def add(self, target, args=None, kwargs=None, **options)
Add an Async job to this context. Takes an Async object or the arguments to construct an Async object as arguments. Returns the newly added Async object.
5.585721
4.844337
1.153041
if not persistence_engine: from furious.config import get_default_persistence_engine persistence_engine = get_default_persistence_engine() if not persistence_engine: raise RuntimeError( 'Specify a valid persistence_engine to load the context....
def load(cls, context_id, persistence_engine=None)
Load and instantiate a Context from the persistence_engine.
3.557886
3.283724
1.083491
import copy options = copy.deepcopy(self._options) if self._insert_tasks: options['insert_tasks'] = reference_to_path(self._insert_tasks) if self._persistence_engine: options['persistence_engine'] = reference_to_path( self._persistence_...
def to_dict(self)
Return this Context as a dict suitable for json encoding.
4.558424
4.078996
1.117536
import copy context_options = copy.deepcopy(context_options_dict) tasks_inserted = context_options.pop('_tasks_inserted', False) insert_tasks = context_options.pop('insert_tasks', None) if insert_tasks: context_options['insert_tasks'] = path_to_reference(i...
def from_dict(cls, context_options_dict)
Return a context job from a dict output by Context.to_dict.
2.92037
2.822536
1.034662
if not self._result: if not self._persistence_engine: return None self._result = self._persistence_engine.get_context_result(self) return self._result
def result(self)
Return the context result object pulled from the persistence_engine if it has been set.
5.396107
2.526429
2.135863
from google.appengine.api import taskqueue try: inserted = _insert_tasks(tasks, queue, *args, **kwargs) return inserted except taskqueue.DuplicateTaskNameError: # At least one task failed in our batch, attempt to re-insert the # remaining tasks. Named tasks can never...
def insert_tasks_ignore_duplicate_names(tasks, queue, *args, **kwargs)
Insert a batch of tasks into a specific queue. If a DuplicateTaskNameError is raised, loop through the tasks and insert the remaining, ignoring and logging the duplicate tasks. Returns the number of successfully inserted tasks.
5.193713
4.81602
1.078424
from furious.context import get_current_async # Get the recently finished Async object. async = get_current_async() # Pull out the result data and log it. for result in async.result: logging.info(result)
def log_results()
This is the callback that is run once the Async task is finished. It takes the output from grep and logs it.
9.075356
7.202626
1.260006
Async(target=grep, args=[query, directory]).start()
def build_and_start(query, directory)
This function will create and then start a new Async task with the default callbacks argument defined in the decorator.
25.04883
23.103191
1.084215
return ['%s: %s' % (item, line) for line in open(item) if re.search(query, line)]
def grep_file(query, item)
This function performs the actual grep on a given file.
4.058116
4.077024
0.995363
dir_contents = os.listdir(directory) results = [] for item in dir_contents: path = os.path.join(directory, item) if os.path.isdir(path): build_and_start(query, path) else: if item.endswith('.py'): results.extend(grep_file(query, path)) ...
def grep(query, directory)
This function will search through the directory structure of the application and for each directory it finds it launches an Async task to run itself. For each .py file it finds, it actually greps the file and then returns the found output.
2.642286
2.543678
1.038766
from furious.job_utils import path_to_reference config = get_config() option_value = config[option_name] # If no known_modules were give, make it an empty dict. if not known_modules: known_modules = {} module_path = known_modules.get(option_value) or option_value return path_...
def _get_configured_module(option_name, known_modules=None)
Get the module specified by the value of option_name. The value of the configuration option will be used to load the module by name from the known module list or treated as a path if not found in known_modules. Args: option_name: name of persistence module known_modules: dictionary of module...
4.876507
4.343842
1.122625
checked = set() result = _find_furious_yaml(os.path.dirname(config_file), checked) if not result: result = _find_furious_yaml(os.getcwd(), checked) return result
def find_furious_yaml(config_file=__file__)
Traverse directory trees to find a furious.yaml file Begins with the location of this file then checks the working directory if not found Args: config_file: location of this file, override for testing Returns: the path of furious.yaml or None if not found
2.869292
3.012744
0.952385
directory = start while directory not in checked: checked.add(directory) for fs_yaml_name in FURIOUS_YAML_NAMES: yaml_path = os.path.join(directory, fs_yaml_name) if os.path.exists(yaml_path): return yaml_path directory = os.path.dirname(direc...
def _find_furious_yaml(start, checked)
Traverse the directory tree identified by start until a directory already in checked is encountered or the path of furious.yaml is found. Checked is present both to make the loop termination easy to reason about and so the same directories do not get rechecked Args: start: the path to ...
2.312061
2.428633
0.952001
furious_yaml_path = path or find_furious_yaml() if furious_yaml_path is None: logging.debug("furious.yaml not found.") return None with open(furious_yaml_path) as yaml_file: return yaml_file.read()
def _load_yaml_config(path=None)
Open and return the yaml contents.
3.37372
3.264011
1.033612
data_map = default_config() # If we were given config data to use, use it. Otherwise, see if there is # a furious.yaml to read the config from. Note that the empty string will # result in the default config being used. if config_data is None: config_data = _load_yaml_config() if...
def _parse_yaml_config(config_data=None)
Gets the configuration from the found furious.yaml file and parses the data. Returns: a dictionary parsed from the yaml file
5.043298
4.861831
1.037325
joins_group = [] for join in self._joins: append_new = True for join_group in joins_group: if join_group[0]['table'] == join['table'] and join_group[0]['ons'] == join['ons']: join_group.append(join) append_new = Fal...
def _minimize_joins(self)
Minimizing of joins. Left/right and inner join of the same condition is only inner join.
2.226274
2.101462
1.059393
return code = node.xml_node.text try: globs = node_globals.to_dictionary() exec(dedent(code), globs) #pylint: disable=exec-used definitions = [(key, value) for key, value in globs.items() \ if key != '__builtins__' and not node_globals.has_key(key)] ...
def run_code(node: Code, parent_node: Node = None, node_globals: InheritedDict = None, **args): #pylint: disable=unused-argument '''Executes node content as python module and adds its definitions to globals''' if not node.xml_node.text
Executes node content as python module and adds its definitions to globals
3.392084
3.374628
1.005173