code
stringlengths
59
4.4k
docstring
stringlengths
5
7.69k
def info(filepath): info_dictionary = { 'channels': channels(filepath), 'sample_rate': sample_rate(filepath), 'bitrate': bitrate(filepath), 'duration': duration(filepath), 'num_samples': num_samples(filepath), 'encoding': encoding(filepath), 'silent': silent(f...
Get a dictionary of file information Parameters ---------- filepath : str File path. Returns: -------- info_dictionary : dict Dictionary of file information. Fields are: * channels * sample_rate * bitrate * duration * ...
def local_renderer(self): if not self._local_renderer: r = self.create_local_renderer() self._local_renderer = r return self._local_renderer
Retrieves the cached local renderer.
def run(self, inputRecord): predictionNumber = self._numPredictions self._numPredictions += 1 result = opf_utils.ModelResult(predictionNumber=predictionNumber, rawInput=inputRecord) return result
Run one iteration of this model. :param inputRecord: (object) A record object formatted according to :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict` result format. :returns: (:...
def update_memo(self, task_id, task, r): if not self.memoize or not task['memoize']: return if task['hashsum'] in self.memo_lookup_table: logger.info('Updating appCache entry with latest %s:%s call' % (task['func_name'], task_id)) self.memo_loo...
Updates the memoization lookup table with the result from a task. Args: - task_id (int): Integer task id - task (dict) : A task dict from dfk.tasks - r (Result future): Result future A warning is issued when a hash collision occurs during the update. This...
def get_arena_image(self, obj: BaseAttrDict): badge_id = obj.arena.id for i in self.constants.arenas: if i.id == badge_id: return 'https://royaleapi.github.io/cr-api-assets/arenas/arena{}.png'.format(i.arena_id)
Get the arena image URL Parameters --------- obj: official_api.models.BaseAttrDict An object that has the arena ID in ``.arena.id`` Can be ``Profile`` for example. Returns None or str
def request_roster(self, version = None): processor = self.stanza_processor request = Iq(stanza_type = "get") request.set_payload(RosterPayload(version = version)) processor.set_response_handlers(request, self._get_success, self._get_error) pro...
Request roster from server. :Parameters: - `version`: if not `None` versioned roster will be requested for given local version. Use "" to request full roster. :Types: - `version`: `unicode`
def create(self, stylename, **kwargs): if stylename == "default": self[stylename] = style(stylename, self._ctx, **kwargs) return self[stylename] k = kwargs.get("template", "default") s = self[stylename] = self[k].copy(stylename) for attr in kwargs: ...
Creates a new style which inherits from the default style, or any other style which name is supplied to the optional template parameter.
def _create_element_list(self): element_set = stoich.elements(self.compounds) return sorted(list(element_set))
Extract an alphabetically sorted list of elements from the material's compounds. :returns: Alphabetically sorted list of elements.
def python_value(self, value): value = coerce_to_bytes(value) obj = HashValue(value) obj.field = self return obj
Convert the database value to a pythonic value.
def encoding(self): if self.redirect is not None: return self.redirect.encoding else: return super(TeeStringIO, self).encoding
Gets the encoding of the `redirect` IO object Doctest: >>> redirect = io.StringIO() >>> assert TeeStringIO(redirect).encoding is None >>> assert TeeStringIO(None).encoding is None >>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding >>> ...
def get_items(self): ret=[] l=self.xpath_ctxt.xpathEval("d:item") if l is not None: for i in l: ret.append(DiscoItem(self, i)) return ret
Get the items contained in `self`. :return: the items contained. :returntype: `list` of `DiscoItem`
def dist(self, src, tar, weights='exponential', max_length=8): return self.dist_abs(src, tar, weights, max_length, True)
Return normalized distance between the Eudex hashes of two terms. This is Eudex distance normalized to [0, 1]. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison weights : str, iterable, or generat...
def _getClassInstance(path, args=None): if not path.endswith(".py"): return None if args is None: args = {} classname = AtomShieldsScanner._getClassName(path) basename = os.path.basename(path).replace(".py", "") sys.path.append(os.path.dirname(path)) try: mod = __import__(basename, globals(), local...
Returns a class instance from a .py file. Args: path (str): Absolute path to .py file args (dict): Arguments passed via class constructor Returns: object: Class instance or None
def draw_buffers(self, near, far): self.ctx.disable(moderngl.DEPTH_TEST) helper.draw(self.gbuffer.color_attachments[0], pos=(0.0, 0.0), scale=(0.25, 0.25)) helper.draw(self.gbuffer.color_attachments[1], pos=(0.5, 0.0), scale=(0.25, 0.25)) helper.draw_depth(self.gbuffer.depth_attachment, ...
Draw framebuffers for debug purposes. We need to supply near and far plane so the depth buffer can be linearized when visualizing. :param near: Projection near value :param far: Projection far value
def money(min=0, max=10): value = random.choice(range(min * 100, max * 100)) return "%1.2f" % (float(value) / 100)
Return a str of decimal with two digits after a decimal mark.
def _tz(self, z): return (z-self.param_dict['psf-zslab'])*self.param_dict[self.zscale]
Transform z to real-space coordinates from tile coordinates
def set_action(self,action): if action is None: if self.xmlnode.hasProp("action"): self.xmlnode.unsetProp("action") return if action not in ("remove","update"): raise ValueError("Action must be 'update' or 'remove'") action = unicode(action) ...
Set the action of the item. :Parameters: - `action`: the new action or `None`. :Types: - `action`: `unicode`
def parallel_tfa_lcdir(lcdir, templateinfo, lcfileglob=None, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, ...
This applies TFA in parallel to all LCs in a directory. Parameters ---------- lcdir : str This is the directory containing the light curve files to process.. templateinfo : dict or str This is either the dict produced by `tfa_templates_lclist` or the pickle produced by the sam...
def build_message(self, data): if not data: return None return Message( id=data['message']['mid'], platform=self.platform, text=data['message']['text'], user=data['sender']['id'], timestamp=data['timestamp'], raw=data, ...
Return a Message instance according to the data received from Facebook Messenger API.
def _handle_array(toks): if len(toks) == 5 and toks[1] == '{' and toks[4] == '}': subtree = toks[2:4] signature = ''.join(s for (_, s) in subtree) [key_func, value_func] = [f for (f, _) in subtree] def the_dict_func(a_dict, variant=0): elements = \...
Generate the correct function for an array signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str
def outer_right_join(self, join_streamlet, window_config, join_function): from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_RIGHT, window_config, join_function, self, join_streamlet) self._add_ch...
Return a new Streamlet by outer right join_streamlet with this streamlet
def new(ABF,forceNewFigure=False,title=None,xlabel=None,ylabel=None): if len(pylab.get_fignums()) and forceNewFigure==False: return pylab.figure(figsize=(8,6)) pylab.grid(alpha=.5) pylab.title(ABF.ID) pylab.ylabel(ABF.units) pylab.xlabel("seconds") if xlabel: pylab.xlabel(xla...
makes a new matplotlib figure with default dims and DPI. Also labels it with pA or mV depending on ABF.
def _getExperimentDescriptionSchema(): installPath = os.path.dirname(os.path.abspath(__file__)) schemaFilePath = os.path.join(installPath, "experimentDescriptionSchema.json") return json.loads(open(schemaFilePath, 'r').read())
Returns the experiment description schema. This implementation loads it in from file experimentDescriptionSchema.json. Parameters: -------------------------------------------------------------------------- Returns: returns a dict representing the experiment description schema.
def generate_dirlist_html(FS, filepath): yield '<table class="dirlist">' if filepath == '/': filepath = '' for name in FS.listdir(filepath): full_path = pathjoin(filepath, name) if FS.isdir(full_path): full_path = full_path + '/' yield u'<tr><td><a href="{0}">{0}<...
Generate directory listing HTML Arguments: FS (FS): filesystem object to read files from filepath (str): path to generate directory listings for Keyword Arguments: list_dir (callable: list[str]): list file names in a directory isdir (callable: bool): os.path.isdir Yields: ...
def _random_token(self, bits=128): alphabet = string.ascii_letters + string.digits + '-_' num_letters = int(math.ceil(bits / 6.0)) return ''.join(random.choice(alphabet) for i in range(num_letters))
Generates a random token, using the url-safe base64 alphabet. The "bits" argument specifies the bits of randomness to use.
def run(self, data, results=None, mask=None, positions=None): model_image = results.last.unmasked_model_image galaxy_tuples = results.last.constant.name_instance_tuples_for_class(g.Galaxy) results_copy = copy.copy(results.last) for name, galaxy in galaxy_tuples: optimizer = s...
Run a fit for each galaxy from the previous phase. Parameters ---------- data: LensData results: ResultsCollection Results from all previous phases mask: Mask The mask positions Returns ------- results: HyperGalaxyResults ...
def set_share_path(self, share_path): assert share_path == "" or share_path.startswith("/") if share_path == "/": share_path = "" assert share_path in ("", "/") or not share_path.endswith("/") self.share_path = share_path
Set application location for this resource provider. @param share_path: a UTF-8 encoded, unquoted byte string.
def new_comment(self, string, start, end, line): prefix = line[:start[1]] if prefix.strip(): self.current_block.add(string, start, end, line) else: block = Comment(start[0], end[0], string) self.blocks.append(block) self.current_block = block
Possibly add a new comment. Only adds a new comment if this comment is the only thing on the line. Otherwise, it extends the noncomment block.
def make_sub_element(parent, tag, nsmap=None): if use_lxml: return etree.SubElement(parent, tag, nsmap=nsmap) return etree.SubElement(parent, tag)
Wrapper for etree.SubElement, that takes care of unsupported nsmap option.
def open(self): if self.seed_url: self.driver_adapter.open(self.seed_url) self.wait_for_page_to_load() return self raise UsageError("Set a base URL or URL_TEMPLATE to open this page.")
Open the page. Navigates to :py:attr:`seed_url` and calls :py:func:`wait_for_page_to_load`. :return: The current page object. :rtype: :py:class:`Page` :raises: UsageError
def get_request_date(cls, req): date = None for header in ['x-amz-date', 'date']: if header not in req.headers: continue try: date_str = cls.parse_date(req.headers[header]) except DateFormatError: continue tr...
Try to pull a date from the request by looking first at the x-amz-date header, and if that's not present then the Date header. Return a datetime.date object, or None if neither date header is found or is in a recognisable format. req -- a requests PreparedRequest object
def _prepare_pending(self): if not self._unprepared_pending: return for handler in list(self._unprepared_pending): self._configure_io_handler(handler) self.check_events()
Prepare pending handlers.
def get_parm(self, key): if key in self.__parm.keys(): return self.__parm[key] return None
Get parameter of FIO
def getdevice_by_uuid(uuid): with settings(hide('running', 'warnings', 'stdout'), warn_only=True): res = run_as_root('blkid -U %s' % uuid) if not res.succeeded: return None return res
Get a HDD device by uuid Example:: from burlap.disk import getdevice_by_uuid device = getdevice_by_uuid("356fafdc-21d5-408e-a3e9-2b3f32cb2a8c") if device: mount(device,'/mountpoint')
def build_machine_type(cls, min_cores, min_ram): min_cores = min_cores or job_model.DEFAULT_MIN_CORES min_ram = min_ram or job_model.DEFAULT_MIN_RAM min_ram *= GoogleV2CustomMachine._MB_PER_GB cores = cls._validate_cores(min_cores) ram = cls._validate_ram(min_ram) memory_to_cpu_ratio = ram / cor...
Returns a custom machine type string.
def merge_dicts(d1, d2, _path=None): if _path is None: _path = () if isinstance(d1, dict) and isinstance(d2, dict): for k, v in d2.items(): if isinstance(v, MissingValue) and v.name is None: v.name = '.'.join(_path + (k,)) if isinstance(v, DeletedValue): ...
Merge dictionary d2 into d1, overriding entries in d1 with values from d2. d1 is mutated. _path is for internal, recursive use.
def cur_space(self, name=None): if name is None: return self._impl.model.currentspace.interface else: self._impl.model.currentspace = self._impl.spaces[name] return self.cur_space()
Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned.
def _find_ancestor_from_name(self, name): if self.parent is None: return None if self.parent.get_name() == name: return self.parent return self.parent._find_ancestor_from_name(name)
Returns the ancestor that has a task with the given name assigned. Returns None if no such ancestor was found. :type name: str :param name: The name of the wanted task. :rtype: Task :returns: The ancestor.
def _apply_unique_checks(self, i, r, unique_sets, summarize=False, context=None): for key, code, message in self._unique_checks: value = None values = unique_sets[key] if isinstance(key, basestring): fi...
Apply unique checks on `r`.
def read(self, filenames): for fn in filenames: try: self.configs[fn] = ordered_json.load(fn) except IOError: self.configs[fn] = OrderedDict() except Exception as e: self.configs[fn] = OrderedDict() logging.warni...
Read a list of files. Their configuration values are merged, with preference to values from files earlier in the list.
def rm(self, filename): try: self._ftp.delete(filename) except error_perm: try: current_folder = self._ftp.pwd() self.cd(filename) except error_perm: print('550 Delete operation failed %s ' 'does no...
Delete a file from the server. :param filename: the file to be deleted. :type filename: string
def update(ctx, name, description, tags, private): user, project_name = get_project_or_local(ctx.obj.get('project')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description if private is not None: update_dict['is_public'] ...
Update project. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon update foobar --description="Image Classification with DL using TensorFlow" ``` \b ```bash $ polyaxon update mike1/foobar --description="Image Classification with DL using TensorFlow"...
def open(self): self.path = self._prepare_dir(self.topdir) self._copy_executable(area_path=self.path) self._save_logging_levels(area_path=self.path) self._put_python_modules(modules=self.python_modules, area_path=self.path)
Open the working area Returns ------- None
def do_internal_run(self, initial_count=0, subblock=None, update_derr=True): self._inner_run_counter = initial_count; good_step = True n_good_steps = 0 CLOG.debug('Running...') _last_residuals = self.calc_residuals().copy() while ((self._inner_run_counter < self.run_length) & goo...
Takes more steps without calculating J again. Given a fixed damping, J, JTJ, iterates calculating steps, with optional Broyden or eigendirection updates. Iterates either until a bad step is taken or for self.run_length times. Called internally by do_run_2() but is also useful on its own...
def matlab_formatter(level, vertices, codes=None): vertices = numpy_formatter(level, vertices, codes) if codes is not None: level = level[0] headers = np.vstack(( [v.shape[0] for v in vertices], [level]*len(vertices))).T vertices = np.vstack( list(it.__next__() for it in ...
`MATLAB`_ style contour formatter. Contours are returned as a single Nx2, `MATLAB`_ style, contour array. There are two types of rows in this format: * Header: The first element of a header row is the level of the contour (the lower level for filled contours) and the second element is the numb...
def _stream_data_chunked(self, environ, block_size): if "Darwin" in environ.get("HTTP_USER_AGENT", "") and environ.get( "HTTP_X_EXPECTED_ENTITY_LENGTH" ): WORKAROUND_CHUNK_LENGTH = True buf = environ.get("HTTP_X_EXPECTED_ENTITY_LENGTH", "0") length = int(b...
Get the data from a chunked transfer.
def norm_and_check(source_tree, requested): if os.path.isabs(requested): raise ValueError("paths must be relative") abs_source = os.path.abspath(source_tree) abs_requested = os.path.normpath(os.path.join(abs_source, requested)) norm_source = os.path.normcase(abs_source) norm_requested = os.p...
Normalise and check a backend path. Ensure that the requested backend path is specified as a relative path, and resolves to a location under the given source tree. Return an absolute version of the requested path.
def _days_in_month(year, month): "year, month -> number of days in that month in that year." assert 1 <= month <= 12, month if month == 2 and _is_leap(year): return 29 return _DAYS_IN_MONTH[month]
year, month -> number of days in that month in that year.
def _transmit_create(self, channel_metadata_item_map): for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size): serialized_chunk = self._serialize_items(list(chunk.values())) try: self.client.create_content_metadata(serialized...
Transmit content metadata creation to integrated channel.
def str_from_text(text): REGEX = re.compile('<text>((.|\n)+)</text>', re.UNICODE) match = REGEX.match(text) if match: return match.group(1) else: return None
Return content of a free form text block as a string.
def embed(self, url, **kwargs): try: provider = self.provider_for_url(url) except OEmbedMissingEndpoint: raise else: try: stored_match = StoredOEmbed.objects.filter( match=url, maxwidth=kwargs.get('maxwi...
The heart of the matter
def gen_drawdown_table(returns, top=10): df_cum = ep.cum_returns(returns, 1.0) drawdown_periods = get_top_drawdowns(returns, top=top) df_drawdowns = pd.DataFrame(index=list(range(top)), columns=['Net drawdown in %', 'Peak date', ...
Places top drawdowns in a table. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. top : int, optional The amount of top drawdowns to find (default 10). Returns ------- df...
def _run_supervisor(self): import time still_supervising = lambda: ( multiprocessing.active_children() or not self.log_queue.empty() or not self.exception_queue.empty()) try: while still_supervising(): try: ...
Poll the queues that the worker can use to communicate with the supervisor, until all the workers are done and all the queues are empty. Handle messages as they appear.
def rename_file(self, relativePath, name, newName, replace=False, verbose=True): relativePath = os.path.normpath(relativePath) if relativePath == '.': relativePath = '' dirInfoDict, errorMessage = self.get_directory_info(relativePath) assert dirInfoDict is not None, errorMess...
Rename a directory in the repository. It insures renaming the file in the system. :Parameters: #. relativePath (string): The relative to the repository path of the directory where the file is located. #. name (string): The file name. #. newName (string): The file new name. ...
def comments_load(self): self.comment_times,self.comment_sweeps,self.comment_tags=[],[],[] self.comments=0 self.comment_text="" try: self.comment_tags = list(self.ABFblock.segments[0].eventarrays[0].annotations['comments']) self.comment_times = list(self.ABFblock....
read the header and populate self with information about comments
def _createSegment(cls, connections, lastUsedIterationForSegment, cell, iteration, maxSegmentsPerCell): while connections.numSegments(cell) >= maxSegmentsPerCell: leastRecentlyUsedSegment = min( connections.segmentsForCell(cell), key=lambda segment : lastUsedIterationForSe...
Create a segment on the connections, enforcing the maxSegmentsPerCell parameter.
def loadJsonValueFromFile(inputFilePath): with open(inputFilePath) as fileObj: value = json.load(fileObj) return value
Loads a json value from a file and converts it to the corresponding python object. inputFilePath: Path of the json file; Returns: python value that represents the loaded json value
def handle_move(self, dest_path): if "/by_tag/" not in self.path: raise DAVError(HTTP_FORBIDDEN) if "/by_tag/" not in dest_path: raise DAVError(HTTP_FORBIDDEN) catType, tag, _rest = util.save_split(self.path.strip("/"), "/", 2) assert catType == "by_tag" a...
Change semantic of MOVE to change resource tags.
def load_document(self, id): fields = self.redis.hgetall(id) if six.PY3: f2 = {to_string(k): to_string(v) for k, v in fields.items()} fields = f2 try: del fields['id'] except KeyError: pass return Document(id=id, **fields)
Load a single document by id
def _toStringSubclass(self, text, subclass): self.endData() self.handle_data(text) self.endData(subclass)
Adds a certain piece of text to the tree as a NavigableString subclass.
def Loc(kind, loc=None): @llrule(loc, lambda parser: [kind]) def rule(parser): result = parser._accept(kind) if result is unmatched: return result return result.loc return rule
A rule that accepts a token of kind ``kind`` and returns its location, or returns None.
def add(self, *args, **kwargs): if 'question' in kwargs and isinstance(kwargs['question'], Question): question = kwargs['question'] else: question = Question(*args, **kwargs) self.questions.setdefault(question.key, []).append(question) return question
Add a Question instance to the questions dict. Each key points to a list of Question instances with that key. Use the `question` kwarg to pass a Question instance if you want, or pass in the same args you would pass to instantiate a question.
def detect_color_support(env): if env.get('COLORFUL_DISABLE', '0') == '1': return NO_COLORS if env.get('COLORFUL_FORCE_8_COLORS', '0') == '1': return ANSI_8_COLORS if env.get('COLORFUL_FORCE_16_COLORS', '0') == '1': return ANSI_16_COLORS if env.get('COLORFUL_FORCE_256_COLORS', '0...
Detect what color palettes are supported. It'll return a valid color mode to use with colorful. :param dict env: the environment dict like returned by ``os.envion``
def _getAttrMap(self): if not getattr(self, 'attrMap'): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap
Initializes a map representation of this tag's attributes, if not already initialized.
def rollaxis(a, axis, start=0): if isinstance(a, np.ndarray): return np.rollaxis(a, axis, start) if axis not in range(a.ndim): raise ValueError( 'rollaxis: axis (%d) must be >=0 and < %d' % (axis, a.ndim)) if start not in range(a.ndim + 1): raise ValueError( ...
Roll the specified axis backwards, until it lies in a given position. Args: a (array_like): Input array. axis (int): The axis to roll backwards. The positions of the other axes do not change relative to one another. start (int, optional): The axis is rolled until it lies before this ...
def dist( self, src, tar, word_approx_min=0.3, char_approx_min=0.73, tests=2 ** 12 - 1, ): return ( synoname(src, tar, word_approx_min, char_approx_min, tests, False) / 14 )
Return the normalized Synoname distance between two words. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison word_approx_min : float The minimum word approximation value to signal a 'word_appro...
def _gzip_sqlitecurve(sqlitecurve, force=False): if force: cmd = 'gzip -k -f %s' % sqlitecurve else: cmd = 'gzip -k %s' % sqlitecurve try: outfile = '%s.gz' % sqlitecurve if os.path.exists(outfile) and not force: os.remove(sqlitecurve) return outfile ...
This just compresses the sqlitecurve in gzip format. FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).
def hash(self, id): h = md5(id).hexdigest() return os.path.join(self.path, h+self.type)
Creates a unique filename in the cache for the id.
def update(self, key, value): if key not in self.value: self.value[key] = ReducedMetric(self.reducer) self.value[key].update(value)
Updates a value of a given key and apply reduction
def connected_channel(self): if not self.channel_id: return None return self._lavalink.bot.get_channel(int(self.channel_id))
Returns the voice channel the player is connected to.
def gmv(a, b): return np.exp(np.square(np.log(a) - np.log(b)).mean())
Geometric mean variance
def intersection(tiles, *args): tiles = listify(tiles) + listify(args) if len(tiles) < 2: return tiles[0] tile = tiles[0] l, r = tile.l.copy(), tile.r.copy() for tile in tiles[1:]: l = amax(l, tile.l) r = amin(r, tile.r) return Tile(l, ...
Intersection of tiles, returned as a tile >>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5])) Tile [1, 1] -> [4, 4] ([3, 3])
def has_credentials(self): if not self.credentials: return False elif (self.credentials.access_token_expired and not self.credentials.refresh_token): return False else: return True
Returns True if there are valid credentials for the current user.
def _do_action_left(self, state): reward = 0 for row in range(4): merge_candidate = -1 merged = np.zeros((4,), dtype=np.bool) for col in range(4): if state[row, col] == 0: continue if (merge_candidate != -1 and ...
Executes action 'Left'.
def run(self, next_task): self.event.wait() self.task() self.event.clear() next_task.event.set()
Wait for the event, run the task, trigger the next task.
def save(self, msg, args): self.send_message(msg.channel, "Saving current state...") self._bot.plugins.save_state() self.send_message(msg.channel, "Done.")
Causes the bot to write its current state to backend.
def add_link(cls, attr, title='', display=''): global klass_count klass_count += 1 fn_name = 'dyn_fn_%d' % klass_count cls.list_display.append(fn_name) if not title: title = attr.capitalize() _display = display def _link(self, obj): field_o...
Adds a ``list_display`` attribute that appears as a link to the django admin change page for the type of object being shown. Supports double underscore attribute name dereferencing. :param attr: Name of the attribute to dereference from the corresponding object, i.e. wha...
def install_apt(self, fn=None, package_name=None, update=0, list_only=0): r = self.local_renderer assert self.genv[ROLE] apt_req_fqfn = fn or (self.env.apt_requirments_fn and self.find_template(self.env.apt_requirments_fn)) if not apt_req_fqfn: return [] assert os.pat...
Installs system packages listed in apt-requirements.txt.
def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20): url = self.url + "collections/" response = self._conn.get(url, headers={"Accept": accept}) self._collections = [] for item in response.get("collections", []): collection_url = url + item["id"] + "/" colle...
Update the list of Collections contained by this API Root. This invokes the ``Get Collections`` endpoint.
def parent_callback(self, executor_fu): with self._update_lock: if not executor_fu.done(): raise ValueError("done callback called, despite future not reporting itself as done") if executor_fu != self.parent: if executor_fu.exception() is None and not isins...
Callback from a parent future to update the AppFuture. Used internally by AppFuture, and should not be called by code using AppFuture. Args: - executor_fu (Future): Future returned by the executor along with callback. This may not be the current parent future, as the parent f...
def stat(self, input_filepath, scale=None, rms=False): effect_args = ['channels', '1', 'stat'] if scale is not None: if not is_number(scale) or scale <= 0: raise ValueError("scale must be a positive number.") effect_args.extend(['-s', '{:f}'.format(scale)]) ...
Display time and frequency domain statistical information about the audio. Audio is passed unmodified through the SoX processing chain. Unlike other Transformer methods, this does not modify the transformer effects chain. Instead it computes statistics on the output file that would be c...
def _synoname_strip_punct(self, word): stripped = '' for char in word: if char not in set(',-./:;"&\'()!{|}?$%*+<=>[\\]^_`~'): stripped += char return stripped.strip()
Return a word with punctuation stripped out. Parameters ---------- word : str A word to strip punctuation from Returns ------- str The word stripped of punctuation Examples -------- >>> pe = Synoname() >>> pe._syn...
def _updateBoostFactorsGlobal(self): if (self._localAreaDensity > 0): targetDensity = self._localAreaDensity else: inhibitionArea = ((2 * self._inhibitionRadius + 1) ** self._columnDimensions.size) inhibitionArea = min(self._numColumns, inhibitionArea) targetDensi...
Update boost factors when global inhibition is used
def _hook_write_mem(self, uc, access, address, size, value, data): self._mem_delta[address] = (value, size) return True
Captures memory written by Unicorn
def _get_flow_for_token(csrf_token): flow_pickle = session.pop( _FLOW_KEY.format(csrf_token), None) if flow_pickle is None: return None else: return pickle.loads(flow_pickle)
Retrieves the flow instance associated with a given CSRF token from the Flask session.
def upload_bel_namespace(self, update: bool = False) -> Namespace: if not self.is_populated(): self.populate() namespace = self._get_default_namespace() if namespace is None: log.info('making namespace for %s', self._get_namespace_name()) return self._make_nam...
Upload the namespace to the PyBEL database. :param update: Should the namespace be updated first?
def outputs(ctx): user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: PolyaxonClient().job.download_outputs(user, project_name, _job) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not dow...
Download outputs for job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job -j 1 outputs ```
def _build_stat(self, idx): nameordered = self.samples.keys() nameordered.sort() newdat = pd.DataFrame([self.samples[i].stats_dfs[idx] \ for i in nameordered], index=nameordered)\ .dropna(axis=1, how='all') return newdat
Returns a data frame with Sample stats for each step
def csi_wrap(self, value, capname, *args): if isinstance(value, str): value = value.encode('utf-8') return b''.join([ self.csi(capname, *args), value, self.csi('sgr0'), ])
Return a value wrapped in the selected CSI and does a reset.
def _extract_links(self): extracted = dict() try: for key, value in self.request.links.items(): parsed = urlparse(value["url"]) fragment = "{path}?{query}".format(path=parsed[2], query=parsed[4]) extracted[key] = fragment parsed = l...
Extract self, first, next, last links from a request response
def remove_dcm2nii_underprocessed(filepaths): cln_flist = [] len_sorted = sorted(filepaths, key=len) for idx, fpath in enumerate(len_sorted): remove = False fname = op.basename(fpath) rest = len_sorted[idx+1:] for rest_fpath in rest: rest_file = op.basename(rest_...
Return a subset of `filepaths`. Keep only the files that have a basename longer than the others with same suffix. This works based on that dcm2nii appends a preffix character for each processing step it does automatically in the DICOM to NifTI conversion. Parameters ---------- filepaths: iterab...
def platform_detect(): pi = pi_version() if pi is not None: return RASPBERRY_PI plat = platform.platform() if plat.lower().find('armv7l-with-debian') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('armv7l-with-ubuntu') > -1: return BEAGLEBONE_BLACK elif plat.lower()...
Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.
def height(self): if len(self.coords) <= 1: return 0 return np.max(self.yy) - np.min(self.yy)
Get the height of a bounding box encapsulating the line.
def pushd(path): saved = os.getcwd() os.chdir(path) try: yield saved finally: os.chdir(saved)
A context that enters a given directory and restores the old state on exit. The original directory is returned as the context variable.
def getLabels(self, start=None, end=None): if len(self._recordsCache) == 0: return { 'isProcessing': False, 'recordLabels': [] } try: start = int(start) except Exception: start = 0 try: end = int(end) except Exception: end = self._recordsCache[-1]....
Get the labels on classified points within range start to end. Not inclusive of end. :returns: (dict) with format: :: { 'isProcessing': boolean, 'recordLabels': list of results } ``isProcessing`` - currently always false as recalculation blocks; used if ...
def to_representation(self, instance): updated_course = copy.deepcopy(instance) enterprise_customer_catalog = self.context['enterprise_customer_catalog'] updated_course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url( updated_course['key'] ) ...
Return the updated course data dictionary. Arguments: instance (dict): The course data. Returns: dict: The updated course data.
def Match(pattern, s): if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s)
Matches the string with the pattern, caching the compiled regexp.
def end(self): results = self.communicationChannel.receive() if self.nruns != len(results): import logging logger = logging.getLogger(__name__) logger.warning( 'too few results received: {} results received, {} expected'.format( len...
wait until all event loops end and returns the results.
def Negative(other_param, mode="invert", reroll_count_max=2): return ForceSign( other_param=other_param, positive=False, mode=mode, reroll_count_max=reroll_count_max )
Converts another parameter's results to negative values. Parameters ---------- other_param : imgaug.parameters.StochasticParameter Other parameter which's sampled values are to be modified. mode : {'invert', 'reroll'}, optional How to change the signs. Valid values are ``invert...
def IsErrorSuppressedByNolint(category, linenum): return (_global_error_suppressions.get(category, False) or linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: ...