code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def disconnect(self): for signal, kwargs in self.connections: signal.disconnect(self, **kwargs)
Disconnect all connected signal types from this receiver.
def handle_error(self, request, client_address): if self.can_ignore_error(): return thread = threading.current_thread() msg("Error in request ({0}): {1} in {2}\n{3}", client_address, repr(request), thread.name, traceback.format_exc())
Handle an error gracefully.
def Init(service_client=None): global CONN global label_map global unknown_label if service_client is None: service_client_cls = fs_client.InsecureGRPCServiceClient fleetspeak_message_listen_address = ( config.CONFIG["Server.fleetspeak_message_listen_address"] or None) fleetspeak_server = co...
Initializes the Fleetspeak connector.
def _sanitize_windows_name(cls, arcname, pathsep): table = cls._windows_illegal_name_trans_table if not table: illegal = ':<>|"?*' table = str.maketrans(illegal, '_' * len(illegal)) cls._windows_illegal_name_trans_table = table arcname = arcname.translate(tabl...
Replace bad characters and remove trailing dots from parts.
def token(self): if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, self._token_url) return self._toke...
obtains a token from the site
def frame_update_count(self): result = 1000000 for column in self._columns: for widget in column: if widget.frame_update_count > 0: result = min(result, widget.frame_update_count) return result
The number of frames before this Layout should be updated.
def resources_preparing_factory(app, wrapper): settings = app.app.registry.settings config = settings.get(CONFIG_RESOURCES, None) if not config: return resources = [(k, [wrapper(r, GroupResource(k, v)) for r in v]) for k, v in config] settings[CONFIG_RESOURCES] = resources
Factory which wrap all resources in settings.
def seek(self, offset, whence=SEEK_SET): if whence == SEEK_SET: self.__sf.seek(offset) elif whence == SEEK_CUR: self.__sf.seek(self.tell() + offset) elif whence == SEEK_END: self.__sf.seek(self.__sf.filesize - offset)
Reposition the file pointer.
def _nested_transactional(fn): @wraps(fn) def wrapped(self, *args, **kwargs): try: rv = fn(self, *args, **kwargs) except _TransactionalPolicyViolationError as e: getattr(self, _TX_HOLDER_ATTRIBUTE).rollback() rv = e.result return rv return wrapped
In a transactional method create a nested transaction.
def diff(self, filename, wildcard='*'): other = MAVParmDict() if not other.load(filename): return keys = sorted(list(set(self.keys()).union(set(other.keys())))) for k in keys: if not fnmatch.fnmatch(str(k).upper(), wildcard.upper()): continue ...
show differences with another parameter file
def WSDLUriToVersion(self, uri): value = self._wsdl_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
Return the WSDL version related to a WSDL namespace uri.
def to_glyphs_kerning(self): for master_id, source in self._sources.items(): for (left, right), value in source.font.kerning.items(): left_match = UFO_KERN_GROUP_PATTERN.match(left) right_match = UFO_KERN_GROUP_PATTERN.match(right) if left_match: left = "@...
Add UFO kerning to GSFont.
def close(self): logging.debug('Closing for user {user}'.format(user=self.id.name)) self.id.release_name() for room in self._rooms.values(): room.disconnect(self)
Closes the connection by removing the user from all rooms
def _find_ble_controllers(self): controllers = self.bable.list_controllers() return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy]
Get a list of the available and powered BLE controllers
def dot(vec1, vec2): if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) elif isinstance(vec1, Vector4) and isinstance(vec2, Vector4): return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) + (vec1.w * vec2.w) ...
Returns the dot product of two Vectors
def _load_image(cls, rkey): v = cls._stock[rkey] img = None itype = v['type'] if itype in ('stock', 'data'): img = tk.PhotoImage(format=v['format'], data=v['data']) elif itype == 'created': img = v['image'] else: img = tk.PhotoImage(fil...
Load image from file or return the cached instance.
def _initialize_progress_bar(self): widgets = ['Download: ', Percentage(), ' ', Bar(), ' ', AdaptiveETA(), ' ', FileTransferSpeed()] self._downloadProgressBar = ProgressBar( widgets=widgets, max_value=self._imageCount).start()
Initializes the progress bar
def _next_channel(self): chanid = self._channel_counter while self._channels.get(chanid) is not None: self._channel_counter = (self._channel_counter + 1) & 0xffffff chanid = self._channel_counter self._channel_counter = (self._channel_counter + 1) & 0xffffff retur...
you are holding the lock
def to_native_units(self, motor): assert abs(self.degrees_per_minute) <= motor.max_dpm,\ "invalid degrees-per-minute: {} max DPM is {}, {} was requested".format( motor, motor.max_dpm, self.degrees_per_minute) return self.degrees_per_minute/motor.max_dpm * motor.max_speed
Return the native speed measurement required to achieve desired degrees-per-minute
def login_password(self, value): password = self.selenium.find_element(*self._password_input_locator) password.clear() password.send_keys(value)
Set the value of the login password field.
def _gcs_list_keys(bucket, pattern): data = [{'Name': obj.metadata.name, 'Type': obj.metadata.content_type, 'Size': obj.metadata.size, 'Updated': obj.metadata.updated_on} for obj in _gcs_get_keys(bucket, pattern)] return google.datalab.utils.commands.render_dictionary(data...
List all Google Cloud Storage keys in a specified bucket that match a pattern.
def create_command_dir(self): cmd_dir = os.path.join(self.archive_dir, "insights_commands") os.makedirs(cmd_dir, 0o700) return cmd_dir
Create the "sos_commands" dir
def static_method(cls, f): setattr(cls, f.__name__, staticmethod(f)) return f
Decorator which dynamically binds static methods to the model for later use.
def reduce_output_path(path=None, pdb_name=None): if not path: if not pdb_name: raise NameError( "Cannot save an output for a temporary file without a PDB" "code specified") pdb_name = pdb_name.lower() output_path = Path(global_settings['structural...
Defines location of Reduce output files relative to input files.
def serialize_tag(tag, *, indent=None, compact=False, quote=None): serializer = Serializer(indent=indent, compact=compact, quote=quote) return serializer.serialize(tag)
Serialize an nbt tag to its literal representation.
def _sync_projects(self, projects_json): for project_json in projects_json: project_id = project_json['id'] self.projects[project_id] = Project(project_json, self)
Populate the user's projects from a JSON encoded list.
def create_note(self, from_email, content): if from_email is None or not isinstance(from_email, six.string_types): raise MissingFromEmail(from_email) endpoint = '/'.join((self.endpoint, self.id, 'notes')) add_headers = {'from': from_email, } return self.noteFactory.create( ...
Create a note for this incident.
def getPollingRate(self): print '%s call getPollingRate' % self.port sPollingRate = self.__sendCommand('pollperiod')[0] try: iPollingRate = int(sPollingRate)/1000 fPollingRate = round(float(sPollingRate)/1000, 3) return fPollingRate if fPollingRate > iPollingR...
get data polling rate for sleepy end device
def clone(url, tmpdir=None): if tmpdir is None: tmpdir = tempfile.mkdtemp() name = os.path.basename(url).replace('.git', '') dest = '%s/%s' %(tmpdir,name) return_code = os.system('git clone %s %s' %(url,dest)) if return_code == 0: return dest bot.error('Error cloning repo.') ...
clone a repository from Github
def after_third_friday(day=None): day = day if day is not None else datetime.datetime.now() now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0) now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR) return day > now
check if day is after month's 3rd friday
def find_subclass(cls, name): if name == cls.__name__: return cls for sc in cls.__sub_classes__: r = sc.find_subclass(name) if r != None: return r
Find a subclass with a given name
def calculate_tree_length(self): tree_length = 0 for ext in self.tree: tree_length += len(ext) + 2 for relpath in self.tree[ext]: tree_length += len(relpath) + 2 for filename in self.tree[ext][relpath]: tree_length += len(filena...
Walks the tree and calculate the tree length
def on_new_request(self, task): task['status'] = self.taskdb.ACTIVE self.insert_task(task) self.put_task(task) project = task['project'] self._cnt['5m'].event((project, 'pending'), +1) self._cnt['1h'].event((project, 'pending'), +1) self._cnt['1d'].event((project,...
Called when a new request is arrived
def _decode_request(self, encoded_request): obj = self.serializer.loads(encoded_request) return request_from_dict(obj, self.spider)
Decode an request previously encoded
def authorized_tenants(self): if self.is_authenticated and self._authorized_tenants is None: endpoint = self.endpoint try: self._authorized_tenants = utils.get_project_list( user_id=self.id, auth_url=endpoint, to...
Returns a memoized list of tenants this user may access.
def get(self, uri): return self.send_request( "{0}://{1}:{2}{3}{4}".format( self.get_protocol(), self.host, self.port, uri, self.client_id ) )
Send a request to given uri.
def auth_oauth2(self) -> dict: oauth_data = { 'client_id': self._app_id, 'display': 'mobile', 'response_type': 'token', 'scope': '+66560', 'v': self.API_VERSION } response = self.post(self.OAUTH_URL, oauth_data) url_params = get...
Authorizes a user by OAuth2 to get access token
def _has_fr_route(self): if self._should_use_fr_error_handler(): return True if not request.url_rule: return False return self.owns_endpoint(request.url_rule.endpoint)
Encapsulating the rules for whether the request was to a Flask endpoint
def refreshLabels( self ): itemCount = self.itemCount() title = self.itemsTitle() if ( not itemCount ): self._itemsLabel.setText(' %s per page' % title) else: msg = ' %s per page, %i %s total' % (title, itemCount, title) self._itemsLabel.setText...
Refreshes the labels to display the proper title and count information.
def create_mysql_cymysql(username, password, host, port, database, **kwargs): return create_engine( _create_mysql_cymysql(username, password, host, port, database), **kwargs )
create an engine connected to a mysql database using cymysql.
def _get_dis_func(self, union): union_types = union.__args__ if NoneType in union_types: union_types = tuple( e for e in union_types if e is not NoneType ) if not all(hasattr(e, "__attrs_attrs__") for e in union_types): raise ValueError( ...
Fetch or try creating a disambiguation function for a union.
def chunk_iter(iterable, chunk_size): while True: chunk = [] try: for _ in range(chunk_size): chunk.append(next(iterable)) yield chunk except StopIteration: if chunk: yield chunk break
A generator that yields chunks of iterable, chunk_size at a time.
def _cdist_scipy(x, y, exponent=1): metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
Pairwise distance between the points in two sets.
def MarkDone(self, responses): client_id = responses.request.client_id self.AddResultsToCollection(responses, client_id) self.MarkClientDone(client_id)
Mark a client as done.
def update(self): con = self.subpars.pars.control self(con.ypoints.shape[0])
Determine the number of branches
def _assert_transition(self, event): state = self.domain.state()[0] if event not in STATES_MAP[state]: raise RuntimeError("State transition %s not allowed" % event)
Asserts the state transition validity.
def _invoke_callbacks(self, *args, **kwargs): for callback in self._done_callbacks: _helpers.safe_invoke_callback(callback, *args, **kwargs)
Invoke all done callbacks.
def send(self, enc, load, tries=1, timeout=60): payload = {'enc': enc} payload['load'] = load pkg = self.serial.dumps(payload) self.socket.send(pkg) self.poller.register(self.socket, zmq.POLLIN) tried = 0 while True: polled = self.poller.poll(timeout *...
Takes two arguments, the encryption type and the base payload
def list_buckets(self, offset=0, limit=100): if limit > 100: raise Exception("Zenobase can't handle limits over 100") return self._get("/users/{}/buckets/?order=label&offset={}&limit={}".format(self.client_id, offset, limit))
Limit breaks above 100
def dump_database(self): db_file = self.create_file_name(self.databases['source']['name']) self.print_message("Dumping postgres database '%s' to file '%s'" % (self.databases['source']['name'], db_file)) self.export_pgpassword('source') args = [ "pg_...
Create dumpfile from postgres database, and return filename.
def __get_user(self): storage = object.__getattribute__(self, '_LazyUser__storage') user = getattr(self.__auth, 'get_user')() setattr(storage, self.__user_name, user) return user
Return the real user object.
def file_resolve(backend, filepath): recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_datetime()) for file_to_resolve in filepath: if not os.path.exists(file_to_resolve):...
Mark a conflicted file as resolved, so that a merge can be completed
def device_changed(self, old_state, new_state): if (self._mounter.is_addable(new_state) and not self._mounter.is_addable(old_state) and not self._mounter.is_removable(old_state)): self.auto_add(new_state)
Mount newly mountable devices.
def _find_recorder(recorder, tokens, index): if recorder is None: for recorder_factory in _RECORDERS: recorder = recorder_factory.maybe_start_recording(tokens, index) if recorder is not None: return recorde...
Given a current recorder and a token index, try to find a recorder.
def initiate_forgot_password(self): params = { 'ClientId': self.client_id, 'Username': self.username } self._add_secret_hash(params, 'SecretHash') self.client.forgot_password(**params)
Sends a verification code to the user to use to change their password.
def get(self, name): lxc_meta_path = self._service.lxc_path(name, constants.LXC_META_FILENAME) meta = LXCMeta.load_from_file(lxc_meta_path) lxc = self._loader.load(name, meta) return lxc
Retrieves a single LXC by name
def _normalizeCursor(self, x, y): width, height = self.get_size() assert width != 0 and height != 0, 'can not print on a console with a width or height of zero' while x >= width: x -= width y += 1 while y >= height: if self._scrollMode == 'scroll': ...
return the normalized the cursor position.
def toggle_deriv(self, evt=None, value=None): "toggle derivative of data" if value is None: self.conf.data_deriv = not self.conf.data_deriv expr = self.conf.data_expr or '' if self.conf.data_deriv: expr = "deriv(%s)" % expr self.write_messa...
toggle derivative of data
def convert(self,label,units=None,conversion_function=convert_time): label_no = self.get_label_no(label) new_label, new_column = self.get_converted(label_no,units,conversion_function) labels = [LabelDimension(l) for l in self.labels] labels[label_no] = new_label matrix = self.mat...
converts a dimension in place
def validate_config(self): if self.location == 'localhost': if 'browserName' not in self.config.keys(): msg = "Add the 'browserName' in your local_config: e.g.: 'Firefox', 'Chrome', 'Safari'" self.runner.critical_log(msg) raise BromeBrowserConfigExcept...
Validate that the browser config contains all the needed config
def validate(self, value, redis): value = super().validate(value, redis) if is_hashed(value): return value return make_password(value)
hash passwords given via http
def local_address(self): if not self._local_address: self._local_address = self.proto.reader._transport.get_extra_info('sockname') if len(self._local_address) == 4: self._local_address = self._local_address[:2] return self._local_address
Local endpoint address as a tuple
def make_node(cls, node, *args): if node is None: node = cls() assert isinstance(node, SymbolARGUMENT) or isinstance(node, cls) if not isinstance(node, cls): return cls.make_node(None, node, *args) for arg in args: assert isinstance(arg, SymbolARGUMENT...
This will return a node with an argument_list.
def multidispatch(*, nargs=None, nouts=None): def wrapper(f): return wraps(f)(MultiDispatchFunction(f, nargs=nargs, nouts=nouts)) return wrapper
multidispatch decorate of both functools.singledispatch and func
def reference_fasta(self): if self._db_location: ref_files = glob.glob(os.path.join(self._db_location, "*", self._REF_FASTA)) if ref_files: return ref_files[0]
Absolute path to the fasta file with EricScript reference data.
def device_added(self, device): if not self._mounter.is_handleable(device): return if self._has_actions('device_added'): GLib.timeout_add(500, self._device_added, device) else: self._device_added(device)
Show discovery notification for specified device object.
def vertex_normals(vertices, faces): def normalize_v3(arr): lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2) arr /= lens[:, np.newaxis] tris = vertices[faces] facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) normalize_v3(facenorms) norm = np.zeros(...
Calculates the normals of a triangular mesh
def resample(self, inds): new = copy.deepcopy(self) for arr in self.arrays: x = getattr(new, arr) setattr(new, arr, x[inds]) return new
Returns copy of constraint, with mask rearranged according to indices
def _mod_bufsize_linux(iface, *args, **kwargs): ret = {'result': False, 'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'} cmd = '/sbin/ethtool -G ' + iface if not kwargs: return ret if args: ret['comment'] = 'Unknown arguments: ' + ' '.join([six.tex...
Modify network interface buffer sizes using ethtool
def devices(self): self.verify_integrity() if session.get('u2f_device_management_authorized', False): if request.method == 'GET': return jsonify(self.get_devices()), 200 elif request.method == 'DELETE': response = self.remove_device(request.json) ...
Manages users enrolled u2f devices
def check_deps(deps): if not isinstance(deps, list): deps = [deps] checks = list(Environment.has_apps(deps)) if not all(checks): for name, available in list(dict(zip(deps, checks)).items()): if not available: error_msg = "The required a...
check whether specific requirements are available.
def extract_worker_exc(*arg, **kw): _self = arg[0] if not isinstance(_self, StrategyBase): return for _worker_prc, _main_q, _rslt_q in _self._workers: _task = _worker_prc._task if _task.action == 'setup': continue while True: try: _exc ...
Get exception added by worker
def check_dependency(self, operation, dependency): if isinstance(dependency[1], SQLBlob): return dependency[3] == operation return super(MigrationAutodetector, self).check_dependency(operation, dependency)
Enhances default behavior of method by checking dependency for matching operation.
def user_feature_update(self, userid, payload): response, status_code = self.__pod__.User.post_v1_admin_user_uid_features_update( sessionToken=self.__session__, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) ...
update features by user id
def task_master(self): if self._task_master is None: self._task_master = build_task_master(self.config) return self._task_master
A `TaskMaster` object for manipulating work
def annotate_snapshot(self, snapshot): if hasattr(snapshot, 'classes'): return snapshot.classes = {} for classname in list(self.index.keys()): total = 0 active = 0 merged = Asized(0, 0) for tobj in self.index[classname]: ...
Store additional statistical data in snapshot.
def create_result(self, env_name, other_val, meta, val, dividers): args = [env_name] if other_val is NotSpecified: other_val = None if not dividers: args.extend([None, None]) elif dividers[0] == ':': args.extend([other_val, None]) elif dividers...
Set default_val and set_val depending on the seperator
def to_utf8(path, output_path=None): if output_path is None: basename, ext = os.path.splitext(path) output_path = basename + "-UTF8Encode" + ext text = smartread(path) write(text, output_path)
Convert any text file to utf8 encoding.
def _get_metrics_to_collect(self, instance_key, additional_metrics): if instance_key not in self.metrics_to_collect_by_instance: self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(additional_metrics) return self.metrics_to_collect_by_instance[instance_key]
Return and cache the list of metrics to collect.
def merge_pres_feats(pres, features): sub = [] for psub, fsub in zip(pres, features): exp = [] for pexp, fexp in zip(psub, fsub): lst = [] for p, f in zip(pexp, fexp): p.update(f) lst.append(p) exp.append(lst) sub.append...
Helper function to merge pres and features to support legacy features argument
def poisson_consensus_se(data, k, n_runs=10, **se_params): clusters = [] for i in range(n_runs): assignments, means = poisson_cluster(data, k) clusters.append(assignments) clusterings = np.vstack(clusters) consensus = CE.cluster_ensembles(clusterings, verbose=False, N_clusters_max=k) ...
Initializes Poisson State Estimation using a consensus Poisson clustering.
def replace(parent, idx, value, check_value=_NO_VAL): if isinstance(parent, dict): if idx not in parent: raise JSONPatchError("Item does not exist") elif isinstance(parent, list): idx = int(idx) if idx < 0 or idx >= len(parent): raise JSONPatchError("List index out of range") if check_valu...
Replace a value in a dict.
def config(self, config): for section, data in config.items(): for variable, value in data.items(): self.set_value(section, variable, value)
Set config values from config dictionary.
def start_subscribe_worker(self, loop): url = self.base_url + "api/0.1.0/subscribe" task = loop.create_task(self.asynchronously_get_data(url + "?name={0}".format(self.entity_id))) asyncio.set_event_loop(loop) loop.run_until_complete(task) self.event_loop = loop
Switch to new event loop as a thread and run until complete.
def build_groups(self, tokens): groups = {} for token in tokens: match_type = MatchType.start if token.group_end else MatchType.single groups[token.group_start] = (token, match_type) if token.group_end: groups[token.group_end] = (token, MatchType.end) ...
Build dict of groups from list of tokens
def subtract(self, jobShape): self.shape = Shape(self.shape.wallTime, self.shape.memory - jobShape.memory, self.shape.cores - jobShape.cores, self.shape.disk - jobShape.disk, self.shape.preemptable)
Subtracts the resources necessary to run a jobShape from the reservation.
def revert(self): if self.filepath: if path.isfile(self.filepath): serialised_file = open(self.filepath, "r") try: self.state = json.load(serialised_file) except ValueError: print("No JSON information could be re...
Revert the state to the version stored on disc.
def appointment(self): return django_apps.get_model(self.appointment_model).objects.get( pk=self.request.GET.get("appointment") )
Returns the appointment instance for this request or None.
def select(self, choice_scores): min_num_scores = min([len(s) for s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger....
Use the top k learner's scores for usage in rewards for the bandit calculation
def __updateRequest(self, rect, dy): if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock())....
Repaint line number area if necessary
def check_matrix(m): if m.shape != (4, 4): raise ValueError("The argument must be a 4x4 array.") if max(abs(m[3, 0:3])) > eps: raise ValueError("The given matrix does not have correct translational part") if abs(m[3, 3] - 1.0) > eps: raise ValueError("The lower right element of the g...
Check the sanity of the given 4x4 transformation matrix
def add(env, securitygroup_id, network_component, server, interface): _validate_args(network_component, server, interface) mgr = SoftLayer.NetworkManager(env.client) component_id = _get_component_id(env, network_component, server, interface) ret = mgr.attach_securitygroup_component(securitygroup_id, ...
Attach an interface to a security group.
async def refresh_data(self): queue = await self.get_queue() history = await self.get_history() totals = {} for k in history: if k[-4:] == 'size': totals[k] = self._convert_size(history.get(k)) self.queue = {**totals, **queue}
Refresh the cached SABnzbd queue data
def stop(self): self.state = False with display_manager(self.display) as d: d.record_disable_context(self.ctx) d.ungrab_keyboard(X.CurrentTime) with display_manager(self.display2): d.record_disable_context(self.ctx) d.ungrab_keyboard(X.CurrentTime)
Stop listening for keyboard input events.
def _bdd(node): try: bdd = _BDDS[node] except KeyError: bdd = _BDDS[node] = BinaryDecisionDiagram(node) return bdd
Return a unique BDD.
def add_env(self, name, val): if name in self.env_vars: raise KeyError(name) self.env_vars[name] = val
Add an environment variable to the docker run invocation
def snap(self, path=None): if path is None: path = "/tmp" else: path = path.rstrip("/") day_dir = datetime.datetime.now().strftime("%d%m%Y") hour_dir = datetime.datetime.now().strftime("%H%M") ensure_snapshot_dir(path+"/"+self.cam_id+"/"+day_dir+"/"+hour_d...
Get a snapshot and save it to disk.
def writeline(self, x, node=None, extra=0): self.newline(node, extra) self.write(x)
Combination of newline and write.
def nPercentile(requestContext, seriesList, n): assert n, 'The requested percent is required to be greater than 0' results = [] for s in seriesList: s_copy = TimeSeries(s.name, s.start, s.end, s.step, sorted(not_none(s))) if not s_copy: continue ...
Returns n-percent of each series in the seriesList.
def _send_textmetrics(metrics): data = [' '.join(map(six.text_type, metric)) for metric in metrics] + [''] return '\n'.join(data)
Format metrics for the carbon plaintext protocol