Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
364,300
def remove_user(self, name): try: cmd = SON([("dropUser", name)]) coll.delete_one({"user": name}) return raise
Remove user `name` from this :class:`Database`. User `name` will no longer have permissions to access this :class:`Database`. :Parameters: - `name`: the name of the user to remove
364,301
def is_inexact(arg): return (is_inexact(mag(arg)) if is_quantity(arg) else is_npscalar(u, np.inexact) or is_npvalue(arg, np.inexact))
is_inexact(x) yields True if x is a number represented by floating-point data (i.e., either a non-integer real number or a complex number) and False otherwise.
364,302
def set_defaults(self, default_values, recursive = False): result = Parameters() if recursive: RecursiveObjectWriter.copy_properties(result, default_values) RecursiveObjectWriter.copy_properties(result, self) else: ObjectWriter.set_properties(result,...
Set default values from specified Parameters and returns a new Parameters object. :param default_values: Parameters with default parameter values. :param recursive: (optional) true to perform deep copy, and false for shallow copy. Default: false :return: a new Parameters object.
364,303
def get_stdev(self, asset_type): load_times = [] if asset_type == : for page in self.pages: if page.time_to_first_byte is not None: load_times.append(page.time_to_first_byte) elif asset_type not in self.asset_types and asset_type ...
Returns the standard deviation for a set of a certain asset type. :param asset_type: ``str`` of the asset type to calculate standard deviation for. :returns: A ``int`` or ``float`` of standard deviation, depending on the self.decimal_precision
364,304
def selfconsistency(self, u_int, J_coup, mean_field_prev=None): if mean_field_prev is None: mean_field_prev = np.array([self.param[]]*2) hlog = [mean_field_prev] self.oper[] = self.inter_spin_hamiltonian(u_int, J_coup) converging = True half_fill = (self.par...
Iterates over the hamiltonian to get the stable selfcosistent one
364,305
def column_rename(self, existing_name, hsh=None): try: existing_name = str(existing_name) except UnicodeEncodeError: pass if hsh is None: hsh = self._hash() if self._name: return %(self._name, self._remove_hashes(existing_name), ...
Like unique_name, but in addition must be unique to each column of this feature. accomplishes this by prepending readable string to existing column name and replacing unique hash at end of column name.
364,306
def _subthread_handle_accepted(self, client): conn, addr = client if self.handle_incoming(conn, addr): logging.info(.format(addr)) conn.setblocking(False) self.clients[conn] = addr self.register(conn) else: logging.info(.forma...
Gets accepted clients from the queue object and sets up the client socket. The client can then be found in the clients dictionary with the socket object as the key.
364,307
def cublasStrmm(handle, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb, C, ldc): status = _libcublas.cublasStrmm_v2(handle, _CUBLAS_SIDE_MODE[side], _CUBLAS_FILL_MODE[uplo], _CUBLAS...
Matrix-matrix product for real triangular matrix.
364,308
def unlink_chunk(self, x, z): if self.size < 2*SECTOR_LENGTH: return self.file.seek(4 * (x + 32*z)) self.file.write(pack(">IB", 0, 0)[1:]) self.file.seek(SECTOR_LENGTH + 4 * (x + 32*z)) self.file.write(pack(">I", 0)) curre...
Remove a chunk from the header of the region file. Fragmentation is not a problem, chunks are written to free sectors when possible.
364,309
def lpc(x, N=None): m = len(x) if N is None: N = m - 1 elif N > m-1: x.resize(N+1) X = fft(x, 2**nextpow2(2.*len(x)-1)) R = real(ifft(abs(X)**2)) R = R/(m-1.) a, e, ref = LEVINSON(R, N) return a, e
Linear Predictor Coefficients. :param x: :param int N: default is length(X) - 1 :Details: Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order forward linear predictor that predicts the current value value of the real-valued time series x based on past samples: .. ma...
364,310
def head(self, url): bot.debug( %url) return self._call(url, func=requests.head)
head request, typically used for status code retrieval, etc.
364,311
def get_transition (self, input_symbol, state): if (input_symbol, state) in self.state_transitions: return self.state_transitions[(input_symbol, state)] elif state in self.state_transitions_any: return self.state_transitions_any[state] elif self.default_transit...
This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from ...
364,312
def solidangle_errorprop(twotheta, dtwotheta, sampletodetectordistance, dsampletodetectordistance, pixelsize=None): SAC = solidangle(twotheta, sampletodetectordistance, pixelsize) if pixelsize is None: pixelsize = 1 return (SAC, (sampletodetectordistance * (4 * dsampletodetectordist...
Solid-angle correction for two-dimensional SAS images with error propagation Inputs: twotheta: matrix of two-theta values dtwotheta: matrix of absolute error of two-theta values sampletodetectordistance: sample-to-detector distance dsampletodetectordistance: absolute error of sample...
364,313
def data(self): res = {: self.error_list} res.update(super(ValidationErrors, self).data) return res
Returns a dictionnary containing all the passed data and an item ``error_list`` which holds the result of :attr:`error_list`.
364,314
def areObservableElements(self, elementNames): if not(hasattr(elementNames, "__len__")): raise TypeError( "Element name should be a array of strings." + "I receive this {0}" .format(elementNames)) return self._evaluateArray(elementNam...
Mention if all elements are observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool
364,315
def update(self, personId, emails=None, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): check_type(emails, list) check_type(displayName, basestring) check_type(firstName, basestring...
Update details for a person, by ID. Only an admin can update a person's details. Email addresses for a person cannot be changed via the Webex Teams API. Include all details for the person. This action expects all user details to be present in the request. A common approach is to first...
364,316
def accel_decrease_height(self, *args): height = self.settings.general.get_int() self.settings.general.set_int(, max(height - 2, 0)) return True
Callback to decrease height.
364,317
def get_cfn_parameters(self): variables = self.get_variables() output = {} for key, value in variables.items(): if hasattr(value, "to_parameter_value"): output[key] = value.to_parameter_value() return output
Return a dictionary of variables with `type` :class:`CFNType`. Returns: dict: variables that need to be submitted as CloudFormation Parameters.
364,318
def FileHeader(self): dt = self.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) if self.flag_bits & 0x08: CRC = compress_size = file_size = 0 else: CRC = self.CRC ...
Return the per-file header as a string.
364,319
def irelay(gen, thru): gen = iter(gen) assert _is_just_started(gen) yielder = yield_from(gen) for item in yielder: with yielder: subgen = thru(item) subyielder = yield_from(subgen) for subitem in subyielder: with subyielder: ...
Create a new generator by relaying yield/send interactions through another generator Parameters ---------- gen: Generable[T_yield, T_send, T_return] the original generator thru: ~typing.Callable[[T_yield], ~typing.Generator] the generator callable through which each interaction is r...
364,320
def parse_args(args=None): import argparse from ttfautohint import __version__, libttfautohint from ttfautohint.cli import USAGE, DESCRIPTION, EPILOG version_string = "ttfautohint-py %s (libttfautohint %s)" % ( __version__, libttfautohint.version_string) if args is None: captu...
Parse command line arguments and return a dictionary of options for ttfautohint.ttfautohint function. `args` can be either None, a list of strings, or a single string, that is split into individual options with `shlex.split`. When `args` is None, the console's default sys.argv are used, and any Sy...
364,321
def read_mutating_webhook_configuration(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.read_mutating_webhook_configuration_with_http_info(name, **kwargs) else: (data) = self.read_mutating_webhook_configuration_with_http_info(name, **kwarg...
read_mutating_webhook_configuration # noqa: E501 read the specified MutatingWebhookConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_mutating_webhook_configuration(...
364,322
def db_create_table(self, table_name, columns): formatted_columns = for col in set(columns): formatted_columns += .format(col.strip().strip(, CREATE TABLE IF NOT EXISTS {} ({});'.format( table_name, formatted_columns ) try: cr = self.db_conn....
Create a temporary DB table. Arguments: table_name (str): The name of the table. columns (list): List of columns to add to the DB.
364,323
def sync_to_db_from_config( cls, druid_config, user, cluster, refresh=True): session = db.session datasource = ( session.query(cls) .filter_by(datasource_name=druid_config[]) .first() ) ...
Merges the ds config from druid_config into one stored in the db.
364,324
def _calculate(self, field): encloser = field.enclosing if encloser: rendered = encloser.get_rendered_fields(RenderContext(self)) if field not in rendered: value = len(rendered) else: value = rendered.index(field) else:...
We want to avoid trouble, so if the field is not enclosed by any other field, we just return 0.
364,325
def _ExtractGoogleSearchQuery(self, url): if not in url or not in url: return None line = self._GetBetweenQEqualsAndAmpersand(url) if not line: return None return line.replace(, )
Extracts a search query from a Google URL. Google Drive: https://drive.google.com/drive/search?q=query Google Search: https://www.google.com/search?q=query Google Sites: https://sites.google.com/site/.*/system/app/pages/ search?q=query Args: url (str): URL. Returns: ...
364,326
def _generate_journal_nested_queries(self, value): third_journal_field = ElasticSearchVisitor.JOURNAL_PAGE_START new_publication_info = ElasticSearchVisitor._preprocess_journal_query_value(third_journal_field, value) queries_for_each_field = [ ge...
Generates ElasticSearch nested query(s). Args: value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma. This value should be of type string. Notes: The value contains at least one of the 3 mentioned ite...
364,327
def hpcluster(self, data: [, str] = None, freq: str = None, id: [str, list] = None, input: [str, list, dict] = None, score: [str, bool, ] = True, procopts: str = None, stmtpassthrough: str = None, ...
Python method to call the HPCLUS procedure Documentation link: https://go.documentation.sas.com/?docsetId=emhpprcref&docsetTarget=emhpprcref_hpclus_toc.htm&docsetVersion=14.2&locale=en :param data: SASdata object or string. This parameter is required. :parm freq: The freq variable can ...
364,328
def _inner(self, x1, x2): return self.tspace._inner(x1.tensor, x2.tensor)
Raw inner product of two elements.
364,329
def get_encrypted_reply(self, message): reply = self.get_reply(message) if not reply: self.logger.warning("No handler responded message %s" % message) return if self.use_encryption: return self.crypto.encrypt_message(reply) else: ...
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。 如果可能,对该 Reply 进行加密。 返回 Reply Render 后的文本。 :param message: 一个 WeRoBot Message 实例。 :return: reply (纯文本)
364,330
def _expand_list(names): if names is None: names = [] elif isinstance(names, basestring): names = [names] results = [] items = {} for name in names: bucket, key = datalab.storage._bucket.parse_name(name) results_len = len(results) if bucket: if not key: re...
Do a wildchar name expansion of object names in a list and return expanded list. The items are expected to exist as this is used for copy sources or delete targets. Currently we support wildchars in the key name only.
364,331
def reverse_readfile(filename): try: with zopen(filename, "rb") as f: if isinstance(f, gzip.GzipFile) or isinstance(f, bz2.BZ2File): for l in reversed(f.readlines()): yield l.decode("utf-8").rstrip() else: fm = mmap.mmap(f.file...
A much faster reverse read of file by using Python's mmap to generate a memory-mapped file. It is slower for very small files than reverse_readline, but at least 2x faster for large files (the primary use of such a method). Args: filename (str): Name of file to read. Yields: ...
364,332
def strduration_long (duration, do_translate=True): if do_translate: global _, _n else: _ = lambda x: x _n = lambda a, b, n: a if n==1 else b if duration < 0: duration = abs(duration) prefix = "-" else: prefix = "" if duration < ...
Turn a time value in seconds into x hours, x minutes, etc.
364,333
def preview(self, components=None, ask=0): ask = int(ask) self.init() component_order, plan_funcs = self.get_component_funcs(components=components) print( % (len(component_order), self.genv.host_string)) if component_order and plan_funcs: if self.verbose:...
Inspects differences between the last deployment and the current code state.
364,334
def SetScrollPercent(self, horizontalPercent: float, verticalPercent: float, waitTime: float = OPERATION_WAIT_TIME) -> bool: ret = self.pattern.SetScrollPercent(horizontalPercent, verticalPercent) == S_OK time.sleep(waitTime) return ret
Call IUIAutomationScrollPattern::SetScrollPercent. Set the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation element. horizontalPercent: float or int, a value in [0, 100] or ScrollPattern.NoScrollValue(-1) if no scroll. verticalPercent: f...
364,335
def _keep_this(self, name): for keep_name in self.keep: if name == keep_name: return True return False
Return True if there are to be no modifications to name.
364,336
def lt(self, key, value, includeMissing=False): s value is less (<). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "...
Return entries where the key's value is less (<). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, ...
364,337
def head_object_async(self, path, **kwds): return self.do_request_async(self.api_url + path, , **kwds)
HEAD an object. Depending on request headers, HEAD returns various object properties, e.g. Content-Length, Last-Modified, and ETag. Note: No payload argument is supported.
364,338
def get(app, name): backend = get_all(app).get(name) if not backend: msg = .format(name) raise EntrypointError(msg) return backend
Get a backend given its name
364,339
def _sync_enter(self): if hasattr(self, ): loop = self.loop else: loop = self._client.loop if loop.is_running(): raise RuntimeError( ) return loop.run_until_complete(self.__aenter__())
Helps to cut boilerplate on async context managers that offer synchronous variants.
364,340
def iterscrapers(self, method, mode = None): global discovered if discovered.has_key(self.language) and discovered[self.language].has_key(method): for Scraper in discovered[self.language][method]: yield Scraper
Iterates over all available scrapers.
364,341
def dftphotom(cfg): tb = util.tools.table() ms = util.tools.ms() me = util.tools.measures() die(, fields.size) if rephase: fieldid = fields[0] tb.open(b(os.path.join(cfg.vis, ))) phdirinfo = tb.getcell(b, fieldid) tb.close() if phdiri...
Run the discrete-Fourier-transform photometry algorithm. See the module-level documentation and the output of ``casatask dftphotom --help`` for help. All of the algorithm configuration is specified in the *cfg* argument, which is an instance of :class:`Config`.
364,342
def file_resolve(backend, filepath): recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException() click.secho("%s - Resolving conflicts" % get_datetime()) for file_to_resolve in filepath: if not os.path.exists(file_to_resolve): raise click.C...
Mark a conflicted file as resolved, so that a merge can be completed
364,343
def wrap_text(text, width): out = [] for paragraph in text.splitlines(): lines = wrap(paragraph, width=width) or [] out.extend(lines) return out
Wrap text paragraphs to the given character width while preserving newlines.
364,344
def add_argument(self, *args, parser=None, autoenv=False, env=None, complete=None, **kwargs): if parser is None: parser = self.argparser action = parser.add_argument(*args, **kwargs) if autoenv: if env is not None: raise TypeE...
Allow cleaner action supplementation. Autoenv will generate an environment variable to be usable as a defaults setter based on the command name and the dest property of the action.
364,345
def application_information(self, application_id): path = .format( appid=application_id) return self.request(path)
The MapReduce application master information resource provides overall information about that mapreduce application master. This includes application id, time it was started, user, name, etc. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
364,346
def svd_thresh(data, threshold=None, n_pc=None, thresh_type=): r if ((not isinstance(n_pc, (int, str, type(None)))) or (isinstance(n_pc, int) and n_pc <= 0) or (isinstance(n_pc, str) and n_pc != )): raise ValueError( ) u, s, v = calculate_svd(d...
r"""Threshold the singular values This method thresholds the input data using singular value decomposition Parameters ---------- data : np.ndarray Input data array, 2D matrix threshold : float or np.ndarray, optional Threshold value(s) n_pc : int or str, optional Number...
364,347
def _set_switch_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {}, u: {}, u: {}, u: ...
Setter method for switch_state, mapped from YANG variable /brocade_system_monitor_ext_rpc/show_system_monitor/output/switch_status/switch_state (system-monitor-health-state-enum) If this variable is read-only (config: false) in the source YANG file, then _set_switch_state is considered as a private method. ...
364,348
def _schedule_pending_unlocked(self, state): while state.jobs and state.unacked < self.window_size_bytes: sender, fp = state.jobs[0] s = fp.read(self.IO_SIZE) if s: state.unacked += len(s) sender.send(mitogen.core.Blob(s)) ...
Consider the pending transfers for a stream, pumping new chunks while the unacknowledged byte count is below :attr:`window_size_bytes`. Must be called with the FileStreamState lock held. :param FileStreamState state: Stream to schedule chunks for.
364,349
def diet(file, configuration, check): config = process.read_yaml_configuration(configuration) process.diet(file, config)
Simple program that either print config customisations for your environment or compresses file FILE.
364,350
def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False): method = cv2.TM_CCOEFF_NORMED if rgb: s_bgr = cv2.split(im_search) i_bgr = cv2.split(im_source) weight = (0.3, 0.3, 0.4) resbgr = [0, 0, 0] for i in range(3):...
Locate image position with cv2.templateFind Use pixel match to find pictures. Args: im_source(string): 图像、素材 im_search(string): 需要查找的图片 threshold: 阈值,当相识度小于该阈值的时候,就忽略掉 Returns: A tuple of found [(point, score), ...] Raises: IOError: when file read error
364,351
def get_internal_header(request: HttpRequest) -> str: return get_header(request=request, header_service=conf.get())
Return request's 'X_POLYAXON_INTERNAL:' header, as a bytestring.
364,352
def set_empty_symbol(self): self.field_name = None self.annotations = None self.ion_type = None self.set_pending_symbol(CodePointArray()) return self
Resets the context, retaining the fields that make it a child of its container (``container``, ``queue``, ``depth``, ``whence``), and sets an empty ``pending_symbol``. This is useful when an empty quoted symbol immediately follows a long string.
364,353
def run(graph, save_on_github=False, main_entity=None): try: ontology = graph.all_ontologies[0] uri = ontology.uri except: ontology = None uri = ";".join([s for s in graph.sources]) ontotemplate = open(ONTODOCS_VIZ_TEMPLATES + "sigmajs.html", "r") t = Templat...
2016-11-30
364,354
def user_getfield(self, field, access_token=None): info = self.user_getinfo([field], access_token) return info.get(field)
Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0
364,355
def threader(group=None, name=None, daemon=True): def decorator(job): def wrapped_job(queue, *args, **kwargs): ret = job(*args, **kwargs) queue.put(ret) def wrap(*args, **kwargs): thread = Thread(group=group, target=wrapped...
decorator to thread functions :param group: reserved for future extension when a ThreadGroup class is implemented :param name: thread name :param daemon: thread behavior :rtype: decorator
364,356
def get(self, *keys, fallback=None): section, *keys = keys out = super().get(section, fallback) while isinstance(out, dict): key = keys.pop(0) out = out.get(key, fallback) return out
Retrieve a value in the config, if the value is not available give the fallback value specified.
364,357
def g_square_bin(dm, x, y, s): def _calculate_tlog(x, y, s, dof, dm): nijk = np.zeros((2, 2, dof)) s_size = len(s) z = [] for z_index in range(s_size): z.append(s.pop()) pass for row_index in range(0, dm.shape[0]): i = dm[row_index, x...
G square test for a binary data. Args: dm: the data matrix to be used (as a numpy.ndarray). x: the first node (as an integer). y: the second node (as an integer). s: the set of neibouring nodes of x and y (as a set()). Returns: p_val: the p-value of conditional independ...
364,358
def to_numpy(self, dtype=None, copy=False): return self._default_to_pandas("to_numpy", dtype=dtype, copy=copy)
Convert the DataFrame to a NumPy array. Args: dtype: The dtype to pass to numpy.asarray() copy: Whether to ensure that the returned value is a not a view on another array. Returns: A numpy array.
364,359
def _init_record(self, record_type_idstr): record_type_data = self._record_type_data_sets[Id(record_type_idstr).get_identifier()] module = importlib.import_module(record_type_data[]) record = getattr(module, record_type_data[]) if record is not None: self._records[re...
Override this from osid.Extensible because Forms use a different attribute in record_type_data.
364,360
def put(self, destination): target = get_target_path(destination, self.localpath) shutil.copytree(self.localpath, target)
Copy the referenced directory to this path The semantics of this command are similar to unix ``cp``: if ``destination`` already exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If it does not already exist, the directory will be renamed to this path (the ...
364,361
def __learn_oneself(self): if not self.__parent_path or not self.__text_nodes: raise Exception("This error occurred because the step constructor\ had insufficient textnodes or it had empty string\ for its parent xpath") ...
calculate cardinality, total and average string length
364,362
def __pop_frames_above(self, frame): while self.__stack[-1] is not frame: self.__pop_top_frame() assert self.__stack
Pops all the frames above, but not including the given frame.
364,363
def netconf_state_datastores_datastore_locks_lock_type_global_lock_global_lock_locked_time(self, **kwargs): config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") datastores = ET.SubElement(netcon...
Auto Generated Code
364,364
def library_line(self, file_name): gulplib_set = lambda: in os.environ.keys() readable = lambda f: os.path.isfile(f) and os.access(f, os.R_OK) ...
Specifies GULP library file to read species and potential parameters. If using library don't specify species and potential in the input file and vice versa. Make sure the elements of structure are in the library file. Args: file_name: Name of GULP library file Retur...
364,365
def sortTitles(self, by): titles = sorted(iter(self)) if by == : return sorted( titles, reverse=True, key=lambda title: self[title].subjectLength) if by == : return sorted( titles, reverse=True, k...
Sort titles by a given attribute and then by title. @param by: A C{str}, one of 'length', 'maxScore', 'medianScore', 'readCount', or 'title'. @raise ValueError: If an unknown C{by} value is given. @return: A sorted C{list} of titles.
364,366
def GetValueByPath(self, path_segments): key = self.root_key for path_segment in path_segments: if isinstance(key, dict): try: key = key[path_segment] except KeyError: return None elif isinstance(key, list): try: list_index = int(path_segme...
Retrieves a plist value by path. Args: path_segments (list[str]): path segment strings relative to the root of the plist. Returns: object: The value of the key specified by the path or None.
364,367
def shift(self, periods: int, axis: libinternals.BlockPlacement = 0, fill_value: Any = None) -> List[]: return [ self.make_block_same_class( self.values.shift(periods=periods, fill_value=fill_value), placement=self.mg...
Shift the block by `periods`. Dispatches to underlying ExtensionArray and re-boxes in an ExtensionBlock.
364,368
def get_config(): cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440-post" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "canmatrix/_version.py" cfg.verbose = False return cfg
Create, populate and return the VersioneerConfig() object.
364,369
def get_Note(self, string=0, fret=0, maxfret=24): if 0 <= string < self.count_strings(): if 0 <= fret <= maxfret: s = self.tuning[string] if type(s) == list: s = s[0] n = Note(int(s) + fret) n.string = strin...
Return the Note on 'string', 'fret'. Throw a RangeError if either the fret or string is unplayable. Examples: >>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4']) >>> t,get_Note(0, 0) 'A-3' >>> t.get_Note(0, 1) 'A#-3' >>> t.get_Note(1, 0) ...
364,370
def filter_pyfqn(cls, value, relative_to=0): def collect_packages(element, packages): parent = element.eContainer() if parent: collect_packages(parent, packages) packages.append(element.name) packages = [] collect_packages(value, pac...
Returns Python form of fully qualified name. Args: relative_to: If greater 0, the returned path is relative to the first n directories.
364,371
def _interval(dates): interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval
Return the distance between all dates and 0 if they are different
364,372
def get_complete_ph_dos(partial_dos_path, phonopy_yaml_path): a = np.loadtxt(partial_dos_path).transpose() d = loadfn(phonopy_yaml_path) structure = get_structure_from_dict(d[]) total_dos = PhononDos(a[0], a[1:].sum(axis=0)) pdoss = {} for site, pdos in zip(structure, a[1:]): pdo...
Creates a pymatgen CompletePhononDos from a partial_dos.dat and phonopy.yaml files. The second is produced when generating a Dos and is needed to extract the structure. Args: partial_dos_path: path to the partial_dos.dat file. phonopy_yaml_path: path to the phonopy.yaml file.
364,373
def boolean(flag): s = flag.lower() if s in (, , ): return True elif s in (, , ): return False raise ValueError( % s)
Convert string in boolean
364,374
def CreateUser(self, database_link, user, options=None): if options is None: options = {} database_id, path = self._GetDatabaseIdWithPathForUser(database_link, user) return self.Create(user, path, , ...
Creates a user. :param str database_link: The link to the database. :param dict user: The Azure Cosmos user to create. :param dict options: The request options for the request. :return: The created User. :rtype: dict
364,375
def __updateStack(self, key): if key == Key.ENTER: key = if key == Key.TAB: key = if key == Key.BACKSPACE: if ConfigManager.SETTINGS[UNDO_USING_BACKSPACE] and self.phraseRunner...
Update the input stack in non-hotkey mode, and determine if anything further is needed. @return: True if further action is needed
364,376
def _parse_message(self, data): try: _, values = data.split() values = values.split() if len(values) <= 3: self.event_data, self.partition, self.event_type = values self.version = 1 else: ...
Parses the raw message from the device. :param data: message data to parse :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
364,377
def get_subset(self, subset_ids): num_existing_keys = sum([1 for key in subset_ids if key in self.__data]) if subset_ids is not None and num_existing_keys > 0: data = self.__get_subset_from_dict(self.__data, subset_ids) ...
Returns a smaller dataset identified by their keys/sample IDs. Parameters ---------- subset_ids : list List od sample IDs to extracted from the dataset. Returns ------- sub-dataset : MLDataset sub-dataset containing only requested sample IDs.
364,378
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): if kern1.on_separate_dims(kern2) and isinstance(p, DiagonalGaussian): eKxz1 = expectation(p, (kern1, feat1)) eKxz2 = expectation(p, (kern2, feat2)) return eKxz1[:, :, None] * eKxz2[:, None, :] Ka, Kb = kern1, ker...
Compute the expectation: expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n) - Ka_{.,.}, Kb_{.,.} :: RBF kernels Ka and Kb as well as Z1 and Z2 can differ from each other. :return: N x dim(Z1) x dim(Z2)
364,379
def stopPoll(self, msg_identifier, reply_markup=None): p = _strip(locals(), more=[]) p.update(_dismantle_message_identifier(msg_identifier)) return self._api_request(, _rectify(p))
See: https://core.telegram.org/bots/api#stoppoll :param msg_identifier: a 2-tuple (``chat_id``, ``message_id``), a 1-tuple (``inline_message_id``), or simply ``inline_message_id``. You may extract this value easily with :meth:`amanobot.message_identifier`
364,380
def _retry_task(provider, job_descriptor, task_id, task_attempt): td_orig = job_descriptor.find_task_descriptor(task_id) new_task_descriptors = [ job_model.TaskDescriptor({ : task_id, : task_attempt }, td_orig.task_params, td_orig.task_resources) ] _resolve_task_resources...
Retry task_id (numeric id) assigning it task_attempt.
364,381
def propose_template(self, template_id, from_account): tx_hash = self.send_transaction( , (template_id,), transact={: from_account.address, : from_account.password}) return self.get_tx_receipt(tx_hash).status == 1
Propose a template. :param template_id: id of the template, str :param from_account: Account :return: bool
364,382
def list_repos(**kwargs): ** _check_apt() repos = {} sources = sourceslist.SourcesList() for source in sources.list: if _skip_source(source): continue repo = {} repo[] = source.file repo[] = getattr(source, , []) repo[] = source.disabled re...
Lists all repos in the sources.list (and sources.lists.d) files CLI Example: .. code-block:: bash salt '*' pkg.list_repos salt '*' pkg.list_repos disabled=True
364,383
def write_resume_point(self): try: resume_pts = self.attrs["resume_points"].tolist() except KeyError: resume_pts = [] try: niterations = self.niterations except KeyError: niterations = 0 resume_pts.append(niterations) ...
Keeps a list of the number of iterations that were in a file when a run was resumed from a checkpoint.
364,384
def get_ip_address(domain): if "://" not in domain: domain = "http://" + domain hostname = urlparse(domain).netloc if not hostname: raise ValueError("Can't parse hostname!") return socket.gethostbyname(hostname)
Get IP address for given `domain`. Try to do smart parsing. Args: domain (str): Domain or URL. Returns: str: IP address. Raises: ValueError: If can't parse the domain.
364,385
def list_(): * ret = {} for line in (__salt__[] ([, , ], python_shell=False).splitlines()): if not in line: continue comps = line.split() device = comps[1] ret[device] = {"device": device} for comp in comps[2:]: ...
List the RAID devices. CLI Example: .. code-block:: bash salt '*' raid.list
364,386
def run(self, circuit): name = circuit.name dag = circuit_to_dag(circuit) del circuit for passset in self.working_list: for pass_ in passset: dag = self._do_pass(pass_, dag, passset.options) circuit = dag_to_circuit(dag) circuit.name =...
Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit.
364,387
def __query_options(self): options = 0 if self.__tailable: options |= _QUERY_OPTIONS["tailable_cursor"] if self.__slave_okay or self.__pool._slave_okay: options |= _QUERY_OPTIONS["slave_okay"] if not self.__timeout: options |= _QUERY_OPTIONS["...
Get the query options string to use for this query.
364,388
def _check_method(self, method): estimator = self._postfit_estimator if not hasattr(estimator, method): msg = "The wrapped estimator does not have a method.".format( estimator, method ) raise AttributeError(msg) return getattr(estima...
Check if self.estimator has 'method'. Raises ------ AttributeError
364,389
def save(self, data=None, shape=None, dtype=None, returnoffset=False, photometric=None, planarconfig=None, extrasamples=None, tile=None, contiguous=True, align=16, truncate=False, compress=0, rowsperstrip=None, predictor=False, colormap=None, description=None, datetim...
Write numpy array and tags to TIFF file. The data shape's last dimensions are assumed to be image depth, height (length), width, and samples. If a colormap is provided, the data's dtype must be uint8 or uint16 and the data values are indices into the last dimension of the colorm...
364,390
def simple_spend_p2sh(all_from_pubkeys, from_privkeys_to_use, to_address, to_satoshis, change_address=None, min_confirmations=0, api_key=None, coin_symbol=): assert is_valid_coin_symbol(coin_symbol), coin_symbol assert isinstance(to_satoshis, int), to_satoshis assert api_key, if change_a...
Simple method to spend from a p2sh address. all_from_pubkeys is a list of *all* pubkeys for the address in question. from_privkeys_to_use is a list of all privkeys that will be used to sign the tx (and no more). If the address is a 2-of-3 multisig and you supply 1 (or 3) from_privkeys_to_use this will bre...
364,391
def get_phi_comps_from_recfile(recfile): iiter = 1 iters = {} f = open(recfile,) while True: line = f.readline() if line == : break if "starting phi for this iteration" in line.lower() or \ "final phi" in line.lower(): contributions = {} ...
read the phi components from a record file by iteration Parameters ---------- recfile : str pest record file name Returns ------- iters : dict nested dictionary of iteration number, {group,contribution}
364,392
def _init_sub_groups(self, parent): if self._sub_groups: for sub_group in self._sub_groups: for component in split_path_components(sub_group): fp = os.path.join(parent.full_path, component) if os.path.exists(fp): ...
Initialise sub-groups, and create any that do not already exist.
364,393
def orbit(self, x1_px, y1_px, x2_px, y2_px): px_per_deg = self.vport_radius_px / float(self.orbit_speed) radians_per_px = 1.0 / px_per_deg * np.pi / 180.0 t2p = self.position - self.target M = Matrix4x4.rotation_around_origin((x1_px - x2_px) * radians_per_px, ...
Causes the camera to "orbit" around the target point. This is also called "tumbling" in some software packages.
364,394
def count_residues(self, record, pdb_record): mutations = self.get_record_mutations(record) pdb_chains = set([m[] for m in mutations]) assert(len(pdb_chains) == 1) pdb_chain = pdb_chains.pop() return len(pdb_record.get(, {}).get(pdb_chain, {}).get(, ))
Count the number of residues in the chains for the case.
364,395
def temp_water(self): th_swir2 = 0.03 water = self.water_test() clear_sky_water = water & (self.swir2 < th_swir2) clear_water_temp = self.tirs1.copy() clear_water_temp[~clear_sky_water] = np.nan clear_water_temp[~self.mask] = np.nan pct...
Use water to mask tirs and find 82.5 pctile Equation 7 and 8 (Zhu and Woodcock, 2012) Parameters ---------- is_water: ndarray, boolean water mask, water is True, land is False swir2: ndarray tirs1: ndarray Output ------ float: ...
364,396
def _keynat(string): r = [] for c in string: if c.isdigit(): if r and isinstance(r[-1], int): r[-1] = r[-1] * 10 + int(c) else: r.append(int(c)) else: r.append(9 + ord(c)) return r
A natural sort helper function for sort() and sorted() without using regular expression.
364,397
def delete(self, ids): url = build_uri_with_ids(, ids) return super(ApiIPv4, self).delete(url)
Method to delete ipv4's by their ids :param ids: Identifiers of ipv4's :return: None
364,398
def cli(yamlfile, directory, out, classname, format): DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
Generate graphviz representations of the biolink model
364,399
def MotionBlur(k=5, angle=(0, 360), direction=(-1.0, 1.0), order=1, name=None, deterministic=False, random_state=None): k_param = iap.handle_discrete_param(k, "k", value_range=(3, None), tuple_to_uniform=True, list_to_choice=True, allow_floats=False) angle_param...
Augmenter that sharpens images and overlays the result with the original image. dtype support:: See ``imgaug.augmenters.convolutional.Convolve``. Parameters ---------- k : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional Kernel size to use. ...