Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
341,900
def nameserver(self): with self._mutex: if not self._parent: return None elif self._parent.name == : return self else: return self._parent.nameserver
The name server of the node (i.e. its top-most parent below /).
341,901
def _offload(self, args, **extra_args): if not isinstance(args, argparse.Namespace): raise Exception("args should of an instance of argparse.Namespace") freight_forwarder = FreightForwarder() commercial_invoice = freight_forwarder.commercial_invoice( ...
Export is the entry point for exporting docker images.
341,902
def get_currency_aggregate_by_symbol(self, symbol: str) -> CurrencyAggregate: currency = self.get_by_symbol(symbol) result = self.get_currency_aggregate(currency) return result
Creates currency aggregate for the given currency symbol
341,903
def tensors_blocked_by_false(ops): blocked = [] def recurse(op): if op.type == "Switch": blocked.append(op.outputs[1]) else: for out in op.outputs: for c in out.consumers(): recurse(c) for op in ops: recurse(op) r...
Follows a set of ops assuming their value is False and find blocked Switch paths. This is used to prune away parts of the model graph that are only used during the training phase (like dropout, batch norm, etc.).
341,904
def import_from_ding0(file, network): if isinstance(file, str): ding0_nd = load_nd_from_pickle(filename=file) else: ding0_nd = file ding0_mv_grid = ding0_nd._mv_grid_districts[0].mv_grid ding0_mv_grid.close_circuit_breakers() network.mv_grid = _build_mv_gr...
Import an eDisGo grid topology from `Ding0 data <https://github.com/openego/ding0>`_. This import method is specifically designed to load grid topology data in the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via pickles. The import of the grid topology includes * the...
341,905
def find_clusters(network, mask=[], t_labels=False): r mask = sp.array(mask, ndmin=1) if mask.dtype != bool: raise Exception() if sp.size(mask) == network.Np: (p_clusters, t_clusters) = _site_percolation(network, mask) elif sp.size(mask) == network.Nt: (p_clus...
r""" Identify connected clusters of pores in the network. This method can also return a list of throat cluster numbers, which correspond to the cluster numbers of the pores to which the throat is connected. Either site and bond percolation can be considered, see description of input arguments for ...
341,906
def __accept_reject(self, prompt, accepted_text, rejected_text, display_rejected): accept_event = threading.Event() result_ref = [False] def perform(): def accepted(): result_ref[0] = True accept_event.set() def rejected(): ...
Return a boolean value for accept/reject.
341,907
def is_info_germline(rec): if hasattr(rec, "INFO"): status = rec.INFO.get("STATUS", "").lower() else: status = rec.info.get("STATUS", "").lower() return status == "germline" or status.find("loh") >= 0
Check if a variant record is germline based on INFO attributes. Works with VarDict's annotation of STATUS.
341,908
def set_app_args(self, *args): if args: self._set(, .join(args)) return self._section
Sets ``sys.argv`` for python apps. Examples: * pyargv="one two three" will set ``sys.argv`` to ``('one', 'two', 'three')``. :param args:
341,909
def to_bytes(obj, encoding=, errors=None, nonstring=): if isinstance(obj, binary_type): return obj return obj.encode(encoding, errors) except UnicodeEncodeError: if original_errors in (None, ): return_string = obj.encode(, ) ...
Make sure that a string is a byte string :arg obj: An object to make sure is a byte string. In most cases this will be either a text string or a byte string. However, with ``nonstring='simplerepr'``, this can be used as a traceback-free version of ``str(obj)``. :kwarg encoding: The en...
341,910
def power_on(self): if not self.is_powered_on(): log.debug(, self.ip, self.port) self.send_key(keys.POWER)
Power on the set-top box.
341,911
def _tosubs(self, ixlist): n = len(ixlist) N = self._n ss = [] ms = [] if n == 0: return ss, ms j = 0 ix = ixlist[j] if ix >= N or ix < -N: raise IndexError( % (ix, N)) if ix < 0: i...
Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss).
341,912
def _cleave_interface(self, bulk_silica, tile_x, tile_y, thickness): O_buffer = self._O_buffer tile_z = int(math.ceil((thickness + 2*O_buffer) / bulk_silica.periodicity[2])) bulk = mb.recipes.TiledCompound(bulk_silica, n_tiles=(tile_x, tile_y, tile_z)) interface = mb.Compound(p...
Carve interface from bulk silica. Also includes a buffer of O's above and below the surface to ensure the interface is coated.
341,913
async def download_media(self, *args, **kwargs): if self.document or self.photo: return await self._client.download_media( self.document or self.photo, *args, **kwargs)
Downloads the media in this result (if there is a document, the document will be downloaded; otherwise, the photo will if present). This is a wrapper around `client.download_media <telethon.client.downloads.DownloadMethods.download_media>`.
341,914
def write_tile_if_changed(store, tile_data, coord, format): existing_data = store.read_tile(coord, format) if not existing_data or \ not tiles_are_equal(existing_data, tile_data, format): store.write_tile(tile_data, coord, format) return True else: return False
Only write tile data if different from existing. Try to read the tile data from the store first. If the existing data matches, don't write. Returns whether the tile was written.
341,915
def _feed_buffer(self, n=1): buffer = bytearray(self._stream.read()) while len(buffer) < n: try: message = yield from self._protocol.recv() except ConnectionClosed: message = None if message is None: break ...
Feed the data buffer by reading a Websocket message. :param n: if given, feed buffer until it contains at least n bytes
341,916
def register(self, model, index): self.model_to_indexes[model].add(index) if not self.connected: connections.index_name = {} from django.conf import settings kwargs = {} for name, params in settings.ELASTICSEARCH_CONNECTIONS.items(): ...
Register the model with the registry
341,917
def batch_length(batch): n = None for value in six.itervalues(batch): if n is None: n = len(value) elif len(value) != n: raise PescadorError() return n
Determine the number of samples in a batch. Parameters ---------- batch : dict A batch dictionary. Each value must implement `len`. All values must have the same `len`. Returns ------- n : int >= 0 or None The number of samples in this batch. If the batch has n...
341,918
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None): if not database: database = DEFAULT_DB_ALIAS if not changelog_file: changelog_file = get_changelog_file_for_database(database) try: doc = minidom.parse(changelog_file) except ExpatError as ex:...
Finds best matching target migration file
341,919
def get_markdown_files(self, dir_): md_files = OrderedSet() for root, _, files in os.walk(dir_): for name in files: split = os.path.splitext(name) if len(split) == 1: continue if split[1] in (, , ): ...
Get all the markdown files in a folder, recursively Args: dir_: str, a toplevel folder to walk.
341,920
def CREATE(self, value, offset, size): tx = self.world.last_transaction address = tx.address if tx.result == : self.world.set_code(tx.address, tx.return_data) else: self.world.delete_account(address) address = 0 return address
Create a new account with associated code
341,921
def frame_vars_to_xml(frame_f_locals, hidden_ns=None): xml = "" keys = dict_keys(frame_f_locals) if hasattr(keys, ): keys.sort() else: keys = sorted(keys) return_values_xml = for k in keys: try: v = frame_f_locals[k] eval_full_val = sh...
dumps frame variables to XML <var name="var_name" scope="local" type="type" value="value"/>
341,922
def update_all_tags_cache(self): self._all_tags_cache = None self._all_tags_cache_list = {} self._all_tags_cache_list_admin = {} self._organisational_tags_to_task = {} self.get_all_tags() self.get_all_tags_names_as_list() self.get_or...
Force the cache refreshing
341,923
def sep(a1, b1, a2, b2): tol = 1e-15 v = CartesianVector.from_spherical(1.0, a1, b1) v2 = CartesianVector.from_spherical(1.0, a2, b2) d = v.dot(v2) c = v.cross(v2).mod res = math.atan2(c, d) if abs(res) < tol: return 0.0 else: return res
Angular spearation between two points on a unit sphere. This will be an angle between [0, π] radians. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longitude-like and latitude-like...
341,924
def updatePlotWidget(self): pw = self.getPlotWidget() pw.reset() results = self.resultsModel.getCheckedItems() for result in results: if isinstance(result, ExperimentalData): spectrum = result.spectra[] spectrum.legend = .format(resu...
Updating the plotting widget should not require any information about the current state of the widget.
341,925
def canonizePath(path): return os.path.abspath(os.path.normpath(os.path.realpath(path)))
Returns the absolute, normalized, real path of something. This takes care of symbolic links, redundant separators, etc.
341,926
def broadcast(*args, **kwargs): from .dataarray import DataArray from .dataset import Dataset exclude = kwargs.pop(, None) if exclude is None: exclude = set() if kwargs: raise TypeError( % list(kwargs)) args = align(*args, join=, copy=False, exclude...
Explicitly broadcast any number of DataArray or Dataset objects against one another. xarray objects automatically broadcast against each other in arithmetic operations, so this function should not be necessary for normal use. If no change is needed, the input data is returned to the output without ...
341,927
def label_from_folder(self, label_cls:Callable=None, **kwargs)->: "Give a label to each filename depending on its folder." return self.label_from_func(func=lambda o: (o.parts if isinstance(o, Path) else o.split(os.path.sep))[-2], label_cls=label_cls, **kwargs)
Give a label to each filename depending on its folder.
341,928
def input(input_id, name, value_class=NumberValue): def _init(): return value_class( name, input_id=input_id, is_input=True, index=-1 ) def _decorator(cls): setattr(cls, input_id, _init()) ...
Add input to controller
341,929
def maximum_clique(G, sampler=None, lagrange=2.0, **sampler_args): if G is None: raise ValueError("Expected NetworkX graph!") complement_G = nx.complement(G) return dnx.maximum_independent_set(complement_G, sampler, lagrange, **sampler_args)
Returns an approximate maximum clique. A clique in an undirected graph G = (V, E) is a subset of the vertex set `C \subseteq V` such that for every two vertices in C there exists an edge connecting the two. This is equivalent to saying that the subgraph induced by C is complete (in some cases, the term ...
341,930
def _try_coerce_result(self, result): if isinstance(result, np.ndarray): mask = isna(result) if result.dtype.kind in [, ]: result = result.astype() result[mask] = tslibs.iNaT elif isinstance(result, (np.integer, np.float)): result...
reverse of try_coerce_args / try_operate
341,931
def create_with_dst_resource_provisioning( cls, cli, src_resource_id, dst_resource_config, max_time_out_of_sync, name=None, remote_system=None, src_spa_interface=None, src_spb_interface=None, dst_spa_interface=None, dst_spb_interface=None, dst_resource_element...
Create a replication session along with destination resource provisioning. :param cli: the rest cli. :param src_resource_id: id of the replication source, could be lun/fs/cg. :param dst_resource_config: `UnityResourceConfig` object. The user chosen config for des...
341,932
def make_request( url, method=, query=None, body=None, auth=None, timeout=10, client=None, macaroons=None): headers = {} kwargs = {: timeout, : headers} if body is not None: if isinstance(body, collections.Mapping): body = json.dumps(body) kwargs[] = bod...
Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the query key and values. @param body The optional body as a string or as a JSON decoded dict. @param auth The optional username and ...
341,933
def get_groups_data(self, groups): s value will hold. ' data = {} for group in groups: data.update(self.get_group_data(group)) return data
Gets aggregated data from a list of groups. Vars are collected in order so, for any groups which define the same var twice, the last group's value will hold.
341,934
def bandwidth(self): self._bandwidth = self.lib.iperf_get_test_rate(self._test) return self._bandwidth
Target bandwidth in bits/sec
341,935
def reset_avaliable(self, folder): try: self.list_script_model.removeRows(0, self.list_script_model.rowCount()) if self.cmb_select_type.currentText() == : self.avaliable = find_scripts_in_python_files(folder) elif self.cmb_select_type.currentText() ==...
Resets the dialog box by finding all avaliable scripts that can be imported in the input folder :param folder: folder in which to find scripts
341,936
def query(self, table_name, index_name=None, consistent_read=None, key_condition_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, projection_expression=None, ...
A `Query`_ operation uses the primary key of a table or a secondary index to directly access items from that table or index. :param str table_name: The name of the table containing the requested items. :param bool consistent_read: Determines the read consistency model: If ...
341,937
def is_owner(self, user): if user.is_authenticated: return self.created_by.id == user.id return False
Checks if user is the owner of object Parameters ---------- user: get_user_model() instance Returns ------- bool Author ------ Himanshu Shankar (https://himanshus.com)
341,938
def download_resource(self, download_url, target, guard): download_url = download_url.strip() if not os.path.isabs(target): target = os.path.join(config.config_dir, target) if os.path.exists(os.path.join(target, guard)): self.LOG.info("Already have in ..." % (d...
Helper to download and install external resources.
341,939
def topsSSE(symbols=None, on_data=None, token=, version=): return _runSSE(, symbols, on_data, token, version)
TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book. TOPS is ideal for developers needing both quote and trade data. https://iexcloud.io/docs/api/#tops Args: symbols (string); Tickers to request on_data ...
341,940
def main(): file= methx,methy,fmt="","", plot_key= norm_by="" no_plot = pmag.get_flag_arg_from_sys() if not no_plot: do_plot = True else: do_plot = False if in sys.argv: print(main.__doc__) sys.exit() if in sys.argv: ind=sys.ar...
NAME biplot_magic.py DESCRIPTION makes a biplot of specified variables from magic_measurements.txt format file SYNTAX biplot_magic.py [-h] [-i] [command line options] INPUT takes magic formated magic_measurments file OPTIONS -h prints help message and quits ...
341,941
def age(self): if self.Death: age = self.Death - self.Born else: age = datetime.date.today() - self.Born return age.days
Calculates the animals age, relative to the current date (if alive) or the date of death (if not).
341,942
def md( self, url, width="original"): self.log.info() images, title, desc, photoId = self.get_photo_metadata(url) if len(title) == 0: tag = photoId else: tag = "%(title)s %(photoId)s" % locals() image = image...
*generate a multimarkdown image link viewable anywhere (no sign-in needed for private photos)* **Key Arguments:** - ``url`` -- the share URL for the flickr image (or just the unique photoid) - ``width`` -- the pixel width of the fully resolved image. Default *original*. [75, 100, 150, ...
341,943
def all_leaves(self, graph=None): if graph is None: graph = self.graph return [key for key in graph if not graph[key]]
Return a list of all leaves (nodes with no downstreams)
341,944
def _get_triplet(dd): return _s(dd[]), _s(dd.get(, NoResponse)), _s(dd.get(, NoResponse))
Return a triplet from a dialogue dictionary. :param dd: Dialogue dictionary. :type dd: Dict[str, str] :return: (query, response, error response) :rtype: (str, str | NoResponse, str | NoResponse)
341,945
def vbar_stack(self, stackers, **kw): 20162017bluered2016blue2016201620162017red2017 result = [] for kw in _double_stack(stackers, "bottom", "top", **kw): result.append(self.vbar(**kw)) return result
Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to ...
341,946
def clear_input(self): for item in listdir(self.input_dir): item_path = path.join(self.input_dir, item) if path.isfile(item_path): remove(item_path) logger.debug( % item_path) return
Remove all the input files (at the end of a reading).
341,947
def channels_get_integrations(self, room_id, **kwargs): return self.__call_api_get(, roomId=room_id, kwargs=kwargs)
Retrieves the integrations which the channel has
341,948
def fromFile(self, fname): spec, f, bins, dur = audiotools.spectrogram(fname, **self.specgramArgs) self.updateImage(spec, bins, f) return dur
Displays a spectrogram of an audio file. Supported formats see :func:`sparkle.tools.audiotools.audioread` :param fname: file path of the audiofile to display :type fname: str :returns: float -- duration of audio recording (seconds)
341,949
def by_occupied_housing_units(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.occupied_housing_units.name, asc...
Search zipcode information by occupied house of units.
341,950
def get_inputs( self, start=0, stop=None, threshold=None, security_level=None, ): return extended.GetInputsCommand(self.adapter)( seed=self.seed, start=start, stop=stop, threshold=th...
Gets all possible inputs of a seed and returns them, along with the total balance. This is either done deterministically (by generating all addresses until :py:meth:`find_transactions` returns an empty result), or by providing a key range to search. :param start: St...
341,951
def sanitize_for_archive(url, headers, payload): if DiscourseClient.PKEY in payload: payload.pop(DiscourseClient.PKEY) return url, headers, payload
Sanitize payload of a HTTP request by removing the token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :returns url, headers and the sanitized payload
341,952
def stop_daemon(self, payload=None): kill_signal = signals[] self.process_handler.kill_all(kill_signal, True) self.running = False return {: , : }
Kill current processes and initiate daemon shutdown. The daemon will shut down after a last check on all killed processes.
341,953
def visit_boolean_query(self, node): left = node.left.accept(self) right = node.right.accept(self) is_journal_keyword_op = isinstance(left, KeywordOp) and left.left == Keyword() if is_journal_keyword_op: journal_and_volume_conjunction = _restructure_if_volume_follo...
Convert BooleanRule into AndOp or OrOp nodes.
341,954
def _decode_length(self, offset, sizeof_char): sizeof_2chars = sizeof_char << 1 fmt = "<2{}".format( if sizeof_char == 1 else ) highbit = 0x80 << (8 * (sizeof_char - 1)) length1, length2 = unpack(fmt, self.m_charbuff[offset:(offset + sizeof_2chars)]) if (length1 & high...
Generic Length Decoding at offset of string The method works for both 8 and 16 bit Strings. Length checks are enforced: * 8 bit strings: maximum of 0x7FFF bytes (See http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#692) * 16 bit strings: maxi...
341,955
def p_expr_assign(p): if len(p) == 5: p[0] = ast.Assignment(p[1], p[4], True, lineno=p.lineno(2)) else: p[0] = ast.Assignment(p[1], p[3], False, lineno=p.lineno(2))
expr : variable EQUALS expr | variable EQUALS AND expr
341,956
def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): data = get_host(name=name, mac=mac, **api_opts) if data and in data: l = [] for a in data[]: if in a: l.append(a[]) if allow_array: return l if l: ret...
Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae
341,957
def get_filehandle(self): if os.path.exists(self.filename): self.filehandle = SD(self.filename, SDC.READ) logger.debug("Loading dataset {}".format(self.filename)) else: raise IOError("Path {} does not exist.".format(self.filename))
Get HDF4 filehandle.
341,958
def run_once(function, state={}, errors={}): @six.wraps(function) def _wrapper(*args, **kwargs): if function in errors: six.reraise(*errors[function]) try: return state[function] except KeyError: try: state[function] ...
A memoization decorator, whose purpose is to cache calls.
341,959
def from_bytes(data: Union[str, bytes]) -> str: if isinstance(data, str): return data return str(data, )
:param data: A UTF8 byte string. :type data: Union[str, bytes] :return: `data` decoded from UTF8. :rtype: str
341,960
def do_menu(self, line): print() print() print() print() print() print() print() print() print()
Display a menu of command-line options. Command syntax is: menu
341,961
def calculo(self): T = self.kwargs["T"] rho = self.kwargs["rho"] P = self.kwargs["P"] if self._composition == "A": A = self.kwargs["A"] elif self._composition == "xa": xa = self.kwargs["xa"] A = xa/(1-(1-xa)*(1-Mw/Ma)) ...
Calculate procedure
341,962
def create(self, friendly_name=None, description=None): if not self.exists(): try: response = self._api.datasets_insert(self._name_parts, friendly_name=friendly_name, description=description) except Ex...
Creates the Dataset with the specified friendly name and description. Args: friendly_name: (optional) the friendly name for the dataset if it is being created. description: (optional) a description for the dataset if it is being created. Returns: The Dataset. Raises: Exception if th...
341,963
def _put_request(self, url, headers, data=None): return self._session.put(url, headers=headers, data=data)
Issue a PUT request to the specified endpoint with the data provided. :param url: str :pararm headers: dict :param data: dict
341,964
def get_res_configs(self, rid, config=None, fallback=True): self._analyse() if not rid: raise ValueError(" should be set") if not isinstance(rid, int): raise ValueError(" must be an int") if rid not in self.resource_values: log.warning("The ...
Return the resources found with the ID `rid` and select the right one based on the configuration, or return all if no configuration was set. But we try to be generous here and at least try to resolve something: This method uses a fallback to return at least one resource (the first one in the li...
341,965
def _interpolate(self, colors, n=100): gradient = [] for i in _range(n): l = len(colors) - 1 x = int(1.0 * i / n * l) x = min(x + 0, l) y = min(x + 1, l) base = 1.0 * n / l * x d = (i - base) / (1.0 * n / l) ...
Returns intermediary colors for given list of colors.
341,966
def get_resource_notification_session(self, resource_receiver, proxy): if not self.supports_resource_notification(): raise errors.Unimplemented() return sessions.ResourceNotificationSession(proxy=proxy, runtime=self._runtime, receiver=resource_receiver)
Gets the resource notification session for the given bin. arg: resource_receiver (osid.resource.ResourceReceiver): notification callback arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceNotificationSession) - ``a ResourceNotificationSes...
341,967
def run(self): while True: self.open_lock.acquire() if self.stopped(): return self.__open() self.open_lock.release()
This override threading.Thread to open socket and wait for messages.
341,968
def _ip_unnumbered_name(self, **kwargs): method_name = \ % kwargs[] ip_unnumbered_name = getattr(self._interface, method_name) config = ip_unnumbered_name(**kwargs) if kwargs[]: tag = config.find( % tag).set(, ) return config
Return the `ip unnumbered` donor name XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True...
341,969
def Indicator(pos, size, dtype): x = numpy.zeros(size, dtype=dtype) x[pos] = 1 return x
Returns an array of length size and type dtype that is everywhere 0, except in the index in pos. :param pos: (int) specifies the position of the one entry that will be set. :param size: (int) The total size of the array to be returned. :param dtype: The element type (compatible with NumPy array()) of ...
341,970
def uninitialize_ui(self): LOGGER.debug("> Uninitializing Component ui.".format(self.__class__.__name__)) self.__remove_actions() self.__view.expanded.disconnect(self.__view__expanded) self.__view.doubleClicked.disconnect(self.__view__doubleClicked) self.__v...
Uninitializes the Component ui. :return: Method success. :rtype: bool
341,971
def is_effective_member(self, group_id, netid): self._valid_group_id(group_id) url = "{}/group/{}/effective_member/{}".format(self.API, group_id, netid) try: ...
Returns True if the netid is in the group, False otherwise.
341,972
def command_flush_for(self, id_type, command_id, status): id_types = (, , , ) status_types = (, , ) if id_type not in id_types or status not in status_types: raise ValueError("Invalid arguments.") if isinstance(command_id, list): comm...
Flush commands for an individual device. Args: id_type (str): One of 'computers', 'computergroups', 'mobiledevices', or 'mobiledevicegroups'. id_value (str, int, list): ID value(s) for the devices to flush. More than one device should be passed as IDs ...
341,973
def HexEscape(self, string, match, **unused_kwargs): logging.debug(.format(string)) hex_string = match.group(1) try: hex_string = binascii.unhexlify(hex_string) hex_string = codecs.decode(hex_string, ) self.string += hex_string except (TypeError, binascii.Error): raise error...
Converts a hex escaped string.
341,974
def server_cert_present(name, public_key, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ret = {: name, : True, : , : {}} exists = __salt__[](name, region, key, keyid, profile) log.debug(, locals()) if exists: ret[] = .form...
Crete server certificate. .. versionadded:: 2015.8.0 name (string) The name for the server certificate. Do not include the path in this value. public_key (string) The contents of the public key certificate in PEM-encoded format. private_key (string) The contents of the privat...
341,975
def decrypt(self, data): aes_key, hmac_key = self.keys sig = data[-self.SIG_SIZE:] data = data[:-self.SIG_SIZE] if six.PY3 and not isinstance(data, bytes): data = salt.utils.stringutils.to_bytes(data) mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).diges...
verify HMAC-SHA256 signature and decrypt data with AES-CBC
341,976
def _sub32(ins): op1, op2 = tuple(ins.quad[2:]) if is_int(op2): if int(op2) == 0: output = _32bit_oper(op1) output.append() output.append() return output rev = op1[0] != and not is_int(op1) and op2[0] == output = _32bit_oper(op1, op2, r...
Pops last 2 dwords from the stack and subtract them. Then push the result onto the stack. NOTE: The operation is TOP[0] = TOP[-1] - TOP[0] If TOP[0] is 0, nothing is done
341,977
def main(extension, strict_extensions, default_extension, x): logbook.StderrHandler().push_application() create_args(x, zipline.extension_args) load_extensions( default_extension, extension, strict_extensions, os.environ, )
Top level zipline entry point.
341,978
def application(handler, adapter_cls=WerkzeugAdapter): adapter = adapter_cls() def wrapper(environ, start_response): request = adapter.to_request(environ) response = handler(request) response_func = adapter.from_response(response) return response_func(environ, start_respons...
Converts an anillo function based handler in a wsgi compiliant application function. :param adapter_cls: the wsgi adapter implementation (default: wekrzeug) :returns: wsgi function :rtype: callable
341,979
def RunOnce(self): start_time = time.time() processed = 0 queue_manager = queue_manager_lib.QueueManager(token=self.token) for queue in self.queues: queue_manager.FreezeTimestamp() fetch_messages_start = time.time() notifications = queue_manager.GetNotifications(qu...
Processes one set of messages from Task Scheduler. The worker processes new jobs from the task master. For each job we retrieve the session from the Task Scheduler. Returns: Total number of messages processed by this call.
341,980
def aggregated_records(all_records, key_fields=KEY_FIELDS): flow_table = defaultdict(_FlowStats) for flow_record in all_records: key = tuple(getattr(flow_record, attr) for attr in key_fields) if any(x is None for x in key): continue flow_table[key].update(flow_record) ...
Yield dicts that correspond to aggregates of the flow records given by the sequence of FlowRecords in `all_records`. Skips incomplete records. This will consume the `all_records` iterator, and requires enough memory to be able to read it entirely. `key_fields` optionally contains the fields over which t...
341,981
def wells(self, *args) -> List[Well]: if not args: res = self._wells elif isinstance(args[0], int): res = [self._wells[idx] for idx in args] elif isinstance(args[0], str): res = [self.wells_by_index()[idx] for idx in args] else: ra...
Accessor function used to generate a list of wells in top -> down, left -> right order. This is representative of moving down `rows` and across `columns` (e.g. 'A1', 'B1', 'C1'...'A2', 'B2', 'C2') With indexing one can treat it as a typical python list. To access well A1, for example, s...
341,982
def matrixToHTML(data,names=None,units=None,bookName=None,sheetName=None,xCol=None): if not names: names=[""]*len(data[0]) if data.dtype.names: names=list(data.dtype.names) if not units: units=[""]*len(data[0]) for i in range(len(units)): if names[i] ...
Put 2d numpy data into a temporary HTML file.
341,983
def assert_child_key_has_value(self, parent, child, caller): assert parent, ("parent parameter must be specified.") assert child, ("child parameter must be specified.") self.assert_key_has_value(parent, caller) try: child_exists = child in self[parent] excep...
Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used to construct error messages Raises: ...
341,984
def fill_dataset_tree(self, tree, data_sets): tree.model().removeRows(0, tree.model().rowCount()) for index, (time, script) in enumerate(data_sets.items()): name = script.settings[] type = script.name item_time = QtGui.QStandardItem(str(time)) i...
fills the tree with data sets where datasets is a dictionary of the form Args: tree: data_sets: a dataset Returns:
341,985
def order(self, quote_id, store_view=None, license_id=None): return self.call(, [quote_id, store_view, license_id])
Allows you to create an order from a shopping cart (quote). Before placing the order, you need to add the customer, customer address, shipping and payment methods. :param quote_id: Shopping cart ID (quote ID) :param store_view: Store view ID or code :param license_id: Website li...
341,986
def __checkAttributes(self): for a in self.__class__.required: if not self.attributes.has_key(a): raise SchemaError,\ \ %(self.__class__, a) for a,v in self.attributes.items(): if type(v) is dict: ...
Checks that required attributes have been defined, attributes w/default cannot be required. Checks all defined attributes are legal, attribute references are not subject to this test.
341,987
def parse_input(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument(, , type=str, help="Specify a configuration file") return parser.parse_args()
Parses command line input.
341,988
def build_quantity(orig_text, text, item, values, unit, surface, span, uncert): if surface.lower() in [, , ] or \ re.search(r, surface) or \ re.search(r, surface) or \ re.search(r, surface, re.IGNORECASE): logging.debug(u, surface) return elif ...
Build a Quantity object out of extracted information.
341,989
def orifice_expansibility_1989(D, Do, P1, P2, k): r return 1.0 - (0.41 + 0.35*(Do/D)**4)*(P1 - P2)/(k*P1)
r'''Calculates the expansibility factor for orifice plate calculations based on the geometry of the plate, measured pressures of the orifice, and the isentropic exponent of the fluid. .. math:: \epsilon = 1- (0.41 + 0.35\beta^4)\Delta P/\kappa/P_1 Parameters ---------- D : ...
341,990
def trim_N_nucleotides(prefix, suffix): if in prefix: rightmost_index = prefix.rfind() logger.debug( "Trimming %d nucleotides from read prefix ", rightmost_index + 1, prefix) prefix = prefix[rightmost_index + 1:] if in suffix: leftmost_ind...
Drop all occurrences of 'N' from prefix and suffix nucleotide strings by trimming.
341,991
def normalize(self, inplace=True): phi = self if inplace else self.copy() if not inplace: return phi
Normalizes the distribution. In case of a Gaussian Distribution the distribution is always normalized, therefore this method doesn't do anything and has been implemented only for a consistent API across distributions.
341,992
def _add_creator(self): creator = self._creator creator.__doc__ = ( % self._nsptagname ) self._add_to_class(self._new_method_name, creator)
Add a ``_new_{prop_name}()`` method to the element class that creates a new, empty element of the correct type, having no attributes.
341,993
def get_decoded_jwt(request): jwt_cookie = request.COOKIES.get(jwt_cookie_name(), None) if not jwt_cookie: return None return jwt_decode_handler(jwt_cookie)
Grab jwt from jwt cookie in request if possible. Returns a decoded jwt dict if it can be found. Returns None if the jwt is not found.
341,994
def init_process(self) -> None: default_loop = asyncio.get_event_loop() if default_loop.is_running(): default_loop.close() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) else: self.loop = default_loop super(...
GunicornWorker 初始化回调
341,995
def get_classifications(subcategory_key): classifications = definition(subcategory_key)[] return sorted(classifications, key=lambda k: k[])
Get hazard or exposure classifications. :param subcategory_key: The hazard or exposure key :type subcategory_key: str :returns: List of hazard or exposure classifications :rtype: list
341,996
def upload_file(self, item, chunk_size=DEFAULT_UPLOAD_CHUNK_SIZE): if item is None: raise ValueError() item = Path(item) if not isinstance(item, Path) else item if not item.exists(): raise ValueError() if not item.is_file(): raise ValueError...
Uploads a file :param item: path to the item you want to upload :type item: str or Path :param chunk_size: Only applies if file is bigger than 4MB. Chunk size for uploads. Must be a multiple of 327.680 bytes :return: uploaded file :rtype: DriveItem
341,997
def acquire_node(self, node): try: return node.set(self.resource, self.lock_key, nx=True, px=self.ttl) except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError): return False
acquire a single redis node
341,998
def handle_err(self, exc): if self.reset_rx_on_error and isinstance(exc[1], (RxSyncError, EightbTenbError)): self.fifo_readout.print_readout_status() self.fifo_readout.reset_rx() else: if not self.abort_run.is_set(): self.abort(ms...
Handling of Exceptions. Parameters ---------- exc : list, tuple Information of the exception of the format (type, value, traceback). Uses the return value of sys.exc_info().
341,999
def setup_tree(self): self.tree.insert("", tk.END, text="Example 1", iid="1") self.tree.insert("", tk.END, text="Example 2", iid="2") self.tree.insert("2", tk.END, text="Example Child") self.tree.heading("
Setup an example Treeview