code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def peers(**kwargs): ntp_peers = salt.utils.napalm.call( napalm_device, 'get_ntp_peers', **{ } ) if not ntp_peers.get('result'): return ntp_peers ntp_peers_list = list(ntp_peers.get('out', {}).keys()) ntp_peers['out'] = ntp_peers_list return ntp_peers
Returns a list the NTP peers configured on the network device. :return: configured NTP peers as list. CLI Example: .. code-block:: bash salt '*' ntp.peers Example output: .. code-block:: python [ '192.168.0.1', '172.17.17.1', '172.17.17.2', ...
def transform(self, data, centers=None): centers = centers or self.centers_ hypercubes = [ self.transform_single(data, cube, i) for i, cube in enumerate(centers) ] hypercubes = [cube for cube in hypercubes if len(cube)] return hypercubes
Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`. Empty hypercubes are removed from the result Parameters =========== data: array-like Data to find in entries in cube. Warning: first column must be index ...
def set_color(self, ipaddr, hue, sat, bri, kel, fade): cmd = {"payloadtype": PayloadType.SETCOLOR, "target": ipaddr, "hue": hue, "sat": sat, "bri": bri, "kel": kel, "fade": fade} self._send_command(cmd)
Send SETCOLOR message.
def validate_model(self): model: AssetAllocationModel = self.get_asset_allocation_model() model.logger = self.logger valid = model.validate() if valid: print(f"The model is valid. Congratulations") else: print(f"The model is invalid.")
Validate the model
def capture_heroku_database(self): self.print_message("Capturing database backup for app '%s'" % self.args.source_app) args = [ "heroku", "pg:backups:capture", "--app=%s" % self.args.source_app, ] if self.args.use_pgbackups: args = [ ...
Capture Heroku database backup.
def clone(self, parent=None): a = Attribute(self.qname(), self.value) a.parent = parent return a
Clone this object. @param parent: The parent for the clone. @type parent: L{element.Element} @return: A copy of this object assigned to the new parent. @rtype: L{Attribute}
def _get_at_from_session(self): try: return self.request.session['oauth_%s_access_token' % get_token_prefix( self.request_token_url)] except KeyError: raise OAuthError( _('No acces...
Get the saved access token for private resources from the session.
def GenerateDSP(dspfile, source, env): version_num = 6.0 if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 10.0: g = _GenerateV10DSP(dspfile, source, env) g.Build() elif version_num >= 7.0: g = _GenerateV7DSP(dspfile,...
Generates a Project file based on the version of MSVS that is being used
def estimate_sub_second_time(files, interval=0.0): if interval <= 0.0: return [exif_time(f) for f in tqdm(files, desc="Reading image capture time")] onesecond = datetime.timedelta(seconds=1.0) T = datetime.timedelta(seconds=interval) for i, f in tqdm(enumerate(files), desc="Estimating subsecond ...
Estimate the capture time of a sequence with sub-second precision EXIF times are only given up to a second of precision. This function uses the given interval between shots to estimate the time inside that second that each picture was taken.
def delete(self): response = self.session.request("delete:Message", [ self.message_id ]) self.data = response return self
Delete the draft.
def is_manifest_valid(self, manifest_id): response = self.get_manifest_validation_result(manifest_id) if response.status_code != 200: raise Exception(response.status_code) content = json.loads(response.content) if not content['processed']: return None if c...
Check validation shortcut :param: manifest_id (string) id received in :method:`validate_manifest` :returns: * True if manifest was valid * None if manifest wasn't checked yet * validation dict if not valid
def verify_token(self, token, **kwargs): nonce = kwargs.get('nonce') token = force_bytes(token) if self.OIDC_RP_SIGN_ALGO.startswith('RS'): if self.OIDC_RP_IDP_SIGN_KEY is not None: key = self.OIDC_RP_IDP_SIGN_KEY else: key = self.retrieve_...
Validate the token signature.
def from_cif_file(cif_file, source='', comment=''): r = CifParser(cif_file) structure = r.get_structures()[0] return Header(structure, source, comment)
Static method to create Header object from cif_file Args: cif_file: cif_file path and name source: User supplied identifier, i.e. for Materials Project this would be the material ID number comment: User comment that goes in header Returns: ...
def _output_format(self, out, fmt_j=None, fmt_p=None): if self.output_format == 'pandas': if fmt_p is not None: return fmt_p(out) else: return self._convert_output(out) if fmt_j: return fmt_j(out) return out
Output formatting handler
def to_api_repr(self): resource = {self.entity_type: self.entity_id} if self.role is not None: resource["role"] = self.role return resource
Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource
def save_cert(domain, master): result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "...
Save the certificate for master icinga2 node. Returns:: icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld CLI Example: .. code-block:: bash salt '*' icinga2.save_ce...
def validate_attribute(attr, name, expected_type=None, required=False): if expected_type: if type(expected_type) == list: if not _check_type(attr, expected_type): raise InvalidTypeError(name, type(attr), expected_type) else: if not _check_type(attr, [expected_...
Validates that an attribute meets expectations. This function will check if the given attribute value matches a necessary type and/or is not None, an empty string, an empty list, etc. It will raise suitable exceptions on validation failure. @param attr The value to validate. @param name The attrib...
def _flush(self): if not self.enabled: return try: try: self.lock.acquire() self.flush() except Exception: self.log.error(traceback.format_exc()) finally: if self.lock.locked(): self.l...
Decorator for flushing handlers with an lock, catching exceptions
async def get_available_abilities(self, units: Union[List[Unit], Units], ignore_resource_requirements=False) -> List[List[AbilityId]]: return await self._client.query_available_abilities(units, ignore_resource_requirements)
Returns available abilities of one or more units.
def remove_whitespace(s): ignores = {} for ignore in html_ignore_whitespace_re.finditer(s): name = "{}{}{}".format(r"{}", uuid.uuid4(), r"{}") ignores[name] = ignore.group() s = s.replace(ignore.group(), name) s = whitespace_re(r' ', s).strip() for name, val in ignores.items(): ...
Unsafely attempts to remove HTML whitespace. This is not an HTML parser which is why its considered 'unsafe', but it should work for most implementations. Just use on at your own risk. @s: #str -> HTML with whitespace removed, ignoring <pre>, script, textarea and code tags
def _check_if_ins_is_dup(self, start, insertion): is_dup = False variant_start = None dup_candidate_start = start - len(insertion) - 1 dup_candidate = self._ref_seq[dup_candidate_start:dup_candidate_start + len(insertion)] if insertion == dup_candidate: is_dup = True ...
Helper to identify an insertion as a duplicate :param start: 1-based insertion start :type start: int :param insertion: sequence :type insertion: str :return (is duplicate, variant start) :rtype (bool, int)
def relpath(self, start='.'): cwd = self._next_class(start) return cwd.relpathto(self)
Return this path as a relative path, based from `start`, which defaults to the current working directory.
def makeaddress(self, label): addr = address.new(label) if not addr.repo: addr.repo = self.address.repo if not addr.path: addr.path = self.address.path return addr
Turn a label into an Address with current context. Adds repo and path if given a label that only has a :target part.
def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False): if events is None: events = ["push"] data = { "type": hook_type, "config": config, "events": events, "active": active } url...
Creates a new hook, and returns the created hook. :param auth.Authentication auth: authentication object, must be admin-level :param str repo_name: the name of the repo for which we create the hook :param str hook_type: The type of webhook, either "gogs" or "slack" :param dict config: S...
def set_line_width(self, width): "Set line width" self.line_width=width if(self.page>0): self._out(sprintf('%.2f w',width*self.k))
Set line width
def apply_with_summary(input_layer, operation, *op_args, **op_kwargs): return layers.apply_activation(input_layer.bookkeeper, input_layer.tensor, operation, activation_args=op_args, acti...
Applies the given operation to `input_layer` and create a summary. Args: input_layer: The input layer for this op. operation: An operation that takes a tensor and the supplied args. *op_args: Extra arguments for operation. **op_kwargs: Keyword arguments for the operation. Returns: A new layer w...
def is_merged(sheet, row, column): for cell_range in sheet.merged_cells: row_low, row_high, column_low, column_high = cell_range if (row in range(row_low, row_high)) and \ (column in range(column_low, column_high)): if ((column_high - column_low) < sheet.ncols - 1) and \ ...
Check if a row, column cell is a merged cell
def _acronym_lic(self, license_statement): pat = re.compile(r'\(([\w+\W?\s?]+)\)') if pat.search(license_statement): lic = pat.search(license_statement).group(1) if lic.startswith('CNRI'): acronym_licence = lic[:4] else: acronym_licence...
Convert license acronym.
def setup(self, helper=None, **create_kwargs): if self.created: return self.set_helper(helper) self.create(**create_kwargs) return self
Setup this resource so that is ready to be used in a test. If the resource has already been created, this call does nothing. For most resources, this just involves creating the resource in Docker. :param helper: The resource helper to use, if one was not provided when this ...
def import_(zone, path): ret = {'status': True} _dump_cfg(path) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=path, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'...
Import the configuration to memory from stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.import epyon /zones/epyon.cfg
def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window: if size is None: width, height = 1280, 720 else: width, height = size if samples < 0 or (samples & (samples - 1)) != 0: raise Exception('Invalid number of samples: %d' % samples) w...
Create the main window. Args: size (tuple): The width and height of the window. samples (int): The number of samples. Keyword Args: fullscreen (bool): Fullscreen? title (bool): The title of the window. threaded (bool): Threaded? Retu...
def dump(*args, **kwargs): kwargs.update(dict(cls=NumpyEncoder, sort_keys=True, indent=4, separators=(',', ': '))) return _json.dump(*args, **kwargs)
Dump a numpy.ndarray to file stream. This works exactly like the usual `json.dump()` function, but it uses our custom serializer.
def wildcard_allowed_actions(self, pattern=None): wildcard_allowed = [] for statement in self.statements: if statement.wildcard_actions(pattern) and statement.effect == "Allow": wildcard_allowed.append(statement) return wildcard_allowed
Find statements which allow wildcard actions. A pattern can be specified for the wildcard action
def NegateQueryFilter(es_query): query = es_query.to_dict().get("query", {}) filtered = query.get("filtered", {}) negated_filter = filtered.get("filter", {}) return Not(**negated_filter)
Return a filter removing the contents of the provided query.
def _pause(self): if self._input_func in self._netaudio_func_list: body = {"cmd0": "PutNetAudioCommand/CurEnter", "cmd1": "aspMainZone_WebUpdateStatus/", "ZoneName": "MAIN ZONE"} try: if self.send_post_command( ...
Send pause command to receiver command via HTTP post.
def _create_batches(self, X, batch_size, shuffle_data=True): if shuffle_data: X = shuffle(X) if batch_size > X.shape[0]: batch_size = X.shape[0] max_x = int(np.ceil(X.shape[0] / batch_size)) X = np.resize(X, (max_x, batch_size, X.shape[-1])) return X
Create batches out of a sequence of data. This function will append zeros to the end of your data to ensure that all batches are even-sized. These are masked out during training.
def _bubbleP(cls, T): c = cls._blend["bubble"] Tj = cls._blend["Tj"] Pj = cls._blend["Pj"] Tita = 1-T/Tj suma = 0 for i, n in zip(c["i"], c["n"]): suma += n*Tita**(i/2.) P = Pj*exp(Tj/T*suma) return P
Using ancillary equation return the pressure of bubble point
def fetchThreads(self, thread_location, before=None, after=None, limit=None): threads = [] last_thread_timestamp = None while True: if limit and len(threads) >= limit: break candidates = self.fetchThreadList( before=last_thread_timestamp, t...
Get all threads in thread_location. Threads will be sorted from newest to oldest. :param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER :param before: Fetch only thread before this epoch (in ms) (default all threads) :param after: Fetch only thread after this ...
def output(output_id, name, value_class=NumberValue): def _init(): return value_class( name, input_id=output_id, is_input=False, index=-1 ) def _decorator(cls): setattr(cls, output_id, _init()) ...
Add output to controller
def create_attributes(klass, attributes, previous_object=None): if previous_object is not None: return {'name': attributes.get('name', previous_object.name)} return { 'name': attributes.get('name', ''), 'defaultLocale': attributes['default_locale'] }
Attributes for space creation.
def convert_random_normal(node, **kwargs): name, input_nodes, attrs = get_inputs(node, kwargs) mean = float(attrs.get("loc", 0)) scale = float(attrs.get("scale", 1.0)) shape = convert_string_to_list(attrs.get('shape', '[]')) dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'fl...
Map MXNet's random_normal operator attributes to onnx's RandomNormal operator and return the created node.
def include(self): include_param = self.qs.get('include', []) if current_app.config.get('MAX_INCLUDE_DEPTH') is not None: for include_path in include_param: if len(include_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']: raise InvalidInclude("Yo...
Return fields to include :return list: a list of include information
def change_keys(obj, convert): if isinstance(obj, (str, int, float)): return obj if isinstance(obj, dict): new = obj.__class__() for k, v in obj.items(): new[convert(k)] = change_keys(v, convert) elif isinstance(obj, (list, set, tuple)): new = obj.__class__(change...
Recursively goes through the dictionary obj and replaces keys with the convert function.
def iter_nautilus(method): solution = None while method.current_iter: preference_class = init_nautilus(method) pref = preference_class(method, None) default = ",".join(map(str, pref.default_input())) while method.current_iter: method.print_current_iteration() ...
Iterate NAUTILUS method either interactively, or using given preferences if given Parameters ---------- method : instance of NAUTILUS subclass Fully initialized NAUTILUS method instance
def upcoming_shabbat(self): if self.is_shabbat: return self saturday = self.gdate + datetime.timedelta( (12 - self.gdate.weekday()) % 7) return HDate(saturday, diaspora=self.diaspora, hebrew=self.hebrew)
Return the HDate for either the upcoming or current Shabbat. If it is currently Shabbat, returns the HDate of the Saturday.
def compute_layers(elements: List[Keccak256]) -> List[List[Keccak256]]: elements = list(elements) assert elements, 'Use make_empty_merkle_tree if there are no elements' if not all(isinstance(item, bytes) for item in elements): raise ValueError('all elements must be bytes') if any(len(item) != 32...
Computes the layers of the merkletree. First layer is the list of elements and the last layer is a list with a single entry, the merkleroot.
def fill_in_by_selector(self, selector, value): elem = find_element_by_jquery(world.browser, selector) elem.clear() elem.send_keys(value)
Fill in the form element matching the CSS selector.
def ffPDC(self): A = self.A() return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2), keepdims=True)))
Full frequency partial directed coherence. .. math:: \mathrm{ffPDC}_{ij}(f) = \\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}}
def get_example_extractions(fname): "Get extractions from one of the examples in `cag_examples`." with open(fname, 'r') as f: sentences = f.read().splitlines() rdf_xml_dict = {} for sentence in sentences: logger.info("Reading \"%s\"..." % sentence) html = tc.send_query(sentence, ...
Get extractions from one of the examples in `cag_examples`.
def _check_smart_storage_message(self): ssc_mesg = self.smart_storage_config_message result = True raid_message = "" for element in ssc_mesg: if "Success" not in element['MessageId']: result = False raid_message = element['MessageId'] r...
Check for smart storage message. :returns: result, raid_message
def ip2hex(ip): parts = ip.split(".") if len(parts) != 4: return None ipv = 0 for part in parts: try: p = int(part) if p < 0 or p > 255: return None ipv = (ipv << 8) + p except: return None return ipv
Converts an ip to a hex value that can be used with a hex bit mask
def get_locations_from_coords(self, longitude, latitude, levels=None): resp = requests.get(SETTINGS['url'] + '/point/4326/%s,%s?generation=%s' % (longitude, latitude, SETTINGS['generation'])) resp.raise_for_status() geos = [] for feature in resp.json().itervalues(): try: ...
Returns a list of geographies containing this point.
def content_create(self, key, model, contentid, meta, protected=False): params = {'id': contentid, 'meta': meta} if protected is not False: params['protected'] = 'true' data = urlencode(params) path = PROVISION_MANAGE_CONTENT + model + '/' return self._request(path, ...
Creates a content entity bucket with the given `contentid`. This method maps to https://github.com/exosite/docs/tree/master/provision#post---create-content-entity. Args: key: The CIK or Token for the device model: contentid: The ID used to name the entity bu...
def add(self, operator): if not isinstance(operator, Scope): raise ParameterError('Operator {} must be a TaskTransformer ' 'or FeatureExtractor'.format(operator)) for key in operator.fields: self._time[key] = [] for tdim, idx in enumer...
Add an operator to the Slicer Parameters ---------- operator : Scope (TaskTransformer or FeatureExtractor) The new operator to add
def configure(): log_levels = { 5: logging.NOTSET, 4: logging.DEBUG, 3: logging.INFO, 2: logging.WARNING, 1: logging.ERROR, 0: logging.CRITICAL } logging.captureWarnings(True) root_logger = logging.getLogger() if settings.CFG["debug"]: details_...
Load logging configuration from our own defaults.
def precision_score(y_true, y_pred, average='micro', suffix=False): true_entities = set(get_entities(y_true, suffix)) pred_entities = set(get_entities(y_pred, suffix)) nb_correct = len(true_entities & pred_entities) nb_pred = len(pred_entities) score = nb_correct / nb_pred if nb_pred > 0 else 0 ...
Compute the precision. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample. The best value is 1 and the worst value is 0. A...
def get_status(self): result = '' if self._data_struct is not None: result = self._data_struct[KEY_STATUS] return result
Return the status embedded in the JSON error response body, or an empty string if the JSON couldn't be parsed.
def _service_by_name(name): services = _available_services() name = name.lower() if name in services: return services[name] for service in six.itervalues(services): if service['file_path'].lower() == name: return service basename, ext = os.path.splitext(service['filen...
Return the service info for a service by label, filename or path
def tasks_all_replaced_predicate( service_name, old_task_ids, task_predicate=None ): try: task_ids = get_service_task_ids(service_name, task_predicate) except DCOSHTTPException: print('failed to get task ids for service {}'.format(service_name)) task_ids = [] ...
Returns whether ALL of old_task_ids have been replaced with new tasks :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by get_service_task_ids :type old_task_ids: [str] :param task_predicate: filter to use w...
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True): graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( 'Scope "%s" already exists. Provide explicit scope names when ' 'importing multiple instances of the model.') % scope t_input, t_prep_...
Import model GraphDef into the current graph.
def fileMD5(filename, partial=True): filesize = os.path.getsize(filename) md5 = hash_md5() block_size = 2**20 try: if (not partial) or filesize < 2**24: with open(filename, 'rb') as f: while True: data = f.read(block_size) if no...
Calculate partial MD5, basically the first and last 8M of the file for large files. This should signicicantly reduce the time spent on the creation and comparison of file signature when dealing with large bioinformat ics datasets.
def _find_file_meta(metadata, bucket_name, saltenv, path): env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = {} for bucket in env_meta: if bucket_name in bucket: bucket_meta = bucket[bucket_name] files_meta = list(list(filter((lambda k: 'Key' in k), bucket_met...
Looks for a file's metadata in the S3 bucket cache file
def copymode(self, target): shutil.copymode(self.path, self._to_backend(target))
Copies the mode of this file on the `target` file. The owner is not copied.
def _add_example_helper(self, example): for label, example_field in example.fields.items(): if not any(label == f.name for f in self.all_fields): raise InvalidSpec( "Example for '%s' has unknown field '%s'." % (self.name, label), ...
Validates examples for structs without enumerated subtypes.
def rowsum_stdev(x, beta): r n = x.size betabar = (1.0/n) * np.dot(x, beta) stdev = np.sqrt((1.0/n) * np.sum(np.power(np.multiply(x, beta) - betabar, 2))) return stdev/betabar
r"""Compute row sum standard deviation. Compute for approximation x, the std dev of the row sums s(x) = ( 1/n \sum_k (x_k beta_k - betabar)^2 )^(1/2) with betabar = 1/n dot(beta,x) Parameters ---------- x : array beta : array Returns ------- s(x)/betabar : float Notes ...
def extract_references_from_string(source, is_only_references=True, recid=None, reference_format="{title} {volume} ({year}) {page}", linker_callback=None, ...
Extract references from a raw string. The first parameter is the path to the file. It returns a tuple (references, stats). If the string does not only contain references, improve accuracy by specifing ``is_only_references=False``. The standard reference format is: {title} {volume} ({year}) {page}...
def markers(self, values): if not isinstance(values, list): raise TypeError("Markers must be a list of objects") self.options["markers"] = values
Set the markers. Args: values (list): list of marker objects. Raises: ValueError: Markers must be a list of objects.
def getOPOrUserServices(openid_services): op_services = arrangeByType(openid_services, [OPENID_IDP_2_0_TYPE]) openid_services = arrangeByType(openid_services, OpenIDServiceEndpoint.openid_type_uris) return op_services or openid_services
Extract OP Identifier services. If none found, return the rest, sorted with most preferred first according to OpenIDServiceEndpoint.openid_type_uris. openid_services is a list of OpenIDServiceEndpoint objects. Returns a list of OpenIDServiceEndpoint objects.
def _filter_sources(self, sources): filtered, hosts = [], [] for source in sources: if 'error' in source: continue filtered.append(source) hosts.append(source['host_name']) return sorted(filtered, key=lambda s: self._hosts...
Remove sources with errors and return ordered by host success. :param sources: List of potential sources to connect to. :type sources: list :returns: Sorted list of potential sources without errors. :rtype: list
def verify_month(self, now): return self.month == "*" or str(now.month) in self.month.split(" ")
Verify the month
def _peek(tokens, n=0): return tokens.peek(n=n, skip=_is_comment, drop=True)
peek and drop comments
def __set_name(self, value): if not value or not len(value): raise ValueError("Invalid name.") self.__name = value
Sets the name of the treatment. @param value:str
def setbpf(self, bpf): self._bpf = min(bpf, self.BPF) self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS)
Set number of bits per float output
def OpenFileObject(cls, path_spec_object, resolver_context=None): if not isinstance(path_spec_object, path_spec.PathSpec): raise TypeError('Unsupported path specification type.') if resolver_context is None: resolver_context = cls._resolver_context if path_spec_object.type_indicator == definitio...
Opens a file-like object defined by path specification. Args: path_spec_object (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built in context which is not multi process safe. Returns: FileIO: file-like object or No...
def comment_set(self): ct = ContentType.objects.get_for_model(self.__class__) qs = Comment.objects.filter( content_type=ct, object_pk=self.pk) qs = qs.exclude(is_removed=True) qs = qs.order_by('-submit_date') return qs
Get the comments that have been submitted for the chat
def mosaic_info(name, pretty): cl = clientv1() echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty)
Get information for a specific mosaic
def get_tags_of_recurring_per_page(self, recurring_id, per_page=1000, page=1): return self._get_resource_per_page( resource=RECURRING_TAGS, per_page=per_page, page=page, params={'recurring_id': recurring_id}, )
Get tags of recurring per page :param recurring_id: the recurring id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
def clean_already_reported(self, comments, file_name, position, message): for comment in comments: if ((comment['path'] == file_name and comment['position'] == position and comment['user']['login'] == self.requester.username)): ...
message is potentially a list of messages to post. This is later converted into a string.
def process_queue(queue=None, **kwargs): while True: item = queue.get() if item is None: queue.task_done() logger.info(f"{queue}: exiting process queue.") break filename = os.path.basename(item) try: queue.next_task(item, **kwargs) ...
Loops and waits on queue calling queue's `next_task` method. If an exception occurs, log the error, log the exception, and break.
def set(self, key, value): changed = super().set(key=key, value=value) if not changed: return False self._log.info('Saving configuration to "%s"...', self._filename) with open(self._filename, 'w') as stream: stream.write(self.content) self._log.info('S...
Updates the value of the given key in the file. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made.
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if number == 0: return 0 if number < MIN_WEI or number > MAX_WEI: raise ValueE...
Takes a number of wei and converts it to any other ether unit.
def get_anki_phrases_english(limit=None): texts = set() for lang in ANKI_LANGUAGES: df = get_data(lang) phrases = df.eng.str.strip().values texts = texts.union(set(phrases)) if limit and len(texts) >= limit: break return sorted(texts)
Return all the English phrases in the Anki translation flashcards >>> len(get_anki_phrases_english(limit=100)) > 700 True
def get_ssl(self, host_and_port=None): if not host_and_port: host_and_port = self.current_host_and_port return self.__ssl_params.get(host_and_port)
Get SSL params for the given host. :param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port
def search(self): for cb in SearchUrl.search_callbacks: try: v = cb(self) if v is not None: return v except Exception as e: raise
Search for a url by returning the value from the first callback that returns a non-None value
def wait_for_signal(self, timeout=None): timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE win32event.WaitForSingleObject(self.signal_event, timeout_ms)
wait for the signal; return after the signal has occurred or the timeout in seconds elapses.
def publish(self, artifact): self.env.add_artifact(artifact) self._log(logging.DEBUG, "Published {} to domain.".format(artifact))
Publish artifact to agent's environment. :param artifact: artifact to be published :type artifact: :py:class:`~creamas.core.artifact.Artifact`
def entity_to_protobuf(entity): entity_pb = entity_pb2.Entity() if entity.key is not None: key_pb = entity.key.to_protobuf() entity_pb.key.CopyFrom(key_pb) for name, value in entity.items(): value_is_list = isinstance(value, list) value_pb = _new_value_pb(entity_pb, name) ...
Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :rtype: :class:`.entity_pb2.Entity` :returns: The protobuf representing the entity.
def extract_followups(task): callbacks = task.request.callbacks errbacks = task.request.errbacks task.request.callbacks = None return {'link': callbacks, 'link_error': errbacks}
Retrieve callbacks and errbacks from provided task instance, disables tasks callbacks.
def to_ufo_family_user_data(self, ufo): if not self.use_designspace: ufo.lib[FONT_USER_DATA_KEY] = dict(self.font.userData)
Set family-wide user data as Glyphs does.
def read_electrodes(self, electrodes): for nr, electrode in enumerate(electrodes): index = self.get_point_id( electrode, self.char_lengths['electrode']) self.Electrodes.append(index)
Read in electrodes, check if points already exist
def read_json_flag(fobj): if isinstance(fobj, string_types): with open(fobj, 'r') as fobj2: return read_json_flag(fobj2) txt = fobj.read() if isinstance(txt, bytes): txt = txt.decode('utf-8') data = json.loads(txt) name = '{ifo}:{name}:{version}'.format(**data) out = ...
Read a `DataQualityFlag` from a segments-web.ligo.org JSON file
def get_lyrics_letssingit(song_name): lyrics = "" url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = urlopen(url).read() soup = BeautifulSoup(html, "html.parser") link = soup.find('a', {'class': 'high_profile'}) ...
Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement
def _construct_request(self): if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed_endpoint.netloc) head = { "Accept": "application/json", "User-Agent...
Utility for constructing the request header and connection
def create_map(self, pix): k0 = self._m0.shift_to_coords(pix) k1 = self._m1.shift_to_coords(pix) k0[np.isfinite(k1)] = k1[np.isfinite(k1)] k0[~np.isfinite(k0)] = 0 return k0
Create a new map with reference pixel coordinates shifted to the pixel coordinates ``pix``. Parameters ---------- pix : `~numpy.ndarray` Reference pixel of new map. Returns ------- out_map : `~numpy.ndarray` The shifted map.
def topics(self, exclude_internal_topics=True): topics = set(self._partitions.keys()) if exclude_internal_topics: return topics - self.internal_topics else: return topics
Get set of known topics. Arguments: exclude_internal_topics (bool): Whether records from internal topics (such as offsets) should be exposed to the consumer. If set to True the only way to receive records from an internal topic is subscribing to it. D...
def show_popup(self, *args, **kwargs): self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog) self.mw.setWindowTitle(self.popuptitle) self.mw.setWindowModality(QtCore.Qt.ApplicationModal) w = QtGui.QWidget() self.mw.setCentralWidget(w) vbox = QtGui.QVBoxLayout(w) ...
Show a popup with a textedit :returns: None :rtype: None :raises: None
def _get_op_name(op, special): opname = op.__name__.strip('_') if special: opname = '__{opname}__'.format(opname=opname) return opname
Find the name to attach to this method according to conventions for special and non-special methods. Parameters ---------- op : binary operator special : bool Returns ------- op_name : str
def get_word(byte_iterator): byte_values = list(itertools.islice(byte_iterator, 2)) try: word = (byte_values[0] << 8) | byte_values[1] except TypeError, err: raise TypeError("Can't build word from %s: %s" % (repr(byte_values), err)) return word
return a uint16 value >>> g=iter([0x1e, 0x12]) >>> v=get_word(g) >>> v 7698 >>> hex(v) '0x1e12'
def _openResources(self): arr = self._fun() check_is_an_array(arr) self._array = arr
Evaluates the function to result an array
def get_setting_with_envfallback(setting, default=None, typecast=None): try: from django.conf import settings except ImportError: return default else: fallback = getattr(settings, setting, default) value = os.environ.get(setting, fallback) if typecast: val...
Get the given setting and fall back to the default of not found in ``django.conf.settings`` or ``os.environ``. :param settings: The setting as a string. :param default: The fallback if ``setting`` is not found. :param typecast: A function that converts the given value from string to another typ...