Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
338,100
def cost_min2(self, alpha): n = self.V.dim() ax = alpha[:n] ay = alpha[n:] q2, r2 = self.get_q2_r2(ax, ay) Lax = self.L * a...
Residual formulation, Hessian is a low-rank update of the identity.
338,101
def guess_bytes(bstring): if isinstance(bstring, str): raise UnicodeError( "This string was already decoded as Unicode. You should pass " "bytes to guess_bytes, not Unicode." ) if bstring.startswith(b) or bstring.startswith(b): return bstring.decode(), ...
NOTE: Using `guess_bytes` is not the recommended way of using ftfy. ftfy is not designed to be an encoding detector. In the unfortunate situation that you have some bytes in an unknown encoding, ftfy can guess a reasonable strategy for decoding them, by trying a few common encodings that can be disting...
338,102
def send_sticker(self, sticker, **options): return self.bot.api_call( "sendSticker", chat_id=str(self.id), sticker=sticker, **options )
Send a sticker to the chat. :param sticker: Sticker to send (file or string) :param options: Additional sendSticker options (see https://core.telegram.org/bots/api#sendsticker)
338,103
def to_pydatetime(self): return datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())
Converts datetime2 object into Python's datetime.datetime object @return: naive datetime.datetime
338,104
def remove_app(name, site): ret = {: name, : {}, : str(), : None} current_apps = __salt__[](site) if name not in current_apps: ret[] = .format(name) ret[] = True elif __opts__[]: ret[] = .format(name) ret[] = {: name, ...
Remove an IIS application. :param str name: The application name. :param str site: The IIS site name. Usage: .. code-block:: yaml site0-v1-app-remove: win_iis.remove_app: - name: v1 - site: site0
338,105
def add_hard_link(self, **kwargs): t take up any additional space on the the ISO. This API can be used to create hard links between two files on the ISO9660 filesystem, between two files on the Joliet filesystem, or between a file on the ISO9660 filesystem and the Joliet filesy...
Add a hard link to the ISO. Hard links are alternate names for the same file contents that don't take up any additional space on the the ISO. This API can be used to create hard links between two files on the ISO9660 filesystem, between two files on the Joliet filesystem, or between a ...
338,106
def send_change_notification(hub, topic_url, updated_content=None): if updated_content: body = base64.b64decode(updated_content[]) else: body, updated_content = get_new_content(hub.config, topic_url) b64_body = updated_content[] headers = updated_content[] link_header = header...
7. Content Distribution
338,107
def schedule(self, scheduled_time, func, args=None, kwargs=None, interval=None, repeat=None, result_ttl=None, ttl=None, timeout=None, id=None, description=None, queue_name=None, meta=None): if interval is not None and result_ttl is None: ...
Schedule a job to be periodically executed, at a certain interval.
338,108
def init_body_buffer(self, method, headers): content_length = headers.get("CONTENT-LENGTH", None) if method in (HTTPMethod.POST, HTTPMethod.PUT): if content_length is None: raise HTTPErrorBadRequest("HTTP Method requires a CONTENT-LENGTH header") self.co...
Sets up the body_buffer and content_length attributes based on method and headers.
338,109
def sql(self, sql, *params): self.ops.append(self.migrator.sql(sql, *params))
Execure raw SQL.
338,110
def data_item_path(cls, project, dataset, data_item): return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/dataItems/{data_item}", project=project, dataset=dataset, data_item=data_item, )
Return a fully-qualified data_item string.
338,111
def delete_service(name, namespace=, **kwargs): ** cfg = _setup_conn(**kwargs) try: api_instance = kubernetes.client.CoreV1Api() api_response = api_instance.delete_namespaced_service( name=name, namespace=namespace) return api_response.to_dict() except (...
Deletes the kubernetes service defined by name and namespace CLI Examples:: salt '*' kubernetes.delete_service my-nginx default salt '*' kubernetes.delete_service name=my-nginx namespace=default
338,112
def preprocess_cell(self, cell, resources, cell_index): from nbformat.notebooknode import NotebookNode attach_names = [] for k, attach in cell.get(, {}).items(): for mime_type in self.extract_output_types: if mime_type in attach: ...
Also extracts attachments
338,113
def distances(x, y, px, py, plot=False): length_line = np.sqrt((x[1] - x[0]) ** 2 + (y[1] - y[0]) ** 2) horizontal = (np.diff(y) == 0) vertical = (np.diff(x) == 0) dist = [] dpl = [] counter = 0 for xp, yp in zip(px, py): dp = np.sqrt((xp - x) ** 2 + (yp - y) ** 2) ...
Compute shortest distance of points (px, py) to the line described by the end points in (x, y). Parameters ---------- x,y: x and y coordinates of line px: x coordinates of data points py: y coordiante of data points Returns ------- distances: list of distances
338,114
def translate_func(name, block, args): inline = name.startswith() real_name = if inline: name, real_name = name.split() arglist = .join(args) + if args else code = % (name, arglist) scope = ":this, :arguments" for arg in args: scope += % (repr(arg), arg) ...
Translates functions and all nested functions to Python code. name - name of that function (global functions will be available under var while inline will be available directly under this name ) block - code of the function (*with* brackets {} ) args - arguments that this function take...
338,115
def edge(self, id1, id2): if id1 in self and \ id2 in self and \ self[id2] in self[id1].links: return self[id1].links.edge(id2) return None
Returns the edge between the nodes with given id1 and id2.
338,116
def list_tables(self, limit=None, start_table=None): data = {} if limit: data[] = limit if start_table: data[] = start_table json_input = json.dumps(data) return self.make_request(, json_input)
Return a list of table names associated with the current account and endpoint. :type limit: int :param limit: The maximum number of tables to return. :type start_table: str :param limit: The name of the table that starts the list. If you ran a previous list_tables ...
338,117
def preference_form_builder(form_base_class, preferences=[], **kwargs): registry = form_base_class.registry preferences_obj = [] if len(preferences) > 0: for pref in preferences: if isinstance(pref, string_types): preferences_obj.append(registry.get(name=pre...
Return a form class for updating preferences :param form_base_class: a Form class used as the base. Must have a ``registry` attribute :param preferences: a list of :py:class: :param section: a section where the form builder will load preferences
338,118
def get_file_head(file_name): text = None try: with open(file_name, , encoding=) as fh: text = fh.read(512000) except: try: with open(file_name, , encoding=sys.getfilesystemencoding()) as fh: text = fh.read(512000) except: l...
Returns the first 512000 bytes of the file's contents.
338,119
def apply_dict_depth_first(nodes, func, depth=0, as_dict=True, parents=None, pre=None, post=None): if as_dict: items = OrderedDict() else: items = [] if parents is None: parents = [] node_count = len(nodes) for i, (k, node) in enumerate(nodes.iteritems()): firs...
This function is similar to the `apply_depth_first` except that it operates on the `OrderedDict`-based structure returned from `apply_depth_first` when `as_dict=True`. Note that if `as_dict` is `False`, the result of this function is given in the entry/tuple form.
338,120
def lpc(y, order): if not isinstance(order, int) or order < 1: raise ParameterError("order must be an integer > 0") util.valid_audio(y, mono=True) return __lpc(y, order)
Linear Prediction Coefficients via Burg's method This function applies Burg's method to estimate coefficients of a linear filter on `y` of order `order`. Burg's method is an extension to the Yule-Walker approach, which are both sometimes referred to as LPC parameter estimation by autocorrelation. ...
338,121
def ga4ghImportGlue(): path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(path)
Call this method before importing a ga4gh module in the scripts dir. Otherwise, you will be using the installed package instead of the development package. Assumes a certain directory structure.
338,122
def disconnect(self, ip, port): _check_valid_port_range(port) address = (ip, port) try: self._addresses.remove(address) except ValueError: error = .format(ip, port) log.exception(error) raise ValueError(error) if self._is...
Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self
338,123
def ErrorMsg(): import traceback limit = None _type, value, tb = sys.exc_info() _list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(_type, value) return "Traceback (innermost last):\n" + "%-20s %s" % ( " ".join(_list[:-1]), _list[-1])
Helper to get a nice traceback as string
338,124
def generate_password_hash(password, method=, salt_length=8): salt = method != and gen_salt(salt_length) or h, actual_method = _hash_internal(method, salt, password) return % (actual_method, salt, h)
Hash a password with the given method and salt with with a string of the given length. The format of the string returned includes the method that was used so that :func:`check_password_hash` can check the hash. The format for the hashed string looks like this:: method$salt$hash This method c...
338,125
def unwatch(connection, volume_id): try: volume = connection.get_all_volumes(volume_ids=[volume_id])[0] volume.remove_tag() except EC2ResponseError: pass logger.info(.format(volume_id)) return True
Remove watching of a volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume_id: str :param volume_id: VolumeID to add to the watchlist :returns: bool - True if the watch was successful
338,126
def skip(self, attr): ns = attr.namespace() skip = ( Namespace.xmlns[1], , , , ) return ( Namespace.xs(ns) or ns[1] in skip )
Get whether to skip (filter-out) the specified attribute. @param attr: An attribute. @type attr: I{Attribute} @return: True if should be skipped. @rtype: bool
338,127
def action_checklist_report_extractor(impact_report, component_metadata): context = {} extra_args = component_metadata.extra_args components_list = resolve_from_dictionary( extra_args, ) context[] = resource_url( resources_path(, , )) for key, component in list(components_list...
Extracting action checklist of the impact layer to its own report. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component_metadata: the component metadata. Used to obtain ...
338,128
def mcmc(transform, loglikelihood, parameter_names, nsteps=40000, nburn=400, stdevs=0.1, start = 0.5, **problem): if in problem: numpy.random.seed(problem[]) n_params = len(parameter_names) def like(cube): cube = numpy.array(cube) if (cube <= 1e-10).any() or (cube >= 1-1e-10).any(): return -1e100 ...
**Metropolis Hastings MCMC** with automatic step width adaption. Burnin period is also used to guess steps. :param nburn: number of burnin steps :param stdevs: step widths to start with
338,129
def processFinishedJob(self, batchSystemID, resultStatus, wallTime=None): jobNode = self.removeJob(batchSystemID) jobStoreID = jobNode.jobStoreID if wallTime is not None and self.clusterScaler is not None: self.clusterScaler.addCompletedJob(jobNode, wallTime) if self...
Function reads a processed jobGraph file and updates its state.
338,130
def config(self, charm_id, channel=None): s id. @param channel Optional channel name. {}/{}/meta/charm-config'.format(self.url, _get_path(charm_id)) data = self._get(_add_channel(url, channel)) return data.json()
Get the config data for a charm. @param charm_id The charm's id. @param channel Optional channel name.
338,131
def capture_page_screenshot(self, filename=None): path, link = self._get_screenshot_paths(filename) if hasattr(self._current_application(), ): self._current_application().get_screenshot_as_file(path) else: self._current_application().save_screenshot(path)...
Takes a screenshot of the current page and embeds it into the log. `filename` argument specifies the name of the file to write the screenshot into. If no `filename` is given, the screenshot is saved into file `appium-screenshot-<counter>.png` under the directory where the Robot Fra...
338,132
def is_one_of(obj, types): for type_ in types: if isinstance(obj, type_): return True return False
Return true iff obj is an instance of one of the types.
338,133
def _transition_counts(sequences, lag_time=1, sliding_window=True): if (not sliding_window) and lag_time > 1: return _transition_counts([X[::lag_time] for X in sequences], lag_time=1) classes = np.unique(np.concatenate(sequences)) contains_nan = (classes.dtype...
Count the number of directed transitions in a collection of sequences in a discrete space. Parameters ---------- sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable of state labels. Labels can be integers, strings, or oth...
338,134
def write_hex(fout, buf, offset, width=16): skipped_zeroes = 0 for i, chunk in enumerate(chunk_iter(buf, width)): if chunk == (b"\x00" * width): skipped_zeroes += 1 continue elif skipped_zeroes != 0: fout.write(" -- skipped zeroes: {}\n".format...
Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row
338,135
def identify_vcs(repo_url, guess=False, repo_aliases=REPO_ALIASES): repo_url = unicode(repo_url) vcs = identify_vcs_vs_alias(repo_url, guess=guess, repo_aliases=repo_aliases) if vcs: return vcs no_prefix = .join(repo_url.split("//")[1:]) vcs = identify_vcs_vs_alias(no_prefix...
Determines the type of repo that `repo_url` represents. :param repo_url: Repo URL of unknown type. :returns: VCS type (git, hg, etc) or raises UnknownVCS exception.
338,136
def commit_finished( self, block_id ): self.db.commit() assert block_id+1 in self.vesting, .format(block_id) self.clear_collisions( block_id ) self.clear_vesting(block_id+1)
Called when the block is finished. Commits all data.
338,137
def check(self, diff): path = diff.b_path assert any( path.endswith(ext) for ext in importlib.machinery.SOURCE_SUFFIXES )
Check that the new file introduced is a python source file
338,138
async def sleep_async(self, seconds): try: await self.lock_async() await asyncio.sleep(seconds) except asyncio.TimeoutError: _logger.debug("Connection %r timed out while waiting for lock acquisition.", self.container_id) finally: self.rele...
Lock the connection for a given number of seconds. :param seconds: Length of time to lock the connection. :type seconds: int
338,139
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: raise NotImplementedError()
Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestH...
338,140
def _get_persistent_boot_devices(self): headers_bios, bios_uri, bios_settings = self._check_bios_resource() boot_settings = self._get_bios_boot_resource(bios_settings) try: boot_sources = boot_settings[] except KeyError: msg =...
Get details of persistent boot devices, its order :returns: List of dictionary of boot sources and list of boot device order :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
338,141
def assertSignalOrdering(self, *expected_events): expected_order = [self._events_seen.index(event) for event in expected_events] actual_order = sorted(expected_order) self.assertEqual( expected_order, actual_order, "\nExpected order of f...
Assert that a signals were fired in a specific sequence. :param expected_events: A (varadic) list of events describing the signals that were fired Each element is a 3-tuple (signal, args, kwargs) that describes the event. .. note:: If you are using :meth...
338,142
def get_ligand_ring_selection(self,ring): ring_names = "" for atom in self.ligrings[ring]: ring_names = ring_names+" "+str(atom) ring_selection = self.topology_data.universe.ligand.select_atoms("name "+ring_names) return ring_selection
MDAnalysis atom selections of aromatic rings present in the ligand molecule. Takes: * ring * - index in self.ligrings dictionary Output: * ring_selection * - MDAnalysis Atom group
338,143
def list_npm_modules(collector, no_print=False): default = ReactServer().default_npm_deps() for _, module in sorted(collector.configuration["__active_modules__"].items()): default.update(module.npm_deps()) if not no_print: print(json.dumps(default, indent=4, sort_keys=True)) return...
List the npm modules that get installed in a docker image for the react server
338,144
def _regenerate_secret_key(self):
Regenerate secret key http://www.mediafire.com/developers/core_api/1.3/getting_started/#call_signature
338,145
def _load_different_url_payload(self, cdx, headers_record, failed_files, cdx_loader): ref_target_uri = (headers_record.rec_headers. get_header()) target_uri = headers_record.rec_headers.get_header() if not ref_tar...
Handle the case where a duplicate of a capture with same digest exists at a different url. If a cdx_server is provided, a query is made for matching url, timestamp and digest. Raise exception if no matches found.
338,146
def isHeld(self): if not os.path.exists(self.lockPath): return False try: mtime = os.stat(self.lockPath).st_mtime except FileNotFoundError as e: return False if self.__checkExpiration(mtime): return False ...
isHeld - True if anyone holds the lock, otherwise False. @return bool - If lock is held by anyone
338,147
def delete_subject(self, subject): url = .join([self.url, , subject]) result, code = self._send_request(url, method="DELETE") if not (code >= 200 and code <= 299): raise ClientError(.format(result)) return result
DELETE /subjects/(string: subject) Deletes the specified subject and its associated compatibility level if registered. It is recommended to use this API only when a topic needs to be recycled or in development environments. :param subject: subject name :returns: version of the schema del...
338,148
def load_hash_configuration(self, hash_name): conf = self.mongo_object.find_one( {: hash_name + } ) return pickle.loads(conf[]) if conf is not None\ else None
Loads and returns hash configuration
338,149
def call_hook(message, attachment=None, color=, short=False, identifier=None, channel=None, username=None, icon_emoji=None): *Hello, from SaltStack base_url = if not identifier: identifier = _get_hook_...
Send message to Slack incoming webhook. :param message: The topic of message. :param attachment: The message to send to the Slacke WebHook. :param color: The color of border of left side :param short: An optional flag indicating whether the value is short enough...
338,150
def _delete_resource(self, url): conn, head = self._construct_request() conn.request("DELETE", url, "", head) resp = conn.getresponse() self._handle_response_errors(, url, resp)
DELETEs the resource at url
338,151
def add_enrichr_parser(subparsers): argparser_enrichr = subparsers.add_parser("enrichr", help="Using Enrichr API to perform GO analysis.") enrichr_opt = argparser_enrichr.add_argument_group("Input arguments") enrichr_opt.add_argument("-i", "--input-list", action="store", dest="gene_list", type=s...
Add function 'enrichr' argument parsers.
338,152
def _create_md5_dict(self): self.sbo_md5 = {} md5_lists = SBoGrep(self.prgnam).checksum() for src, md5 in zip(self.sources, md5_lists): self.sbo_md5[src] = md5
Create md5 dictionary per source
338,153
def _delete_port_profile(self, handle, port_profile, ucsm_ip): try: self._delete_port_profile_from_ucsm(handle, port_profile, ucsm_ip) except Exception as e: LOG.debug(, e) self.ucsm_db.add_port_profile_to_delete_table(port_profile,...
Calls method to delete Port Profile from UCS Manager. If exception is raised by UCSM, then the PP is added to a DB table. The delete timer thread, tried to delete all PPs added to this table when it wakes up.
338,154
def generate_sigproc_header(f): header_string = b header_string += to_sigproc_keyword(b) for keyword in f.header.keys(): if keyword == b: header_string += to_sigproc_keyword(b) + to_sigproc_angle(f.header[b]) elif keyword == b: header_string += to_sigproc_keyw...
Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header
338,155
def get_xml(html, content_tag=, fail_if_empty=False): cont = re.findall(r % {: content_tag}, html, re.MULTILINE | re.DOTALL) if cont: events_terms = .join([l.strip() for l in cont[0][1].splitlines()]) if in cont[0][0]: meta = .join([l.strip() for l in cont...
Extract the content XML from the HTML output of the TRIPS web service. Parameters ---------- html : str The HTML output from the TRIPS web service. content_tag : str The xml tag used to label the content. Default is 'ekb'. fail_if_empty : bool If True, and if the xml content...
338,156
def build(self, pre=None, shortest=False): if pre is None: pre = [] if self.value is not None and rand.maybe(): return utils.val(self.value, pre, shortest=shortest) if self.min == self.max: return self.min res = self._odds_val() if ...
Build the integer, optionally providing a ``pre`` list that *may* be used to define prerequisites for a Field being built. :param list pre: A list of prerequisites to be collected during the building of a Field. :param bool shortest: Whether or not the shortest reference-chain (most minimal) ve...
338,157
def __parse_link_info(self, link): href = link.get("href", "") txt = link.string or href is_rel = is_relative_url(href) if is_rel is True: tmp = "{0}{1}".format(self.mediawiki.base_url, href) elif is_rel is None: tmp = "{0}{1}".format(self.url, hr...
parse the <a> tag for the link
338,158
def check_satpy(readers=None, writers=None, extras=None): from satpy.readers import configs_for_reader from satpy.writers import configs_for_writer print() print() for reader, res in sorted(check_yaml_configs(configs_for_reader(reader=readers), ).items()): print(reader + , res) pri...
Check the satpy readers and writers for correct installation. Args: readers (list or None): Limit readers checked to those specified writers (list or None): Limit writers checked to those specified extras (list or None): Limit extras checked to those specified Returns: bool Tru...
338,159
def pack_int(v): if v == 0: return "\0" ret = while v > 0: c = v & 127 v >>= 7 if v != 0: c = c | 128 ret += chr(c) return ret
Returns <v> as packed string.
338,160
def indent(text, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block): text = text.rstrip() lines = text.split() if lines and lines[0].startswith(): lines[0] = lines[0].replace(, ) + output = [] ...
Returns HTML as a basestring. Parameters ---------- text : basestring Source code, typically SHPAML, but could be a different (but related) language. The remaining parameters specify details about the language used in the source code. To parse SHPAML, pass the same values...
338,161
def wrap(self, wrapping_key, key_to_wrap): if self.java_name not in ("AES", "AESWrap"): raise NotImplementedError(.format(self.java_name)) try: return keywrap.aes_key_wrap(wrapping_key=wrapping_key, key_to_wrap=key_to_wrap, backend=default_backend()) ex...
Wrap key using AES keywrap. :param bytes wrapping_key: Loaded key with which to wrap :param bytes key_to_wrap: Raw key to wrap :returns: Wrapped key :rtype: bytes
338,162
def _lucas_sequence(n, P, Q, k): D = P * P - 4 * Q if n < 2: raise ValueError("n must be >= 2") if k < 0: raise ValueError("k must be >= 0") if D == 0: raise ValueError("D must not be zero") if k == 0: return 0, 2 U = 1 V = P Qk = Q b = _bitlengt...
Return the modular Lucas sequence (U_k, V_k, Q_k). Given a Lucas sequence defined by P, Q, returns the kth values for U and V, along with Q^k, all modulo n.
338,163
def _calculate_order_value_amount(self, asset, value): normalized_date = normalize_date(self.datetime) if normalized_date < asset.start_date: raise CannotOrderDelistedAsset( msg="Cannot order {0}, as it started trading on" ...
Calculates how many shares/contracts to order based on the type of asset being ordered.
338,164
def set_cluster_threshold(self, value): if isinstance(value, int) is False: raise TypeError("The type of __cluster_threshold must be int.") self.__cluster_threshold = value
setter
338,165
def parse_restriction_dist(self, f): parsed_data = dict() firstline = True for l in f[]: if firstline: firstline = False continue s = l.split("\t") if len(s) > 1: nuc = float(s[0].strip()) ...
Parse HOMER tagdirectory petagRestrictionDistribution file.
338,166
def get(self, url=None, parse_data=True, key=None, parameters=None): return self._fetch("GET", url, post_data=None, parse_data=parse_data, key=key, parameters=parameters)
Issue a GET request. Kwargs: url (str): Destination URL parse_data (bool): If true, parse response data key (string): If parse_data==True, look for this key when parsing data parameters (dict): Additional GET parameters to append to the URL Returns: ...
338,167
def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False): "Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`." if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts)) return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts))
Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`.
338,168
def _slice_value(index, context=None): if isinstance(index, Const): if isinstance(index.value, (int, type(None))): return index.value elif index is None: return None else: try: inferred = next(index.infer(context=context)) excep...
Get the value of the given slice index.
338,169
def create(self, name, value): if value is None: raise ValueError() model = Setting.get_model_for_value(value) obj = super(SettingQuerySet, model.objects.all()) \ .create(name=name, value=value) return obj
Creates and returns an object of the appropriate type for ``value``.
338,170
async def set_utc(pyvlx): setutc = SetUTC(pyvlx=pyvlx) await setutc.do_api_call() if not setutc.success: raise PyVLXException("Unable to set utc.")
Enable house status monitor.
338,171
def apply_T9(word): WORD = word index = 0 offset = 0 for iu in iu_sequences(WORD): if iu.start(1) != index: i = iu.start(1) + 1 + offset WORD = WORD[:i] + + WORD[i:] index = iu.start(1) offset += 1 RULE = if word != WORD else ret...
Split /iu/ sequences that do not appear in the first, second, or final syllables.
338,172
def constants_from_enum(cls, module=None): if not issubclass(cls, enum.Enum): raise TypeError("Class is not subclass of enum.".format(cls.__name__)) if module is None: module = cls.__module__ for value in cls: constant(.format(module, str(value)), value) return cls
Decorator for an enum class that generates Gin constants from values. Generated constants have format `module.ClassName.ENUM_VALUE`. The module name is optional when using the constant. Args: cls: Class type. module: The module to associate with the constants, to help handle naming collisions. If ...
338,173
def categorical2transactions(x): assert len(x.shape) == 2 transactions = [] for entry in x: transactions.append([ % (i, val) for i, val in enumerate(entry)]) return transactions
Convert a 2D int array into a transaction list: [ ['x0=1', 'x1=0', ...], ... ] :param x: :return:
338,174
def drafts(self, blogname, **kwargs): url = "/v2/blog/{}/posts/draft".format(blogname) return self.send_api_request("get", url, kwargs, [])
Gets posts that are currently in the blog's drafts :param filter: the post format that you want returned: HTML, text, raw. :returns: a dict created from the JSON response
338,175
def _load_plugins(namespace, instantiate=True): mgr = ExtensionManager( namespace=namespace, on_load_failure_callback=( lambda _, ep, err: LOGGER. warning(.format(ep.name, err)) ) ) if instantiate: plugins = dict( ( ext...
Loads all the plugins for the given namespace Args: namespace(str): Namespace string, as in the setuptools entry_points instantiate(bool): If true, will instantiate the plugins too Returns: dict of str, object: Returns the list of loaded plugins
338,176
def create_exchange_for_vhost(self, exchange, vhost, body): self._api_put( .format( urllib.parse.quote_plus(vhost), urllib.parse.quote_plus(exchange)), data=body )
Create an individual exchange. The body should look like: :: { "type": "direct", "auto_delete": false, "durable": true, "internal": false, "arguments": {} } The type key is mandatory; other ...
338,177
def add_seqs_to_alignment(seqs_fp, aln_fp, moltype=DNA, params=None, accurate=False): if params is None: params = {: aln_fp} else: params[] = aln_fp return align_unaligned_seqs(seqs_fp, moltype, params, accurate)
Returns an Alignment object from seqs and existing Alignment. The "--seed" option can be used for adding unaligned sequences into a highly reliable alignment (seed) consisting of a small number of sequences. Parameters ---------- seqs_fp : string file path of the unaligned sequences ...
338,178
def readspec(filename, read_scan=None): with open(filename, ) as f: sf = {: [], : 0} sf[] = filename lastscannumber = None while True: l = f.readline() if l.startswith(): sf[] = l[2:].strip() elif l.startswith(): ...
Open a SPEC file and read its content Inputs: filename: string the file to open read_scan: None, 'all' or integer the index of scan to be read from the file. If None, no scan should be read. If 'all', all scans should be read. If a number, just the scan with th...
338,179
def _mb_normal_model(self, beta, mini_batch): rand_int = np.random.randint(low=0, high=self.data_length-mini_batch-self.max_lag+1) sample = np.arange(start=rand_int, stop=rand_int+mini_batch) data = self.y[sample] X = self.X[sample, :] Y = data[self.max_lag:] ...
Creates the structure of the model (model matrices, etc) for a mini-batch Normal family ARIMAX model. Here the structure is the same as for _normal_model() but we are going to sample a random choice of data points (of length mini_batch). Parameters ---------- beta : np....
338,180
def _qt_export_vtkjs(self, show=True): return FileDialog(self.app_window, filefilter=[], show=show, directory=os.getcwd(), callback=self.export_vtkjs)
Spawn an save file dialog to export a vtkjs file.
338,181
def build_recursive_delocalize_command(source, outputs, file_provider): command = _LOCALIZE_COMMAND_MAP[file_provider] filtered_outputs = [ var for var in outputs if var.recursive and var.file_provider == file_provider ] return .join([ textwrap.dedent().format( command=command, ...
Return a multi-line string with a shell script to copy recursively. Arguments: source: Folder with the data. For example /mnt/data outputs: a list of OutputFileParam. file_provider: file provider string used to filter the output params; the returned command will only apply ou...
338,182
def _validate_namespaces(namespaces): for source, namespace in namespaces.items(): target = namespace.dest_name _validate_namespace(source) _validate_namespace(target) if source.count("*") > 1 or target.count("*") > 1: raise errors.InvalidConfiguration( ...
Validate wildcards and renaming in namespaces. Target namespaces should have the same number of wildcards as the source. No target namespaces overlap exactly with each other. Logs a warning when wildcard namespaces have a chance of overlapping.
338,183
def show(self, use_pandas=False, rows=10, cols=200): if self._ex is None: print("This H2OFrame has been removed.") return if not self._has_content(): print("This H2OFrame is empty and not initialized.") return if self.nrows == 0: ...
Used by the H2OFrame.__repr__ method to print or display a snippet of the data frame. If called from IPython, displays an html'ized result. Else prints a tabulate'd result.
338,184
def index_to_housecode(index): if index < 0 or index > 255: raise ValueError quotient, remainder = divmod(index, 16) return chr(quotient+ord()) + .format(remainder+1)
Convert a zero-based index to a X10 housecode.
338,185
def touch_multi(self, keys, ttl=0): return _Base.touch_multi(self, keys, ttl=ttl)
Touch multiple keys. Multi variant of :meth:`touch` :param keys: the keys to touch :type keys: :ref:`iterable<argtypes>`. ``keys`` can also be a dictionary with values being integers, in which case the value for each key will be used as the TTL instead of the global ...
338,186
def delete_issue(self, issue_id, params=None): return self._delete(self.API_URL + .format(issue_id), params=params)
Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: Returns:
338,187
def extension(self, name, **kwargs): timer = Timer.create(start=True) name = self.roi.get_source_by_name(name).name schema = ConfigSchema(self.defaults[], optimizer=self.defaults[]) schema.add_option(, ) schema.add_option(, None, , str) ...
Test this source for spatial extension with the likelihood ratio method (TS_ext). This method will substitute an extended spatial model for the given source and perform a one-dimensional scan of the spatial extension parameter over the range specified with the width parameters. The 1-D...
338,188
def _scan( self, fs, dir_path, namespaces=None, ): try: for info in fs.scandir(dir_path, namespaces=namespaces): yield info except FSError as error: if not self.on_error(dir_path, error): ...
Get an iterator of `Info` objects for a directory path. Arguments: fs (FS): A filesystem instance. dir_path (str): A path to a directory on the filesystem. namespaces (list): A list of additional namespaces to include in the `Info` objects. Returns: ...
338,189
def non_dependency (self): result = [p for p in self.lazy_properties if not p.feature.dependency] result.extend(self.non_dependency_) return result
Returns properties that are not dependencies.
338,190
def two_qubit_matrix_to_ion_operations(q0: ops.Qid, q1: ops.Qid, mat: np.ndarray, atol: float = 1e-8 ) -> List[ops.Operation]: kak = linalg.kak_decompositi...
Decomposes a two-qubit operation into MS/single-qubit rotation gates. Args: q0: The first qubit being operated on. q1: The other qubit being operated on. mat: Defines the operation to apply to the pair of qubits. tolerance: A limit on the amount of error introduced by the ...
338,191
def _gather_exposed_methods(self): self._extract_methods_from_container(self) for module in self.modules: self._extract_methods_from_container(module)
Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`.
338,192
def _segment_normalized_cnvkit(cnr_file, work_dir, paired): cnvkit_base = os.path.join(utils.safe_makedir(os.path.join(work_dir, "cnvkit")), dd.get_sample_name(paired.tumor_data)) cnr_file = chromhacks.bed_to_standardonly(cnr_file, paired.tumor_data, headers="chromosome", ...
Segmentation of normalized inputs using CNVkit.
338,193
def find_binding(name, node, package=None): for child in node.children: ret = None if child.type == syms.for_stmt: if _find(name, child.children[1]): return child n = find_binding(name, make_suite(child.children[-1]), package) if n: ret = n ...
Returns the node which binds variable name, otherwise None. If optional argument package is supplied, only imports will be returned. See test cases for examples.
338,194
def _create_cluster_connection(self, node): LOGGER.debug(, node.ip, node.port) conn = _Connection( node.ip, node.port, 0, self._read, self._on_closed, self.io_loop, cluster_node=True, ...
Create a connection to a Redis server. :param node: The node to connect to :type node: tredis.cluster.ClusterNode
338,195
def _parse_edge(graph, node, text, yes_color=, no_color=): try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label=, color=yes_color) graph.edge(node, no, lab...
parse dumped edge
338,196
def geos2cf(area): proj_dict = area.proj_dict args = dict(perspective_point_height=proj_dict.get(), latitude_of_projection_origin=proj_dict.get(), longitude_of_projection_origin=proj_dict.get(), grid_mapping_name=, semi_major_axis=proj_dict.ge...
Return the cf grid mapping for the geos projection.
338,197
def _error_traceback_html(exc_info, traceback_): html = return html.format(error=exc_info[1], traceback=traceback_)
Generates error traceback HTML. :param tuple exc_info: Output of :func:`sys.exc_info` function. :param traceback: Output of :func:`traceback.format_exc` function.
338,198
def interior_nesting(cls, elem1, xpath, namespaces=None): for elem2 in elem1.xpath(xpath, namespaces=namespaces): child_elem1 = etree.Element(elem1.tag) for k in elem1.attrib: child_elem1.set(k, elem1.get(k)) child_elem1.text, elem2.text = elem2...
for elem1 containing elements at xpath, embed elem1 inside each of those elements, and then remove the original elem1
338,199
def SendKeys(self, keys: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME) -> None: self.SetFocus() SendKeys(keys, interval, waitTime)
Make control have focus first and type keys. `self.SetFocus` may not work for some controls, you may need to click it to make it have focus. keys: str, keys to type, see the docstring of `SendKeys`. interval: float, seconds between keys.