Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
372,500
def message(self, value): if value == self._defaults[] and in self._values: del self._values[] else: self._values[] = value
The message property. Args: value (string). the property value.
372,501
def parse_midi_event(self, fp): chunk_size = 0 try: ec = self.bytes_to_int(fp.read(1)) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldnt know what these events are supposed to do, but I keep finding if ev...
Parse a MIDI event. Return a dictionary and the number of bytes read.
372,502
def gzip_open_text(path, encoding=None): if encoding is None: encoding = sys.getdefaultencoding() assert os.path.isfile(path) is_compressed = False try: gzip.open(path, mode=).read(1) except IOError: pass else: is_compressed = True if is_compressed: ...
Opens a plain-text file that may be gzip'ed. Parameters ---------- path : str The file. encoding : str, optional The encoding to use. Returns ------- file-like A file-like object. Notes ----- Generally, reading gzip'ed files with gzip.open is very slow,...
372,503
def _set_snps(self, snps, build=37): self._snps = snps self._build = build
Set `_snps` and `_build` properties of this ``Individual``. Notes ----- Intended to be used internally to `lineage`. Parameters ---------- snps : pandas.DataFrame individual's genetic data normalized for use with `lineage` build : int bui...
372,504
def _compare_or_regex_search(a, b, regex=False): if not regex: op = lambda x: operator.eq(x, b) else: op = np.vectorize(lambda x: bool(re.search(b, x)) if isinstance(x, str) else False) is_a_array = isinstance(a, np.ndarray) is_b_array = isinstance(b, np.n...
Compare two array_like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array_like or scalar b : array_like or scalar regex : bool, default False ...
372,505
def video_pixel_noise_bottom(x, model_hparams, vocab_size): input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25) inputs = x if model_hparams.mode == tf.estimator.ModeKeys.TRAIN: background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3]) input_shape = common_layers.shape_list(...
Bottom transformation for video.
372,506
def get_grade_systems(self): if self.retrieved: raise errors.IllegalState() self.retrieved = True return objects.GradeSystemList(self._results, runtime=self._runtime)
Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.*
372,507
def precision(y, y_pred): tp = true_positives(y, y_pred) fp = false_positives(y, y_pred) return tp / (tp + fp)
Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. Returns: -------- precision : float
372,508
def create_user(self, Name, EmailAddress, **kwargs): return self.edit_user(, Name=Name, EmailAddress=EmailAddress, **kwargs)
Create user (undocumented API feature). :param Name: User name (login for privileged, required) :param EmailAddress: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequest: When user a...
372,509
def url_to_string(url): try: page = urllib2.urlopen(url) except (urllib2.HTTPError, urllib2.URLError) as err: ui.error(c.MESSAGES["url_unreachable"], err) sys.exit(1) return page
Return the contents of a web site url as a string.
372,510
def tableExists(self, login, tableName): self.send_tableExists(login, tableName) return self.recv_tableExists()
Parameters: - login - tableName
372,511
def subproc_call(cmd, timeout=None): try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command timeout!".format(cmd)) logger.warn(e....
Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1.
372,512
def div_img(img1, div2): if is_img(div2): return img1.get_data()/div2.get_data() elif isinstance(div2, (float, int)): return img1.get_data()/div2 else: raise NotImplementedError( .format(type(img1), ...
Pixelwise division or divide by a number
372,513
def combination_step(self): tprv = self.t self.t = 0.5 * float(1. + np.sqrt(1. + 4. * tprv**2)) if not self.opt[]: self.Yprv = self.Y.copy() self.Y = self.X + ((tprv - 1.) / self.t) * (self.X - self.Xprv)
Build next update by a smart combination of previous updates. (standard FISTA :cite:`beck-2009-fast`).
372,514
def uniq(seq): seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
Return a copy of seq without duplicates.
372,515
def visit(self, func): base_len = len(self.name) return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/")))
Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() ...
372,516
def genchanges(self): chparams = self.params.copy() debpath = os.path.join(self.buildroot, self.rule.output_files[0]) chparams.update({ : .format(**chparams), : self._metahash().hexdigest(), : util.hash_file(debpath, hashlib.sha1()).hexdigest(), ...
Generate a .changes file for this package.
372,517
def hook(self, function, dependencies=None): if not isinstance(dependencies, (Iterable, type(None), str)): raise TypeError("Invalid list of dependencies provided!") if not hasattr(function, "__deps__"): function.__deps__ = dependencies ...
Tries to load a hook Args: function (func): Function that will be called when the event is called Kwargs: dependencies (str): String or Iterable with modules whose hooks should be called before this one Raises: :class:TypeError Note that the depend...
372,518
def spin_in_system(incl, long_an): return np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0.,0.,1.])))
Spin in the plane of sky of a star given its inclination and "long_an" incl - inclination of the star in the plane of sky long_an - longitude of ascending node (equator) of the star in the plane of sky Return: spin - in plane of sky
372,519
def rpm_versioned_name(cls, name, version, default_number=False): regexp = re.compile(r) auto_provides_regexp = re.compile(r) if (not version or version == cls.get_default_py_version() and not default_number): found = regexp.search(name) ...
Properly versions the name. For example: rpm_versioned_name('python-foo', '26') will return python26-foo rpm_versioned_name('pyfoo, '3') will return python3-pyfoo If version is same as settings.DEFAULT_PYTHON_VERSION, no change is done. Args: name: name to v...
372,520
def _convert_localized_value(value: LocalizedValue) -> LocalizedIntegerValue: integer_values = {} for lang_code, _ in settings.LANGUAGES: local_value = value.get(lang_code, None) if local_value is None or local_value.strip() == : local_value = None ...
Converts from :see:LocalizedValue to :see:LocalizedIntegerValue.
372,521
def set_password(cls, instance, raw_password): hash_callable = getattr( instance.passwordmanager, "hash", instance.passwordmanager.encrypt ) password = hash_callable(raw_password) if six.PY2: instance.user_password = password.decode("utf8") ...
sets new password on a user using password manager :param instance: :param raw_password: :return:
372,522
def visit_ifexp(self, node, parent): newnode = nodes.IfExp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.test, newnode), self.visit(node.body, newnode), self.visit(node.orelse, newnode), ) return newnode
visit a IfExp node by returning a fresh instance of it
372,523
def reference_cluster(envs, name): edges = [ set([env[], ref]) for env in envs for ref in env[] ] prev, cluster = set(), set([name]) while prev != cluster: prev = set(cluster) to_visit = [] for edge in edges: if cluster & edge: ...
Return set of all env names referencing or referenced by given name. >>> cluster = sorted(reference_cluster([ ... {'name': 'base', 'refs': []}, ... {'name': 'test', 'refs': ['base']}, ... {'name': 'local', 'refs': ['test']}, ... ], 'test')) >>> cluster == ['base', 'local', 'test...
372,524
def validate_href(image_href): try: response = requests.head(image_href) if response.status_code != http_client.OK: raise exception.ImageRefValidationFailed( image_href=image_href, reason=("Got HTTP code %s instead of 200 i...
Validate HTTP image reference. :param image_href: Image reference. :raises: exception.ImageRefValidationFailed if HEAD request failed or returned response code not equal to 200. :returns: Response to HEAD request.
372,525
async def connect( cls, url, *, apikey=None, insecure=False): profile, session = await bones.SessionAPI.connect( url=url, apikey=apikey, insecure=insecure) return profile, cls(session)
Make an `Origin` by connecting with an apikey. :return: A tuple of ``profile`` and ``origin``, where the former is an unsaved `Profile` instance, and the latter is an `Origin` instance made using the profile.
372,526
def crop_to_bounding_box(image, offset_height, offset_width, target_height, target_width, dynamic_shape=False): image = ops.convert_to_tensor(image, name=) _Check3DImage(image, require_static=(not dynamic_shape)) height, width, _ = _ImageDimensions(image, dynamic_shape=dynamic_shape) ...
Crops an image to a specified bounding box. This op cuts a rectangular part out of `image`. The top-left corner of the returned image is at `offset_height, offset_width` in `image`, and its lower-right corner is at `offset_height + target_height, offset_width + target_width`. Args: image: 3-D tensor wit...
372,527
def format_box(title, ch="*"): lt = len(title) return [(ch * (lt + 8)), (ch * 3 + " " + title + " " + ch * 3), (ch * (lt + 8)) ]
Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** *************************
372,528
def format_error(module, error): logging.error(module) print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(, )) exit(1)
Format the error for the given module.
372,529
def with_retry(cls, methods): retry_with_backoff = retry( retry_on_exception=lambda e: isinstance(e, BotoServerError), wait_exponential_multiplier=1000, wait_exponential_max=10000 ) for method in methods: m = getattr(cls, method, None) if isinstance(m, collection...
Wraps the given list of methods in a class with an exponential-back retry mechanism.
372,530
def get_value(self, name): ns = self._get_current_namespace() value = ns[name] try: self.send_spyder_msg(, data=value) except: self.send_spyder_msg(, data=None) self._do_publish_pdb_state = False
Get the value of a variable
372,531
def mrc_to_marc(mrc): lines = [ line for line in mrc.splitlines() if line.strip() ] def split_to_parts(lines): for line in lines: first_part, second_part = line.split(" L ", 1) yield line, first_part, second_part.lstrip() control_lines...
Convert MRC data format to MARC XML. Args: mrc (str): MRC as string. Returns: str: XML with MARC.
372,532
def wait(self): finished_pids = [ ] while self.running_procs: finished_pids.extend(self.poll()) return finished_pids
wait until all jobs finish and return a list of pids
372,533
def initialize(self, conf, ctx): config = get_config()[] elasticsearch_class = import_name(config[]) self.es = elasticsearch_class(**config[]) self.index = config[] self.doc_type = config[]
Initialization steps: 1. Prepare elasticsearch connection, including details for indexing.
372,534
def k_weights_int(self): nk = np.prod(self.k_mesh) _weights = self.k_weights * nk weights = np.rint(_weights).astype() assert (np.abs(weights - _weights) < 1e-7 * nk).all() return np.array(weights, dtype=)
Returns ------- ndarray Geometric k-point weights (number of arms of k-star in BZ). dtype='intc' shape=(irreducible_kpoints,)
372,535
def update_screen_id(self): self.status_update_event.clear() try: self.send_message({MESSAGE_TYPE: TYPE_GET_SCREEN_ID}) except UnsupportedNamespace: pass self.status_update_event.wait() self.status_update_event.clear()
Sends a getMdxSessionStatus to get the screenId and waits for response. This function is blocking If connected we should always get a response (send message will launch app if it is not running).
372,536
def list_objects(self): for i in self._execute(): _id, code = i yield _id, code, self.deserialize(code)
list the entire of objects with their (id, serialized_form, actual_value)
372,537
def _example_short_number(region_code): metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = metadata.short_code if desc.example_number is not None: return desc.example_number return U_EMPTY_STRING
Gets a valid short number for the specified region. Arguments: region_code -- the region for which an example short number is needed. Returns a valid short number for the specified region. Returns an empty string when the metadata does not contain such information.
372,538
def move_committees(src, dest): comm, sub_comm = import_committees(src) save_committees(comm, dest) save_subcommittees(comm, dest)
Import stupid yaml files, convert to something useful.
372,539
def createTemporaryCredentials(clientId, accessToken, start, expiry, scopes, name=None): for scope in scopes: if not isinstance(scope, six.string_types): raise exceptions.TaskclusterFailure() if expiry - start > datetime.timedelta(days=31): raise exceptions.Taskclus...
Create a set of temporary credentials Callers should not apply any clock skew; clock drift is accounted for by auth service. clientId: the issuing clientId accessToken: the issuer's accessToken start: start time of credentials (datetime.datetime) expiry: expiration time of credentials, (dateti...
372,540
async def fetch_bikes() -> List[dict]: async with ClientSession() as session: try: async with session.get() as request: document = document_fromstring(await request.text()) except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_...
Gets the full list of bikes from the bikeregister site. The data is hidden behind a form post request and so we need to extract an xsrf and session token with bs4. todo add pytest tests :return: All the currently registered bikes. :raise ApiError: When there was an error connecting to the API.
372,541
def add_dashboard_tag(self, id, tag_value, **kwargs): kwargs[] = True if kwargs.get(): return self.add_dashboard_tag_with_http_info(id, tag_value, **kwargs) else: (data) = self.add_dashboard_tag_with_http_info(id, tag_value, **kwargs) return dat...
Add a tag to a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_dashboard_tag(id, tag_value, async_req=True) >>> result = thread.get() ...
372,542
def _process_callback(self, statefield): try: session_csrf_token = session.get() state = _json_loads(urlsafe_b64decode(request.args[].encode())) csrf_token = state[] code = request.args[] except (KeyError, ValueError): logge...
Exchange the auth code for actual credentials, then redirect to the originally requested page.
372,543
def chipqc(bam_file, sample, out_dir): sample_name = dd.get_sample_name(sample) logger.warning("ChIPQC is unstable right now, if it breaks, turn off the tool.") if utils.file_exists(out_dir): return _get_output(out_dir) with tx_tmpdir() as tmp_dir: rcode = _sample_template(sample, t...
Attempt code to run ChIPQC bioconductor packate in one sample
372,544
def i2c_master_read(self, addr, length, flags=I2C_NO_FLAGS): data = array.array(, (0,) * length) status, rx_len = api.py_aa_i2c_read_ext(self.handle, addr, flags, length, data) _raise_i2c_status_code_error_if_failure(status) del data[rx_len:] return byte...
Make an I2C read access. The given I2C device is addressed and clock cycles for `length` bytes are generated. A short read will occur if the device generates an early NAK. The transaction is finished with an I2C stop condition unless the I2C_NO_STOP flag is set.
372,545
def imshow(self, array, *args, **kwargs): if isinstance(array, Array2D): return self._imshow_array2d(array, *args, **kwargs) image = super(Axes, self).imshow(array, *args, **kwargs) self.autoscale(enable=None, axis=, tight=None) return image
Display an image, i.e. data on a 2D regular raster. If ``array`` is a :class:`~gwpy.types.Array2D` (e.g. a :class:`~gwpy.spectrogram.Spectrogram`), then the defaults are _different_ to those in the upstream :meth:`~matplotlib.axes.Axes.imshow` method. Namely, the defaults are -...
372,546
def sys_path(self): from .vendor.vistir.compat import JSONDecodeError current_executable = vistir.compat.Path(sys.executable).as_posix() if not self.python or self.python == current_executable: return sys.path elif any([sys.prefix == self.prefix, not self.is_venv]):...
The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list
372,547
def buildDQMasks(imageObjectList,configObj): if not isinstance(imageObjectList, list): imageObjectList = [imageObjectList] for img in imageObjectList: img.buildMask(configObj[], configObj[])
Build DQ masks for all input images.
372,548
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool: ancestors = node.ancestors() if hasattr(node, "ancestors") else [] for ancestor in itertools.chain([node], ancestors): if ( ancestor.name in ("Exception", "BaseException") and ancestor.root().name == EXCEPTI...
Return true if the given class node is subclass of exceptions.Exception.
372,549
def _Kw(rho, T): if rho < 0 or rho > 1250 or T < 273.15 or T > 1073.15: raise NotImplementedError("Incoming out of bound") d = rho/1000. Mw = 18.015268 gamma = [6.1415e-1, 4.825133e4, -6.770793e4, 1.01021e7] pKg = 0 for i, g in enumerate(gamma): pKg += g/T*...
Equation for the ionization constant of ordinary water Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] Returns ------- pKw : float Ionization constant in -log10(kw), [-] Notes ------ Raise :class:`NotImplementedError` if in...
372,550
def import_class(clspath): modpath, clsname = split_clspath(clspath) __import__(modpath) module = sys.modules[modpath] return getattr(module, clsname)
Given a clspath, returns the class. Note: This is a really simplistic implementation.
372,551
def get_next_holiday(self, division=None, date=None): date = date or datetime.date.today() for holiday in self.get_holidays(division=division): if holiday[] > date: return holiday
Returns the next known bank holiday :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: dict
372,552
def extraSelections(self): if not isinstance(self._mode, Normal): return [] selection = QTextEdit.ExtraSelection() selection.format.setBackground(QColor()) selection.format.setForeground(QColor()) selection.cursor = self._qpart.textCursor() selection...
In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
372,553
def data_complete(datadir, sitedir, get_container_name): if any(not path.isdir(sitedir + x) for x in (, , )): return False if docker.is_boot2docker():
Return True if the directories and containers we're expecting are present in datadir, sitedir and containers
372,554
def scansion_prepare(self,meter=None,conscious=False): import prosodic config=prosodic.config if not meter: if not hasattr(self,): return x=getattr(self,) if not x.keys(): return meter=x.keys()[0] ckeys="\t".join(sorted([str(x) for x in meter.constraints])) self.om("\t".join([makeminlength(st...
Print out header column for line-scansions for a given meter.
372,555
def _get_anchor_data(anchor_data, glyphSet, components, anchor_name): anchors = [] for component in components: for anchor in glyphSet[component.baseGlyph].anchors: if anchor.name == anchor_name: anchors.append((anchor, component)) break if len(ancho...
Get data for an anchor from a list of components.
372,556
def to_uri(url): parts = WbUrl.FIRST_PATH.split(url, 1) sep = url[len(parts[0])] if len(parts) > 1 else None scheme_dom = unquote_plus(parts[0]) if six.PY2 and isinstance(scheme_dom, six.binary_type): if scheme_dom == parts[0]: return url ...
Converts a url to an ascii %-encoded form where: - scheme is ascii, - host is punycode, - and remainder is %-encoded Not using urlsplit to also decode partially encoded scheme urls
372,557
def swipe(self, p1, p2=None, direction=None, duration=2.0): try: duration = float(duration) except ValueError: raise ValueError(.format(repr(duration))) if not (0 <= p1[0] <= 1) or not (0 <= p1[1] <= 1): raise InvalidOperationException(.format(repr(...
Perform swipe action on target device from point to point given by start point and end point, or by the direction vector. At least one of the end point or direction must be provided. The coordinates (x, y) definition for points is the same as for ``click`` event. The components of the direction...
372,558
def GetEntries(self, cut=None, weighted_cut=None, weighted=False): if weighted_cut: hist = Hist(1, -1, 2) branch = self.GetListOfBranches()[0].GetName() weight = self.GetWeight() self.SetWeight(1) self.Draw(.format(branch, branch, hist.GetName...
Get the number of (weighted) entries in the Tree Parameters ---------- cut : str or rootpy.tree.cut.Cut, optional (default=None) Only entries passing this cut will be included in the count weighted_cut : str or rootpy.tree.cut.Cut, optional (default=None) Apply ...
372,559
def update_job(job_id): data = request.get_json(force=True) try: current_app.apscheduler.modify_job(job_id, **data) job = current_app.apscheduler.get_job(job_id) return jsonify(job) except JobLookupError: return jsonify(dict(error_message= % job_id), status=404) ex...
Updates a job.
372,560
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None: "Callback function that writes epoch end appropriate data to Tensorboard." self._write_metrics(iteration=iteration, last_metrics=last_metrics)
Callback function that writes epoch end appropriate data to Tensorboard.
372,561
def _knn(self, i, X, high_dim=True): knns = [] for j in range(X.shape[0]): if j != i: if high_dim: distance = self._high_dim_sim(X[i], X[j], idx=i) else: distance = self._low_dim_sim(X[i], X[j]) ...
Performs KNN search based on high/low-dimensional similarity/distance measurement
372,562
def set_debug(self, debug=1): self._check_if_ready() self.debug = debug self.main_loop.debug = debug
Set the debug level. :type debug: int :param debug: The debug level.
372,563
def _configure_node(): print("") msg = "Cooking..." if env.parallel: msg = "[{0}]: {1}".format(env.host_string, msg) print(msg) with settings(hide(, , ), warn_only=True): sudo("mv {0} {0}.1".format(LOGFILE)) cmd = "RUBYOPT=-Ku chef-solo" if whyrun: cmd ...
Exectutes chef-solo to apply roles and recipes to a node
372,564
def set_load_resistance(self, resistance): new_val = int(round(resistance * 100)) if not 0 <= new_val <= 50000: raise ValueError("Load Resistance should be between 0-500 ohms") self._load_mode = self.SET_TYPE_RESISTANCE self._load_value = new_val self.__set_p...
Changes load to resistance mode and sets resistance value. Rounds to nearest 0.01 Ohms :param resistance: Load Resistance in Ohms (0-500 ohms) :return: None
372,565
def value_compare(left, right, ordering=1): try: ltype = left.__class__ rtype = right.__class__ if ltype in list_types or rtype in list_types: if left == None: return ordering elif right == None: return - ordering le...
SORT VALUES, NULL IS THE LEAST VALUE :param left: LHS :param right: RHS :param ordering: (-1, 0, 1) TO AFFECT SORT ORDER :return: The return value is negative if x < y, zero if x == y and strictly positive if x > y.
372,566
async def download_media(self, *args, **kwargs): return await self._client.download_media(self, *args, **kwargs)
Downloads the media contained in the message, if any. Shorthand for `telethon.client.downloads.DownloadMethods.download_media` with the ``message`` already set.
372,567
def _removeOldBackRefs(senderkey, signal, receiver, receivers): try: index = receivers.index(receiver) except ValueError: return False else: oldReceiver = receivers[index] del receivers[index] found = 0 signals = connections.get(signal) i...
Kill old sendersBack references from receiver This guards against multiple registration of the same receiver for a given signal and sender leaking memory as old back reference records build up. Also removes old receiver instance from receivers
372,568
def min_item(self): if self.is_empty(): raise ValueError("Tree is empty") node = self._root while node.left is not None: node = node.left return node.key, node.value
Get item with min key of tree, raises ValueError if tree is empty.
372,569
def update(self, retry=2) -> None: try: _LOGGER.debug("Updating device state.") key = ON_KEY if not self._flip_on_off else OFF_KEY self.state = self._device.readCharacteristic(HANDLE) == key except (bluepy.btle.BTLEException, AttributeError): if r...
Synchronize state with switch.
372,570
def frombed(args): p = OptionParser(frombed.__doc__) p.add_option("--gapsize", default=100, type="int", help="Insert gaps of size [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args gapsize = opts.g...
%prog frombed bedfile Generate AGP file based on bed file. The bed file must have at least 6 columns. With the 4-th column indicating the new object.
372,571
def __get_extra_extension_classes(paths): extra_classes = [] wset = pkg_resources.WorkingSet([]) distributions, _ = wset.find_plugins(pkg_resources.Environment(paths)) for dist in distributions: sys.path.append(dist.location) wset.add(dist) for entry_point in wset.iter_entry_p...
Banana banana
372,572
def keyring_parser(path): sections = [] with open(path) as keyring: lines = keyring.readlines() for line in lines: line = line.strip() if line.startswith() and line.endswith(): sections.append(line.strip()) return sections
This is a very, very, dumb parser that will look for `[entity]` sections and return a list of those sections. It is not possible to parse this with ConfigParser even though it is almost the same thing. Since this is only used to spit out warnings, it is OK to just be naive about the parsing.
372,573
def shelter_find(self, **kwargs): def shelter_find_parser(root, has_records): for shelter in root.find("shelters"): has_records["has_records"] = True record = {} for field in shelter: record[field.tag] = field...
shelter.find wrapper. Returns a generator of shelter record dicts matching your search criteria. :rtype: generator :returns: A generator of shelter record dicts. :raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have reached the maximum number of records your cr...
372,574
def login(self, params): if in params: return self.login_with_password(params) elif in params: return self.login_with_resume_token(params) else: self.auth_failed(**params)
Login either with resume token or password.
372,575
def GET_AUTH(self, courseid): course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) return self.show_page(course, web.input())
GET request
372,576
def delete_resource_subscription(self, device_id, _resource_path, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) else: (data) = self.delete_resource_subscription_with_ht...
Remove a subscription # noqa: E501 To remove an existing subscription from a resource path. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501 This method makes a ...
372,577
def K(self): K = np.eye(3, dtype=np.float64) K[0, 0] = self.focal[0] K[1, 1] = self.focal[1] K[0, 2] = self.resolution[0] / 2.0 K[1, 2] = self.resolution[1] / 2.0 return K
Get the intrinsic matrix for the Camera object. Returns ----------- K : (3, 3) float Intrinsic matrix for camera
372,578
def save_genome_fitness(self, delimiter=, filename=, with_cross_validation=False): with open(filename, ) as f: w = csv.writer(f, delimiter=delimiter) best_fitness = [c.fitness for c in self.most...
Saves the population's best and average fitness.
372,579
def alterar(self, id_logicalenvironment, name): if not is_valid_int_param(id_logicalenvironment): raise InvalidParameterError( u) url = + str(id_logicalenvironment) + logical_environment_map = dict() logical_environment_map[] = name code...
Change Logical Environment from by the identifier. :param id_logicalenvironment: Identifier of the Logical Environment. Integer value and greater than zero. :param name: Logical Environment name. String with a minimum 2 and maximum of 80 characters :return: None :raise InvalidParamete...
372,580
def get_output_file(self, in_file, instance, field, **kwargs): return NamedTemporaryFile(mode=, suffix= % ( get_model_name(instance), field.name, self.get_ext()), delete=False)
Creates a temporary file. With regular `FileSystemStorage` it does not need to be deleted, instaed file is safely moved over. With other cloud based storage it is a good idea to set `delete=True`.
372,581
def create_csr(ca_name, bits=2048, CN=, C=, ST=, L=, O=, OU=None, emailAddress=None, subjectAltName=None, cacert_path=None, ca_filename=None, ...
Create a Certificate Signing Request (CSR) for a particular Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default i...
372,582
def greedy(problem, graph_search=False, viewer=None): return _search(problem, BoundedPriorityQueue(), graph_search=graph_search, node_factory=SearchNodeHeuristicOrdered, graph_replace_when_better=True, viewer=viewer)
Greedy search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
372,583
def infer_module_name(filename, fspath): filename, _ = os.path.splitext(filename) for f in fspath: short_name = f.relative_path(filename) if short_name: if short_name.endswith(os.path.sep + "__init__"): short_name = short_name[:short_name.rfind(os.pa...
Convert a python filename to a module relative to pythonpath.
372,584
def sign(hash,priv,k=0): f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023ec05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde037404663045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7 if k == 0: ...
Returns a DER-encoded signature from a input of a hash and private key, and optionally a K value. Hash and private key inputs must be 64-char hex strings, k input is an int/long. >>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e' >>> p = 'c05694a7af0e01dceb63e5912a415c28d3f...
372,585
def parse(self, *args, **kw): ev = in kw and kw.pop() if ev and not isinstance(ev, int): raise TypeError("error exit value should be an integer") try: self.cmdline = self.parser.parse_args(*args, **kw) except OptParseError: if ev: ...
Parse command line, fill `fuse_args` attribute.
372,586
def get_conversation_reference(activity: Activity) -> ConversationReference: return ConversationReference(activity_id=activity.id, user=copy(activity.from_property), bot=copy(activity.recipient), ...
Returns the conversation reference for an activity. This can be saved as a plain old JSON object and then later used to message the user proactively. Usage Example: reference = TurnContext.get_conversation_reference(context.request) :param activity: :return:
372,587
def stop(self): yield from self._stop_ubridge() with (yield from self._execute_lock): self._hw_virtualization = False if self.is_running(): log.info(.format(self._name, self._process.pid)) try: if self.acp...
Stops this QEMU VM.
372,588
def glob_by_extensions(directory, extensions): directorycheck(directory) files = [] xt = files.extend for ex in extensions: xt(glob.glob(.format(directory, ex))) return files
Returns files matched by all extensions in the extensions list
372,589
def add(self, steamid_or_accountname_or_email): m = MsgProto(EMsg.ClientAddFriend) if isinstance(steamid_or_accountname_or_email, (intBase, int)): m.body.steamid_to_add = steamid_or_accountname_or_email elif isinstance(steamid_or_accountname_or_email, SteamUser): ...
Add/Accept a steam user to be your friend. When someone sends you an invite, use this method to accept it. :param steamid_or_accountname_or_email: steamid, account name, or email :type steamid_or_accountname_or_email: :class:`int`, :class:`.SteamID`, :class:`.SteamUser`, :class:`str` ....
372,590
def killCellRegion(self, centerColumn, radius): self.deadCols = topology.wrappingNeighborhood(centerColumn, radius, self._columnDimensions) self.deadColumnInputSpan = self.getConnectedSpan(self.deadCols) self.removeDead...
Kill cells around a centerColumn, within radius
372,591
def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs): kwargs[] = True if kwargs.get(): return self.get_namespaced_custom_object_with_http_info(group, version, namespace, plural, name, **kwargs) else: (data) = self.get_namespac...
Returns a namespace scoped custom object This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_namespaced_custom_object(group, version, namespace, plural, name, async_req=True) >>> result = thread.ge...
372,592
def train_rf_classifier( collected_features, test_fraction=0.25, n_crossval_iterations=20, n_kfolds=5, crossval_scoring_metric=, classifier_to_pickle=None, nworkers=-1, ): accuracy if (isinstance(collected_features,str) and os.path.exists(collect...
This gets the best RF classifier after running cross-validation. - splits the training set into test/train samples - does `KFold` stratified cross-validation using `RandomizedSearchCV` - gets the `RandomForestClassifier` with the best performance after CV - gets the confusion matrix for the test set ...
372,593
def efficient_risk(self, target_risk, risk_free_rate=0.02, market_neutral=False): if not isinstance(target_risk, float) or target_risk < 0: raise ValueError("target_risk should be a positive float") if not isinstance(risk_free_rate, (int, float)): raise ValueError("risk_...
Calculate the Sharpe-maximising portfolio for a given volatility (i.e max return for a target risk). :param target_risk: the desired volatility of the resulting portfolio. :type target_risk: float :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02 :type...
372,594
def integrate(self, min, max, attr=None, info={}): if numpy.isscalar(min): min = [min for i in range(self.ndims)] if numpy.isscalar(max): max = [max for i in range(self.ndims)] min = numpy.array(min, dtype=, order=) max = numpy.array(max, dtype=, order=)...
Calculate the total number of points between [min, max). If attr is given, also calculate the sum of the weight. This is a M log(N) operation, where M is the number of min/max queries and N is number of points.
372,595
def c_metadata(api, args, verbose=False): obj = api.get_object(args[].split()[-1]) if not set_metadata(args[], obj): return json.dumps(obj.metadata.read(), indent=4)
Set or get metadata associated with an object:: usage: cdstar metadata <URL> [<JSON>] <JSON> Path to metadata in JSON, or JSON literal.
372,596
def transcripts(self): transcript_id_results = self.db.query( select_column_names=[], filter_column=, filter_value=self.id, feature=, distinct=False, required=False) return [ self.gen...
Property which dynamically construct transcript objects for all transcript IDs associated with this gene.
372,597
def thread_partition_array(x): "Partition work arrays for multithreaded addition and multiplication" n_threads = get_threadpool_size() if len(x.shape) > 1: maxind = x.shape[1] else: maxind = x.shape[0] bounds = np.array(np.linspace(0, maxind, n_threads + 1), dtype=) cmin = bounds...
Partition work arrays for multithreaded addition and multiplication
372,598
def parseline(self, line: str) -> Tuple[str, str, str]: statement = self.statement_parser.parse_command_only(line) return statement.command, statement.args, statement.command_and_args
Parse the line into a command name and a string containing the arguments. NOTE: This is an override of a parent class method. It is only used by other parent class methods. Different from the parent class method, this ignores self.identchars. :param line: line read by readline :retur...
372,599
def NetshStaticIp(interface, ip=u, subnet=u, gw=u): args = [ , , , , , , interface, , ip, subnet, gw, ] res = client_utils_common.Execute( , args, time_limit=-1, bypass_whitelist=True) return res
Changes interface to a staticly set IP. Sets IP configs to local if no paramaters passed. Args: interface: Name of the interface. ip: IP address. subnet: Subnet mask. gw: IP address of the default gateway. Returns: A tuple of stdout, stderr, exit_status.