code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def message(self, value): """The message property. Args: value (string). the property value. """ if value == self._defaults['message'] and 'message' in self._values: del self._values['message'] else: self._values['message'] = value
The message property. Args: value (string). the property value.
def parse_midi_event(self, fp): """Parse a MIDI event. Return a dictionary and the number of bytes read. """ chunk_size = 0 try: ec = self.bytes_to_int(fp.read(1)) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldn't read event type " "and channel data from file.") # Get the nibbles event_type = (ec & 0xf0) >> 4 channel = ec & 0x0f # I don't know what these events are supposed to do, but I keep finding # them. The parser ignores them. if event_type < 8: raise FormatError('Unknown event type %d. Byte %d.' % (event_type, self.bytes_read)) # Meta events can have strings of variable length 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("Couldn't read meta event from file.") return ({'event': event_type, 'meta_event': meta_event, 'data': data}, chunk_size) elif event_type in [12, 13]: # Program change and Channel aftertouch events only have one # parameter try: param1 = fp.read(1) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldn't read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) return ({'event': event_type, 'channel': channel, 'param1': param1}, chunk_size) else: try: param1 = fp.read(1) param2 = fp.read(1) chunk_size += 2 self.bytes_read += 2 except: raise IOError("Couldn't read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) param2 = self.bytes_to_int(param2) return ({'event': event_type, 'channel': channel, 'param1': param1, 'param2': param2}, chunk_size)
Parse a MIDI event. Return a dictionary and the number of bytes read.
def gzip_open_text(path, encoding=None): """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. """ if encoding is None: encoding = sys.getdefaultencoding() assert os.path.isfile(path) is_compressed = False try: gzip.open(path, mode='rb').read(1) except IOError: pass else: is_compressed = True if is_compressed: if six.PY2: import codecs zf = gzip.open(path, 'rb') reader = codecs.getreader(encoding) fh = reader(zf) else: fh = gzip.open(path, mode='rt', encoding=encoding) else: # the following works in Python 2.7, thanks to future fh = open(path, mode='r', 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.
def _set_snps(self, snps, build=37): """ 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 """ 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
def _compare_or_regex_search(a, b, regex=False): """ 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 """ 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) # numpy deprecation warning to have i8 vs integer comparisons if is_datetimelike_v_numeric(a, b): result = False # numpy deprecation warning if comparing numeric vs string-like 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] = 'ndarray(dtype={dtype})'.format(dtype=a.dtype) if is_b_array: type_names[1] = 'ndarray(dtype={dtype})'.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
def video_pixel_noise_bottom(x, model_hparams, vocab_size): """Bottom transformation for video.""" 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.
def get_grade_systems(self): """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.* """ if self.retrieved: raise errors.IllegalState('List has already been retrieved.') 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.*
def precision(y, y_pred): """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 """ 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
def create_user(self, Name, 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 """ return self.edit_user('new', 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
def url_to_string(url): """ Return the contents of a web site url as a string. """ 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.
def tableExists(self, login, tableName): """ Parameters: - login - tableName """ self.send_tableExists(login, tableName) return self.recv_tableExists()
Parameters: - login - tableName
def subproc_call(cmd, timeout=None): """ 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. """ 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('utf-8')) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode('utf-8')) 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.
def div_img(img1, div2): """ Pixelwise division or divide by a number """ if is_img(div2): return img1.get_data()/div2.get_data() elif isinstance(div2, (float, int)): return img1.get_data()/div2 else: raise NotImplementedError('Cannot divide {}({}) by ' '{}({})'.format(type(img1), img1, type(div2), div2))
Pixelwise division or divide by a number
def combination_step(self): """Build next update by a smart combination of previous updates. (standard FISTA :cite:`beck-2009-fast`). """ # Update t step tprv = self.t self.t = 0.5 * float(1. + np.sqrt(1. + 4. * tprv**2)) # Update Y if not self.opt['FastSolve']: 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`).
def uniq(seq): """ Return a copy of seq without duplicates. """ 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.
def visit(self, func): """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 """ 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
def genchanges(self): """Generate a .changes file for this package.""" chparams = self.params.copy() debpath = os.path.join(self.buildroot, self.rule.output_files[0]) chparams.update({ 'fullversion': '{epoch}:{version}-{release}'.format(**chparams), 'metahash': self._metahash().hexdigest(), 'deb_sha1': util.hash_file(debpath, hashlib.sha1()).hexdigest(), 'deb_sha256': util.hash_file(debpath, hashlib.sha256() ).hexdigest(), 'deb_md5': util.hash_file(debpath, hashlib.md5()).hexdigest(), 'deb_bytes': os.stat(debpath).st_size, # TODO: having to do this split('/')[-1] is absurd: 'deb_filename': debpath.split('/')[-1], }) output = '\n'.join([ 'Format: 1.8', # Static date string for repeatable builds: 'Date: Tue, 01 Jan 2013 00:00:00 -0700', 'Source: {package_name}', 'Binary: {package_name}', 'Architecture: {arch}', 'Version: {fullversion}', 'Distribution: {distro}', 'Urgency: {urgency}', 'Maintainer: {packager}', 'Description: ', ' {package_name} - {short_description}', 'Changes: ', ' {package_name} ({fullversion}) {distro}; urgency={urgency}', ' .', ' * Built by Butcher - metahash for this build is {metahash}', 'Checksums-Sha1: ', ' {deb_sha1} {deb_bytes} {deb_filename}', 'Checksums-Sha256: ', ' {deb_sha256} {deb_bytes} {deb_filename}', 'Files: ', ' {deb_md5} {deb_bytes} {section} {priority} {deb_filename}', '' # Newline at end of file. ]).format(**chparams) return output
Generate a .changes file for this package.
def hook(self, function, dependencies=None): """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. """ if not isinstance(dependencies, (Iterable, type(None), str)): raise TypeError("Invalid list of dependencies provided!") # Tag the function with its dependencies if not hasattr(function, "__deps__"): function.__deps__ = dependencies # If a module is loaded before all its dependencies are loaded, put # it in _later list and don't load yet if self.isloaded(function.__deps__): self.append(function) else: self._later.append(function) # After each module load, retry to resolve dependencies 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.
def spin_in_system(incl, long_an): """ 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 """ #print "*** spin_in_system", incl, long_an, np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0,0,1]))) # Rz(long_an) Rx(incl) [0, 0, 1] 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
def rpm_versioned_name(cls, name, version, default_number=False): """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. """ regexp = re.compile(r'^python(\d*|)-(.*)') auto_provides_regexp = re.compile(r'^python(\d*|)dist(.*)') if (not version or version == cls.get_default_py_version() and not default_number): found = regexp.search(name) # second check is to avoid renaming of python2-devel to # python-devel if found and found.group(2) != 'devel': if 'epel' not in cls.template: return 'python-{0}'.format(regexp.search(name).group(2)) return name versioned_name = name if version: if regexp.search(name): versioned_name = re.sub(r'^python(\d*|)-', 'python{0}-'.format( version), name) elif auto_provides_regexp.search(name): versioned_name = re.sub( r'^python(\d*|)dist', 'python{0}dist'.format( version), name) else: versioned_name = 'python{0}-{1}'.format(version, name) if ('epel' in cls.template and version != cls.get_default_py_version()): versioned_name = versioned_name.replace('{0}'.format( version), '%{{python{0}_pkgversion}}'.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.
def _convert_localized_value(value: LocalizedValue) -> LocalizedIntegerValue: """Converts from :see:LocalizedValue to :see: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.
def set_password(cls, instance, raw_password): """ sets new password on a user using password manager :param instance: :param raw_password: :return: """ # support API for both passlib 1.x and 2.x 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:
def visit_ifexp(self, node, parent): """visit a IfExp node by returning a fresh instance of it""" 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
def reference_cluster(envs, name): """ 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 """ edges = [ set([env['name'], ref]) for env in envs for ref in env['refs'] ] prev, cluster = set(), set([name]) while prev != cluster: # While cluster grows prev = set(cluster) to_visit = [] for edge in edges: if cluster & edge: # Add adjacent nodes: cluster |= edge else: # Leave only edges that are out # of cluster for the next round: 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
def validate_href(image_href): """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. """ 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.
async def connect( cls, url, *, apikey=None, insecure=False): """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. """ 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.
def crop_to_bounding_box(image, offset_height, offset_width, target_height, target_width, dynamic_shape=False): """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`. """ image = ops.convert_to_tensor(image, name='image') _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('offset_width must be >= 0.') if offset_height < 0: raise ValueError('offset_height must be >= 0.') if width < (target_width + offset_width): raise ValueError('width must be >= target + offset.') if height < (target_height + offset_height): raise ValueError('height must be >= target + offset.') 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`.
def format_box(title, ch="*"): """ Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** ************************* """ 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 *** *************************
def format_error(module, error): """Format the error for the given module.""" logging.error(module) # Beautify JSON error print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': ')) exit(1)
Format the error for the given module.
def with_retry(cls, methods): """ Wraps the given list of methods in a class with an exponential-back retry mechanism. """ 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.
def get_value(self, name): """Get the value of a variable""" ns = self._get_current_namespace() value = ns[name] try: self.send_spyder_msg('data', data=value) except: # * There is no need to inform users about # these errors. # * value = None makes Spyder to ignore # petitions to display a value self.send_spyder_msg('data', data=None) self._do_publish_pdb_state = False
Get the value of a variable
def mrc_to_marc(mrc): """ Convert MRC data format to MARC XML. Args: mrc (str): MRC as string. Returns: str: XML with MARC. """ # ignore blank lines 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) # convert controlfield lines 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 # convert datafield lines 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.
def wait(self): """wait until all jobs finish and return a list of pids """ 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
def initialize(self, conf, ctx): """Initialization steps: 1. Prepare elasticsearch connection, including details for indexing. """ config = get_config()['ElasticsearchIndexBolt'] elasticsearch_class = import_name(config['elasticsearch_class']) self.es = elasticsearch_class(**config['elasticsearch_init']) self.index = config['index'] self.doc_type = config['doc_type']
Initialization steps: 1. Prepare elasticsearch connection, including details for indexing.
def k_weights_int(self): """ Returns ------- ndarray Geometric k-point weights (number of arms of k-star in BZ). dtype='intc' shape=(irreducible_kpoints,) """ nk = np.prod(self.k_mesh) _weights = self.k_weights * nk weights = np.rint(_weights).astype('intc') assert (np.abs(weights - _weights) < 1e-7 * nk).all() return np.array(weights, dtype='intc')
Returns ------- ndarray Geometric k-point weights (number of arms of k-star in BZ). dtype='intc' shape=(irreducible_kpoints,)
def update_screen_id(self): """ 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). """ self.status_update_event.clear() # This gets the screenId but always throws. Couldn't find a better way. 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).
def list_objects(self): ''' list the entire of objects with their (id, serialized_form, actual_value) ''' for i in self._execute('select * from objects'): _id, code = i yield _id, code, self.deserialize(code)
list the entire of objects with their (id, serialized_form, actual_value)
def _example_short_number(region_code): """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. """ 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.
def move_committees(src, dest): """ Import stupid yaml files, convert to something useful. """ comm, sub_comm = import_committees(src) save_committees(comm, dest) save_subcommittees(comm, dest)
Import stupid yaml files, convert to something useful.
def createTemporaryCredentials(clientId, accessToken, start, expiry, scopes, name=None): """ 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} """ for scope in scopes: if not isinstance(scope, six.string_types): raise exceptions.TaskclusterFailure('Scope must be string') # Credentials can only be valid for 31 days. I hope that # this is validated on the server somehow... if expiry - start > datetime.timedelta(days=31): raise exceptions.TaskclusterFailure('Only 31 days allowed') # We multiply times by 1000 because the auth service is JS and as a result # uses milliseconds instead of seconds cert = dict( version=1, scopes=scopes, start=calendar.timegm(start.utctimetuple()) * 1000, expiry=calendar.timegm(expiry.utctimetuple()) * 1000, seed=utils.slugId().encode('ascii') + utils.slugId().encode('ascii'), ) # if this is a named temporary credential, include the issuer in the certificate if name: cert['issuer'] = utils.toStr(clientId) sig = ['version:' + utils.toStr(cert['version'])] if name: sig.extend([ 'clientId:' + utils.toStr(name), 'issuer:' + utils.toStr(clientId), ]) sig.extend([ 'seed:' + utils.toStr(cert['seed']), 'start:' + utils.toStr(cert['start']), 'expiry:' + utils.toStr(cert['expiry']), 'scopes:' ] + scopes) sigStr = '\n'.join(sig).encode() if isinstance(accessToken, six.text_type): accessToken = accessToken.encode() sig = hmac.new(accessToken, sigStr, hashlib.sha256).digest() cert['signature'] = utils.encodeStringForB64Header(sig) newToken = hmac.new(accessToken, cert['seed'], hashlib.sha256).digest() newToken = utils.makeB64UrlSafe(utils.encodeStringForB64Header(newToken)).replace(b'=', b'') return { 'clientId': name or clientId, 'accessToken': newToken, 'certificate': 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}
async def fetch_bikes() -> List[dict]: """ 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. """ async with ClientSession() as session: try: async with session.get('https://www.bikeregister.com/stolen-bikes') 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='_token']") if len(token) != 1: raise ApiError(f"Couldn't extract token from page.") else: token = token[0].value xsrf_token = request.cookies["XSRF-TOKEN"] laravel_session = request.cookies["laravel_session"] # get the bike data headers = { 'cookie': f'XSRF-TOKEN={xsrf_token}; laravel_session={laravel_session}', 'origin': 'https://www.bikeregister.com', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0', 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'accept': '*/*', 'referer': 'https://www.bikeregister.com/stolen-bikes', 'authority': 'www.bikeregister.com', 'x-requested-with': 'XMLHttpRequest', } data = [ ('_token', token), ('make', ''), ('model', ''), ('colour', ''), ('reporting_period', '1'), ] try: async with session.post('https://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 # if cant open a session 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.
def add_dashboard_tag(self, id, tag_value, **kwargs): # noqa: E501 """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. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.add_dashboard_tag_with_http_info(id, tag_value, **kwargs) # noqa: E501 else: (data) = self.add_dashboard_tag_with_http_info(id, tag_value, **kwargs) # noqa: E501 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.
def _process_callback(self, statefield): """ Exchange the auth code for actual credentials, then redirect to the originally requested page. """ # retrieve session and callback variables try: session_csrf_token = session.get('oidc_csrf_token') state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8'))) csrf_token = state['csrf_token'] code = request.args['code'] except (KeyError, ValueError): logger.debug("Can't retrieve CSRF token, state, or code", exc_info=True) return True, self._oidc_error() # check callback CSRF token passed to IdP # against session CSRF token held by user if csrf_token != session_csrf_token: logger.debug("CSRF token mismatch") return True, self._oidc_error() # make a request to IdP to exchange the auth code for OAuth credentials flow = self._flow_for_request() credentials = flow.step2_exchange(code) id_token = credentials.id_token if not self._is_id_token_valid(id_token): logger.debug("Invalid ID token") if id_token.get('hd') != current_app.config[ 'OIDC_GOOGLE_APPS_DOMAIN']: return True, self._oidc_error( "You must log in with an account from the {0} domain." .format(current_app.config['OIDC_GOOGLE_APPS_DOMAIN']), self.WRONG_GOOGLE_APPS_DOMAIN) return True, self._oidc_error() # store credentials by subject # when Google is the IdP, the subject is their G+ account number self.credentials_store[id_token['sub']] = credentials.to_json() # Retrieve the extra statefield data try: response = self.extra_data_serializer.loads(state[statefield]) except BadSignature: logger.error('State field was invalid') return True, self._oidc_error() # set a persistent signed cookie containing the ID token # and redirect to the final destination self._set_cookie_id_token(id_token) return False, response
Exchange the auth code for actual credentials, then redirect to the originally requested page.
def chipqc(bam_file, sample, out_dir): """Attempt code to run ChIPQC bioconductor packate in one sample""" 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: # local_sitelib = utils.R_sitelib() 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
def i2c_master_read(self, addr, length, flags=I2C_NO_FLAGS): """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. """ data = array.array('B', (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.
def imshow(self, array, *args, **kwargs): """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 """ if isinstance(array, Array2D): return self._imshow_array2d(array, *args, **kwargs) image = super(Axes, self).imshow(array, *args, **kwargs) self.autoscale(enable=None, axis='both', 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
def sys_path(self): """ The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list """ 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
def buildDQMasks(imageObjectList,configObj): """ Build DQ masks for all input images. """ # Insure that input imageObject is a list if not isinstance(imageObjectList, list): imageObjectList = [imageObjectList] for img in imageObjectList: img.buildMask(configObj['single'], configObj['bits'])
Build DQ masks for all input images.
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool: """ Return true if the given class node is subclass of exceptions.Exception. """ 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.
def _Kw(rho, 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 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 """ # Check input parameters if rho < 0 or rho > 1250 or T < 273.15 or T > 1073.15: raise NotImplementedError("Incoming out of bound") # The internal method of calculation use rho in g/cm³ d = rho/1000. # Water molecular weight different 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
def import_class(clspath): """Given a clspath, returns the class. Note: This is a really simplistic implementation. """ 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.
def get_next_holiday(self, division=None, date=None): """ 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 """ date = date or datetime.date.today() for holiday in self.get_holidays(division=division): if holiday['date'] > 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
def extraSelections(self): """ In normal mode - QTextEdit.ExtraSelection which highlightes the cursor """ if not isinstance(self._mode, Normal): return [] selection = QTextEdit.ExtraSelection() selection.format.setBackground(QColor('#ffcc22')) selection.format.setForeground(QColor('#000000')) selection.cursor = self._qpart.textCursor() selection.cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return [selection]
In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
def data_complete(datadir, sitedir, get_container_name): """ Return True if the directories and containers we're expecting are present in datadir, sitedir and containers """ if any(not path.isdir(sitedir + x) for x in ('/files', '/run', '/solr')): return False if docker.is_boot2docker(): # Inspect returns None if the container doesn't exist. return all(docker.inspect_container(get_container_name(x)) for x in ('pgdata', 'venv')) return path.isdir(datadir + '/venv') and path.isdir(sitedir + '/postgres')
Return True if the directories and containers we're expecting are present in datadir, sitedir and containers
def scansion_prepare(self,meter=None,conscious=False): """Print out header column for line-scansions for a given meter. """ import prosodic config=prosodic.config if not meter: if not hasattr(self,'_Text__bestparses'): return x=getattr(self,'_Text__bestparses') 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['linelen']), makeminlength(str("parse"),config['linelen']),"meter","num_parses","num_viols","score_viols",ckeys]),conscious=conscious)
Print out header column for line-scansions for a given meter.
def _get_anchor_data(anchor_data, glyphSet, components, anchor_name): """Get data for an anchor from a list of components.""" 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 = '%s_%d' % (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.
def to_uri(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 """ 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('utf-8', 'ignore') scheme_dom = scheme_dom.rsplit('/', 1) domain = scheme_dom[-1] try: domain = to_native_str(domain.encode('idna'), 'utf-8') except UnicodeError: # the url is invalid and this is probably not a domain pass if len(scheme_dom) > 1: url = to_native_str(scheme_dom[0], 'utf-8') + '/' + domain else: url = domain if len(parts) > 1: url += sep rest = parts[1] try: rest.encode('ascii') except UnicodeEncodeError: rest = quote(to_native_str(rest, 'utf-8')) 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
def swipe(self, p1, p2=None, direction=None, duration=2.0): """ 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 """ try: duration = float(duration) except ValueError: raise ValueError('Argument `duration` should be <float>. Got {}'.format(repr(duration))) if not (0 <= p1[0] <= 1) or not (0 <= p1[1] <= 1): raise InvalidOperationException('Swipe origin out of screen. {}'.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('Swipe end not set.') 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
def GetEntries(self, cut=None, weighted_cut=None, weighted=False): """ 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. """ if weighted_cut: hist = Hist(1, -1, 2) branch = self.GetListOfBranches()[0].GetName() weight = self.GetWeight() self.SetWeight(1) self.Draw('{0}=={1}>>{2}'.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.
def update_job(job_id): """Updates a job.""" 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 %s not found' % job_id), status=404) except Exception as e: return jsonify(dict(error_message=str(e)), status=500)
Updates a job.
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.
def _knn(self, i, X, high_dim=True): """Performs KNN search based on high/low-dimensional similarity/distance measurement""" 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
def set_debug(self, debug=1): """ Set the debug level. :type debug: int :param debug: The debug level. """ self._check_if_ready() self.debug = debug self.main_loop.debug = debug
Set the debug level. :type debug: int :param debug: The debug level.
def _configure_node(): """Exectutes chef-solo to apply roles and recipes to a node""" print("") msg = "Cooking..." if env.parallel: msg = "[{0}]: {1}".format(env.host_string, msg) print(msg) # Backup last report with settings(hide('stdout', 'warnings', 'running'), warn_only=True): sudo("mv {0} {0}.1".format(LOGFILE)) # Build chef-solo command cmd = "RUBYOPT=-Ku chef-solo" if whyrun: cmd += " --why-run" cmd += ' -l {0} -j /etc/chef/node.json'.format(env.loglevel) if ENABLE_LOGS: cmd += ' | tee {0}'.format(LOGFILE) if env.loglevel == "debug": print("Executing Chef Solo with the following command:\n" "{0}".format(cmd)) with settings(hide('warnings', 'running'), 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 'chef-solo: command not found' in output: print( colors.red( "\nFAILED: Chef Solo is not installed on this node")) print( "Type 'fix node:{0} deploy_chef' 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
def set_load_resistance(self, resistance): """ 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 """ 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
def value_compare(left, right, ordering=1): """ 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. """ 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.
async def 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. """ 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.
def _removeOldBackRefs(senderkey, signal, receiver, receivers): """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 """ try: index = receivers.index(receiver) # need to scan back references here and remove senderkey 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
def min_item(self): """Get item with min key of tree, raises ValueError if tree is empty.""" 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.
def update(self, retry=2) -> None: """Synchronize state with switch.""" 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.
def frombed(args): """ %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. """ 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() # Reindex 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.
def __get_extra_extension_classes(paths): """ Banana banana """ 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='hotdoc.extensions', name='get_extension_classes'): try: activation_function = entry_point.load() classes = activation_function() # pylint: disable=broad-except 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
def keyring_parser(path): """ 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. """ sections = [] with open(path) as keyring: lines = keyring.readlines() for line in lines: line = line.strip('\n') 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.
def shelter_find(self, **kwargs): """ 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. """ def shelter_find_parser(root, has_records): """ The parser that is used with the ``_do_autopaginating_api_call`` method for auto-pagination. :param lxml.etree._Element root: The root Element in the response. :param dict has_records: A dict that we track the loop state in. dicts are passed by references, which is how this works. """ 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.
def login(self, params): """Login either with resume token or password.""" if 'password' in params: return self.login_with_password(params) elif 'resume' in params: return self.login_with_resume_token(params) else: self.auth_failed(**params)
Login either with resume token or password.
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) return self.show_page(course, web.input())
GET request
def delete_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501 """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. """ kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous'): return self.delete_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 else: (data) = self.delete_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501 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.
def K(self): """ Get the intrinsic matrix for the Camera object. Returns ----------- K : (3, 3) float Intrinsic matrix for camera """ 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
def save_genome_fitness(self, delimiter=' ', filename='fitness_history.csv', with_cross_validation=False): """ Saves the population's best and average fitness. """ with open(filename, 'w') 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: # pragma: no cover 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.
def alterar(self, id_logicalenvironment, name): """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. """ if not is_valid_int_param(id_logicalenvironment): raise InvalidParameterError( u'The identifier of Logical Environment is invalid or was not informed.') url = 'logicalenvironment/' + str(id_logicalenvironment) + '/' logical_environment_map = dict() logical_environment_map['name'] = name code, xml = self.submit( {'logical_environment': logical_environment_map}, 'PUT', 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.
def get_output_file(self, in_file, instance, field, **kwargs): """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`.""" return NamedTemporaryFile(mode='rb', suffix='_%s_%s%s' % ( 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`.
def create_csr(ca_name, bits=2048, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, subjectAltName=None, cacert_path=None, ca_filename=None, csr_path=None, csr_filename=None, digest='sha256', type_ext=False, cert_type='server', replace=False): ''' 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 ''' set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not ca_exists(ca_name, ca_filename=ca_filename): return ('Certificate for CA named "{0}" does not exist, please create ' 'it first.').format(ca_name) if not csr_path: csr_path = '{0}/{1}/certs/'.format(cert_base_path(), ca_name) if not os.path.exists(csr_path): os.makedirs(csr_path) CN_ext = '_{0}'.format(cert_type) if type_ext else '' if not csr_filename: csr_filename = '{0}{1}'.format(CN, CN_ext) csr_f = '{0}/{1}.csr'.format(csr_path, csr_filename) if not replace and os.path.exists(csr_f): return 'Certificate Request "{0}" already exists'.format(csr_f) key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) req = OpenSSL.crypto.X509Req() req.get_subject().C = C req.get_subject().ST = ST req.get_subject().L = L req.get_subject().O = O if OU: req.get_subject().OU = OU req.get_subject().CN = CN if emailAddress: req.get_subject().emailAddress = emailAddress try: extensions = get_extensions(cert_type)['csr'] extension_adds = [] for ext, value in extensions.items(): if isinstance(value, six.string_types): value = salt.utils.stringutils.to_bytes(value) extension_adds.append( OpenSSL.crypto.X509Extension( salt.utils.stringutils.to_bytes(ext), False, value ) ) except AssertionError as err: log.error(err) extensions = [] if subjectAltName: if X509_EXT_ENABLED: if isinstance(subjectAltName, six.string_types): subjectAltName = [subjectAltName] extension_adds.append( OpenSSL.crypto.X509Extension( b'subjectAltName', False, b', '.join(salt.utils.data.encode(subjectAltName)) ) ) else: raise ValueError('subjectAltName cannot be set as X509 ' 'extensions are not supported in pyOpenSSL ' 'prior to version 0.15.1. Your ' 'version: {0}.'.format(OpenSSL_version)) if X509_EXT_ENABLED: req.add_extensions(extension_adds) req.set_pubkey(key) req.sign(key, salt.utils.stringutils.to_str(digest)) # Write private key and request with salt.utils.files.fopen('{0}/{1}.key'.format(csr_path, csr_filename), 'wb+') as priv_key: priv_key.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) ) ) with salt.utils.files.fopen(csr_f, 'wb+') as csr: csr.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate_request( OpenSSL.crypto.FILETYPE_PEM, req ) ) ) ret = 'Created Private Key: "{0}{1}.key." '.format( csr_path, csr_filename ) ret += '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
def greedy(problem, graph_search=False, viewer=None): ''' Greedy search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. ''' 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.
def infer_module_name(filename, fspath): """Convert a python filename to a module relative to pythonpath.""" filename, _ = os.path.splitext(filename) for f in fspath: short_name = f.relative_path(filename) if short_name: # The module name for __init__.py files is the directory. 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, '.') # We have not found filename relative to anywhere in pythonpath. return ''
Convert a python filename to a module relative to pythonpath.
def sign(hash,priv,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 = 'c05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde03740466' >>> k = 4 # chosen by fair dice roll, guaranteed to be random >>> sign(h,p,k) '3045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7' ''' 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 # High S value is non-standard (soon to be invalid) if s > (N / 2): s = N - s r, s = inttoDER(r), inttoDER(s) olen = dechex(len(r+s)//2,1) return '30' + 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'
def parse(self, *args, **kw): """Parse command line, fill `fuse_args` attribute.""" ev = 'errex' in kw and kw.pop('errex') 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.
def get_conversation_reference(activity: Activity) -> ConversationReference: """ 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: """ 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:
def stop(self): """ Stops this QEMU VM. """ yield from self._stop_ubridge() with (yield from self._execute_lock): # stop the QEMU process self._hw_virtualization = False if self.is_running(): log.info('Stopping QEMU VM "{}" PID={}'.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('QEMU VM "{}" PID={} is still running'.format(self._name, self._process.pid)) self._process = None self._stop_cpulimit() yield from super().stop()
Stops this QEMU VM.
def glob_by_extensions(directory, extensions): """ Returns files matched by all extensions in the extensions list """ directorycheck(directory) files = [] xt = files.extend for ex in extensions: xt(glob.glob('{0}/*.{1}'.format(directory, ex))) return files
Returns files matched by all extensions in the extensions list
def add(self, steamid_or_accountname_or_email): """ 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. """ 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.
def killCellRegion(self, centerColumn, radius): """ Kill cells around a centerColumn, within radius """ self.deadCols = topology.wrappingNeighborhood(centerColumn, radius, self._columnDimensions) self.deadColumnInputSpan = self.getConnectedSpan(self.deadCols) self.removeDeadColumns()
Kill cells around a centerColumn, within radius
def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs): """ 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. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): 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.
def train_rf_classifier( collected_features, test_fraction=0.25, n_crossval_iterations=20, n_kfolds=5, crossval_scoring_metric='f1', classifier_to_pickle=None, nworkers=-1, ): '''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. ''' if (isinstance(collected_features,str) and os.path.exists(collected_features)): with open(collected_features,'rb') as infd: fdict = pickle.load(infd) elif isinstance(collected_features, dict): fdict = collected_features else: LOGERROR("can't figure out the input collected_features arg") return None tfeatures = fdict['features_array'] tlabels = fdict['labels_array'] tfeaturenames = fdict['availablefeatures'] tmagcol = fdict['magcol'] tobjectids = fdict['objectids'] # split the training set into training/test samples using stratification # to keep the same fraction of variable/nonvariables in each training_features, testing_features, training_labels, testing_labels = ( train_test_split( tfeatures, tlabels, test_size=test_fraction, random_state=RANDSEED, stratify=tlabels ) ) # get a random forest classifier clf = RandomForestClassifier(n_jobs=nworkers, random_state=RANDSEED) # this is the grid def for hyperparam optimization rf_hyperparams = { "max_depth": [3,4,5,None], "n_estimators":sp_randint(100,2000), "max_features": sp_randint(1, 5), "min_samples_split": sp_randint(2, 11), "min_samples_leaf": sp_randint(2, 11), } # run the stratified kfold cross-validation on training features using our # random forest classifier object cvsearch = RandomizedSearchCV( clf, param_distributions=rf_hyperparams, n_iter=n_crossval_iterations, scoring=crossval_scoring_metric, cv=StratifiedKFold(n_splits=n_kfolds, shuffle=True, random_state=RANDSEED), random_state=RANDSEED ) LOGINFO('running grid-search CV to optimize RF hyperparameters...') cvsearch_classifiers = cvsearch.fit(training_features, training_labels) # report on the classifiers' performance _gridsearch_report(cvsearch_classifiers.cv_results_) # get the best classifier after CV is done bestclf = cvsearch_classifiers.best_estimator_ bestclf_score = cvsearch_classifiers.best_score_ bestclf_hyperparams = cvsearch_classifiers.best_params_ # test this classifier on the testing set 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) # write the classifier, its training/testing set, and its stats to the # pickle if requested outdict = {'features':tfeatures, 'labels':tlabels, 'feature_names':tfeaturenames, 'magcol':tmagcol, 'objectids':tobjectids, 'kwargs':{'test_fraction':test_fraction, 'n_crossval_iterations':n_crossval_iterations, 'n_kfolds':n_kfolds, 'crossval_scoring_metric':crossval_scoring_metric, 'nworkers':nworkers}, 'collect_kwargs':fdict['kwargs'], 'testing_features':testing_features, 'testing_labels':testing_labels, 'training_features':training_features, 'training_labels':training_labels, 'best_classifier':bestclf, 'best_score':bestclf_score, 'best_hyperparams':bestclf_hyperparams, 'best_recall':recscore, 'best_precision':precscore, 'best_f1':f1score, 'best_confmatrix':confmatrix} if classifier_to_pickle: with open(classifier_to_pickle,'wb') as outfd: pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL) # return this classifier and accompanying info 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.
def efficient_risk(self, target_risk, risk_free_rate=0.02, market_neutral=False): """ 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 """ 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)), } # The equality constraint is either "weights sum to 1" (default), or # "weights sum to 0" (market neutral). 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
def integrate(self, min, max, attr=None, 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. """ 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='f8', order='C') max = numpy.array(max, dtype='f8', order='C') 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.
def c_metadata(api, args, verbose=False): """ Set or get metadata associated with an object:: usage: cdstar metadata <URL> [<JSON>] <JSON> Path to metadata in JSON, or JSON literal. """ obj = api.get_object(args['<URL>'].split('/')[-1]) if not set_metadata(args['<JSON>'], 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.
def transcripts(self): """ Property which dynamically construct transcript objects for all transcript IDs associated with this gene. """ transcript_id_results = self.db.query( select_column_names=['transcript_id'], filter_column='gene_id', filter_value=self.id, feature='transcript', distinct=False, required=False) # We're doing a SQL query for each transcript ID to fetch # its particular information, might be more efficient if we # just get all the columns here, but how do we keep that modular? 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.
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='int') cmin = bounds[:-1] cmax = bounds[1:] return cmin, cmax
Partition work arrays for multithreaded addition and multiplication
def parseline(self, line: str) -> Tuple[str, str, str]: """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) """ 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)
def NetshStaticIp(interface, ip=u'127.0.0.9', subnet=u'255.255.255.255', gw=u'127.0.0.1'): """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. """ args = [ '/c', 'netsh', 'interface', 'ip', 'set', 'address', interface, 'static', ip, subnet, gw, '1' ] # pylint: disable=undefined-variable res = client_utils_common.Execute( 'cmd', 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.