Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
18,700
def is_byte_range_valid(start, stop, length): if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: return 0 <= start < stop elif start >= stop: return False return 0 <= start < length
Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7
18,701
def _build_specs(self, specs, kwargs, fp_precision): if specs is None: overrides = param.ParamOverrides(self, kwargs, allow_extra_keywords=True) extra_kwargs = overrides.extra_keywords() kwargs = dict([(k,v) for (k,v) in k...
Returns the specs, the remaining kwargs and whether or not the constructor was called with kwarg or explicit specs.
18,702
def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True): stars = [] stars.extend(st) botstars = [] botstars.extend(bst) if len(stars) == 1: stars.append("undefined") if len(botstars) == 1: botstars.appen...
Post process tags in a message. :param str user: The user ID. :param str msg: The user's formatted message. :param str reply: The raw RiveScript reply for the message. :param []str st: The array of ``<star>`` matches from the trigger. :param []str bst: The array of ``<botstar>``...
18,703
def run(self, module, post_check): try: _cwd = os.getcwd() _sys_path = list(sys.path) _sys_argv = list(sys.argv) sys.path.insert(0, os.path.dirname(self._path)) sys.argv = [os.path.basename(self._path)] +...
Execute the configured source code in a module and run any post checks. Args: module (Module) : a module to execute the configured code in. post_check(callable) : a function that can raise an exception if expected post-conditions are not met after code execution...
18,704
def merge_extras(items, config): final = {} for extra_name in items[0]["disambiguate"].keys(): in_files = [] for data in items: in_files.append(data["disambiguate"][extra_name]) out_file = "%s-allmerged%s" % os.path.splitext(in_files[0]) if in_files[0].endswith("...
Merge extra disambiguated reads into a final BAM file.
18,705
def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]: if not hasattr(self, "_raw_xsrf_token"): cookie = self.get_cookie("_xsrf") if cookie: version, token, timestamp = self._decode_xsrf_token(cookie) else: version, token...
Read or generate the xsrf token in its raw form. The raw_xsrf_token is a tuple containing: * version: the version of the cookie from which this token was read, or None if we generated a new token in this request. * token: the raw token data; random (non-ascii) bytes. * timest...
18,706
def group_add(self, name=): if not hasattr(self, name): self.__dict__[name] = Group(self, name) self.loaded_groups.append(name)
Dynamically add a group instance to the system if not exist. Parameters ---------- name : str, optional ('Ungrouped' as default) Name of the group Returns ------- None
18,707
def to_json(data, filename=, indent=4): with open(filename, ) as f: f.write(json.dumps(data, indent=indent))
Write an object to a json file :param data: The object :param filename: The name of the file :param indent: The indentation of the file :return: None
18,708
def send_once(remote, codes, count=None, device=None, address=None): args = [, remote] + codes _call(args, count, device, address)
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str codes: [str] count: int device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subproc...
18,709
def POST(self): if self._POST is None: save_env = dict() for key in (, , ): if key in self.environ: save_env[key] = self.environ[key] save_env[] = if TextIOWrapper: fb = TextIOWrapper(self.body, encod...
The HTTP POST body parsed into a MultiDict. This supports urlencoded and multipart POST requests. Multipart is commonly used for file uploads and may result in some of the values beeing cgi.FieldStorage objects instead of strings. Multiple values per key are possible. S...
18,710
def crossdomain(f): @wraps(f) def decorator(self, *args, **kwargs): if not self.cors_enabled and in request.headers: return self._make_response(405, "CORS request rejected") resp = f(self, *args, **kwargs) h = resp.headers current_app.logger.debug("Req...
This decorator sets the rules for the crossdomain request per http method. The settings are taken from the actual resource itself, and returned as per the CORS spec. All CORS requests are rejected if the resource's `allow_methods` doesn't include the 'OPTIONS' method.
18,711
def _expand_variable_match(positional_vars, named_vars, match): positional = match.group("positional") name = match.group("name") if name is not None: try: return six.text_type(named_vars[name]) except KeyError: raise ValueError( "Named variable ...
Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable t...
18,712
def hash_str(data, hasher=None): hasher = hasher or hashlib.sha1() hasher.update(data) return hasher
Checksum hash a string.
18,713
def assign_objective_requisite(self, objective_id=None, requisite_objective_id=None): if objective_id is None or requisite_objective_id is None: raise NullArgument() ors = ObjectiveRequisiteSession(self._objective_bank_id, runtime=self._runtime) ids_arg = {: []} for ...
Creates a requirement dependency between two Objectives. arg: objective_id (osid.id.Id): the Id of the dependent Objective arg: requisite_objective_id (osid.id.Id): the Id of the required Objective raise: AlreadyExists - objective_id already mapped to ...
18,714
def sunion(self, keys, *args): func = lambda left, right: left.union(right) return self._apply_to_sets(func, "SUNION", keys, *args)
Emulate sunion.
18,715
def verify_submit(self, job_ids, timeout, delay, **kwargs): if self.skip: return False jobs = self.wait_for_jobs(job_ids, timeout, delay) self.get_logs(jobs, log_file=kwargs.get("log_file")) return self._check_outcome(jobs)
Verifies that the results were successfully submitted.
18,716
def key_size(self): if self.key_algorithm in {PubKeyAlgorithm.ECDSA, PubKeyAlgorithm.ECDH}: return self._key.keymaterial.oid return next(iter(self._key.keymaterial)).bit_length()
*new in 0.4.1* The size pertaining to this key. ``int`` for non-EC key algorithms; :py:obj:`constants.EllipticCurveOID` for EC keys.
18,717
def run_toy_DistilledSGLD(gpu_id): X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 teacher_net = get_toy_sym(True, teacher_noise_precision) student_net = get_toy_sym(False) data_shape = (minibatch_size,) + X.shape[1::] teacher_data_inputs = {: nd.zeros...
Run DistilledSGLD on toy dataset
18,718
def input_fields(self, preamble, *args): self.new_section() if preamble is not None: self.message(preamble) if any([True for x in args if len(x) > 3]): self.message() output_dict = { } for field in args: (field_name, prompt, field_t...
Get a set of fields from the user. Optionally a preamble may be shown to the user secribing the fields to return. The fields are specified as the remaining arguments with each field being a a list with the following entries: - a programmer-visible name for the field - a ...
18,719
def _extract_authors(pub, idx, _root): logger_ts.info("enter extract_authors") try: names = False logger_ts.info("extract_authors: KeyError: author data not provided, {}".format(e)) if names: auth = if isinstance(names, ...
Create a concatenated string of author names. Separate names with semi-colons. :param any pub: Publication author structure is ambiguous :param int idx: Index number of Pub
18,720
def create_queue_wrapper(name, queue_size, fed_arrays, data_sources, *args, **kwargs): qtype = SingleInputMultiQueueWrapper if in kwargs else QueueWrapper return qtype(name, queue_size, fed_arrays, data_sources, *args, **kwargs)
Arguments name: string Name of the queue queue_size: integer Size of the queue fed_arrays: list array names that will be fed by this queue data_sources: dict (lambda/method, dtype) tuples, keyed on array names
18,721
def read_playlists(self): self.playlists = [] self.selected_playlist = -1 files = glob.glob(path.join(self.stations_dir, )) if len(files) == 0: return 0, -1 else: for a_file in files: a_file_name = .join(path.basename(a_file).split()[:-1]) ...
get already loaded playlist id
18,722
def negative_directional_index(close_data, high_data, low_data, period): catch_errors.check_for_input_len_diff(close_data, high_data, low_data) ndi = (100 * smma(negative_directional_movement(high_data, low_data), period) / atr(close_data, period) ) return ndi
Negative Directional Index (-DI). Formula: -DI = 100 * SMMA(-DM) / ATR
18,723
def exec_container_commands(self, action, c_name, **kwargs): config_cmds = action.config.exec_commands if not config_cmds: return None return self.exec_commands(action, c_name, run_cmds=config_cmds)
Runs all configured commands of a container configuration inside the container instance. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :return: List of exec command return values (e...
18,724
def get_composite_keywords(ckw_db, fulltext, skw_spans): timer_start = time.clock() ckw_out = {} skw_as_components = [] for composite_keyword in ckw_db.values(): ckw_count = 0 matched_spans = [] for regex in composite_keyw...
Return a list of composite keywords bound with number of occurrences. :param ckw_db: list of KewordToken objects (they are supposed to be composite ones) :param fulltext: string to search in :param skw_spans: dictionary of already identified single keywords :return : dictionary of m...
18,725
def make_prototype_request(*args, **kwargs): if args and inspect.isclass(args[0]) and issubclass(args[0], Request): request_cls, arg_list = args[0], args[1:] return request_cls(*arg_list, **kwargs) if args and isinstance(args[0], Request): if args[1:] or kwargs: raise_ar...
Make a prototype Request for a Matcher.
18,726
def get_autype_list(self, code_list): code_list = unique_and_normalize_list(code_list) for code in code_list: if code is None or is_str(code) is False: error_str = ERROR_STR_PREFIX + "the type of param in code_list is wrong" return RET_ERROR, error_s...
获取给定股票列表的复权因子 :param code_list: 股票列表,例如['HK.00700'] :return: (ret, data) ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 ===================== =========== ==============================================================...
18,727
def registerDirectory(self,name,physicalPath,directoryType,cleanupMode, maxFileAge,description): url = self._url + "/directories/register" params = { "f" : "json", "name" : name, "physicalPath" : physicalPath, "directoryT...
Registers a new server directory. While registering the server directory, you can also specify the directory's cleanup parameters. You can also register a directory by using its JSON representation as a value of the directory parameter. Inputs: name - The name of the server d...
18,728
def is_git_directory_clean(path_to_repo: Path, search_parent_dirs: bool = True, check_untracked: bool = False) -> None: repo = Repo(str(path_to_repo), search_parent_directories=search_parent_dirs) logger.debug("is_git_directory_clean check for repo in p...
Check that the git working directory is in a clean state and raise exceptions if not. :path_to_repo: The path of the git repo
18,729
def _generate_for_subfolder(self, sid): name = self._sanitise_sheetname(uni(Folders.id_to_name(sid))) ws = self.workbook.add_worksheet(name) fmt = self.formats ws.write("A1", "Dossier report", fmt[]) ws.write("A2", "%s | %s" % (uni(self.folder_name), na...
Generate report for a subfolder. :param sid: The subfolder id; assumed valid
18,730
def dispatch(restricted=False): FlagWatch.reset() def _test(to_test): return list(filter(lambda h: h.test(), to_test)) def _invoke(to_invoke): while to_invoke: unitdata.kv().set(, False) for handler in list(to_invoke): to_invoke.remove(handler) ...
Dispatch registered handlers. When dispatching in restricted mode, only matching hook handlers are executed. Handlers are dispatched according to the following rules: * Handlers are repeatedly tested and invoked in iterations, until the system settles into quiescence (that is, until no new handlers...
18,731
def random_walk(network): latest = network.latest_transmission_recipient() if (not network.transmissions() or latest is None): sender = random.choice(network.nodes(type=Source)) else: sender = latest receiver = random.choice(sender.neighbors(direction="to", type=Agent)) sende...
Take a random walk from a source. Start at a node randomly selected from those that receive input from a source. At each step, transmit to a randomly-selected downstream node.
18,732
def num_dml_affected_rows(self): result = self._job_statistics().get("numDmlAffectedRows") if result is not None: result = int(result) return result
Return the number of DML rows affected by the job. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows :rtype: int or None :returns: number of DML rows affected by the job, or None if job is not yet complete.
18,733
def bbox(width=1.0, height=1.0, depth=1.0): width, height, depth = width / 2.0, height / 2.0, depth / 2.0 pos = numpy.array([ width, -height, depth, width, height, depth, -width, -height, depth, width, height, depth, -width, height, depth, -width, -height, de...
Generates a bounding box with (0.0, 0.0, 0.0) as the center. This is simply a box with ``LINE_STRIP`` as draw mode. Keyword Args: width (float): Width of the box height (float): Height of the box depth (float): Depth of the box Returns: A :py:class:`demosys.opengl.vao.VAO` ...
18,734
def valid_processor_options(processors=None): if processors is None: processors = [ dynamic_import(p) for p in tuple(settings.THUMBNAIL_PROCESSORS) + tuple(settings.THUMBNAIL_SOURCE_GENERATORS)] valid_options = set([, , ]) for processor in processors: ...
Return a list of unique valid options for a list of image processors (and/or source generators)
18,735
def training_data(job_id): offset = request.args.get(, 0) limit = request.args.get(, 0) cur.execute(, (job_id, offset, limit)) training_examples = [{:v,:l} for v,l in cur] data = { : training_examples } if int(request.args.get(, 0)) > 0: cur.execute("SELECT vector->> AS...
Returns training_examples for a given job_id from offset to limit If full_info parameter is greater than 0, will return extra architecture info, GET /jobs/139/vectors?offset=0&limit=10&full_info=1 { "labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3}, "label":0}, ...
18,736
def flux_balance(model, reaction, tfba, solver): fba = _get_fba_problem(model, tfba, solver) fba.maximize(reaction) for reaction in model.reactions: yield reaction, fba.get_flux(reaction)
Run flux balance analysis on the given model. Yields the reaction id and flux value for each reaction in the model. This is a convenience function for sertting up and running the FluxBalanceProblem. If the FBA is solved for more than one parameter it is recommended to setup and reuse the FluxBalancePr...
18,737
def princomp(x): (M,N) = x.shape Mean = x.mean(0) y = x - Mean cov = numpy.dot(y.transpose(),y) / (M-1) (V,PC) = numpy.linalg.eig(cov) order = (-V).argsort() coeff = PC[:,order] return coeff
Determine the principal components of a vector of measurements Determine the principal components of a vector of measurements x should be a M x N numpy array composed of M observations of n variables The output is: coeffs - the NxN correlation matrix that can be used to transform x into its compone...
18,738
def edit_asn(self, auth, asn, attr): self._logger.debug("edit_asn called; asn: %s attr: %s" % (unicode(asn), unicode(attr))) req_attr = [ ] allowed_attr = [ , ] self._check_attr(attr, req_attr, allowed_attr) asns = self.list_asn(auth, asn) ...
Edit AS number * `auth` [BaseAuth] AAA options. * `asn` [integer] AS number to edit. * `attr` [asn_attr] New AS attributes. This is the documentation of the internal backend function. It's exposed over XML-RPC,...
18,739
def html_print_file(self, catalog, destination): with open(destination, mode=, encoding=) as t_f: for text in catalog: pnum = catalog[text][] edition = catalog[text][] metadata = .join(catalog[text][]) transliteration = .join(c...
Prints text_file in html. :param catalog: text file you wish to pretty print :param destination: where you wish to save the HTML data :return: output in html_file.html.
18,740
def startElement (self, name, attrs): s a start method for this element, call it start_' + name, None) if func: func(attrs)
if there's a start method for this element, call it
18,741
def delete_view(self, request, object_id, extra_context=None): parent_folder = None try: obj = self.queryset(request).get(pk=unquote(object_id)) parent_folder = obj.parent except self.model.DoesNotExist: obj = None r = super(FolderAdmin, self...
Overrides the default to enable redirecting to the directory view after deletion of a folder. we need to fetch the object and find out who the parent is before super, because super will delete the object and make it impossible to find out the parent folder to redirect to.
18,742
def notebook_to_rst(npth, rpth, rdir, cr=None): ntbk = nbformat.read(npth, nbformat.NO_CONVERT) notebook_object_to_rst(ntbk, rpth, rdir, cr)
Convert notebook at `npth` to rst document at `rpth`, in directory `rdir`. Parameter `cr` is a CrossReferenceLookup object.
18,743
def requireCompatibleAPI(): if in sys.modules: import sip for api in (, ): if sip.getapi(api) != 2: raise RuntimeError( % (api, sip.getapi(api)))
If PyQt4's API should be configured to be compatible with PySide's (i.e. QString and QVariant should not be explicitly exported, cf. documentation of sip.setapi()), call this function to check that the PyQt4 was properly imported. (It will always be configured this way by this module, b...
18,744
def get_info( self, userSpecifier, **kwargs ): request = Request( , ) request.set_path_param( , userSpecifier ) response = self.ctx.request(request) if response.content_type is None...
Fetch the user information for the specified user. This endpoint is intended to be used by the user themself to obtain their own information. Args: userSpecifier: The User Specifier Returns: v20.response.Response containing the results from submi...
18,745
def get_text_for_repeated_menu_item( self, request=None, current_site=None, original_menu_tag=, **kwargs ): source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT return self.repeated_item_text or getattr( self, source_field_name, self.title )
Return the a string to use as 'text' for this page when it is being included as a 'repeated' menu item in a menu. You might want to override this method if you're creating a multilingual site and you have different translations of 'repeated_item_text' that you wish to surface.
18,746
def disable_on_env(func): @wraps(func) def func_wrapper(*args, **kwargs): function_name = func.__name__ VALIDATORS_DISABLED = os.getenv(, ) disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split()] force_run = kwargs.get(, False) try: ...
Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, the ``value`` (first positional argument) passed to ``func``. If enabled, the result of ``func``.
18,747
def imbox(xy, w, h, angle=0.0, **kwargs): from matplotlib.patches import Rectangle return imbound(Rectangle, xy, w, h, angle, **kwargs)
draw boundary box :param xy: start index xy (ji) :param w: width :param h: height :param angle: :param kwargs: :return:
18,748
def load_files(files, tag=None, sat_id=None, altitude_bin=None): output = [None]*len(files) drop_idx = [] for (i,file) in enumerate(files): try: data = netcdf_file(file, mode=, mmap=False) new = {} ...
Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file.
18,749
def write_data(filename, data, data_format=None, compress=False, add=False): create_parent_folder(filename) if not isinstance(data_format, MimeType): data_format = get_data_format(filename) if data_format.is_tiff_format(): return write_tiff_image(filename, data, compress) if data_...
Write image data to file Function to write image data to specified file. If file format is not provided explicitly, it is guessed from the filename extension. If format is TIFF, geo information and compression can be optionally added. :param filename: name of file to write data to :type filename: ...
18,750
def flatten(nested_list): return_list = [] for i in nested_list: if isinstance(i,list): return_list += flatten(i) else: return_list.append(i) return return_list
converts a list-of-lists to a single flat list
18,751
def _win32_junction(path, link, verbose=0): path = os.path.abspath(path) link = os.path.abspath(link) from ubelt import util_cmd if os.path.isdir(path): if verbose: print() command = .format(link, path) else: if verbose: ...
On older (pre 10) versions of windows we need admin privledges to make symlinks, however junctions seem to work. For paths we do a junction (softlink) and for files we use a hard link CommandLine: python -m ubelt._win32_links _win32_junction Example: >>> # xdoc: +REQUIRES(WIN32) ...
18,752
def _check_nonlocal_and_global(self, node): def same_scope(current): return current.scope() is node from_iter = itertools.chain.from_iterable nonlocals = set( from_iter( child.names for child in node.nodes_of_class(astroid.Nonloc...
Check that a name is both nonlocal and global.
18,753
def drawPoints(points, bg=): import sys points = list(points) try: points = [(int(x), int(y)) for x, y in points] except: raise PyBresenhamException() minx = min([x for x, y in points]) maxx = max([x for x, y in points]) miny = min([y for x, y in po...
A small debug function that takes an iterable of (x, y) integer tuples and draws them to the screen.
18,754
def cart_add(self, items, CartId=None, HMAC=None, **kwargs): if not CartId or not HMAC: raise CartException() if isinstance(items, dict): items = [items] if len(items) > 10: raise CartException("You canItem.{0}.OfferListingIdItem.{0}.Quantityoffer_i...
CartAdd. :param items: A dictionary containing the items to be added to the cart. Or a list containing these dictionaries. It is not possible to create an empty cart! example: [{'offer_id': 'rt2ofih3f389nwiuhf8934z87o3f4h', 'quantity': 1}] :par...
18,755
def _save_state(self): ns_prefixes_floating_in = copy.copy(self._ns_prefixes_floating_in) ns_prefixes_floating_out = copy.copy(self._ns_prefixes_floating_out) ns_decls_floating_in = copy.copy(self._ns_decls_floating_in) curr_ns_map = copy.copy(self._curr_ns_map) ns_map_s...
Helper context manager for :meth:`buffer` which saves the whole state. This is broken out in a separate method for readability and tested indirectly by testing :meth:`buffer`.
18,756
def _get_node(template, context, name): for node in template: if isinstance(node, BlockNode) and node.name == name: return node.nodelist.render(context) elif isinstance(node, ExtendsNode): return _get_node(node.nodelist, context, name) return ""
taken originally from http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
18,757
def jsonify(symbol): try: return json.dumps(symbol.toJson(), indent=) except AttributeError: pass return json.dumps(symbol, indent=)
returns json format for symbol
18,758
def dnld_assc(assc_name, go2obj=None, prt=sys.stdout): dirloc, assc_base = os.path.split(assc_name) if not dirloc: dirloc = os.getcwd() assc_locfile = os.path.join(dirloc, assc_base) if not dirloc else assc_name dnld_annotation(assc_locfile, prt) assc_orig = read_gaf(assc...
Download association from http://geneontology.org/gene-associations.
18,759
def __sort_registry(self, svc_ref): with self.__svc_lock: if svc_ref not in self.__svc_registry: raise BundleException("Unknown service: {0}".format(svc_ref)) for spec in svc_ref.get_property(OBJECTCLASS): s...
Sorts the registry, after the update of the sort key of given service reference :param svc_ref: A service reference with a modified sort key
18,760
def _at(self, idx): handle = NDArrayHandle() if idx < 0: length = self.shape[0] idx += length if idx < 0: raise IndexError( % (idx-length, length)) check_call(_LIB.MXNDArrayAt( self.handle, ...
Returns a view of the array sliced at `idx` in the first dim. This is called through ``x[idx]``. Parameters ---------- idx : int index for slicing the `NDArray` in the first dim. Returns ------- NDArray `NDArray` sharing the memory with t...
18,761
def image(request, data): try: width = int(request.GET.get("w", PYDENTICON_WIDTH)) except ValueError: raise SuspiciousOperation("Identicon width must be a positive integer.") try: height = int(request.GET.get("h", PYDENTICON_HEIGHT)) except ValueError: rai...
Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already, the digest will be used as-is....
18,762
def extra_reading_spec(self): field_names = ("frame_number", "action", "reward", "done") data_fields = { name: tf.FixedLenFeature([1], tf.int64) for name in field_names } decoders = { name: tf.contrib.slim.tfexample_decoder.Tensor(tensor_key=name) for name in field_names ...
Additional data fields to store on disk and their decoders.
18,763
def split_array_like(df, columns=None): Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. colum...
Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. columns : ~typing.Collection[str] or str or None ...
18,764
def getrefnames(idf, objname): iddinfo = idf.idd_info dtls = idf.model.dtls index = dtls.index(objname) fieldidds = iddinfo[index] for fieldidd in fieldidds: if in fieldidd: if fieldidd[][0].endswith(): if in fieldidd: return fieldidd[] ...
get the reference names for this object
18,765
def mpub(self, topic, messages, binary=True): if binary: return self.post(, data=pack(messages)[4:], params={: topic, : True}) elif any( in m for m in messages): raise ClientException( ) else:...
Send multiple messages to a topic. Optionally pack the messages
18,766
def _write_value(self, field_type, value): if len(field_type) > 1: field_type = field_type[0] if field_type == self.TYPE_BOOLEAN: self._writeStruct(">B", 1, (1 if value else 0,)) elif field_type == self.TYPE_BYTE: self._writeStruct(">b",...
Writes an item of an array :param field_type: Value type :param value: The value itself
18,767
def encrypt_to(self, f, mac_bytes=10): ctx = EncryptionContext(f, self.p, mac_bytes) yield ctx ctx.finish()
Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'.
18,768
def salt_and_pepper_noise(X, v): X_noise = X.copy() n_features = X.shape[1] mn = X.min() mx = X.max() for i, sample in enumerate(X): mask = np.random.randint(0, n_features, v) for m in mask: if np.random.random() < 0.5: X_noise[i][m] = mn ...
Apply salt and pepper noise to data in X. In other words a fraction v of elements of X (chosen at random) is set to its maximum or minimum value according to a fair coin flip. If minimum or maximum are not given, the min (max) value in X is taken. :param X: array_like, Input data :param v: int,...
18,769
def load(self): self._validate() self._logger.logging_load() formatter = MediaWikiTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
Extract tabular data as |TableData| instances from a MediaWiki text object. |load_source_desc_text| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier ...
18,770
def import_new_atlas_pointings( self, recent=False): self.log.info() if recent: mjd = mjdnow( log=self.log ).get_mjd() recent = mjd - 14 recent = " mjd_obs > %(recent)s " % locals() else: ...
*Import any new ATLAS pointings from the atlas3/atlas4 databases into the ``atlas_exposures`` table of the Atlas Movers database* **Key Arguments:** - ``recent`` -- only sync the most recent 2 weeks of data (speeds things up) **Return:** - None **Usage:** ...
18,771
def compress_encoder(inputs, hparams, strides=(2, 2), kernel_size=(3, 3), name=None): with tf.variable_scope(name, default_name="compress"): x = inputs for i in range(hparams.num_compress_steps // 2): with tf.variable...
Encoder that compresses 2-D inputs by 2**num_compress_steps. Args: inputs: Tensor of shape [batch, height, width, channels]. hparams: HParams. strides: Tuple, strides for conv block. kernel_size: Tuple, kernel window size for conv block. name: string, variable scope. Returns: Tensor of sha...
18,772
def getObjectWorkflowStates(self): workflow = getToolByName(self, ) states = {} for w in workflow.getWorkflowsFor(self): state = api.get_workflow_status_of(self, w.state_var) states[w.state_var] = state return states
This method is used to populate catalog values Returns a dictionary with the workflow id as key and workflow state as value. :return: {'review_state':'active',...}
18,773
def _map_term_using_schema(master, path, term, schema_edges): output = FlatList() for k, v in term.items(): dimension = schema_edges[k] if isinstance(dimension, Dimension): domain = dimension.getDomain() if dimension.fields: if is_data(dimension.field...
IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM
18,774
def PrintField(self, field, value): out = self.out out.write( * self.indent) if self.use_field_number: out.write(str(field.number)) else: if field.is_extension: out.write() if (field.containing_type.GetOptions().message_set_wire_format and field.type == descr...
Print a single field name/value pair.
18,775
def create_doc_dict(self, document, doc_key=None, owner_document=None): if owner_document: doc_field = owner_document._fields.get(doc_key, None) if doc_key else None else: doc_field = document._fields.get(doc_key, None) if doc_key else None doc...
Generate a dictionary representation of the document. (no recursion) DO NOT CALL DIRECTLY
18,776
def from_ep_string(cls, ep_string, location): ep_string = ep_string.strip() if in ep_string: ep_lines = ep_string.split() else: ep_lines = ep_string.split() lines = [l.split()[0].strip().replace(, ) for l in ep_lines] assert le...
Initalize from an EnergyPlus string of a SizingPeriod:DesignDay. args: ep_string: A full string representing a SizingPeriod:DesignDay.
18,777
def _op_to_matrix(self, op: Optional[ops.Operation], qubits: Tuple[ops.Qid, ...] ) -> Optional[np.ndarray]: q1, q2 = qubits matrix = protocols.unitary(op, None) if matrix is None: return None assert ...
Determines the effect of an operation on the given qubits. If the operation is a 1-qubit operation on one of the given qubits, or a 2-qubit operation on both of the given qubits, and also the operation has a known matrix, then a matrix is returned. Otherwise None is returned. A...
18,778
def delete_node(self, node_name, graph=None): if not graph: graph = self.graph if node_name not in graph: raise KeyError( % node_name) graph.pop(node_name) for node, edges in six.iteritems(graph): if node_name in edges: edges....
Deletes this node and all edges referencing it.
18,779
def get_line_pattern_rules(declarations, dirs): property_map = {: , : , : , : , : , : } property_names = property_map.keys() rules = [] for (filter, values) in filtered_property_declarations(declarations, property_names): lin...
Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files.
18,780
def __check_classes(self): msg = ( "Sanic JWT was not initialized properly. It did not received " "an instance of {}" ) if not issubclass(self.authentication_class, Authentication): raise exceptions.InitializationFailure( mess...
Check if any of the default classes (`Authentication`, `Configuration` and / or `Responses`) have been overwitten and if they're still valid
18,781
def read(self, size=None): if size is None: size = self.__size ret_list = [] while size > 0 and self.__buf: data = self.__buf.popleft() size -= len(data) ret_list.append(data) if size < 0: ret_list[-1], remainder = ret_...
Read at most size bytes from this buffer. Bytes read from this buffer are consumed and are permanently removed. Args: size: If provided, read no more than size bytes from the buffer. Otherwise, this reads the entire buffer. Returns: The bytes read from this buf...
18,782
def lowercase(state): return state.to_child( student_result={k.lower(): v for k, v in state.student_result.items()}, solution_result={k.lower(): v for k, v in state.solution_result.items()}, )
Convert all column names to their lower case versions to improve robustness :Example: Suppose we are testing the following SELECT statements * solution: ``SELECT artist_id as id FROM artists`` * student : ``SELECT artist_id as ID FROM artists`` We can write the following SCTs...
18,783
def get_contents_debug_adapter_protocol(self, lst, fmt=None): t need to have the `resolve` method called later on, so, keys don l = len(lst) ret = [] format_str = + str(int(len(str(l - 1)))) + if fmt is not None and fmt.get(, False): format_str = + str(int(len(hex...
This method is to be used in the case where the variables are all saved by its id (and as such don't need to have the `resolve` method called later on, so, keys don't need to embed the reference in the key). Note that the return should be ordered. :return list(tuple(name:str, value:obj...
18,784
def series_resistance(self, channel, resistor_index=None): if resistor_index is None: resistor_index = self.series_resistor_index(channel) value = self._series_resistance(channel) try: if channel == 0: self.calibration.R_hv[resistor_index] = value...
Parameters ---------- channel : int Analog channel index. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from the current context _(i.e., the result of :attr...
18,785
def cartpole(): locals().update(default()) env = max_length = 500 steps = 2e5 normalize_ranges = False network = networks.feed_forward_categorical return locals()
Configuration for the cart pole classic control task.
18,786
def _infer_record_outputs(inputs, unlist, file_vs, std_vs, parallel, to_include=None, exclude=None): fields = [] unlist = set([_get_string_vid(x) for x in unlist]) input_vids = set([_get_string_vid(v) for v in _handle_special_inputs(inputs, file_vs)]) to_include = set([_ge...
Infer the outputs of a record from the original inputs
18,787
def _ows_check_charm_func(state, message, charm_func_with_configs): if charm_func_with_configs: charm_state, charm_message = charm_func_with_configs() if (charm_state != and charm_state != and charm_state is not None): state = workload_state_compare...
Run a custom check function for the charm to see if it wants to change the state. This is only run if not in 'maintenance' and tests to see if the new state is more important that the previous one determined by the interfaces/relations check. @param state: the previously determined state so far. @...
18,788
def S_isothermal_pipe_to_two_planes(D, Z, L=1.): r return 2.*pi*L/log(8.*Z/(pi*D))
r'''Returns the Shape factor `S` of a pipe of constant outer temperature and of outer diameter `D` which is `Z` distance from two infinite isothermal planes of equal temperatures, parallel to each other and enclosing the pipe. Length `L` must be provided, but can be set to 1 to obtain a dimensionless sh...
18,789
def init_layout(self): for child in self.children(): self.child_added(child) self.update_shape({})
Initialize the layout of the toolkit shape. This method is called during the bottom-up pass. This method should initialize the layout of the widget. The child widgets will be fully initialized and layed out when this is called.
18,790
def fetch_by_client_id(self, client_id): if client_id not in self.clients: raise ClientNotFoundError return self.clients[client_id]
Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError
18,791
def fillna(self, column_name, value): if type(column_name) is not str: raise TypeError("column_name must be a str") ret = self[self.column_names()] ret[column_name] = ret[column_name].fillna(value) return ret
Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column_name``, this method attempts to convert the value to the original column's type. If this fails, an error is raised. Parameters ---------- column_...
18,792
def audio_send_stream(self, httptype=None, channel=None, path_file=None, encode=None): if httptype is None or channel is None: raise RuntimeError("Requires htttype and channel") file_audio = { : open(path_file, ), } header = { ...
Params: path_file - path to audio file channel: - integer httptype - type string (singlepart or multipart) singlepart: HTTP content is a continuos flow of audio packets multipart: HTTP content type is multipart/x-mixed-replace, and ...
18,793
def AssignVar(self, value): self.value = value [option.OnAssignVar() for option in self.options]
Assign a value to this Value.
18,794
def dependents(self, on_predicate=None, from_predicate=None): core = set(self.targets(on_predicate)) dependees = defaultdict(set) for target in self.targets(from_predicate): for dependency in target.dependencies: if dependency in core: dependees[target].add(dependency) retur...
Returns a map from targets that satisfy the from_predicate to targets they depend on that satisfy the on_predicate. :API: public
18,795
def __fetch_issue_attachments(self, issue_id): for attachments_raw in self.client.issue_collection(issue_id, "attachments"): attachments = json.loads(attachments_raw) for attachment in attachments[]: yield attachment
Get attachments of an issue
18,796
def getEvents(self): caught_events = self._observer.caught_events self._observer.caught_events = [] for event in caught_events: self._observer.activate_event(event["name"]) return caught_events
Returns a list of all events that have occurred. Empties the internal queue.
18,797
def session_end(self): self.session_depth -= 1 self.session_depth = max(0, self.session_depth) if self.session_depth == 0: self._session_end()
End a session. Se session_begin for an in depth description of TREZOR sessions.
18,798
def report_errors_to_ga(self, errors): hits = [] responses = [] for field_name in sorted(errors): for error_message in errors[field_name]: event = self.format_ga_hit(field_name, error_message) if event: hits.append(event) ...
Report errors to Google Analytics https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
18,799
def postman(host, port=587, auth=(None, None), force_tls=False, options=None): return Postman( host=host, port=port, middlewares=[ middleware.tls(force=force_tls), middleware.auth(*auth), ], **options )
Creates a Postman object with TLS and Auth middleware. TLS is placed before authentication because usually authentication happens and is accepted only after TLS is enabled. :param auth: Tuple of (username, password) to be used to ``login`` to the server. :param force_tls: Whether TLS should...