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 event_type < 8: raise FormatError( % (event_type, self.bytes_read)) if event_type == 0x0f: try: meta_event = self.bytes_to_int(fp.read(1)) (length, chunk_delta) = self.parse_varbyte_as_int(fp) data = fp.read(length) chunk_size += 1 + chunk_delta + length self.bytes_read += 1 + length except: raise IOError("Couldneventmeta_eventdatat read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) return ({: event_type, : channel, : param1}, chunk_size) else: try: param1 = fp.read(1) param2 = fp.read(1) chunk_size += 2 self.bytes_read += 2 except: raise IOError("Couldneventchannelparam1param2': param2}, chunk_size)
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: if six.PY2: import codecs zf = gzip.open(path, ) reader = codecs.getreader(encoding) fh = reader(zf) else: fh = gzip.open(path, mode=, encoding=encoding) else: fh = open(path, mode=, encoding=encoding) return fh
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, and it is preferable to pipe the file into the python script using ``gunzip -c``. The script then reads the file from stdin.
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 build of this ``Individual``'s SNPs
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.ndarray) if is_datetimelike_v_numeric(a, b): result = False elif is_numeric_v_string_like(a, b): result = False else: result = op(a) if is_scalar(result) and (is_a_array or is_b_array): type_names = [type(a).__name__, type(b).__name__] if is_a_array: type_names[0] = .format(dtype=a.dtype) if is_b_array: type_names[1] = .format(dtype=b.dtype) raise TypeError( "Cannot compare types {a!r} and {b!r}".format(a=type_names[0], b=type_names[1])) return result
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 Returns ------- mask : array_like of bool
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(inputs) input_size = tf.reduce_prod(input_shape[:-1]) input_mask = tf.multinomial( tf.log([[input_noise, 1.-input_noise]]), input_size) input_mask = tf.reshape(tf.cast(input_mask, tf.int32), input_shape[:-1]+[1]) inputs = inputs * input_mask + background * (1 - input_mask) return video_bottom(inputs, model_hparams, vocab_size)
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 already exists :raises InvalidUse: When invalid fields are set
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.output.decode()) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode()) return e.output, e.returncode except Exception: logger.warn("Command failed to run.".format(cmd)) return "", -2
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), img1, type(div2), div2))
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() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(name): ... print(name) >>> g1.visit(print_visitor) bar bar/baz bar/quux foo >>> g3.visit(print_visitor) baz quux
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(), : util.hash_file(debpath, hashlib.sha256() ).hexdigest(), : util.hash_file(debpath, hashlib.md5()).hexdigest(), : os.stat(debpath).st_size, : debpath.split()[-1], }) output = .join([ , , , , , , , , , , , , , , , , , , , , , ]).format(**chparams) return output
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 if self.isloaded(function.__deps__): self.append(function) else: self._later.append(function) for ext in self._later: if self.isloaded(ext.__deps__): self._later.remove(ext) self.hook(ext)
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 dependencies are module-wide, that means that if `parent.foo` and `parent.bar` are both subscribed to `example` event and `child` enumerates `parent` as dependcy, **both** `foo` and `bar` must be called in order for the dependcy to get resolved.
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) if found and found.group(2) != : if not in cls.template: return .format(regexp.search(name).group(2)) return name versioned_name = name if version: if regexp.search(name): versioned_name = re.sub(r, .format( version), name) elif auto_provides_regexp.search(name): versioned_name = re.sub( r, .format( version), name) else: versioned_name = .format(version, name) if ( in cls.template and version != cls.get_default_py_version()): versioned_name = versioned_name.replace(.format( version), .format(version)) return versioned_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 version version: version or None Returns: Versioned name or the original name if given version is None.
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 try: integer_values[lang_code] = int(local_value) except (ValueError, TypeError): integer_values[lang_code] = None return LocalizedIntegerValue(integer_values)
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") else: instance.user_password = password cls.regenerate_security_code(instance)
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: cluster |= edge else: to_visit.append(edge) edges = to_visit return cluster
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'] True
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 in response to " "HEAD request." % response.status_code)) except requests.RequestException as e: raise exception.ImageRefValidationFailed(image_href=image_href, reason=e) return response
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) if not dynamic_shape: if offset_width < 0: raise ValueError() if offset_height < 0: raise ValueError() if width < (target_width + offset_width): raise ValueError() if height < (target_height + offset_height): raise ValueError() cropped = array_ops.slice(image, array_ops.pack([offset_height, offset_width, 0]), array_ops.pack([target_height, target_width, -1])) return cropped
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 with shape `[height, width, channels]` offset_height: Vertical coordinate of the top-left corner of the result in the input. offset_width: Horizontal coordinate of the top-left corner of the result in the input. target_height: Height of the result. target_width: Width of the result. dynamic_shape: Whether the input image has undertermined shape. If set to `True`, shape information will be retrieved at run time. Default to `False`. Returns: 3-D tensor of image with shape `[target_height, target_width, channels]` Raises: ValueError: If the shape of `image` is incompatible with the `offset_*` or `target_*` arguments, and `dynamic_shape` is set to `False`.
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, collections.Callable): setattr(cls, method, retry_with_backoff(m)) return cls
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 = [] data_lines = [] for line, first_part, second_part in split_to_parts(lines): if second_part.startswith("$"): data_lines.append(line) else: control_lines.append(line) record = MARCXMLRecord() record.oai_marc = True for line, descr, content in split_to_parts(control_lines): record.controlfields[descr.strip()[:3]] = content def get_subfield_dict(line): fields = ( (field[0], field[1:]) for field in line.split("$$")[1:] ) fields_dict = defaultdict(list) for key, val in fields: fields_dict[key].append(val) return fields_dict for line, descr, content_line in split_to_parts(data_lines): name = descr[:3] i1 = descr[3] i2 = descr[4] record.add_data_field( name, i1, i2, get_subfield_dict(content_line) ) return record.to_XML()
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.TaskclusterFailure() cert = dict( version=1, scopes=scopes, start=calendar.timegm(start.utctimetuple()) * 1000, expiry=calendar.timegm(expiry.utctimetuple()) * 1000, seed=utils.slugId().encode() + utils.slugId().encode(), ) if name: cert[] = utils.toStr(clientId) sig = [ + utils.toStr(cert[])] if name: sig.extend([ + utils.toStr(name), + utils.toStr(clientId), ]) sig.extend([ + utils.toStr(cert[]), + utils.toStr(cert[]), + utils.toStr(cert[]), ] + scopes) sigStr = .join(sig).encode() if isinstance(accessToken, six.text_type): accessToken = accessToken.encode() sig = hmac.new(accessToken, sigStr, hashlib.sha256).digest() cert[] = utils.encodeStringForB64Header(sig) newToken = hmac.new(accessToken, cert[], hashlib.sha256).digest() newToken = utils.makeB64UrlSafe(utils.encodeStringForB64Header(newToken)).replace(b, b) return { : name or clientId, : newToken, : utils.dumpJson(cert), }
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, (datetime.datetime) scopes: list of scopes granted name: credential name (optional) Returns a dictionary in the form: { 'clientId': str, 'accessToken: str, 'certificate': str}
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_err.host}") raise ApiError(f"Could not connect to {con_err.host}") token = document.xpath("//input[@name=]") if len(token) != 1: raise ApiError(f"CouldncookieXSRF-TOKEN={xsrf_token}; laravel_session={laravel_session}originhttps://www.bikeregister.comaccept-encodinggzip, deflate, braccept-languageen-GB,en-US;q=0.9,en;q=0.8user-agentMozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0content-typeapplication/x-www-form-urlencoded; charset=UTF-8accept*/*refererhttps://www.bikeregister.com/stolen-bikesauthoritywww.bikeregister.comx-requested-withXMLHttpRequest_tokenmakemodelcolourreporting_period1https://www.bikeregister.com/stolen-bikes', headers=headers, data=data) as request: bikes = json.loads(await request.text()) except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") except json.JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err.msg}") raise ApiError(f"Could not decode data: {dec_err.msg}") return bikes return []
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 data
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() :param async_req bool :param str id: (required) :param str tag_value: (required) :return: ResponseContainer If the method is called asynchronously, returns the request thread.
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): logger.debug("CanhdOIDC_GOOGLE_APPS_DOMAINOIDC_GOOGLE_APPS_DOMAINsubState field was invalid') return True, self._oidc_error() self._set_cookie_id_token(id_token) return False, response
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, tmp_dir) if rcode: rscript = utils.Rscript_cmd() do.run([rscript, "--no-environ", rcode], "ChIPQC in %s" % sample_name, log_error=False) shutil.move(tmp_dir, out_dir) return _get_output(out_dir)
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 bytes(data)
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 - ``origin='lower'`` (coordinates start in lower-left corner) - ``aspect='auto'`` (pixels are not forced to be square) - ``interpolation='none'`` (no image interpolation is used) In all other usage, the defaults from the upstream matplotlib method are unchanged. Parameters ---------- array : array-like or PIL image The image data. *args, **kwargs All arguments and keywords are passed to the inherited :meth:`~matplotlib.axes.Axes.imshow` method. See Also -------- matplotlib.axes.Axes.imshow for details of the image rendering
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]): return sys.path cmd_args = [self.python, "-c", "import json, sys; print(json.dumps(sys.path))"] path, _ = vistir.misc.run(cmd_args, return_object=False, nospin=True, block=True, combine_stderr=False, write_to_stdout=False) try: path = json.loads(path.strip()) except JSONDecodeError: path = sys.path return path
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 == EXCEPTIONS_MODULE ): return True return False
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**i Q = d*exp(-0.864671+8659.19/T-22786.2/T**2*d**(2./3)) pKw = -12*(log10(1+Q)-Q/(Q+1)*d*(0.642044-56.8534/T-0.375754*d)) + \ pKg+2*log10(Mw/1000) return pKw
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 input isn't in limit: * 0 ≤ ρ ≤ 1250 * 273.15 ≤ T ≤ 1073.15 Examples -------- >>> _Kw(1000, 300) 13.906565 References ---------- IAPWS, Release on the Ionization Constant of H2O, http://www.iapws.org/relguide/Ionization.pdf
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.cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return [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(str("text"),config[]), makeminlength(str("parse"),config[]),"meter","num_parses","num_viols","score_viols",ckeys]),conscious=conscious)
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(anchors) > 1: for i, (anchor, component) in enumerate(anchors): t = Transform(*component.transformation) name = % (anchor.name, i + 1) anchor_data[name] = t.transformPoint((anchor.x, anchor.y)) elif anchors: anchor, component = anchors[0] t = Transform(*component.transformation) anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
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 scheme_dom = scheme_dom.decode(, ) scheme_dom = scheme_dom.rsplit(, 1) domain = scheme_dom[-1] try: domain = to_native_str(domain.encode(), ) except UnicodeError: pass if len(scheme_dom) > 1: url = to_native_str(scheme_dom[0], ) + + domain else: url = domain if len(parts) > 1: url += sep rest = parts[1] try: rest.encode() except UnicodeEncodeError: rest = quote(to_native_str(rest, )) url += rest 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(p1))) if direction is not None: p2 = [p1[0] + direction[0], p1[1] + direction[1]] elif p2 is not None: p2 = p2 else: raise TypeError() return self.agent.input.swipe(p1[0], p1[1], p2[0], p2[1], duration)
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 vector (x, y) are also expressed in the range of the screen from 0 to 1. See ``CoordinateSystem`` for more details about coordinate system. Examples: Following example shows how to perform a swipe action from (100, 100) to (100, 200) on screen with resolution 1920x1080:: poco.swipe([100.0 / 1920, 100.0 / 1080], [100.0 / 1920, 200.0 / 1080]) Or given by the specific direction instead of end point:: poco.swipe([100.0 / 1920, 100.0 / 1080], direction=[0, 100.0 / 1080]) Args: p1 (:obj:`2-list/2-tuple`): start point p2: end point direction: swipe direction duration (:obj:`float`): time interval in which the swipe action is performed Raises: InvalidOperationException: when the start point of the swipe action lies outside the screen
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()), weighted_cut * cut) self.SetWeight(weight) entries = hist.Integral() elif cut: entries = super(BaseTree, self).GetEntries(str(cut)) else: entries = super(BaseTree, self).GetEntries() if weighted: entries *= self.GetWeight() return entries
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 a weighted selection and determine the weighted number of entries. weighted : bool, optional (default=False) Multiply the number of (weighted) entries by the Tree weight.
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) except Exception as e: return jsonify(dict(error_message=str(e)), status=500)
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]) knns.append([j, distance]) return sorted(knns, key=lambda x: x[1])[:self.perplexity]
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 += " --why-run" cmd += .format(env.loglevel) if ENABLE_LOGS: cmd += .format(LOGFILE) if env.loglevel == "debug": print("Executing Chef Solo with the following command:\n" "{0}".format(cmd)) with settings(hide(, ), warn_only=True): output = sudo(cmd) if (output.failed or "FATAL: Stacktrace dumped" in output or ("Chef Run complete" not in output and "Report handlers complete" not in output)): if in output: print( colors.red( "\nFAILED: Chef Solo is not installed on this node")) print( "Type to install it".format( env.host)) abort("") else: print(colors.red( "\nFAILED: chef-solo could not finish configuring the node\n")) import sys sys.exit(1) else: msg = "\n" if env.parallel: msg += "[{0}]: ".format(env.host_string) msg += "SUCCESS: Node correctly configured" print(colors.green(msg))
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_parameters()
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 left = listwrap(left) right = listwrap(right) for a, b in zip(left, right): c = value_compare(a, b) * ordering if c != 0: return c if len(left) < len(right): return - ordering elif len(left) > len(right): return ordering else: return 0 if ltype is float and isnan(left): left = None ltype = none_type if rtype is float and isnan(right): right = None rtype = none_type null_order = ordering*10 ltype_num = TYPE_ORDER.get(ltype, null_order) rtype_num = TYPE_ORDER.get(rtype, null_order) type_diff = ltype_num - rtype_num if type_diff != 0: return ordering if type_diff > 0 else -ordering if ltype_num == null_order: return 0 elif ltype is builtin_tuple: for a, b in zip(left, right): c = value_compare(a, b) if c != 0: return c * ordering return 0 elif ltype in data_types: for k in sorted(set(left.keys()) | set(right.keys())): c = value_compare(left.get(k), right.get(k)) * ordering if c != 0: return c return 0 elif left > right: return ordering elif left < right: return -ordering else: return 0 except Exception as e: Log.error("Can not compare values {{left}} to {{right}}", left=left, right=right, cause=e)
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) if signals is not None: for sig,recs in connections.get(signal,{}).items(): if sig != signal: for rec in recs: if rec is oldReceiver: found = 1 break if not found: _killBackref( oldReceiver, senderkey ) return True return False
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 retry < 1 or not self._connect(): self.available = False _LOGGER.error("Failed to update device state.", exc_info=True) return None return self.update(retry-1) self.available = True return None
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.gapsize agpfile = bedfile.replace(".bed", ".agp") fw = open(agpfile, "w") bed = Bed(bedfile, sorted=False) for object, beds in groupby(bed, key=lambda x: x.accn): beds = list(beds) for i, b in enumerate(beds): if gapsize and i != 0: print("\t".join(str(x) for x in \ (object, 0, 0, 0, "U", \ gapsize, "scaffold", "yes", "map")), file=fw) print("\t".join(str(x) for x in \ (object, 0, 0, 0, "W", \ b.seqid, b.start, b.end, b.strand)), file=fw) fw.close() return reindex([agpfile, "--inplace"])
%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_points(group=, name=): try: activation_function = entry_point.load() classes = activation_function() except Exception as exc: info("Failed to load %s %s" % (entry_point.module_name, exc)) debug(traceback.format_exc()) continue for klass in classes: extra_classes.append(klass) return extra_classes
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.text yield record return self._do_autopaginating_api_call( "shelter.find", kwargs, shelter_find_parser )
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 credentials allow you to receive.
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_http_info(device_id, _resource_path, **kwargs) return data
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 synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.delete_resource_subscription(device_id, _resource_path, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required) :param str _resource_path: The URL of the resource. (required) :return: None If the method is called asynchronously, returns the request thread.
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_fit_genomes] avg_fitness = self.get_fitness_mean() if with_cross_validation: cv_best_fitness = [c.cross_fitness for c in self.most_fit_genomes] cv_avg_fitness = self.get_average_cross_validation_fitness() for best, avg, cv_best, cv_avg in zip(best_fitness, avg_fitness, cv_best_fitness, cv_avg_fitness): w.writerow([best, avg, cv_best, cv_avg]) else: for best, avg in zip(best_fitness, avg_fitness): w.writerow([best, avg])
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, xml = self.submit( {: logical_environment_map}, , url) return self.response(code, xml)
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 InvalidParameterError: The identifier of Logical Environment or name is null and invalid. :raise NomeAmbienteLogicoDuplicadoError: There is already a registered Logical Environment with the value of name. :raise AmbienteLogicoNaoExisteError: Logical Environment not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response.
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, csr_path=None, csr_filename=None, digest=, type_ext=False, cert_type=, replace=False): DNS:somednsname.comDNS:1.2.3.4IP:1.2.3.4IP:2001:4801:7821:77:be76:4eff:fe11:e51email:me@i.like.pie.coms requests library w/out the second entry in the above list .. versionadded:: 2015.8.0 cert_type Specify the general certificate type. Can be either `server` or `client`. Indicates the set of common extensions added to the CSR. .. code-block:: cfg server: { : , : , : } client: { : , : , : } type_ext boolean. Whether or not to extend the filename with CN_[cert_type] This can be useful if a server and client certificate are needed for the same CN. Defaults to False to avoid introducing an unexpected file naming pattern The files normally named some_subject_CN.csr and some_subject_CN.key will then be saved replace Replace this signing request even if it exists .. versionadded:: 2015.5.1 Writes out a Certificate Signing Request (CSR) If the file already exists, the function just returns assuming the CSR already exists. If the following values were set:: ca.cert_base_path= ca_name= CN= the resulting CSR, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.csr /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt tls.create_csr test {0}_ca_certCertificate for CA named "{0}" does not exist, please create it first.{0}/{1}/certs/_{0}{0}{1}{0}/{1}.csrCertificate Request "{0}" already existscsrsubjectAltName, subjectAltName cannot be set as X509 extensions are not supported in pyOpenSSL prior to version 0.15.1. Your version: {0}.{0}/{1}.keywb+wb+Created Private Key: "{0}{1}.key." Created CSR for "{0}": "{1}{2}.csr."'.format( CN, csr_path, csr_filename ) return ret
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 is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None subjectAltName valid subjectAltNames in full form, e.g. to add DNS entry you would call this function with this value: examples: ['DNS:somednsname.com', 'DNS:1.2.3.4', 'IP:1.2.3.4', 'IP:2001:4801:7821:77:be76:4eff:fe11:e51', 'email:me@i.like.pie.com'] .. note:: some libraries do not properly query IP: prefixes, instead looking for the given req. source with a DNS: prefix. To be thorough, you may want to include both DNS: and IP: entries if you are using subjectAltNames for destinations for your TLS connections. e.g.: requests to https://1.2.3.4 will fail from python's requests library w/out the second entry in the above list .. versionadded:: 2015.8.0 cert_type Specify the general certificate type. Can be either `server` or `client`. Indicates the set of common extensions added to the CSR. .. code-block:: cfg server: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'serverAuth', 'keyUsage': 'digitalSignature, keyEncipherment' } client: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'clientAuth', 'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment' } type_ext boolean. Whether or not to extend the filename with CN_[cert_type] This can be useful if a server and client certificate are needed for the same CN. Defaults to False to avoid introducing an unexpected file naming pattern The files normally named some_subject_CN.csr and some_subject_CN.key will then be saved replace Replace this signing request even if it exists .. versionadded:: 2015.5.1 Writes out a Certificate Signing Request (CSR) If the file already exists, the function just returns assuming the CSR already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting CSR, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.csr /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_csr test
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.path.sep)] return short_name.replace(os.path.sep, ) return
Convert a python filename to a module relative to pythonpath.
372,584
def sign(hash,priv,k=0): f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023ec05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde037404663045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7 if k == 0: k = generate_k(priv, hash) hash = int(hash,16) priv = int(priv,16) r = int(privtopub(dechex(k,32),True)[2:],16) % N s = ((hash + (r*priv)) * modinv(k,N)) % N if s > (N / 2): s = N - s r, s = inttoDER(r), inttoDER(s) olen = dechex(len(r+s)//2,1) return + olen + r + s
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 = 'c05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde03740466' >>> k = 4 # chosen by fair dice roll, guaranteed to be random >>> sign(h,p,k) '3045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7'
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: sys.exit(ev) raise return self.fuse_args
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), conversation=copy(activity.conversation), channel_id=activity.channel_id, service_url=activity.service_url)
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.acpi_shutdown: yield from self._control_vm("system_powerdown") yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=30) else: self._process.terminate() yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=3) except ProcessLookupError: pass except asyncio.TimeoutError: if self._process: try: self._process.kill() except ProcessLookupError: pass if self._process.returncode is None: log.warn(.format(self._name, self._process.pid)) self._process = None self._stop_cpulimit() yield from super().stop()
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): m.body.steamid_to_add = steamid_or_accountname_or_email.steam_id else: m.body.accountname_or_email_to_add = steamid_or_accountname_or_email self._steam.send_job(m)
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` .. note:: Adding by email doesn't not work. It's only mentioned for the sake of completeness.
372,590
def killCellRegion(self, centerColumn, radius): self.deadCols = topology.wrappingNeighborhood(centerColumn, radius, self._columnDimensions) self.deadColumnInputSpan = self.getConnectedSpan(self.deadCols) self.removeDeadColumns()
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_namespaced_custom_object_with_http_info(group, version, namespace, plural, name, **kwargs) return data
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.get() :param async_req bool :param str group: the custom resource's group (required) :param str version: the custom resource's version (required) :param str namespace: The custom resource's namespace (required) :param str plural: the custom resource's plural name. For TPRs this would be lowercase plural kind. (required) :param str name: the custom object's name (required) :return: object If the method is called asynchronously, returns the request thread.
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(collected_features)): with open(collected_features,) as infd: fdict = pickle.load(infd) elif isinstance(collected_features, dict): fdict = collected_features else: LOGERROR("canfeatures_arraylabels_arrayavailablefeaturesmagcolobjectidsrunning grid-search CV to optimize RF hyperparameters... performance _gridsearch_report(cvsearch_classifiers.cv_results_) bestclf = cvsearch_classifiers.best_estimator_ bestclf_score = cvsearch_classifiers.best_score_ bestclf_hyperparams = cvsearch_classifiers.best_params_ test_predicted_labels = bestclf.predict(testing_features) recscore = recall_score(testing_labels, test_predicted_labels) precscore = precision_score(testing_labels,test_predicted_labels) f1score = f1_score(testing_labels, test_predicted_labels) confmatrix = confusion_matrix(testing_labels, test_predicted_labels) outdict = {:tfeatures, :tlabels, :tfeaturenames, :tmagcol, :tobjectids, :{:test_fraction, :n_crossval_iterations, :n_kfolds, :crossval_scoring_metric, :nworkers}, :fdict[], :testing_features, :testing_labels, :training_features, :training_labels, :bestclf, :bestclf_score, :bestclf_hyperparams, :recscore, :precscore, :f1score, :confmatrix} if classifier_to_pickle: with open(classifier_to_pickle,) as outfd: pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL) return outdict
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 Runs on the output dict from functions that produce dicts similar to that produced by `collect_nonperiodic_features` above. Parameters ---------- collected_features : dict or str This is either the dict produced by a `collect_*_features` function or the pickle produced by the same. test_fraction : float This sets the fraction of the input set that will be used as the test set after training. n_crossval_iterations : int This sets the number of iterations to use when running the cross-validation. n_kfolds : int This sets the number of K-folds to use on the data when doing a test-train split. crossval_scoring_metric : str This is a string that describes how the cross-validation score is calculated for each iteration. See the URL below for how to specify this parameter: http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter By default, this is tuned for binary classification and uses the F1 scoring metric. Change the `crossval_scoring_metric` to another metric (probably 'accuracy') for multi-class classification, e.g. for periodic variable classification. classifier_to_pickle : str If this is a string indicating the name of a pickle file to write, will write the trained classifier to the pickle that can be later loaded and used to classify data. nworkers : int This is the number of parallel workers to use in the RandomForestClassifier. Set to -1 to use all CPUs on your machine. Returns ------- dict A dict containing the trained classifier, cross-validation results, the input data set, and all input kwargs used is returned, along with cross-validation score metrics.
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_free_rate should be numeric") args = (self.expected_returns, self.cov_matrix, self.gamma, risk_free_rate) target_constraint = { "type": "ineq", "fun": lambda w: target_risk - np.sqrt(objective_functions.volatility(w, self.cov_matrix)), } if market_neutral: if self.bounds[0][0] is not None and self.bounds[0][0] >= 0: warnings.warn( "Market neutrality requires shorting - bounds have been amended", RuntimeWarning, ) self.bounds = self._make_valid_bounds((-1, 1)) constraints = [ {"type": "eq", "fun": lambda x: np.sum(x)}, target_constraint, ] else: constraints = self.constraints + [target_constraint] result = sco.minimize( objective_functions.negative_sharpe, x0=self.initial_guess, args=args, method="SLSQP", bounds=self.bounds, constraints=constraints, ) self.weights = result["x"] return dict(zip(self.tickers, self.weights))
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 risk_free_rate: float, optional :param market_neutral: whether the portfolio should be market neutral (weights sum to zero), defaults to False. Requires negative lower weight bound. :param market_neutral: bool, optional :raises ValueError: if ``target_risk`` is not a positive float :raises ValueError: if ``risk_free_rate`` is non-numeric :return: asset weights for the efficient risk portfolio :rtype: dict
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=) if (min).shape[-1] != self.ndims: raise ValueError("dimension of min does not match Node") if (max).shape[-1] != self.ndims: raise ValueError("dimension of max does not match Node") min, max = broadcast_arrays(min, max) return _core.KDNode.integrate(self, min, max, attr, info)
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.genome.transcript_by_id(result[0]) for result in transcript_id_results ]
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[:-1] cmax = bounds[1:] return cmin, cmax
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 :return: tuple containing (command, args, line)
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.