Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
350,200
def videometadata(ctx, city, date, outpath): db = ctx.obj[] today = ctx.obj[].date() event = cliutil.get_event(db, city, date, today) data = event.as_dict() cliutil.handle_raw_output(ctx, data) evdir = "{}-{}".format(event.city.name, event.slug) config = OrderedDict() config[] =...
Generate metadata for video records. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): show the N-th last meetup
350,201
def handle_cd_command(arg): CD_CMD = tokens = arg.split(CD_CMD + ) directory = tokens[-1] if len(tokens) > 1 else None if not directory: return False, "No folder name was provided." try: os.chdir(directory) subprocess.call([]) return True, None except OSErro...
Handles a `cd` shell command by calling python's os.chdir.
350,202
def _get_item_labels(self, item, no_from_study=False): subject_id = self.inv_map_subject_id(item.subject_id) visit_id = self.inv_map_visit_id(item.visit_id) subj_label, sess_label = self._get_labels( item.frequency, subject_id, visit_id) if not no_from_study and item...
Returns the labels for the XNAT subject and sessions given the frequency and provided IDs.
350,203
def shutdown(self, ssc=None, grace_secs=0, timeout=259200): logging.info("Stopping TensorFlow nodes") ps_list, worker_list, eval_list = [], [], [] for node in self.cluster_info: (ps_list if node[] == else eval_list if node[] == else worker_list).append(node) if timeout > 0: ...
Stops the distributed TensorFlow cluster. For InputMode.SPARK, this will be executed AFTER the `TFCluster.train()` or `TFCluster.inference()` method completes. For InputMode.TENSORFLOW, this will be executed IMMEDIATELY after `TFCluster.run()` and will wait until the TF worker nodes complete. Args: ...
350,204
def _read_cmap(self): try: i = 0 colormap = {0: (0, 0, 0)} with open(settings.COLORMAP) as cmap: lines = cmap.readlines() for line in lines: if i == 0 and in line: i = 1 ...
reads the colormap from a text file given in settings.py. See colormap_cubehelix.txt. File must contain 256 RGB values
350,205
def assign_rotatable(mol): mol.require("Valence") mol.require("Topology") bs = set([(u, v) for u, v, _ in mol.bonds_iter()]) for r in mol.rings: for a, b in iterator.consecutive(r + [r[0]], 2): bs -= {(a, b)} bs -= {(b, a)} for u, v in bs: unc = mol.neigh...
Assign rotatable bonds (single and not terminal and not in ring)
350,206
def max_load(network, boundaries=[], filename=None, two_cb=False): cmap_line = plt.cm.jet cmap_link = plt.cm.jet array_line = [[] * len(network.lines), network.lines.index] array_link = [[] * len(network.links), network.links.index] if network.lines_t.q0.empty: load_lines = pd.Se...
Plot maximum loading of each line. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direction boundaries: array Set boundaries of heatmap axis two_cb: boo...
350,207
def _coord(sequence, start, mirna, precursor, iso): dif = abs(mirna[0] - start) if start < mirna[0]: iso.t5 = sequence[:dif].upper() elif start > mirna[0]: iso.t5 = precursor[mirna[0] - 1:mirna[0] - 1 + dif].lower() elif start == mirna[0]: iso.t5 = "NA" if dif > 4: ...
Define t5 and t3 isomirs
350,208
def create_spectrum(spectrum_name): try: spectrum_description = nmrstarlib.SPECTRUM_DESCRIPTIONS[spectrum_name] except KeyError: raise NotImplementedError("Experiment type is not defined.") spectrum = plsimulator.Spectrum(spectrum_name, spectrum_description["Lab...
Initialize spectrum and peak descriptions. :param str spectrum_name: Name of the spectrum from which peak list will be simulated. :return: Spectrum object. :rtype: :class:`~nmrstarlib.plsimulator.Spectrum`
350,209
def activate(self, bounce_id): self._check_values() req_url = + str(bounce_id) + h1 = HTTPConnection() dta = urlencode({"data": "blank"}).encode() req = h1.request( , req_url, dta, { : , ...
Activates a deactivated bounce.
350,210
def get(cls, scope=None): if scope is None: scope = cls.default if isinstance(scope, string_types) and scope in cls._keywords: return getattr(cls, scope) return scope
Return default or predefined URLs from keyword, pass through ``scope``.
350,211
def add_binary_file(self, filename, address=0, overwrite=False): with open(filename, ) as fin: self.add_binary(fin.read(), address, overwrite)
Open given binary file and add its contents. Set `overwrite` to ``True`` to allow already added data to be overwritten.
350,212
def page_erase(addr): if __verbose: print("Erasing page: 0x%x..." % (addr)) buf = struct.pack("<BI", 0x41, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: raise Exception("DFU: erase fail...
Erases a single page.
350,213
def area(triangles=None, crosses=None, sum=False): if crosses is None: crosses = cross(triangles) area = (np.sum(crosses**2, axis=1)**.5) * .5 if sum: return np.sum(area) return area
Calculates the sum area of input triangles Parameters ---------- triangles : (n, 3, 3) float Vertices of triangles crosses : (n, 3) float or None As a speedup don't re- compute cross products sum : bool Return summed area or individual triangle area Returns ---------- ...
350,214
def renamed_class(cls): class DeprecationWrapper(cls): def __init__(self, config=None, env=None, logger_creator=None): old_name = cls.__name__.replace("Trainer", "Agent") new_name = cls.__name__ logger.warn("DeprecationWarning: {} has been renamed to {}. ". ...
Helper class for renaming Agent => Trainer with a warning.
350,215
def sort_ordered_objects(items, getter=lambda x: x): return sorted(items, key=lambda x: getattr(getter(x), OrderedBase.CREATION_COUNTER_FIELD, -1))
Sort an iterable of OrderedBase instances. Args: items (iterable): the objects to sort getter (callable or None): a function to extract the OrderedBase instance from an object. Examples: >>> sort_ordered_objects([x, y, z]) >>> sort_ordered_objects(v.items(), getter=lambda e: e[...
350,216
def filter_dup(lst, lists): t have lower rank in another list ' max_rank = len(lst) + 1 dct = to_ranked_dict(lst) dicts = [to_ranked_dict(l) for l in lists] return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in dicts)]
filters lst to only include terms that don't have lower rank in another list
350,217
def vrf_attr_add(arg, opts, shell_opts): if arg is None: print("ERROR: Please specify the RT of the VRF to view.", file=sys.stderr) sys.exit(1) if arg.lower() in (, ): arg = None try: v = VRF.search({ : , : , : arg } ...
Add attributes to a VRF
350,218
def __unhook_dll(self, event): debug = event.debug pid = event.get_pid() for hook_api_stub in self.__get_hooks_for_dll(event): hook_api_stub.unhook(debug, pid)
Unhook the requested API calls (in self.apiHooks). This method is called automatically whenever a DLL is unloaded.
350,219
def search_for(self, dependency): if dependency.is_root: return PackageCollection(dependency, [self._package]) for constraint in self._search_for.keys(): if ( constraint.name == dependency.name and constraint.constraint.intersect(depend...
Search for the specifications that match the given dependency. The specifications in the returned list will be considered in reverse order, so the latest version ought to be last.
350,220
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs): config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface input = ET.SubElement(get_ip_interface, "input") request_type = ET.SubElement(inp...
Auto Generated Code
350,221
def standardize(self, mol): mol = copy.deepcopy(mol) Chem.SanitizeMol(mol) mol = Chem.RemoveHs(mol) mol = self.disconnect_metals(mol) mol = self.normalize(mol) mol = self.reionize(mol) Chem.AssignStereochemistry(mol, force=True, cleanIt=True) ...
Return a standardized version the given molecule. The standardization process consists of the following stages: RDKit :py:func:`~rdkit.Chem.rdmolops.RemoveHs`, RDKit :py:func:`~rdkit.Chem.rdmolops.SanitizeMol`, :class:`~molvs.metal.MetalDisconnector`, :class:`~molvs.normalize.Normalizer`, ...
350,222
def persist(self): with open(self.persist_file, ) as f: json.dump({ : self.cookies, : self.user_alias, }, f, indent=2) self.logger.debug( % self.persist_file)
持久化会话信息
350,223
def _unset_magic_constants(self): if in self._replace: del self._replace[] if in self._replace: del self._replace[] if in self._replace: del self._replace[] if in self._replace: del self._replace[]
Removes magic constants from current replace list.
350,224
def _wait_until_exp(self, timeout, error, function, *args): error = error.replace(, self._format_timeout(timeout)) def wait_func(): return None if function(*args) else error self._wait_until_no_error_exp(timeout, wait_func)
This replaces the method from Selenium2Library to fix the major logic error in it
350,225
def i2c_reply(self, data): reply_data = [] address = (data[0] & 0x7f) + (data[1] << 7) register = data[2] & 0x7f + data[3] << 7 reply_data.append(register) for i in range(4, len(data), 2): data_item = (data[i] & 0x7f) + (data[i + 1] << 7) reply_d...
This method receives replies to i2c_read requests. It stores the data for each i2c device address in a dictionary called i2c_map. The data is retrieved via a call to i2c_get_read_data() in pymata.py It a callback was specified in pymata.i2c_read, the raw data is sent through the callback ...
350,226
def start_thread(self, target, args, kwargs): thread_obj = threading.Thread(target=target, args=args, kwargs=kwargs, daemon=True) thread_obj.start()
Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments. .. versionadded:: 0.5.0
350,227
def enabled(self): if self._mode == COLOR_AUTO: return sys.stdout.isatty() return self._mode == COLOR_ON
True if coloring is currently enabled
350,228
def _validate_hands(hands, missing): for h, m in zip(hands, missing): for value in m: if dominoes.hand.contains_value(h, value): return False return True
Validates hands, based on values that are supposed to be missing from them. :param list hands: list of Hand objects to validate :param list missing: list of sets that indicate the values that are supposed to be missing from the respective Hand objects :...
350,229
def pre_flight_headers(self, request, methods): methods = .join(m.value for m in methods) headers = { : methods, : } allow_origin = self.allow_origin(request) if allow_origin: headers = dict_filter(headers, { ...
Generate pre-flight headers.
350,230
def __json_truefalse_parse(json_object): for key in (, , , ): if (key in json_object and isinstance(json_object[key], six.text_type)): if json_object[key] == : json_object[key] = True if json_object[key] == : json_objec...
Parse 'True' / 'False' strings in certain known fields
350,231
def configure(): log_levels = { 5: logging.NOTSET, 4: logging.DEBUG, 3: logging.INFO, 2: logging.WARNING, 1: logging.ERROR, 0: logging.CRITICAL } logging.captureWarnings(True) root_logger = logging.getLogger() if settings.CFG["debug"]: de...
Load logging configuration from our own defaults.
350,232
def distinfo_dirname(cls, name, version): name = name.replace(, ) return .join([name, version]) + DISTINFO_EXT
The *name* and *version* parameters are converted into their filename-escaped form, i.e. any ``'-'`` characters are replaced with ``'_'`` other than the one in ``'dist-info'`` and the one separating the name from the version number. :parameter name: is converted to a standard distributi...
350,233
def s_res(self, components=None): if components is None: return self.apparent_power else: not_included = [_ for _ in components if _ not in self.apparent_power.index] labels_included = [_ for _ in components if _ not in not_include...
Get apparent power in kVA at line(s) and transformer(s). Parameters ---------- components : :obj:`list` List of string representatives of :class:`~.grid.components.Line` or :class:`~.grid.components.Transformer`. If not provided defaults to return apparent po...
350,234
def accountSummary(self, reqId, account, tag, value, curency): return _swigibpy.EWrapper_accountSummary(self, reqId, account, tag, value, curency)
accountSummary(EWrapper self, int reqId, IBString const & account, IBString const & tag, IBString const & value, IBString const & curency)
350,235
def to_flasgger(self, app=None, definitions=None, paths=None): if Schema is None: raise RuntimeError() return flasgger.utils.apispec_to_template( app, self, definitions=definitions, paths=paths )
Converts APISpec dict to flasgger suitable dict also adds definitions and paths (optional)
350,236
def audiolazy_namer(name): sp_name = name.split(".") try: data = getattr(audiolazy, sp_name[0]) if isinstance(data, audiolazy.StrategyDict): module_name = data.default.__module__ else: module_name = data.__module__ if not module_name.startswith("audiolazy"): del modul...
Process a name to get Sphinx reStructuredText internal references like ``:obj:`name <audiolazy.lazy_something.name>``` for a given name string, specific for AudioLazy.
350,237
def system(self, cmd): enc = DEFAULT_ENCODING patterns = [pexpect.TIMEOUT, pexpect.EOF] EOF_index = patterns.index(pexpect.EOF) res_idx = child.expect_list...
Execute a command in a subshell. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- int : child's exitstatus
350,238
def fit_predict(self, comparison_vectors, match_index=None): self.fit(comparison_vectors, match_index) result = self.predict(comparison_vectors) return result
Train the classifier. Parameters ---------- comparison_vectors : pandas.DataFrame The comparison vectors. match_index : pandas.MultiIndex The true matches. return_type : str Deprecated. Use recordlinkage.options instead. Use the option ...
350,239
def refresh_access_token(self, refresh_token, redirect_uri=None): redirect = redirect_uri or self._redirect_uri resp_text = _http(, , refresh_token=refresh_token, client_id=self._client_id, client_secret=self._client_secret, ...
Refresh access token.
350,240
def pay_sign_dict( appid, pay_sign_key, add_noncestr=True, add_timestamp=True, add_appid=True, **kwargs ): assert pay_sign_key, "PAY SIGN KEY IS EMPTY" if add_appid: kwargs.update({: appid}) if add_noncestr: kwargs.update({: generate_token()}) if add_times...
支付参数签名
350,241
async def post_annotations(self, entry, **kwargs): params = dict({: self.token, : [], : , : }) if in kwargs: params[] = kwargs[] if in kwargs: params[] = kwargs[] if in kwargs: ...
POST /api/annotations/{entry}.{_format} Creates a new annotation. :param entry \w+ integer The entry ID :return
350,242
def update_objective_bank(self, objective_bank_form): if self._catalog_session is not None: return self._catalog_session.update_catalog(catalog_form=objective_bank_form) collection = JSONClientValidated(, collection=, ...
Updates an existing objective bank. arg: objective_bank_form (osid.learning.ObjectiveBankForm): the form containing the elements to be updated raise: IllegalState - ``objective_bank_form`` already used in an update transaction raise: InvalidArgument - the fo...
350,243
def show_metering_label(self, metering_label, **_params): return self.get(self.metering_label_path % (metering_label), params=_params)
Fetches information of a certain metering label.
350,244
def _standard_params(klass, ids, metric_groups, **kwargs): end_time = kwargs.get(, datetime.utcnow()) start_time = kwargs.get(, end_time - timedelta(seconds=604800)) granularity = kwargs.get(, GRANULARITY.HOUR) placement = kwargs.get(, PLACEMENT.ALL_ON_TWITTER) params =...
Sets the standard params for a stats request
350,245
def parse_profile_date(text, suppress=False): try: if text == u"Unknown" or text == u"?" or text == u"Not available": return None if text == u"Now": return datetime.datetime.now() seconds_match = re.match(r, text) if seconds_match: return datetime.datetime.now() - datetime.timede...
Parses a MAL date on a profile page. May raise ValueError if a malformed date is found. If text is "Unknown" or "?" or "Not available" then returns None. Otherwise, returns a datetime.date object.
350,246
def slurpLines(file, expand=False): r file = _normalizeToFile(file, "r", expand) try: return file.readlines() finally: file.close()
r"""Read in a complete file (specified by a file handler or a filename string/unicode string) as list of lines
350,247
def set_time(self, time): rest_time = int(self.song_total_time) - self.time - 1 minute = int(rest_time) / 60 sec = int(rest_time) % 60 return str(minute).zfill(2) + + str(sec).zfill(2)
时间状态
350,248
def sql(self, sqlQuery): return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped)
Returns a :class:`DataFrame` representing the result of the given query. :return: :class:`DataFrame` >>> df.createOrReplaceTempView("table1") >>> df2 = spark.sql("SELECT field1 AS f1, field2 as f2 from table1") >>> df2.collect() [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Ro...
350,249
def build(ctx, project, build): ctx.obj = ctx.obj or {} ctx.obj[] = project ctx.obj[] = build
Commands for build jobs.
350,250
def _get_bank_keys_redis_key(bank): opts = _get_redis_keys_opts() return .format( prefix=opts[], separator=opts[], bank=bank )
Return the Redis key for the SET of keys under a certain bank, given the bank name.
350,251
def parse_format_order(cls, format_target): try: pattern = re.compile(settings.FORMAT_STRING_REGEX) return [match.group() for match in pattern.finditer(format_target)] except TypeError: raise exceptions.FormatError( % ...
Dissects the format string and gets the order of the tokens as it finds them l->r Splits on camel case or periods/underscores Modified version from this: http://stackoverflow.com/questions/2277352/python-split-a-string-at-uppercase-letters :param format_target: str, format s...
350,252
def compute_sensori_effect(self, m_env): pos = {m.name: pos for m, pos in zip(self.motors, m_env)} self.robot.goto_position(pos, self.move_duration, wait=True) if self.tracker is not None: return self.tracker.get_object_position(self.tracked_obj)
Move the robot motors and retrieve the tracked object position.
350,253
def get_reverse_dependency_tree(package_name, depth=None, paths=None, build_requires=False, private_build_requires=False): pkgs_list = [[package_name]] g = digraph() g.add_node(package_name) it = iter_package_families(paths) ...
Find packages that depend on the given package. This is a reverse dependency lookup. A tree is constructed, showing what packages depend on the given package, with an optional depth limit. A resolve does not occur. Only the latest version of each package is used, and requirements from all variants of t...
350,254
def expand_var(v, env): if len(v) == 0: return v if v[0] == : v = v[1:] if len(v) and v[0] != : if v in env: v = env[v] else: raise Exception( % v) return v
If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env.
350,255
def parse_uploaded_image(field): args = image_parser.parse_args() image = args[] if image.mimetype not in IMAGES_MIMETYPES: api.abort(400, ) bbox = args.get(, None) if bbox: bbox = [int(float(c)) for c in bbox.split()] field.save(image, bbox=bbox)
Parse an uploaded image and save into a db.ImageField()
350,256
def _verify_support(identity, ecdh): protocol = identity.identity_dict[] if protocol not in {}: raise NotImplementedError( .format(protocol)) if ecdh: raise NotImplementedError() if identity.curve_name not in {formats.CURVE_NIST256}: raise NotImplementedError( ...
Make sure the device supports given configuration.
350,257
def update_callback(self, fd, handle, events): if self._mpoll is None: raise RuntimeError() mpoll = self._mpoll.get(fd) if mpoll is None: raise ValueError(.format(fd)) mpoll.update_callback(handle, events)
Update the event mask associated with an existing callback. If you want to temporarily disable a callback then you can use this method with an *events* argument of ``0``. This is more efficient than removing the callback and adding it again later.
350,258
def _get_nan_block_id(partition_class, n_row=1, n_col=1, transpose=False): global _NAN_BLOCKS if transpose: n_row, n_col = n_col, n_row shape = (n_row, n_col) if shape not in _NAN_BLOCKS: arr = np.tile(np.array(np.NaN), shape) _NAN_BLOCKS[shape] = partition_class.pu...
A memory efficient way to get a block of NaNs. Args: partition_class (BaseFramePartition): The class to use to put the object in the remote format. n_row(int): The number of rows. n_col(int): The number of columns. transpose(bool): If true, swap rows and columns. Ret...
350,259
def _get_rank_limits(comm, arrlen): rank = comm.Get_rank() size = comm.Get_size() end = 0 ranklen = int(arrlen / size) if rank < arrlen % size: ranklen += 1 end = comm.scan(sendobj=ranklen, op=MPI.SUM) begin = end - ranklen return (begin, end)
Determine the chunk of the grid that has to be computed per process. The grid has been 'flattened' and has arrlen length. The chunk assigned to each process depends on its rank in the MPI communicator. Parameters ---------- comm : MPI communicator object Describes topology of network: num...
350,260
def merge(self, keys): deletes = [] for pseudo_key, rows in self._rows.items(): self._additional_rows_date2int(keys, rows) rows = self._intersection(keys, rows) if rows: rows = self._rows_sort(rows) self._rows[pseudo_key] = sel...
Merges the join on pseudo keys of two or more reference data sets. :param list[tuple[str,str]] keys: For each data set the keys of the start and end date.
350,261
def _set_init_system(self, client): if not self.init_system: try: out = ipa_utils.execute_ssh_command( client, ) except Exception as e: raise IpaDistroException( ...
Determine the init system of distribution.
350,262
def _print_dot(targets, components, tasks): print("Warning: dot option is deprecated. Use graph instead.", file=sys.stderr) _print_graph(targets, components, tasks)
Deprecated function; use print_graph. Arguments targets - the targets explicitly requested components - full configuration for all components in a project
350,263
def get_result(self): while self._result is None: if len(self.daplink._commands_to_read) > 0: self.daplink._read_packet() else: assert not self.daplink._crnt_cmd.get_empty() self.daplink.flush() if self._error is not None:...
Get the result of this transfer.
350,264
def fromMessage(klass, message, op_endpoint=UNUSED): self = klass.__new__(klass) self.message = message self.namespace = message.getOpenIDNamespace() self.assoc_handle = message.getArg(OPENID_NS, ) self.sig = message.getArg(OPENID_NS, ) if (self.assoc_handle is ...
Construct me from an OpenID Message. @param message: An OpenID check_authentication Message @type message: L{openid.message.Message} @returntype: L{CheckAuthRequest}
350,265
def make_labels(mapping): labels = mapping.copy() for ae in labels: labels[ae] = strip_calculated_markers(labels[ae]) return labels
Convert aesthetic mapping into text labels
350,266
def find_package_version(self): res = { : None, : None, : None, : None, : None, : None, : None, : None, : None } try: pip_info = self._find_pip_info() except E...
Find the installed version of the specified package, and as much information about it as possible (source URL, git ref or tag, etc.) This attempts, to the best of our ability, to find out if the package was installed from git, and if so, provide information on the origin of that git rep...
350,267
def _parse_uri_options(self, parsed_uri, use_ssl=False, ssl_options=None): ssl_options = ssl_options or {} kwargs = urlparse.parse_qs(parsed_uri.query) vhost = urlparse.unquote(parsed_uri.path[1:]) or DEFAULT_VIRTUAL_HOST options = { : use_ssl, : vhost, ...
Parse the uri options. :param parsed_uri: :param bool use_ssl: :return:
350,268
def structured_traceback(self, etype, evalue, etb, tb_offset=None, context=5): tb_offset = self.tb_offset if tb_offset is None else tb_offset try: etype = etype.__name__ except AttributeError: pass Colors = s...
Return a nice text document describing the traceback.
350,269
def _wiggle_interval(value, wiggle=0.5 ** 44): r if -wiggle < value < wiggle: return 0.0, True elif wiggle <= value <= 1.0 - wiggle: return value, True elif 1.0 - wiggle < value < 1.0 + wiggle: return 1.0, True else: return np.nan, False
r"""Check if ``value`` is in :math:`\left[0, 1\right]`. Allows a little bit of wiggle room outside the interval. Any value within ``wiggle`` of ``0.0` will be converted to ``0.0` and similar for ``1.0``. .. note:: There is also a Fortran implementation of this function, which will be us...
350,270
def get_option(self, name, default=None): if self.options is None: return default return self.options.get(name, default)
Returns the value of the given option if it is defined, returns the given default value otherwise. :type name: str :param name: The option name. :type default: object :param default: A default value.
350,271
def viewbox_mouse_event(self, event): BaseCamera.viewbox_mouse_event(self, event) if event.type == : s = 1.1 ** - event.delta[1] self._scale_factor *= s if self._distance is not None: self._distance *= s self.view_changed()
The ViewBox received a mouse event; update transform accordingly. Default implementation adjusts scale factor when scolling. Parameters ---------- event : instance of Event The event.
350,272
def update_views(self):
Update stats views.
350,273
def update(self, friendly_name=values.unset, identity=values.unset, deployment_sid=values.unset, enabled=values.unset): data = values.of({ : friendly_name, : identity, : deployment_sid, : enabled, }) payload = self._version...
Update the DeviceInstance :param unicode friendly_name: A human readable description for this Device. :param unicode identity: An identifier of the Device user. :param unicode deployment_sid: The unique SID of the Deployment group. :param bool enabled: The enabled :returns: Upd...
350,274
def get_groups(self, limit=100, offset=0): url = self.TEAM_GROUPS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
Get all groups from your current team
350,275
def _update_phi(self): self.phi = self._compute_empirical_phi(self.beta) _checkParam(, self.phi, self.PARAMLIMITS, self.PARAMTYPES) self._eta_from_phi() dbeta = 1.0e-3 self.dphi_dbeta = scipy.misc.derivative(self._compute_empirical_phi, self.beta, dx=dbet...
Compute `phi`, `dphi_dbeta`, and `eta` from `g` and `frxy`.
350,276
def non_neighbors(graph, node, t=None): if graph.is_directed(): values = chain(graph.predecessors(node, t=t), graph.successors(node, t=t)) else: values = graph.neighbors(node, t=t) nbors = set(values) | {node} return (nnode for nnode in graph if nnode not in nbors)
Returns the non-neighbors of the node in the graph at time t. Parameters ---------- graph : DyNetx graph Graph to find neighbors. node : node The node whose neighbors will be returned. t : snapshot id (default=None) If None the non-neighbors...
350,277
def to_str(value): value = from_str(value) if value: value = value.replace(, ) if in value: value = + value + elif value is None: value = return value
Encode zfs safe string (used for name, path, ...)
350,278
def hook(self, id_num): json = None if int(id_num) > 0: url = self._build_url(, str(id_num), base_url=self._api) json = self._json(self._get(url), 200) return Hook(json, self) if json else None
Get a single hook. :param int id_num: (required), id of the hook :returns: :class:`Hook <github3.repos.hook.Hook>` if successful, otherwise None
350,279
def rename(self, new_folder_name): headers = self.headers endpoint = + self.id payload = + new_folder_name + r = requests.patch(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folde...
Renames the Folder to the provided name. Args: new_folder_name: A string of the replacement name. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: A new Folder representing the folder with ...
350,280
def set_locale(locale): *en_US.UTF-8 lc_ctl = salt.utils.systemd.booted(__context__) if lc_ctl and not (__grains__[] in [] and __grains__[] in [12]): return _localectl_set(locale) if in __grains__[]: if not __salt__[](): __salt__[]() __salt__[]( ...
Sets the current system locale CLI Example: .. code-block:: bash salt '*' locale.set_locale 'en_US.UTF-8'
350,281
def create_flat_start_model(feature_filename, state_stay_probabilities, symbol_list, output_model_directory, output_prototype_filename, htk_trace): create_prototype_m...
Creates a flat start model by using HCompV to compute the global mean and variance. Then uses these global mean and variance to create an N-state model for each symbol in the given list. :param feature_filename: The filename containing the audio and feature file pairs :param output_model_directory: The dir...
350,282
def add(self, delta): if self.lw is None: return Weights(lw=delta) else: return Weights(lw=self.lw + delta)
Increment weights: lw <-lw + delta. Parameters ---------- delta: (N,) array incremental log-weights
350,283
def handle_document(self, line: str, position: int, tokens: ParseResults) -> ParseResults: key = tokens[] value = tokens[] if key not in DOCUMENT_KEYS: raise InvalidMetadataException(self.get_line_number(), line, position, key, value) norm_key = DOCUMENT_KEYS[key] ...
Handle statements like ``SET DOCUMENT X = "Y"``. :raises: InvalidMetadataException :raises: VersionFormatWarning
350,284
def _get_annotation(c, loci): data_ann_temp = {} data_ann = [] counts = Counter() for lid in c.loci2seq: for dbi in list(loci[lid].db_ann.keys()): data_ann_temp[dbi] = {dbi: [loci[lid].db_ann[dbi].ann[x].name for x in list(loci[lid].db_ann[dbi...
get annotation of transcriptional units
350,285
def register_plugin(self): self.main.restore_scrollbar_position.connect( self.restore_scrollbar_position) self.main.add_dockwidget(self)
Register plugin in Spyder's main window
350,286
def recv_rpc(self, context, payload): logger.debug("Adding RPC payload to ControlBuffer queue: %s", payload) self.buf.put((, (context, payload))) with self.cv: self.cv.notifyAll()
Call from any thread
350,287
def parse(url_str): url_str = to_unicode(url_str) result = urlparse(url_str) netloc_parts = result.netloc.rsplit(, 1) if len(netloc_parts) == 1: username = password = None host = netloc_parts[0] else: user_and_pass = netloc_parts[0].split() if len(user_and_pass) ...
Extract all parts from a URL string and return them as a dictionary
350,288
def create(metric, *args, **kwargs): if callable(metric): return CustomMetric(metric, *args, **kwargs) elif isinstance(metric, list): composite_metric = CompositeEvalMetric() for child_metric in metric: composite_metric.add(create(child_metric, *args, **kwargs)) ...
Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a metric. - An instance of `EvalMetric`. ...
350,289
def omega_ratio(returns, risk_free=0.0, required_return=0.0, annualization=APPROX_BDAYS_PER_YEAR): if len(returns) < 2: return np.nan if annualization == 1: return_threshold = required_return elif required_return <= -1: return np.nan else: return_th...
Determines the Omega ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. risk_free : int, float Constant risk-free return throughout the period ...
350,290
def run_trial(self, trial_id = 0, until = None, return_env = True, **opts): until=until or self.max_time env=self.get_env(trial_id = trial_id, **opts) with utils.timer(.format(self.name, trial_id)): env.run(until) if self.dump and not self.dry_run: ...
Run a single trial of the simulation Parameters ---------- trial_id : int
350,291
def jaccard_sims(feature_list): sim_info_list = [] for feature_info in feature_list: md5_source = feature_info[] features_source = feature_info[] for feature_info in feature_list: md5_target = feature_info[] features_target = feature_info[] if md...
Compute Jaccard similarities between all the observations in the feature list. Args: feature_list: a list of dictionaries, each having structure as { 'md5' : String, 'features': list of Strings } Returns: list of dictionaries with structure as {'source': md5 Stri...
350,292
def rasterize(self, dest_resolution, *, polygonize_width=0, crs=WEB_MERCATOR_CRS, fill_value=None, bounds=None, dtype=None, **polygonize_kwargs): from telluric.georaster import merge_all, MergeStrategy from telluric.rasterization import rasterize, NODATA_DEPRECATION_W...
Binarize a FeatureCollection and produce a raster with the target resolution. Parameters ---------- dest_resolution: float Resolution in units of the CRS. polygonize_width : int, optional Width for the polygonized features (lines and points) in pixels, default to...
350,293
def change_password(self, password, new_password, email_code): message = Msg(EMsg.ClientPasswordChange3, extended=True) message.body.password = password message.body.new_password = new_password message.body.code = email_code resp = self.send_job_and_wait(message, timeou...
Change account's password :param password: current account password :type password: :class:`str` :param new_password: new account password :type new_password: :class:`str` :param email_code: confirmation code from email :type email_code: :class:`str` :return: ...
350,294
def run(self, func, tasks, func2=None): progress = 1 total = len(tasks) if len(tasks) == 0: return if func2 is not None: total = total * 2 finished = [] level1 = [] results = [] try: ...
run will send a list of tasks, a tuple with arguments, through a function. the arguments should be ordered correctly. :param func: the function to run with multiprocessing.pool :param tasks: a list of tasks, each a tuple of arguments to process :param func2:...
350,295
def __get_idxs(self, words): if self.bow: return list(itertools.chain.from_iterable( [self.positions[z] for z in words])) else: return self.positions[words]
Returns indexes to appropriate words.
350,296
def get_optimization_gradients(self): grad_array = self.fields.get("Opt point 1 Gradient at each geome") if grad_array is None: return [] else: return np.reshape(grad_array, (-1, len(self.molecule.numbers), 3))
Return the energy gradients of all geometries during an optimization
350,297
def write_members(self): s = "" objattributes = list(self.m_reprdict["positional"].keys()) objattributes.extend(list(self.m_reprdict["options"].keys())) objattributes.sort() for objattr in objattributes: s += 8 * " " + "self." + objattr + "=" if...
write_members
350,298
def get_meteor_ids(model, object_ids): meta = model._meta result = collections.OrderedDict( (str(obj_pk), None) for obj_pk in object_ids ) if isinstance(meta.pk, AleaIdField): return collections.OrderedDict( (obj_pk, obj_pk) for obj_pk in ob...
Return Alea ID mapping for all given ids of specified model.
350,299
def popone(self, key, *default): try: value = self[key] except KeyError: if default: return default[0] raise self._remove_pairs([self._key_ids[self._conform_key(key)].pop(0)]) return value
Remove first of given key and return corresponding value. If key is not found, default is returned if given. >>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)]) >>> m.popone('b') 2 >>> m.items() [('a', 1), ('b', 3), ('c', 4)] >>> m....