code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def download(url, proxies=None): if proxies is None: proxies = [""] for proxy in proxies: if proxy == "": socket.socket = DEFAULT_SOCKET elif proxy.startswith('socks'): if proxy[5] == '4': proxy_type = socks.SOCKS4 else: ...
Download a PDF or DJVU document from a url, eventually using proxies. :params url: The URL to the PDF/DJVU document to fetch. :params proxies: An optional list of proxies to use. Proxies will be \ used sequentially. Proxies should be a list of proxy strings. \ Do not forget to include `...
def selected(self, interrupt=False): self.ao2.output(self.get_title(), interrupt=interrupt)
This object has been selected.
def vote_poll( self, chat_id: Union[int, str], message_id: id, option: int ) -> bool: poll = self.get_messages(chat_id, message_id).poll self.send( functions.messages.SendVote( peer=self.resolve_peer(chat_id), msg_id=message...
Use this method to vote a poll. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. For your personal cloud (Saved Messages) you can simply use "me" or "self". For a contact that exists in your Telegram add...
def is_after(self, ts): if self.timestamp >= int(calendar.timegm(ts.timetuple())): return True return False
Compare this event's timestamp to a give timestamp.
def read_file(filename): if os.path.isfile(filename): with open(filename, 'r') as f: return f.read()
return the contents of the file named filename or None if file not found
def frame_info(self): if not self._logger.isEnabledFor(logging.DEBUG): return '' f = sys._getframe(3) fname = os.path.split(f.f_code.co_filename)[1] return '{}:{}'.format(fname, f.f_lineno)
Return a string identifying the current frame.
def _compare_columns(self, new_columns, old_columns): add_columns = {} remove_columns = {} rename_columns = {} retype_columns = {} resize_columns = {} for key, value in new_columns.items(): if key not in old_columns.keys(): add_columns[key] = T...
a helper method for generating differences between column properties
def __select_builder(lxml_builder, libxml2_builder, cmdline_builder): if prefer_xsltproc: return cmdline_builder if not has_libxml2: if has_lxml: return lxml_builder else: return cmdline_builder return libxml2_builder
Selects a builder, based on which Python modules are present.
def _anchor_path(self, anchor_id): "Absolute path to the data file for `anchor_id`." file_name = '{}.yml'.format(anchor_id) file_path = self._spor_dir / file_name return file_path
Absolute path to the data file for `anchor_id`.
def include_fields(self, *args): r for arg in args: self._includefields.append(arg) return self
r""" Include fields is the fields that you want to be returned when searching. These are in addition to the fields that are always included below. :param args: items passed in will be turned into a list :returns: :class:`Search` >>> bugzilla.sear...
def reset_config(ip, mac): click.echo("Reset configuration of button %s..." % ip) data = { 'single': "", 'double': "", 'long': "", 'touch': "", } request = requests.post( 'http://{}/{}/{}/'.format(ip, URI, mac), data=data, timeout=TIMEOUT) if request.status_co...
Reset the current configuration of a myStrom WiFi Button.
def is_base_datatype(datatype, version=None): if version is None: version = get_default_version() lib = load_library(version) return lib.is_base_datatype(datatype)
Check if the given datatype is a base datatype of the specified version :type datatype: ``str`` :param datatype: the datatype (e.g. ST) :type version: ``str`` :param version: the HL7 version (e.g. 2.5) :return: ``True`` if it is a base datatype, ``False`` otherwise >>> is_base_datatype('ST')...
def _add_parameters(self, parameter_map, parameter_list): for parameter in parameter_list: if parameter.get('$ref'): parameter = self.specification['parameters'].get(parameter.get('$ref').split('/')[-1]) parameter_map[parameter['name']] = parameter
Populates the given parameter map with the list of parameters provided, resolving any reference objects encountered. Args: parameter_map: mapping from parameter names to parameter objects parameter_list: list of either parameter objects or reference objects
def comments(accountable): comments = accountable.issue_comments() headers = sorted(['author_name', 'body', 'updated']) if comments: rows = [[v for k, v in sorted(c.items()) if k in headers] for c in comments] rows.insert(0, headers) print_table(SingleTable(rows)) ...
Lists all comments for a given issue key.
def _on_split_requested(self): orientation = self.sender().text() widget = self.widget(self.tab_under_menu()) if 'horizontally' in orientation: self.split_requested.emit( widget, QtCore.Qt.Horizontal) else: self.split_requested.emit( ...
Emits the split requested signal with the desired orientation.
def _get_ln_a_n_max(self, C, n_sites, idx, rup): ln_a_n_max = C["lnSC1AM"] * np.ones(n_sites) for i in [2, 3, 4]: if np.any(idx[i]): ln_a_n_max[idx[i]] += C["S{:g}".format(i)] return ln_a_n_max
Defines the rock site amplification defined in equations 10a and 10b
def code_timer(reset=False): global CODE_TIMER if reset: CODE_TIMER = CodeTimer() else: if CODE_TIMER is None: return CodeTimer() else: return CODE_TIMER
Sets a global variable for tracking the timer accross multiple files
def show_disk(name=None, kwargs=None, call=None): if not kwargs or 'disk_name' not in kwargs: log.error( 'Must specify disk_name.' ) return False conn = get_conn() return _expand_disk(conn.ex_get_volume(kwargs['disk_name']))
Show the details of an existing disk. CLI Example: .. code-block:: bash salt-cloud -a show_disk myinstance disk_name=mydisk salt-cloud -f show_disk gce disk_name=mydisk
def compose(f: Callable[[Any], Monad], g: Callable[[Any], Monad]) -> Callable[[Any], Monad]: r return lambda x: g(x).bind(f)
r"""Monadic compose function. Right-to-left Kleisli composition of two monadic functions. (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c f <=< g = \x -> g x >>= f
def tone_marks(): return RegexBuilder( pattern_args=symbols.TONE_MARKS, pattern_func=lambda x: u"(?<={}).".format(x)).regex
Keep tone-modifying punctuation by matching following character. Assumes the `tone_marks` pre-processor was run for cases where there might not be any space after a tone-modifying punctuation mark.
def requires_lock(function): def new_lock_requiring_function(self, filename, *args, **kwargs): if self.owns_lock(filename): return function(self, filename, *args, **kwargs) else: raise RequiresLockException() return new_lock_requiring_function
Decorator to check if the user owns the required lock. The first argument must be the filename.
def close(self): if self._mode == _MODE_CLOSED: return try: if self._mode in (_MODE_READ, _MODE_READ_EOF): self._decompressor = None self._buffer = None elif self._mode == _MODE_WRITE: self._fp.write(self._compressor.flu...
Flush and close the file. May be called more than once without error. Once the file is closed, any other operation on it will raise a ValueError.
def libvlc_media_list_new(p_instance): f = _Cfunctions.get('libvlc_media_list_new', None) or \ _Cfunction('libvlc_media_list_new', ((1,),), class_result(MediaList), ctypes.c_void_p, Instance) return f(p_instance)
Create an empty media list. @param p_instance: libvlc instance. @return: empty media list, or NULL on error.
def r2z(r): with np.errstate(invalid='ignore', divide='ignore'): return 0.5 * (np.log(1 + r) - np.log(1 - r))
Function that calculates the Fisher z-transformation Parameters ---------- r : int or ndarray Correlation value Returns ---------- result : int or ndarray Fishers z transformed correlation value
def detect_encoding(fp, default=None): init_pos = fp.tell() try: sample = fp.read( current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024)) result = cchardet.detect(sample) threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9) if result.get('confiden...
Detect the cahracter encoding of a file. :param fp: Open Python file pointer. :param default: Fallback encoding to use. :returns: The detected encoding. .. note:: The file pointer is returned at its original read position.
def friendships_create(self, user_id=None, screen_name=None, follow=None): params = {} set_str_param(params, 'user_id', user_id) set_str_param(params, 'screen_name', screen_name) set_bool_param(params, 'follow', follow) return self._post_api('friendship...
Allows the authenticating users to follow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/create :param str user_id: The screen name of the user for whom to befriend. Required if ``screen_name`` isn't given. :param str screen_name: ...
def remove_option(self, section, name, value=None): if self._is_live(): raise RuntimeError('Submitted units cannot update their options') removed = 0 for option in list(self._data['options']): if option['section'] == section: if option['name'] == name: ...
Remove an option from a unit Args: section (str): The section to remove from. name (str): The item to remove. value (str, optional): If specified, only the option matching this value will be removed If not specified, all options with ``name...
def getAtomLinesForResidueInRosettaStructure(self, resid): lines = [line for line in self.lines if line[0:4] == "ATOM" and resid == int(line[22:27])] if not lines: raise Exception("Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'." % vars()) return lines
We assume a Rosetta-generated structure where residues are uniquely identified by number.
def kabsch_rmsd(P, Q, translate=False): if translate: Q = Q - centroid(Q) P = P - centroid(P) P = kabsch_rotate(P, Q) return rmsd(P, Q)
Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD. Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. translate : bool Use centroids to translate vector P and Q ...
def hidden_cursor(self): self.stream.write(self.hide_cursor) try: yield finally: self.stream.write(self.normal_cursor)
Return a context manager that hides the cursor while inside it and makes it visible on leaving.
def is_analyst_assignment_allowed(self): if not self.allow_edit: return False if not self.can_manage: return False if self.filter_by_user: return False return True
Check if the analyst can be assigned
def inserted_hs_indices(self): if self.dimension_type in DT.ARRAY_TYPES: return [] return [ idx for idx, item in enumerate( self._iter_interleaved_items(self.valid_elements) ) if item.is_insertion ]
list of int index of each inserted subtotal for the dimension. Each value represents the position of a subtotal in the interleaved sequence of elements and subtotals items.
def get_branching_nodes(self): nodes = set() for n in self.graph.nodes(): if self.graph.out_degree(n) >= 2: nodes.add(n) return nodes
Returns all nodes that has an out degree >= 2
def nodes_with_role(rolename): nodes = [n['name'] for n in lib.get_nodes_with_role(rolename, env.chef_environment)] if not len(nodes): print("No nodes found with role '{0}'".format(rolename)) sys.exit(0) return node(*nodes)
Configures a list of nodes that have the given role in their run list
def get_all_parents(self): ownership = Ownership.objects.filter(child=self) parents = Company.objects.filter(parent__in=ownership) for parent in parents: parents = parents | parent.get_all_parents() return parents
Return all parents of this company.
def _get_all_run_infos(self): info_dir = self._settings.info_dir if not os.path.isdir(info_dir): return [] paths = [os.path.join(info_dir, x) for x in os.listdir(info_dir)] return [d for d in [RunInfo(os.path.join(p, 'info')).get_as_dict() for p in paths if os.path.isdir(p...
Find the RunInfos for all runs since the last clean-all.
def register_service(service): frame = inspect.currentframe() m_name = frame.f_back.f_globals['__name__'] m = sys.modules[m_name] m._SERVICE_NAME = service
Register the ryu application specified by 'service' as a provider of events defined in the calling module. If an application being loaded consumes events (in the sense of set_ev_cls) provided by the 'service' application, the latter application will be automatically loaded. This mechanism is used ...
def _looks_like_numpy_function(func_name, numpy_module_name, node): return node.name == func_name and node.parent.name == numpy_module_name
Return True if the current node correspond to the function inside the numpy module in parameters :param node: the current node :type node: FunctionDef :param func_name: name of the function :type func_name: str :param numpy_module_name: name of the numpy module :type numpy_module_name: str ...
def size_in_bytes(self, offset, timestamp, key, value, headers=None): assert not headers, "Headers not supported in v0/v1" magic = self._magic return self.LOG_OVERHEAD + self.record_size(magic, key, value)
Actual size of message to add
def validate_callback(callback): if not(hasattr(callback, '_validated')) or callback._validated == False: assert hasattr(callback, 'on_loop_start') \ or hasattr(callback, 'on_loop_end'), \ 'callback must have `on_loop_start` or `on_loop_end` method' if hasattr(callback,...
validates a callback's on_loop_start and on_loop_end methods Parameters ---------- callback : Callback object Returns ------- validated callback
def _looks_like_resource_file(self, name): if (re.search(r'__init__.(txt|robot|html|tsv)$', name)): return False found_keyword_table = False if (name.lower().endswith(".robot") or name.lower().endswith(".txt") or name.lower().endswith(".tsv")): wit...
Return true if the file has a keyword table but not a testcase table
def lstltc(string, n, lenvals, array): string = stypes.stringToCharP(string) array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=n) n = ctypes.c_int(n) lenvals = ctypes.c_int(lenvals) return libspice.lstltc_c(string, n, lenvals, array)
Given a character string and an ordered array of character strings, find the index of the largest array element less than the given string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstltc_c.html :param string: Upper bound value to search against. :type string: int :param n: Numb...
def _q_iteration(self, Q, Bpp_solver, Vm, Va, pq): dVm = -Bpp_solver.solve(Q) Vm[pq] = Vm[pq] + dVm V = Vm * exp(1j * Va) return V, Vm, Va
Performs a Q iteration, updates Vm.
def elapsed(self, label=None, total=True): t = timer() if label is None: label = self.dfltlbl if label not in self.t0: return 0.0 if label not in self.t0: raise KeyError('Unrecognized timer key %s' % label) te = 0.0 if self.t0[l...
Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label specified by the ``dfltlbl`` parameter of :meth...
def setup(self): if not self.networks(): for _ in range(self.practice_repeats): network = self.create_network() network.role = "practice" self.session.add(network) for _ in range(self.experiment_repeats): network = self.crea...
Create the networks if they don't already exist.
def select_and_start_cluster(self, platform): clusters = self.reactor_config.get_enabled_clusters_for_platform(platform) if not clusters: raise UnknownPlatformException('No clusters found for platform {}!' .format(platform)) retry_contexts =...
Choose a cluster and start a build on it
def get(self): content = {} if self.mime_type is not None: content["type"] = self.mime_type if self.content is not None: content["value"] = self.content return content
Get a JSON-ready representation of this HtmlContent. :returns: This HtmlContent, ready for use in a request body. :rtype: dict
def _index_entities(self): all_ents = pd.DataFrame.from_records( [v.entities for v in self.variables.values()]) constant = all_ents.apply(lambda x: x.nunique() == 1) if constant.empty: self.entities = {} else: keep = all_ents.columns[constant] ...
Sets current instance's entities based on the existing index. Note: Only entity key/value pairs common to all rows in all contained Variables are returned. E.g., if a Collection contains Variables extracted from runs 1, 2 and 3 from subject '01', the returned dict will be {'...
def load_glove(file): model = {} with open(file, encoding="utf8", errors='ignore') as f: for line in f: line = line.split(' ') word = line[0] vector = np.array([float(val) for val in line[1:]]) model[word] = vector return model
Loads GloVe vectors in numpy array. Args: file (str): a path to a glove file. Return: dict: a dict of numpy arrays.
def clear(self, contours=True, components=True, anchors=True, guidelines=True, image=True): self._clear(contours=contours, components=components, anchors=anchors, guidelines=guidelines, image=image)
Clear the glyph. >>> glyph.clear() This clears: - contours - components - anchors - guidelines - image It's possible to turn off the clearing of portions of the glyph with the listed arguments. >>> glyph.clear(guidelines=False)
def _del_module(self, lpBaseOfDll): try: aModule = self.__moduleDict[lpBaseOfDll] del self.__moduleDict[lpBaseOfDll] except KeyError: aModule = None msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll) warnings.warn(msg, RuntimeWarnin...
Private method to remove a module object from the snapshot. @type lpBaseOfDll: int @param lpBaseOfDll: Module base address.
def asDictionary(self): template = { "xmin" : self._xmin, "ymin" : self._ymin, "xmax" : self._xmax, "ymax" : self._ymax, "spatialReference" : self.spatialReference } if self._zmax is not None and \ self._zmin is not None: ...
returns the envelope as a dictionary
def start_recording(self, file='mingus_dump.wav'): w = wave.open(file, 'wb') w.setnchannels(2) w.setsampwidth(2) w.setframerate(44100) self.wav = w
Initialize a new wave file for recording.
def paginator(context, adjacent_pages=2): current_page = context.get('page') paginator = context.get('paginator') if not paginator: return pages = paginator.num_pages current_range = range(current_page - adjacent_pages, current_page + adjacent_pages + 1) page_numbers = [...
To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view.
def compute_We(self, Eemin=None, Eemax=None): if Eemin is None and Eemax is None: We = self.We else: if Eemax is None: Eemax = self.Eemax if Eemin is None: Eemin = self.Eemin log10gmin = np.log10(Eemin / mec2).value ...
Total energy in electrons between energies Eemin and Eemax Parameters ---------- Eemin : :class:`~astropy.units.Quantity` float, optional Minimum electron energy for energy content calculation. Eemax : :class:`~astropy.units.Quantity` float, optional Maximum ele...
def getChemicalPotential(self, solution): if isinstance(solution, Solution): solution = solution.getSolution() self.mu = self.solver.chemicalPotential(solution) return self.mu
Call solver in order to calculate chemical potential.
def get_bug_report(): platform_info = BugReporter.get_platform_info() module_info = { 'version': hal_version.__version__, 'build': hal_version.__build__ } return { 'platform': platform_info, 'pyhal': module_info }
Generate information for a bug report :return: information for bug report
def create(self, name, redirect_uri=None): data = dict(name=name) if redirect_uri: data['redirect_uri'] = redirect_uri auth_request_resource = self.resource.create(data) return (auth_request_resource.attributes['metadata']['device_token'], auth_request_resourc...
Create a new Device object. Devices tie Users and Applications together. For your Application to access and act on behalf of a User, the User must authorize a Device created by your Application. This function will return a `device_token` which you must store and use after the D...
def add_arrow(self, tipLoc, tail=None, arrow=arrow.default): self._arrows.append((tipLoc, tail, arrow))
This method adds a straight arrow that points to @var{TIPLOC}, which is a tuple of integers. @var{TAIL} specifies the starting point of the arrow. It is either None or a string consisting of the following letters: 'l', 'c', 'r', 't', 'm,', and 'b'. Letters 'l', 'c', or 'r' means to ...
def contains(self, key): try: self._api.objects_get(self._bucket, key) except datalab.utils.RequestException as e: if e.status == 404: return False raise e except Exception as e: raise e return True
Checks if the specified item exists. Args: key: the key of the item to lookup. Returns: True if the item exists; False otherwise. Raises: Exception if there was an error requesting information about the item.
def set_spacing(self, new_spacing): if not isinstance(new_spacing, (tuple, list)): raise ValueError('arg must be tuple or list') if len(new_spacing) != self.dimension: raise ValueError('must give a spacing value for each dimension (%i)' % self.dimension) libfn = utils.get...
Set image spacing Arguments --------- new_spacing : tuple or list updated spacing for the image. should have one value for each dimension Returns ------- None
def check_cmake_exists(cmake_command): from subprocess import Popen, PIPE p = Popen( '{0} --version'.format(cmake_command), shell=True, stdin=PIPE, stdout=PIPE) if not ('cmake version' in p.communicate()[0].decode('UTF-8')): sys.stderr.write(' This code is built usi...
Check whether CMake is installed. If not, print informative error message and quits.
async def logs( self, service_id: str, *, details: bool = False, follow: bool = False, stdout: bool = False, stderr: bool = False, since: int = 0, timestamps: bool = False, is_tty: bool = False, tail: str = "all" ) -> Union[str,...
Retrieve logs of the given service Args: details: show service context and extra details provided to logs follow: return the logs as a stream. stdout: return logs from stdout stderr: return logs from stderr since: return logs since this time, as a UNI...
def pad_sentences(sentences, padding_word="</s>"): sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i, sentence in enumerate(sentences): num_padding = sequence_length - len(sentence) new_sentence = sentence + [padding_word] * num_padding padded_sentences.app...
Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences.
def exists(self, digest): return self.conn.client.blob_exists(self.container_name, digest)
Check if a blob exists :param digest: Hex digest of the blob :return: Boolean indicating existence of the blob
def _update(self, **kwargs): path = self._construct_path_to_item() if not kwargs: return return self._http.put(path, json.dumps(kwargs))
Update a resource in a remote Transifex server.
def get_record_value(request, uid, keyword, default=None): value = request.get(keyword) if not value: return default if not isinstance(value, list): return default return value[0].get(uid, default) or default
Returns the value for the keyword and uid from the request
def abort(status_code, message=None): if message is None: message = STATUS_CODES.get(status_code) message = message.decode("utf8") sanic_exception = _sanic_exceptions.get(status_code, SanicException) raise sanic_exception(message=message, status_code=status_code)
Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status ...
def _prepare_resource_chunks(self, resources, resource_delim=','): return [self._prepare_resource_chunk(resources, resource_delim, pos) for pos in range(0, len(resources), self._resources_per_req)]
As in some VirusTotal API methods the call can be made for multiple resources at once this method prepares a list of concatenated resources according to the maximum number of resources per requests. Args: resources: a list of the resources. resource_delim: a string used ...
def row(self, data): for column in self.column_funcs: if callable(column): yield column(data) else: yield utils.lookup(data, *column)
Return a formatted row for the given data.
def add(self, uuid): if uuid: try: x = hash64(uuid) except UnicodeEncodeError: x = hash64(uuid.encode('ascii', 'ignore')) j = x & ((1 << self.b) - 1) w = x >> self.b self.M[j] = max(self.M[j], self._get_rho(w, self.bitco...
Adds a key to the HyperLogLog
def update_buttons(self): current_scheme = self.current_scheme names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass delete_enabled = current_scheme not in names self.delete_button.setEnabled(delete_enabled...
Updates the enable status of delete and reset buttons.
def split_arguments(args): prev = False for i, value in enumerate(args[1:]): if value.startswith('-'): prev = True elif prev: prev = False else: return args[:i+1], args[i+1:] return args, []
Split specified arguments to two list. This is used to distinguish the options of the program and execution command/arguments. Parameters ---------- args : list Command line arguments Returns ------- list : options, arguments options indicate the optional arguments for...
def right(ctx, text, num_chars): num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") elif num_chars == 0: return '' else: return conversions.to_string(text, ctx)[-num_chars:]
Returns the last characters in a text string
def get_route(self, route_id): raw = self.protocol.get('/routes/{id}', id=route_id) return model.Route.deserialize(raw, bind_client=self)
Gets specified route. Will be detail-level if owned by authenticated user; otherwise summary-level. https://strava.github.io/api/v3/routes/#retreive :param route_id: The ID of route to fetch. :type route_id: int :rtype: :class:`stravalib.model.Route`
def merge_dicts(dict1, dict2, deep_merge=True): if deep_merge: if isinstance(dict1, list) and isinstance(dict2, list): return dict1 + dict2 if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for key in dict2: dict1[key] = merge_dic...
Merge dict2 into dict1.
def delete(self): self.close() if self.does_file_exist(): os.remove(self.path)
Delete the file.
def _overwrite(self, n): if os.path.isfile(n[:-4]): shutil.copy2(n[:-4], n[:-4] + ".old") print("Old file {0} saved as {1}.old".format( n[:-4].split("/")[-1], n[:-4].split("/")[-1])) if os.path.isfile(n): shutil.move(n, n[:-4]) print("New f...
Overwrite old file with new and keep file with suffix .old
def create_d1_dn_subject(common_name_str): return cryptography.x509.Name( [ cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.COUNTRY_NAME, "US" ), cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.STATE_OR_PROVINC...
Create the DN Subject for certificate that will be used in a DataONE environment. The DN is formatted into a DataONE subject, which is used in authentication, authorization and event tracking. Args: common_name_str: str DataONE uses simple DNs without physical location information, so ...
def events(self, *events): return self.send_events(self.create_event(e) for e in events)
Sends multiple events in a single message >>> client.events({'service': 'riemann-client', 'state': 'awesome'}) :param \*events: event dictionaries for :py:func:`create_event` :returns: The response message from Riemann
def has_path(self, path, method=None): method = self._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict return path_dict_exists
Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document
def set_category(self, category): pcategory = self.find("general/category") pcategory.clear() name = ElementTree.SubElement(pcategory, "name") if isinstance(category, Category): id_ = ElementTree.SubElement(pcategory, "id") id_.text = category.id name....
Set the policy's category. Args: category: A category object.
def append_tag(self, field_number, wire_type): self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type))
Appends a tag containing field number and wire type information.
def delete_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): request = operations_pb2.DeleteOperationRequest(name=name) self._delete_operation(request, retry=retry, timeout=timeout)
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. Example: >>> from google.api_core import operations_v1 >>> api = operations_v1.OperationsClient() >>> n...
async def enable_digital_reporting(self, command): pin = int(command[0]) await self.core.enable_digital_reporting(pin)
Enable Firmata reporting for a digital pin. :param command: {"method": "enable_digital_reporting", "params": [PIN]} :returns: {"method": "digital_message_reply", "params": [PIN, DIGITAL_DATA_VALUE]}
def rename(name): from peltak.extra.gitflow import logic if name is None: name = click.prompt('Hotfix name') logic.hotfix.rename(name)
Give the currently developed hotfix a new name.
def _validate_sub(claims, subject=None): if 'sub' not in claims: return if not isinstance(claims['sub'], string_types): raise JWTClaimsError('Subject must be a string.') if subject is not None: if claims.get('sub') != subject: raise JWTClaimsError('Invalid subject')
Validates that the 'sub' claim is valid. The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. ...
def get_days_off(transactions): days_off = [] for trans in transactions: date, action, _ = _parse_transaction_entry(trans) if action == 'off': days_off.append(date) return days_off
Return the dates for any 'take day off' transactions.
def rebin(self, factor): if self.pilimage != None: raise RuntimeError, "Cannot rebin anymore, PIL image already exists !" if type(factor) != type(0): raise RuntimeError, "Rebin factor must be an integer !" if factor < 1: return origshape = np.asarray(s...
I robustly rebin your image by a given factor. You simply specify a factor, and I will eventually take care of a crop to bring the image to interger-multiple-of-your-factor dimensions. Note that if you crop your image before, you must directly crop to compatible dimensions ! We update th...
def _exec_cmd(self, args, shell, timeout, stderr): if timeout and timeout <= 0: raise ValueError('Timeout is not a positive value: %s' % timeout) try: (ret, out, err) = utils.run_command( args, shell=shell, timeout=timeout) except psutil.TimeoutExpired: ...
Executes adb commands. Args: args: string or list of strings, program arguments. See subprocess.Popen() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs. ti...
def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False): params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_dir...
Gets the active subscribers in this segment.
def dumps(obj, *args, **kwargs): return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)
Typeless dump an object to json string
def add(user_id, resource_policy, admin, inactive, rate_limit): try: user_id = int(user_id) except ValueError: pass with Session() as session: try: data = session.KeyPair.create( user_id, is_active=not inactive, is_admin=ad...
Add a new keypair. USER_ID: User ID of a new key pair. RESOURCE_POLICY: resource policy for new key pair.
def _reload_config(self, reload_original_config): if reload_original_config: self.original_config = self.running_config self.original_config.set_name('original') paths = self.running_config.get_paths() self.running_config = FortiConfig('running', vdom=self.vdom) f...
This command will update the running config from the live device. Args: * reload_original_config: * If ``True`` the original config will be loaded with the running config before reloading the\ original config. * If ``False`` the original config will r...
def get_relative_to_remote(self): s = self.git("status", "--short", "-b")[0] r = re.compile("\[([^\]]+)\]") toks = r.findall(s) if toks: try: s2 = toks[-1] adj, n = s2.split() assert(adj in ("ahead", "behind")) n...
Return the number of commits we are relative to the remote. Negative is behind, positive in front, zero means we are matched to remote.
def _init(): if (hasattr(_local_context, '_initialized') and _local_context._initialized == os.environ.get('REQUEST_ID_HASH')): return _local_context.registry = [] _local_context._executing_async_context = None _local_context._executing_async = [] _local_context._initialized = os...
Initialize the furious context and registry. NOTE: Do not directly run this method.
def process_response(self, request, response): if hasattr(request, 'COUNTRY_CODE'): response.set_cookie( key=constants.COUNTRY_COOKIE_NAME, value=request.COUNTRY_CODE, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_...
Shares config with the language cookie as they serve a similar purpose
def compute_qkv(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, q_filter_width=1, kv_filter_width=1, q_padding="VALID", kv_padding="VALID", vars_3d_num_heads=0, ...
Computes query, key and value. Args: query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: a Tensor with shape [batch, length_m, channels] total_key_depth: an integer total_value_depth: an integer q_filter_width: An integer specifying how wide you want the query to ...
def data(self): content = { 'form_data': self.form_data, 'token': self.token, 'viz_name': self.viz_type, 'filter_select_enabled': self.datasource.filter_select_enabled, } return content
This is the data object serialized to the js layer
def log(self, time, message, level=None, attachment=None): logger.debug("log queued") args = { "time": time, "message": message, "level": level, "attachment": attachment, } self.queue.put_nowait(("log", args))
Logs a message with attachment. The attachment is a dict of: name: name of attachment data: file content mime: content type for attachment