Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
367,500
def multisplit(s, seps=list(string.punctuation) + list(string.whitespace), blank=True): r seps = str().join(seps) return [s2 for s2 in s.translate(str().join([(chr(i) if chr(i) not in seps else seps[0]) for i in range(256)])).split(seps[0]) if (blank or s2)]
r"""Just like str.split(), except that a variety (list) of seperators is allowed. >>> multisplit(r'1-2?3,;.4+-', string.punctuation) ['1', '2', '3', '', '', '4', '', ''] >>> multisplit(r'1-2?3,;.4+-', string.punctuation, blank=False) ['1', '2', '3', '4'] >>> multisplit(r'1C 234567890', '\x00\x01\x0...
367,501
def handle_change(self, change): op = change[] if op in : self.add(len(change[]), LatLng(*change[])) elif op == : self.add(change[], LatLng(*change[])) elif op == : points = [LatLng(*p) for p in change[]] self.addAll([bridge.encode...
Handle changes from atom ContainerLists
367,502
def verify_space_available(self, search_pattern=r"(\d+) \w+ free"): if self.direction == "put": space_avail = self.remote_space_available(search_pattern=search_pattern) elif self.direction == "get": space_avail = self.local_space_available() if space_avail > self...
Verify sufficient space is available on destination file system (return boolean).
367,503
def removeRedundantVerbChains( foundChains, removeOverlapping = True, removeSingleAraAndEi = False ): eiära toDelete = [] for i in range(len(foundChains)): matchObj1 = foundChains[i] if removeOverlapping: for j in range(i+1, len(foundChains)): matchObj2 = f...
Eemaldab yleliigsed verbiahelad: ahelad, mis katavad osaliselt v6i t2ielikult teisi ahelaid (removeOverlapping == True), yhes6nalised 'ei' ja 'ära' ahelad (kui removeSingleAraAndEi == True); Yldiselt on nii, et ylekattuvaid ei tohiks palju olla, kuna fraaside laiendamisel ...
367,504
def find_files(path, exts=None): files_list = [] for root, dirs, files in os.walk(path): for name in files: files_list.append(os.path.join(root, name)) if exts is not None: return [file for file in files_list if pathlib.Path(file).suffix in exts] return files_l...
查找路径下的文件,返回指定类型的文件列表 :param: * path: (string) 查找路径 * exts: (list) 文件类型列表,默认为空 :return: * files_list: (list) 文件列表 举例如下:: print('--- find_files demo ---') path1 = '/root/fishbase_issue' all_files = find_files(path1) print(all_files) exts_file...
367,505
def offset(self, location, dy=0): if not isinstance(location, Location): location = Location(location, dy) r = Region(self.x+location.x, self.y+location.y, self.w, self.h).clipRegionToScreen() if r is None: raise ValueError("Specified region is not v...
Returns a new ``Region`` offset from this one by ``location`` Width and height remain the same
367,506
def is_rigid(matrix): matrix = np.asanyarray(matrix, dtype=np.float64) if matrix.shape != (4, 4): return False if not np.allclose(matrix[-1], [0, 0, 0, 1]): return False check = np.dot(matrix[:3, :3], matrix[:3, :3].T) return np.allclose(check, np.eye(3))
Check to make sure a homogeonous transformation matrix is a rigid body transform. Parameters ----------- matrix: possibly a transformation matrix Returns ----------- check: bool, True if matrix is a valid (4,4) rigid body transform.
367,507
def URL(base, path, segments=None, defaults=None): url_class = type(Segments.__name__, Segments.__bases__, dict(Segments.__dict__)) segments = [] if segments is None else segments defaults = [] if defaults is None else defaults for segment in segments: setattr...
URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and setting that segment is created dynamically.
367,508
def mutating_method(func): def wrapper(self, *__args, **__kwargs): old_mutable = self._mutable self._mutable = True try: return func(self, *__args, **__kwargs) finally: self._mutable = old_mutable return wrapper
Decorator for methods that are allowed to modify immutable objects
367,509
async def _process_request(self, identity: bytes, empty_frame: list, request: RPCRequest): try: _log.debug("Client %s sent request: %s", identity, request) start_time = datetime.now() reply = await self.rpc_spec.run_handler(request) if self.announce_timin...
Executes the method specified in a JSON RPC request and then sends the reply to the socket. :param identity: Client identity provided by ZeroMQ :param empty_frame: Either an empty list or a single null frame depending on the client type :param request: JSON RPC request
367,510
def create_comment_edit(self, ): pte = JB_PlainTextEdit(parent=self) pte.set_placeholder("Enter a comment before saving...") pte.setMaximumHeight(120) return pte
Create a text edit for comments :returns: the created text edit :rtype: :class:`jukeboxcore.gui.widgets.textedit.JB_PlainTextEdit` :raises: None
367,511
def concatenate_lists(*layers, **kwargs): if not layers: return noop() drop_factor = kwargs.get("drop_factor", 1.0) ops = layers[0].ops layers = [chain(layer, flatten) for layer in layers] concat = concatenate(*layers) def concatenate_lists_fwd(Xs, drop=0.0): drop *= drop...
Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))`
367,512
def command_err(self, code=1, errmsg=, *args, **kwargs): kwargs.setdefault(, 0) kwargs[] = code kwargs[] = errmsg self.replies(*args, **kwargs) return True
Error reply to a command. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
367,513
def exists_alias(self, alias_name, index_name=None): return self._es_conn.indices.exists_alias(index=index_name, name=alias_name)
Check whether or not the given alias exists :return: True if alias already exist
367,514
def publish(self): with db.session.begin_nested(): deposit = self.deposit_class.create(self.metadata) deposit[][] = self.event.user_id deposit[][] = [self.event.user_id] for key, url in self.files: deposit.files[key] = self.g...
Publish GitHub release as record.
367,515
def _validate(self, writing=False): for box in self.DR: if box.box_id != : msg = ( ) self._dispatch_validation_error(msg, writing=writing)
Verify that the box obeys the specifications.
367,516
def p_sequenceItems(self, p): n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
sequenceItems : sequenceItems ',' sequenceItem | sequenceItem
367,517
def wait(self): s gone. d(text="Settings").wait.exists() ' @param_to_property(action=["exists", "gone"]) def _wait(action, timeout=3000): if timeout / 1000 + 5 > int(os.environ.get("JSONRPC_TIMEOUT", 90)): http_timeout = timeout / 1000 + 5 ...
Wait until the ui object gone or exist. Usage: d(text="Clock").wait.gone() # wait until it's gone. d(text="Settings").wait.exists() # wait until it appears.
367,518
def _call_post_with_user_override(self, sap_user_id, url, payload): SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model( , ) oauth_access_token, _ = SAPSuccessFactorsAPIClient.get_oauth_access_token( self.enterprise_configuration.saps...
Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint. Args: sap_user_id (str): The user to use to retrieve an auth token. url (str): The url to post to. payload (str): The json encoded payload to post.
367,519
def view(template=None): if not template: template = "Juice/Plugin/MaintenancePage/index.html" class Maintenance(View): @classmethod def register(cls, app, **kwargs): super(cls, cls).register(app, **kwargs) if cls.get_config("APPLICATION_MAINTENANCE_ON"): ...
Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param template_: The directory containing the view pages :return:
367,520
def Tmatrix(X): T = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]] for row in X: for k in range(3): for l in range(3): T[k][l] += row[k] * row[l] return T
gets the orientation matrix (T) from data in X
367,521
def password_valid(self, wallet): wallet = self._process_value(wallet, ) payload = {"wallet": wallet} resp = self.call(, payload) return resp[] ==
Checks whether the password entered for **wallet** is valid :param wallet: Wallet to check password for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.password_valid( ... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F" ...
367,522
def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False): completed_timestamp = None course_completed = False if completed_date is not None: completed_timestamp = parse_datetime_to_epoch_millis(completed_date) c...
Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data. If completed_date is None and the learner isn't passing, then course completion has not been met. If no remote ID can be found, return None.
367,523
def _pct_diff(self, best, other): return colorize("{}%".format( round(((best-other)/best)*100, 2)).rjust(10), "red")
Calculates and colorizes the percent difference between @best and @other
367,524
def close(self): self.closed = True self._flush_bits_to_stream() self._stream.close()
Close the stream
367,525
def delete_empty_children(self): for child in self.children: child.delete_empty_children() try: if os.path.exists(child.full_path): os.rmdir(child.full_path) except OSError: pass else: self.children.remove(child)
Walk through the children of this node and delete any that are empty.
367,526
def _verify_credentials(self): r = requests.get(self.apiurl + "account/verify_credentials.xml", auth=HTTPBasicAuth(self._username, self._password), headers=self.header) if r.status_code != 200: raise UserLoginFailed("Username or Pass...
An internal method that verifies the credentials given at instantiation. :raises: :class:`Pymoe.errors.UserLoginFailed`
367,527
def encrypt(key, message): try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.encodestring(ret.get()) except Exception as e: raise Exception("Unable to encrypt data: ", e) return encrypted_data.decode()
encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
367,528
def max(a, axis=None): axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _MaxStreamsHandler, _MaxMaskedStreamsHandler, a.dtype, {})
Request the maximum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose maximum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is per...
367,529
def str2rsi(key): rlzi, sid, imt = key.split() return int(rlzi[4:]), int(sid[4:]), imt
Convert a string of the form 'rlz-XXXX/sid-YYYY/ZZZ' into a triple (XXXX, YYYY, ZZZ)
367,530
def _onDisconnect(self, mqttc, obj, rc): self.connectEvent.clear() if rc != 0: self.logger.error("Unexpected disconnect from IBM Watson IoT Platform: %d" % (rc)) else: self.logger.info("Disconnected from IBM Watson IoT Platform")
Called when the client disconnects from IBM Watson IoT Platform. See [paho.mqtt.python#on_disconnect](https://github.com/eclipse/paho.mqtt.python#on_disconnect) for more information # Parameters mqttc (paho.mqtt.client.Client): The client instance for this callback obj ...
367,531
def get_zipped_dataset_from_predictions(predictions): targets = stack_data_given_key(predictions, "targets") outputs = stack_data_given_key(predictions, "outputs") num_videos, num_steps = targets.shape[:2] outputs = outputs[:, :num_steps] targets_placeholder = tf.placeholder(targets.dtype, targets.sha...
Creates dataset from in-memory predictions.
367,532
def put(self, path, data, **options): data, options = self._update_request(data, options) return self.request(, path, data=data, **options)
Parses PUT request options and dispatches a request
367,533
def load(self, env=None): self._load() e = env or \ os.environ.get(RUNNING_MODE_ENVKEY, DEFAULT_RUNNING_MODE) if e in self.config: return self.config[e] logging.warn("Environment was not found.", e)
Load a section values of given environment. If nothing to specified, use environmental variable. If unknown environment was specified, warn it on logger. :param env: environment key to load in a coercive manner :type env: string :rtype: dict
367,534
def _ParseMFTEntry(self, parser_mediator, mft_entry): for attribute_index in range(0, mft_entry.number_of_attributes): try: mft_attribute = mft_entry.get_attribute(attribute_index) self._ParseMFTAttribute(parser_mediator, mft_entry, mft_attribute) except IOError as exception: ...
Extracts data from a NFTS $MFT entry. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. mft_entry (pyfsntfs.file_entry): MFT entry.
367,535
def milestone(self, number): json = None if int(number) > 0: url = self._build_url(, str(number), base_url=self._api) json = self._json(self._get(url), 200) return Milestone(json, self) if json else None
Get the milestone indicated by ``number``. :param int number: (required), unique id number of the milestone :returns: :class:`Milestone <github3.issues.milestone.Milestone>`
367,536
def fixed_vectors_encoding(index_encoded_sequences, letter_to_vector_df): (num_sequences, sequence_length) = index_encoded_sequences.shape target_shape = ( num_sequences, sequence_length, letter_to_vector_df.shape[0]) result = letter_to_vector_df.iloc[ index_encoded_sequences.flatten() ...
Given a `n` x `k` matrix of integers such as that returned by `index_encoding()` and a dataframe mapping each index to an arbitrary vector, return a `n * k * m` array where the (`i`, `j`)'th element is `letter_to_vector_df.iloc[sequence[i][j]]`. The dataframe index and columns names are ignored here; the i...
367,537
def _get(self, *args, **kwargs): messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs) if self.user.is_authenticated(): inbox_messages = self.backend.inbox_list(self.user) else: inbox_messages = [] return messages + inbox_messages, al...
Retrieve unread messages for current user, both from the inbox and from other storages
367,538
def init_providers(self, provider, kwargs): self.provider = notifiers.get_notifier(provider, strict=True) if kwargs.get("fallback"): self.fallback = notifiers.get_notifier(kwargs.pop("fallback"), strict=True) self.fallback_defaults = kwargs.pop("fallback_defaults", {})
Inits main and fallback provider if relevant :param provider: Provider name to use :param kwargs: Additional kwargs :raises ValueError: If provider name or fallback names are not valid providers, a :exc:`ValueError` will be raised
367,539
def window_nuttall(N): r a0 = 0.355768 a1 = 0.487396 a2 = 0.144232 a3 = 0.012604 return _coeff4(N, a0, a1, a2, a3)
r"""Nuttall tapering window :param N: window length .. math:: w(n) = a_0 - a_1 \cos\left(\frac{2\pi n}{N-1}\right)+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)- a_3 \cos\left(\frac{6\pi n}{N-1}\right) with :math:`a_0 = 0.355768`, :math:`a_1 = 0.487396`, :math:`a_2=0.144232` and :math:`a_3=0.012604` .. p...
367,540
def save(self, *args, **kwargs): self.uid = "{}_candidate:{}-{}".format( self.person.uid, self.party.uid, self.race.cycle.uid ) super(Candidate, self).save(*args, **kwargs)
**uid**: :code:`{person.uid}_candidate:{party.uid}-{cycle.ap_code}`
367,541
def archive_handler(unused_build_context, target, fetch, package_dir, tar): package_dest = join(package_dir, basename(urlparse(fetch.uri).path)) package_content_dir = join(package_dir, ) extract_dir = (join(package_content_dir, fetch.name) if fetch.name else package_content_dir) ...
Handle remote downloadable archive URI. Download the archive and cache it under the private builer workspace (unless already downloaded), extract it, and add the content to the package tar. TODO(itamar): Support re-downloading if remote changed compared to local. TODO(itamar): Support more archive...
367,542
def fopen(*args, **kwargs): if six.PY3: try: if args[0] in (0, 1, 2): raise TypeError( .format(args[0]) ) except IndexError: pass binary = None if ((six.PY2 and salt.utils.platform...
Wrapper around open() built-in to set CLOEXEC on the fd. This flag specifies that the file descriptor should be closed when an exec function is invoked; When a file descriptor is allocated (as with open or dup), this bit is initially cleared on the new file descriptor, meaning that descriptor will ...
367,543
def on_release_key(key, callback, suppress=False): return hook_key(key, lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress)
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
367,544
def _get_drift(step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob, name=None): with tf.compat.v1.name_scope(name, , [ step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob ]): drift_parts = [] for step_size, volatility, g...
Compute diffusion drift at the current location `current_state`. The drift of the diffusion at is computed as ```none 0.5 * `step_size` * volatility_parts * `target_log_prob_fn(current_state)` + `step_size` * `grads_volatility` ``` where `volatility_parts` = `volatility_fn(current_state)**2` and `grads...
367,545
def kappa_statistic(self): r if self.population() == 0: return float() random_accuracy = ( (self._tn + self._fp) * (self._tn + self._fn) + (self._fn + self._tp) * (self._fp + self._tp) ) / self.population() ** 2 return (self.accuracy() - random...
r"""Return κ statistic. The κ statistic is defined as: :math:`\kappa = \frac{accuracy - random~ accuracy} {1 - random~ accuracy}` The κ statistic compares the performance of the classifier relative to the performance of a random classifier. :math:`\kappa` = 0 indicates ...
367,546
def run_in_order(l, show_output=True, show_err=True, ignore_err=False, args=(), **kwargs): if show_output is None: show_output = True if show_err is None: show_err = True if ignore_err is None: ignore_err = False if args is None: args = () ...
Processes each element of l in order: if it is a string: execute it as a shell command elif it is a callable, call it with *args, **kwargs l-->list: Each elem is either a string (shell command) or callable Any other type is ignored show_output-->boolean: Show stdout of shell comma...
367,547
def _maybe_unique_host(onion): hosts = [ onion.get_client(nm).hostname for nm in onion.client_names() ] if not hosts: raise ValueError( "Can't access .onion_uri because there are no clients" ) host = hosts[0] for h in hosts[1:]: if h != host: ...
:param onion: IAuthenticatedOnionClients provider :returns: a .onion hostname if all clients have the same name or raises ValueError otherwise
367,548
def _update_doc_in_index(self, index_writer, doc): all_labels = set(self.label_list) doc_labels = set(doc.labels) new_labels = doc_labels.difference(all_labels) for label in new_labels: self.create_label(label) last_mod = datetime.datetime.fromtime...
Add/Update a document in the index
367,549
def _create_breadcrumbs(self, relpath): if relpath == : breadcrumbs = [] else: path_parts = [os.path.basename(self._root)] + relpath.split(os.path.sep) path_links = [.join(path_parts[1:i + 1]) for i, name in enumerate(path_parts)] breadcrumbs = [{: link_path, : name} ...
Create filesystem browsing breadcrumb navigation. That is, make each path segment into a clickable element that takes you to that dir.
367,550
def process(self, salt_data, token, opts): parts = salt_data[].split() if len(parts) < 2: return if parts[1] == : if parts[3] == : self.process_new_job_event(salt_data) if salt_data[][] == : self.minio...
Process events and publish data
367,551
def sec_overview(self): metrics = self.config[][] file_name = self.config[][] data_path = os.path.join(self.data_dir, "data") file_name = os.path.join(data_path, file_name) logger.debug("CSV file %s generation in progress", file_name) csv = ...
Generate the data for the Overview section in the report :return:
367,552
def path_regex(self): regex = r return regex % {: self.locale, : self.platform_regex, : self.version}
Return the regex for the path to the build folder.
367,553
def is_invalid_params(func, *args, **kwargs): if not inspect.isfunction(func): return True funcargs, varargs, varkwargs, defaults = inspect.getargspec(func) if defaults: funcargs = funcargs[:-len(defaults)] if args and len(args) != len(funcargs): return True ...
Check, whether function 'func' accepts parameters 'args', 'kwargs'. NOTE: Method is called after funct(*args, **kwargs) generated TypeError, it is aimed to destinguish TypeError because of invalid parameters from TypeError from inside the function. .. versionadded: 1.9.0
367,554
def submit_mult_calcs(calc_suite_specs, exec_options=None): if exec_options is None: exec_options = dict() if exec_options.pop(, False): print(_print_suite_summary(calc_suite_specs)) _user_verify() calc_suite = CalcSuite(calc_suite_specs) calcs = calc_suite.create_calcs() ...
Generate and execute all specified computations. Once the calculations are prepped and submitted for execution, any calculation that triggers any exception or error is skipped, and the rest of the calculations proceed unaffected. This prevents an error in a single calculation from crashing a large sui...
367,555
def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False): for example in tfds.as_numpy(dataset): inp, out = example[0][input_name], example[1] if len(out.shape) > 1 and out.shape[-1] == 1: out = np.squeeze(out, axis=-1) if num_chunks > 0: inp = np.split(inp, num_chunks...
Takes a tf.Dataset and creates a numpy stream of ready batches.
367,556
def dump_BSE_data_in_GW_run(self, BSE_dump=True): if BSE_dump: self.BSE_TDDFT_options.update(do_bse=1, do_tddft=0) else: self.BSE_TDDFT_options.update(do_bse=0, do_tddft=0)
:param BSE_dump: boolean :return: set the "do_bse" variable to one in cell.in
367,557
def rebuild(self): gantt = self.ganttWidget() scale = gantt.timescale() rect = self.sceneRect() header = gantt.treeWidget().header() options = {} options[] = gantt.dateStart() options[] = gantt.dateEnd() ...
Rebuilds the scene based on the current settings. :param start | <QDate> end | <QDate>
367,558
def main(graph): args = parse_args(graph) if args.drop: drop_all(graph) create_all(graph)
Create and drop databases.
367,559
def add_node(self, op_type, inputs, outputs, op_domain=, op_version=1, **attrs): s domain-version information cannot be found in our domain-version pool (a Python set), we may add it. :param op_type: A string (e.g., Pool and Conv) indicating the type of the NodeProto :param inputs: A li...
Add a NodeProto into the node list of the final ONNX model. If the input operator's domain-version information cannot be found in our domain-version pool (a Python set), we may add it. :param op_type: A string (e.g., Pool and Conv) indicating the type of the NodeProto :param inputs: A list of s...
367,560
def validate(self, value): if not isinstance(value, (list, tuple)) or isinstance(value, str_types): self.raise_error( .format(type(value).__name__)) super(ListField, self).validate(value)
Make sure that the inspected value is of type `list` or `tuple`
367,561
def prepare_native_return_state(native_state): javavm_simos = native_state.project.simos ret_state = native_state.copy() ret_state.regs._ip = ret_state.callstack.ret_addr ret_state.scratch.guard = ret_state.solver.true ret_state.history.jumpkind = ...
Hook target for native function call returns. Recovers and stores the return value from native memory and toggles the state, s.t. execution continues in the Soot engine.
367,562
def vector_similarity(self, vector, items): vector = self.normalize(vector) items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items]) return vector.dot(items_vec.T)
Compute the similarity between a vector and a set of items.
367,563
def get_room(self, id): if id not in self._rooms: self._rooms[id] = Room(self, id) return self._rooms[id]
Get room. Returns: :class:`Room`. Room
367,564
def _delete_ubridge_connection(self, adapter_number): vnet = "ethernet{}.vnet".format(adapter_number) if vnet not in self._vmx_pairs: raise VMwareError("vnet {} not in VMX file".format(vnet)) yield from self._ubridge_send("bridge delete {name}".format(name=vnet))
Deletes a connection in uBridge. :param adapter_number: adapter number
367,565
def delete(self, deleteSubtasks=False): super(Issue, self).delete(params={: deleteSubtasks})
Delete this issue from the server. :param deleteSubtasks: if the issue has subtasks, this argument must be set to true for the call to succeed. :type deleteSubtasks: bool
367,566
def get_logger(name, level=0): level = 0 if not isinstance(level, int) else level level = 0 if level < 0 else level level = 4 if level > 4 else level console = logging.StreamHandler() level = [logging.NOTSET, logging.ERROR, logging.WARN, logging.INFO, lo...
Setup a logging instance
367,567
def fit(self, X, y=None, **fit_params): if self.transform_type not in self.valid_transforms: warnings.warn("Invalid transform type.", stacklevel=2) return self
Fit Unary Math Operator :param y: :return:
367,568
def export(self, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=False, sort=None, ascending=True): if path.endswith(): self.export_arrow(path, column_names, byteorder, shuffle, selection, progress=progress, virtual=virtual, sort=sort, ascendin...
Exports the DataFrame to a file written with arrow :param DataFrameLocal df: DataFrame to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all columns :param str byteorder: = for native, < for little endian and > for big endi...
367,569
def get_orthology_matrix(self, outfile, sc, outdir=None, pid_cutoff=None, bitscore_cutoff=None, evalue_cutoff=None, force_rerun=False): if not outdir: outdir = self.data_dir ortho_matrix = op.join(outdir, outfile) ...
Create the orthology matrix by finding best bidirectional BLAST hits. Genes = rows, strains = columns Runs run_makeblastdb, run_bidirectional_blast, and calculate_bbh for protein sequences. Args: outfile (str): Filename with extension of the orthology matrix (ie. df_orthology.csv) ...
367,570
def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size): vocab_filepath = os.path.join(tmp_dir, vocab_filename) print( + vocab_filepath) if tf.gfile.Exists(vocab_filepath): gs = text_encoder.SubwordTextEncoder(vocab_filepath) return gs example_file = os.path.join(tmp_dir, _EXAMPLES_FILE) g...
Read or create vocabulary.
367,571
def get(self, name): if not isvalidinterface(name): return None config = self.get_block(r % name) resp = dict() resp.update(self._parse_bpduguard(config)) resp.update(self._parse_portfast(config)) resp.update(self._parse_portfast_type(config)) ...
Returns the specified interfaces STP configuration resource The STP interface resource contains the following * name (str): The interface name * portfast (bool): The spanning-tree portfast admin state * bpduguard (bool): The spanning-tree bpduguard admin state *...
367,572
def delete_course(self, courseid): if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) course_fs = self.get_course_fs(courseid) if not course_fs.exists(): raise CourseNotFoundException() course_fs.delete() ...
:param courseid: the course id of the course :raise InvalidNameException or CourseNotFoundException Erase the content of the course folder
367,573
def main(args=sys.argv): try: logging.basicConfig(level=logging.WARN) work_dir = args[1] assert os.path.exists(work_dir), "First argument to lsf_runner.py must be a directory that exists" do_work_on_compute_node(work_dir) except Exception as exc: pr...
Run the work() method from the class instance in the file "job-instance.pickle".
367,574
def fail(self, message, view, type_error=False): exc_class = ConfigTypeError if type_error else ConfigValueError raise exc_class( u.format(view.name, message) )
Raise an exception indicating that a value cannot be accepted. `type_error` indicates whether the error is due to a type mismatch rather than a malformed value. In this case, a more specific exception is raised.
367,575
def visit_Call(self, node): self.generic_visit(node) if node.args: return keywords = set() for k in node.keywords: if k.arg is not None: keywords.add(k.arg) if k.arg is None and isinstance(k.value, ast.D...
Call visitor - used for finding setup() call.
367,576
def process(specs): pout, pin = chain_specs(specs) LOG.info("Processing") sw = StopWatch().start() r = pout.process(pin) if r: print(r) LOG.info("Finished in %s", sw.read())
Executes the passed in list of specs
367,577
def get_lb_conn(dd_driver=None): vm_ = get_configured_provider() region = config.get_cloud_config_value( , vm_, __opts__ ) user_id = config.get_cloud_config_value( , vm_, __opts__ ) key = config.get_cloud_config_value( , vm_, __opts__ ) if not dd_driver: ...
Return a load-balancer conn object
367,578
def fix_virtualenv_tkinter(): if "TCL_LIBRARY" in os.environ: return if not hasattr(sys, "real_prefix"): return if sys.version_info[0] == 2: virtualprefix = sys.prefix sys.prefix = sys.real_prefix import FixTk if "TCL_LIBRAR...
work-a-round for tkinter under windows in a virtualenv: "TclError: Can't find a usable init.tcl..." Known bug, see: https://github.com/pypa/virtualenv/issues/93 There are "fix tk" file here: C:\Python27\Lib\lib-tk\FixTk.py C:\Python34\Lib\tkinter\_fix.py These modules will be au...
367,579
def jsondeclarations(self): l = [] for annotationtype, set in self.annotations: label = None for key, value in vars(AnnotationType).items(): if value == annotationtype: label = key break ...
Return all declarations in a form ready to be serialised to JSON. Returns: list of dict
367,580
def put_metadata(self, key, value, namespace=): self._check_ended() if not isinstance(namespace, string_types): log.warning("ignoring non string type metadata namespace") return if namespace.startswith(): log.warning("Prefix is reserved, drop metad...
Add metadata to segment or subsegment. Metadata is not indexed but can be later retrieved by BatchGetTraces API. :param str namespace: optional. Default namespace is `default`. It must be a string and prefix `AWS.` is reserved. :param str key: metadata key under specified namespace ...
367,581
def show(cls, result): if result.ok: if result.stdout: out = .join(result.stdout) if result.value and result.value != : return .join([out, result.value]) return out if result.value and not cls._is_function_value...
:param TryHaskell.Result result: Parse result of JSON data. :rtype: str|unicode
367,582
def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT): folder = path.split(SEP)[-1] objs = super(GsContainer, self).get_objects(path, marker, limit + 1) objs = [o for o in objs if not (o.size == 0 and o.name == f...
Get objects. Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an extra +1 limit query and ignore any such file objects.
367,583
def _set_scores(self): anom_scores = {} self._compute_derivatives() derivatives_ema = utils.compute_ema(self.smoothing_factor, self.derivatives) for i, (timestamp, value) in enumerate(self.time_series_items): anom_scores[timestamp] = abs(self.derivatives[i] - derivatives_ema[i]) stdev = n...
Compute anomaly scores for the time series.
367,584
def Orth(docs, drop=0.0): ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.orth i += 1 return ids, None
Get word forms.
367,585
def onpick(self, event): if hasattr(event.artist, ): idx = event.artist._mt_legend_item try: self.toggle_artist(self.artists[idx]) except IndexError: pass return if not event.artist.get_visibl...
Called per artist (group), with possibly a list of indices.
367,586
def addproperties( names, bfget=None, afget=None, enableget=True, bfset=None, afset=None, enableset=True, bfdel=None, afdel=None, enabledel=True ): names = ensureiterable(names, exclude=string_types) if isinstance(bfget, MethodType): finalbfget = lambda self, ...
Decorator in charge of adding python properties to cls. {a/b}fget, {a/b}fset and {a/b}fdel are applied to all properties matching names in taking care to not forget default/existing properties. The prefixes *a* and *b* are respectively for after and before default/existing property getter/setter/delete...
367,587
def cycle_running_window(iterable, size): if size > len(iterable): raise ValueError("size can not be greater than length of iterable.") fifo = collections.deque(maxlen=size) cycle = itertools.cycle(iterable) counter = itertools.count(1) length = len(iterable) for i in cycle: ...
Generate n-size cycle running window. Example:: >>> for i in running_windows([1, 2, 3, 4, 5], size=3): ... print(i) [1, 2, 3] [2, 3, 4] [3, 4, 5] [4, 5, 1] [5, 1, 2] **中文文档** 循环位移滑窗函数。
367,588
def alphanum_variable(min_size, max_size, name=None): if name is None: name = if min_size < 0: raise BaseException() field = pp.Word(pp.alphanums, min=min_size, max=max_size) field.setParseAction(lambda s: s[0].strip()) field.leaveWhitespace() ...
Creates the grammar for an alphanumeric code where the size ranges between two values. :param min_size: minimum size :param max_size: maximum size :param name: name for the field :return: grammar for an alphanumeric field of a variable size
367,589
def atlas_get_all_neighbors( peer_table=None ): if os.environ.get("BLOCKSTACK_ATLAS_NETWORK_SIMULATION") != "1": raise Exception("This method is only available when testing with the Atlas network simulator") ret = {} with AtlasPeerTableLocked(peer_table) as ptbl: ret = copy.deepcopy(p...
Get *all* neighbor information. USED ONLY FOR TESTING
367,590
def _init_connection(self): try: self._lock.acquire() response = bytearray(22) self._send_raw(BRIDGE_INITIALIZATION_COMMAND) self._socket.recv_into(response) self._wb1 = response[19] self._wb2 = response[20] ...
Requests the session ids of the bridge. :returns: True, if initialization was successful. False, otherwise.
367,591
def agitator_time_homogeneous(N, P, T, H, mu, rho, D=None, homogeneity=.95): r if not D: D = T*0.5 Np = P*g/rho/N**3/D**5 Re_imp = rho/mu*D**2*N regime_constant = Np**(1/3.)*Re_imp if regime_constant >= min_regime_constant_for_turbulent: Fo = (5.2/regime_constant) else: ...
r'''Calculates time for a fluid mizing in a tank with an impeller to reach a specified level of homogeneity, according to [1]_. .. math:: N_p = \frac{Pg}{\rho N^3 D^5} .. math:: Re_{imp} = \frac{\rho D^2 N}{\mu} .. math:: \text{constant} = N_p^{1/3} Re_{imp} .. math:: ...
367,592
def highlight_options(self, **kwargs): s = self._clone() s._highlight_opts.update(kwargs) return s
Update the global highlighting options used for this request. For example:: s = Search() s = s.highlight_options(order='score')
367,593
def setup_splittable_dax_generated(workflow, input_tables, out_dir, tags): cp = workflow.cp try: num_splits = cp.get_opt_tags("workflow-splittable", "splittable-num-banks", tags) except BaseException: inj_interval = int(cp.get_opt_tags("workflo...
Function for setting up the splitting jobs as part of the workflow. Parameters ----------- workflow : pycbc.workflow.core.Workflow The Workflow instance that the jobs will be added to. input_tables : pycbc.workflow.core.FileList The input files to be split up. out_dir : path ...
367,594
def canonicalize_observed_time_series_with_mask( maybe_masked_observed_time_series): with tf.compat.v1.name_scope(): if hasattr(maybe_masked_observed_time_series, ): observed_time_series = ( maybe_masked_observed_time_series.time_series) is_missing = maybe_masked_observed_time_series...
Extract a Tensor with canonical shape and optional mask. Args: maybe_masked_observed_time_series: a `Tensor`-like object with shape `[..., num_timesteps]` or `[..., num_timesteps, 1]`, or a `tfp.sts.MaskedTimeSeries` containing such an object. Returns: masked_time_series: a `tfp.sts.MaskedTimeS...
367,595
def _isophote_list_to_table(isophote_list): properties = OrderedDict() properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = properties[] = ...
Convert an `~photutils.isophote.IsophoteList` instance to a `~astropy.table.QTable`. Parameters ---------- isophote_list : list of `~photutils.isophote.Isophote` or a `~photutils.isophote.IsophoteList` instance A list of isophotes. Returns ------- result : `~astropy.table.QTable` ...
367,596
def most_hot(self): maxtemp = -270.0 hottest = None for weather in self._forecast.get_weathers(): d = weather.get_temperature() if in d: if d[] > maxtemp: maxtemp = d[] hottest = weather return ho...
Returns the *Weather* object in the forecast having the highest max temperature. The temperature is retrieved using the ``get_temperature['temp_max']`` call; was 'temp_max' key missing for every *Weather* instance in the forecast, ``None`` would be returned. :returns: a *Weather* object...
367,597
def fit_size_models(self, model_names, model_objs, input_columns, output_column="Hail_Size", output_start=5, output_step=5, output_stop=100): print("Fitting si...
Fit size models to produce discrete pdfs of forecast hail sizes. Args: model_names: List of model names model_objs: List of model objects input_columns: List of input variables output_column: Output variable name output_start: Hail size bin start ...
367,598
def linear(m=1, b=0): def f(i): return m * i + b return partial(force, sequence=_advance(f))
Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver
367,599
def setup_argparse(): parser = argparse.ArgumentParser( description= ) parser.add_argument(, action=, version= + __version__) parser.add_argument(, , help= ...
Setup the argparse argument parser :return: instance of argparse :rtype: ArgumentParser