code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def next(transport, wizard, step, data): """ Validate step and go to the next one (or finish the wizard) :param transport: Transport object :param wizard: Wizard block name :param step: Current step number :param data: form data for the step """ step = int(step) wizard = blocks.get(...
Validate step and go to the next one (or finish the wizard) :param transport: Transport object :param wizard: Wizard block name :param step: Current step number :param data: form data for the step
def read_xyz(filename): """Read an XYZ file. The expected format is as follows: The first line contains the number of atoms in the file The second line contains a comment, which is not read. Remaining lines, one for each atom in the file, include an elemental symbol followed by X, Y, and Z coordina...
Read an XYZ file. The expected format is as follows: The first line contains the number of atoms in the file The second line contains a comment, which is not read. Remaining lines, one for each atom in the file, include an elemental symbol followed by X, Y, and Z coordinates in Angstroms. Columns are e...
def _reset_env(self, env: BaseUnityEnvironment): """Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. """ if self.meta_curriculum is not None: return env.reset(train_mode=self.fast_simulatio...
Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment.
def from_parent_deeper( cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs ): """ This returns you subtree of ordered objects relative to the start parent_id (currently only implemented in postgresql) :param resource_id: :param limit_depth: ...
This returns you subtree of ordered objects relative to the start parent_id (currently only implemented in postgresql) :param resource_id: :param limit_depth: :param db_session: :return:
async def keep_alive(self): """A workaround for Satel Integra disconnecting after 25s. Every interval it sends some random question to the device, ignoring answer - just to keep connection alive. """ while True: await asyncio.sleep(self._keep_alive_timeout) ...
A workaround for Satel Integra disconnecting after 25s. Every interval it sends some random question to the device, ignoring answer - just to keep connection alive.
def transitive_edges(graph): """ Return a list of transitive edges. Example of transitivity within graphs: A -> B, B -> C, A -> C in this case the transitive edge is: A -> C @attention: This function is only meaningful for directed acyclic graphs. @type graph: digraph @param ...
Return a list of transitive edges. Example of transitivity within graphs: A -> B, B -> C, A -> C in this case the transitive edge is: A -> C @attention: This function is only meaningful for directed acyclic graphs. @type graph: digraph @param graph: Digraph @rtype: List ...
def cost_fun(x, *args, **kwargs): """Enables minimization (root-finding) for non-zero targets Returns regularized absolute error between target and output of `fun`. Configurable state with function attributes. >>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to c...
Enables minimization (root-finding) for non-zero targets Returns regularized absolute error between target and output of `fun`. Configurable state with function attributes. >>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to compute error >>> cost_fun.target = 1....
def segment(self, source, language=None): """Returns a chunk list from the given sentence. Args: source (str): Source string to segment. language (:obj:`str`, optional): A language code. Returns: A chunk list. (:obj:`budou.chunk.ChunkList`) Raises: ValueError: If :obj:`languag...
Returns a chunk list from the given sentence. Args: source (str): Source string to segment. language (:obj:`str`, optional): A language code. Returns: A chunk list. (:obj:`budou.chunk.ChunkList`) Raises: ValueError: If :obj:`language` is given and it is not included in ...
def setUdpJoinerPort(self, portNumber): """set Joiner UDP Port Args: portNumber: Joiner UDP Port number Returns: True: successful to set Joiner UDP Port False: fail to set Joiner UDP Port """ print '%s call setUdpJoinerPort' % self.port ...
set Joiner UDP Port Args: portNumber: Joiner UDP Port number Returns: True: successful to set Joiner UDP Port False: fail to set Joiner UDP Port
def rescale(inlist, newrange=(0, 1)): """ rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) """ OldMax = max(inlist) OldMin = min(inlist) if OldMin == OldMax: raise RuntimeError('list contains of only one unique value') O...
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum)
def compute_strategy(self, grads): """ Returns: bool - False if grads cannot be packed due to various reasons. """ for g in grads: assert g.shape.is_fully_defined(), "Shape of {} is {}!".format(g.name, g.shape) self._shapes = [g.shape for g in grads] ...
Returns: bool - False if grads cannot be packed due to various reasons.
def parse(self, rec): """Retrieve row data from files associated with the ISATabRecord. """ final_studies = [] for study in rec.studies: source_data = self._parse_study(study.metadata["Study File Name"], ["Source Name", "Sample Name...
Retrieve row data from files associated with the ISATabRecord.
def version_parts(self, best=False): """ Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`. """ version_str = self.version(best=best) if version_str: version_regex = re.compile(r'(\...
Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`.
def get_gear(self, gear_id): """ Get details for an item of gear. http://strava.github.io/api/v3/gear/#show :param gear_id: The gear id. :type gear_id: str :return: The Bike or Shoe subclass object. :rtype: :class:`stravalib.model.Gear` """ retu...
Get details for an item of gear. http://strava.github.io/api/v3/gear/#show :param gear_id: The gear id. :type gear_id: str :return: The Bike or Shoe subclass object. :rtype: :class:`stravalib.model.Gear`
def pdmerge_respeta_tz(func_merge, tz_ant=None, *args, **kwargs): """ Programación defensiva por issue: pandas BUG (a veces, el index pierde el tz): - issue #7795: concat of objects with the same timezone get reset to UTC; - issue #10567: DataFrame combine_first() loses timezone information for ...
Programación defensiva por issue: pandas BUG (a veces, el index pierde el tz): - issue #7795: concat of objects with the same timezone get reset to UTC; - issue #10567: DataFrame combine_first() loses timezone information for datetime columns https://github.com/pydata/pandas/issues/10567 ...
def recognize( self, config, audio, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Performs synchronous speech recognition: receive results after all audio has been sent and...
Performs synchronous speech recognition: receive results after all audio has been sent and processed. Example: >>> from google.cloud import speech_v1p1beta1 >>> from google.cloud.speech_v1p1beta1 import enums >>> >>> client = speech_v1p1beta1.SpeechClient...
def to_color(self): """ Convert textured visuals to a ColorVisuals with vertex color calculated from texture. Returns ----------- vis : trimesh.visuals.ColorVisuals Contains vertex color from texture """ # find the color at each UV coordinate ...
Convert textured visuals to a ColorVisuals with vertex color calculated from texture. Returns ----------- vis : trimesh.visuals.ColorVisuals Contains vertex color from texture
def _read_string(self, cpu, buf): """ Reads a null terminated concrete buffer form memory :todo: FIX. move to cpu or memory """ filename = "" for i in range(0, 1024): c = Operators.CHR(cpu.read_int(buf + i, 8)) if c == '\x00': break...
Reads a null terminated concrete buffer form memory :todo: FIX. move to cpu or memory
def receive_ping(self, ping: Ping): """ Handle a Ping message by answering with a Pong. """ self.log_healthcheck.debug( 'Ping received', message_id=ping.nonce, message=ping, sender=pex(ping.sender), ) pong = Pong(nonce=ping.nonce) ...
Handle a Ping message by answering with a Pong.
def unpack_srec(record): """Unpack given Motorola S-Record record into variables. """ # Minimum STSSCC, where T is type, SS is size and CC is crc. if len(record) < 6: raise Error("record '{}' too short".format(record)) if record[0] != 'S': raise Error( "record '{}' not...
Unpack given Motorola S-Record record into variables.
def get_client_kwargs(self, path): """ Get base keyword arguments for client for a specific path. Args: path (str): Absolute path or URL. Returns: dict: client args """ container, obj = self.split_locator(path) kwargs = dict(conta...
Get base keyword arguments for client for a specific path. Args: path (str): Absolute path or URL. Returns: dict: client args
def _generate_examples(self, images_dir_path, labels_path, setid_path, split_name): """Yields examples.""" with tf.io.gfile.GFile(labels_path, "rb") as f: labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0] with tf.io.gfile.GFile(setid_path, "rb") as f: exam...
Yields examples.
def _vad_collector(self, sample_rate, frame_duration_ms, padding_duration_ms, vad, frames): """Filters out non-voiced audio frames. Given a webrtcvad.Vad and a source of audio frames, yields only the voiced audio. Uses a padded, sliding window algorithm over the au...
Filters out non-voiced audio frames. Given a webrtcvad.Vad and a source of audio frames, yields only the voiced audio. Uses a padded, sliding window algorithm over the audio frames. When more than 90% of the frames in the window are voiced (as reported by the VAD), the collector ...
def main(): """Entry Point""" parser = ArgumentParser(prog="hwinfo") filter_choices = ['bios', 'nic', 'storage', 'gpu', 'cpu'] parser.add_argument("-f", "--filter", choices=filter_choices, help="Query a specific class.") parser.add_argument("-m", "--machine", default='localhost', help="Remote host...
Entry Point
def to_skycoord(self, unit=None): """Convert this distance to an AstroPy ``SkyCoord`` object.""" from astropy.coordinates import SkyCoord from astropy.units import au x, y, z = self.position.au return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au)
Convert this distance to an AstroPy ``SkyCoord`` object.
def convert(self,label,units=None,conversion_function=convert_time): """ converts a dimension in place """ label_no = self.get_label_no(label) new_label, new_column = self.get_converted(label_no,units,conversion_function) labels = [LabelDimension(l) for l in self.labels] labels[l...
converts a dimension in place
def ve_interfaces(self, **kwargs): """list[dict]: A list of dictionary items describing the operational state of ve interfaces along with the ip address associations. Args: rbridge_id (str): rbridge-id for device. callback (function): A function executed upon completion ...
list[dict]: A list of dictionary items describing the operational state of ve interfaces along with the ip address associations. Args: rbridge_id (str): rbridge-id for device. callback (function): A function executed upon completion of the method. The only param...
def _has_valid_type_annotation(self, tokens, i): """Extended check of PEP-484 type hint presence""" if not self._inside_brackets("("): return False # token_info # type string start end line # 0 1 2 3 4 bracket_level = 0 for token in tok...
Extended check of PEP-484 type hint presence
def failMeasurement(self, measurementId, deviceName, failureReason=None): """ Fails the measurement session. :param deviceName: the device name. :param measurementId: the measurement name. :param failureReason: why it failed. :return: true if it was completed. """...
Fails the measurement session. :param deviceName: the device name. :param measurementId: the measurement name. :param failureReason: why it failed. :return: true if it was completed.
def value(self, n: Node) -> str: """Return the text value of the node""" id_n = id(n) idcache = self.id_cache if id_n not in idcache: return "" name = idcache[id_n] tag_cache = self.tag_cache if name not in tag_cache: raise Exception("Incoh...
Return the text value of the node
def db_is_indexing(cls, impl, working_dir): """ Is the system indexing? Return True if so, False if not. """ indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir) return os.path.exists(indexing_lockfile_path)
Is the system indexing? Return True if so, False if not.
def trim(self): '''Remove items that are expired or exceed the max size.''' now_time = time.time() while self._seq and self._seq[0].expire_time < now_time: item = self._seq.popleft() del self._map[item.key] if self._max_items: while self._seq and len...
Remove items that are expired or exceed the max size.
def reset(self): """ Reset the internal buffers for the abstract canvas. """ # Reset our screen buffer self._start_line = 0 self._x = self._y = None self._buffer = _DoubleBuffer(self._buffer_height, self.width) self._reset()
Reset the internal buffers for the abstract canvas.
def com_google_fonts_check_metadata_subsets_order(family_metadata): """METADATA.pb subsets should be alphabetically ordered.""" expected = list(sorted(family_metadata.subsets)) if list(family_metadata.subsets) != expected: yield FAIL, ("METADATA.pb subsets are not sorted " "in alphabetical o...
METADATA.pb subsets should be alphabetically ordered.
def full_outer(self): """ Performs Full Outer Join :return full_outer: dict """ self.get_collections_data() full_outer_join = self.merge_join_docs( set(self.collections_data['left'].keys()) | set(self.collections_data['right'].keys())) return f...
Performs Full Outer Join :return full_outer: dict
def list_features(self, dataset, reverse=False, start=None, limit=None): """Lists features in a dataset. Parameters ---------- dataset : str The dataset id. reverse : str, optional List features in reverse order. Possible value ...
Lists features in a dataset. Parameters ---------- dataset : str The dataset id. reverse : str, optional List features in reverse order. Possible value is "true". start : str, optional The id of the feature after wh...
def setup_generic_relations(model_class): """ Set up GenericRelations for actionable models. """ Action = apps.get_model('actstream', 'action') if Action is None: raise RegistrationError( 'Unable get actstream.Action. Potential circular imports ' 'in initialisation. ...
Set up GenericRelations for actionable models.
def symmetric_decrypt_HMAC(cyphertext, key, hmac_secret): """:raises: :class:`RuntimeError` when HMAC verification fails""" iv = symmetric_decrypt_iv(cyphertext, key) message = symmetric_decrypt_with_iv(cyphertext, key, iv) hmac = hmac_sha1(hmac_secret, iv[-3:] + message) if iv[:13] != hmac[:13]: ...
:raises: :class:`RuntimeError` when HMAC verification fails
def rank(self, dte): '''The rank of a given *dte* in the timeseries''' timestamp = self.pickler.dumps(dte) return self.backend_structure().rank(timestamp)
The rank of a given *dte* in the timeseries
def uninstall_logger(logger=None, module=None): """ Uninstalls given logger in given module or default logger in caller introspected module. :param logger: Logger to uninstall. :type logger: Logger :param module: Module. :type module: ModuleType :return: Definition success. :rtype: bool...
Uninstalls given logger in given module or default logger in caller introspected module. :param logger: Logger to uninstall. :type logger: Logger :param module: Module. :type module: ModuleType :return: Definition success. :rtype: bool
def fft_spectrum(frames, fft_points=512): """This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT). Please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.f...
This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT). Please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html for further details. Args: ...
def full_block_perm(block_permutation, block_structure): """ Extend a permutation of blocks to a permutation for the internal signals of all blocks. E.g., say we have two blocks of sizes ('block structure') ``(2, 3)``, then a block permutation that switches the blocks would be given by the image tuple `...
Extend a permutation of blocks to a permutation for the internal signals of all blocks. E.g., say we have two blocks of sizes ('block structure') ``(2, 3)``, then a block permutation that switches the blocks would be given by the image tuple ``(1,0)``. However, to get a permutation of all 2+3 = 5 channels t...
def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources): """ Converts several files to consumable types. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(prop_set, pro...
Converts several files to consumable types.
def sg_to_sparse(tensor, opt): r"""Converts a dense tensor into a sparse tensor. See `tf.SparseTensor()` in tensorflow. Args: tensor: A `Tensor` with zero-padding (automatically given by chain). opt: name: If provided, replace current tensor's name. Returns: A `SparseT...
r"""Converts a dense tensor into a sparse tensor. See `tf.SparseTensor()` in tensorflow. Args: tensor: A `Tensor` with zero-padding (automatically given by chain). opt: name: If provided, replace current tensor's name. Returns: A `SparseTensor`.
def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"): """Writes perfect supercell and supercells with displacements Args: supercell: perfect supercell cells_with_disps: supercells with displaced atoms filename: root-filename """ # original ce...
Writes perfect supercell and supercells with displacements Args: supercell: perfect supercell cells_with_disps: supercells with displaced atoms filename: root-filename
def generate_lems_file(self, nml_file_name, nml_doc): """ Generate a LEMS file to use in simulations of the NeuroML file """ #pp.pprint(self.simulation_config) #pp.pprint(self.pop_comp_info) #pp.pprint(self.node_set_mappings) if 'output' in s...
Generate a LEMS file to use in simulations of the NeuroML file
def weights(self): 'weights in the input basis (encapsulated in an object)' self._check_estimated() u_input = self.u return _KoopmanWeights(u_input[0:-1], u_input[-1])
weights in the input basis (encapsulated in an object)
def set_button_map(self, button_map): """Set the finger number to button number mapping for tap-to-click. The default mapping on most devices is to have a 1, 2 and 3 finger tap to map to the left, right and middle button, respectively. A device may permit changing the button mapping but disallow specific maps....
Set the finger number to button number mapping for tap-to-click. The default mapping on most devices is to have a 1, 2 and 3 finger tap to map to the left, right and middle button, respectively. A device may permit changing the button mapping but disallow specific maps. In this case :attr:`~libinput.constant.C...
def parse_keytab(keytab): """Read the contents of a KRB5 keytab file, returning a list of credentials listed within Parameters ---------- keytab : `str` path to keytab file Returns ------- creds : `list` of `tuple` the (unique) list of `(username, realm, kvno)` as read ...
Read the contents of a KRB5 keytab file, returning a list of credentials listed within Parameters ---------- keytab : `str` path to keytab file Returns ------- creds : `list` of `tuple` the (unique) list of `(username, realm, kvno)` as read from the keytab file ...
def _release_lock(lock_manager: ConsulLockManager, configuration: CliUnlockConfiguration): """ Unlocks a lock. :param lock_manager: the lock manager :param configuration: the configuration required to unlock the lock """ if configuration.regex_key_enabled: release_information = sorted(li...
Unlocks a lock. :param lock_manager: the lock manager :param configuration: the configuration required to unlock the lock
def get(host="localhost", port=3551, timeout=30): """ Connect to the APCUPSd NIS and request its status. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.send(CMD_STATUS) buffr = "" while not buffr.endswith(EOF): ...
Connect to the APCUPSd NIS and request its status.
def parse_widget_name(widget): ''' Parse a alias:block_name string into separate parts. ''' try: alias, block_name = widget.split(':', 1) except ValueError: raise template.TemplateSyntaxError('widget name must be "alias:block_name" - %s' % widget) return alias, block_name
Parse a alias:block_name string into separate parts.
def generate_stack_policy_args(stack_policy=None): """ Converts a stack policy object into keyword args. Args: stack_policy (:class:`stacker.providers.base.Template`): A template object representing a stack policy. Returns: dict: A dictionary of keyword arguments to be used els...
Converts a stack policy object into keyword args. Args: stack_policy (:class:`stacker.providers.base.Template`): A template object representing a stack policy. Returns: dict: A dictionary of keyword arguments to be used elsewhere.
def init_coefs(self, X): """Computes ... Initialize the following values: self.n_samples self.n_features self.sample_covariance_ self.lam_scale_ """ self.n_samples_, self.n_features_ = X.shape self.sample_covariance_, self.lam_scal...
Computes ... Initialize the following values: self.n_samples self.n_features self.sample_covariance_ self.lam_scale_
def get_field_type(info): """A field python type""" type_ = info.get_type() cls = get_field_class(type_) field = cls(info, type_, None) field.setup() return field.py_type
A field python type
def orbital_spin_nuclear_matrices(L, S, II, ind="z"): ur"""Return the matrix representation of the orbita, electron-spin, and \ nuclear-spin angular momentum operators \ :math:`\hat{\vec{L}}, \hat{\vec{L}}, \hat{\vec{L}}` in the coupled basis \ :math:`[|J, -J\rangle, \cdot, |J, J\rangle]`. INPUT: ...
ur"""Return the matrix representation of the orbita, electron-spin, and \ nuclear-spin angular momentum operators \ :math:`\hat{\vec{L}}, \hat{\vec{L}}, \hat{\vec{L}}` in the coupled basis \ :math:`[|J, -J\rangle, \cdot, |J, J\rangle]`. INPUT: - ``ind`` - A string ("x", "y", "z", "all") indicatin...
def str_to_v1_str(xml_str): """Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API ...
Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API v1 XML doc. E.g.: ``SystemMetadata ...
def fail_if_publish_binary_not_installed(binary, publish_target, install_link): """Exit (with error message) if ``binary` isn't installed""" if not shutil.which(binary): click.secho( "Publishing to {publish_target} requires {binary} to be installed and configured".format( pub...
Exit (with error message) if ``binary` isn't installed
def get_system_category(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries...
Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single ...
def buffered_generator(source_gen, buffer_size=2, use_multiprocessing=False): r""" Generator that runs a slow source generator in a separate process. My generate function still seems faster on test cases. However, this function is more flexible in its compatability. Args: source_gen (itera...
r""" Generator that runs a slow source generator in a separate process. My generate function still seems faster on test cases. However, this function is more flexible in its compatability. Args: source_gen (iterable): slow generator buffer_size (int): the maximal number of items to pre...
def bit_for_bit(model_path, bench_path, config): """ Checks whether the given files have bit for bit solution matches on the given variable list. Args: model_path: absolute path to the model dataset bench_path: absolute path to the benchmark dataset config: the configuration of ...
Checks whether the given files have bit for bit solution matches on the given variable list. Args: model_path: absolute path to the model dataset bench_path: absolute path to the benchmark dataset config: the configuration of the set of analyses Returns: A dictionary create...
def swap_buffers(self): """ Headless window currently don't support double buffering. We only increment the frame counter here. """ self.frames += 1 if self.headless_frames and self.frames >= self.headless_frames: self.close()
Headless window currently don't support double buffering. We only increment the frame counter here.
def insert(self, loc, item): """ Make new MultiIndex inserting new item at location Parameters ---------- loc : int item : tuple Must be same length as number of levels in the MultiIndex Returns ------- new_index : Index """ ...
Make new MultiIndex inserting new item at location Parameters ---------- loc : int item : tuple Must be same length as number of levels in the MultiIndex Returns ------- new_index : Index
def fetch_turbine_data(self, fetch_curve, data_source): r""" Fetches data of the requested wind turbine. Method fetches nominal power as well as power coefficient curve or power curve from a data set provided in the OpenEnergy Database (oedb). You can also import your own power ...
r""" Fetches data of the requested wind turbine. Method fetches nominal power as well as power coefficient curve or power curve from a data set provided in the OpenEnergy Database (oedb). You can also import your own power (coefficient) curves from a file. For that the wind spee...
def loadSignalFromDelimitedFile(filename, timeColumnIdx=0, dataColumnIdx=1, delimiter=',', skipHeader=0) -> Signal: """ reads a delimited file and converts into a Signal :param filename: string :param timeColumnIdx: 0 indexed column number :param dataColumnIdx: 0 indexed column number :param delimit...
reads a delimited file and converts into a Signal :param filename: string :param timeColumnIdx: 0 indexed column number :param dataColumnIdx: 0 indexed column number :param delimiter: char :return a Signal instance
def check_migrations_applied(app_configs, **kwargs): """ A Django check to see if all migrations have been applied correctly. """ from django.db.migrations.loader import MigrationLoader errors = [] # Load migrations from disk/DB try: loader = MigrationLoader(connection, ignore_no_mi...
A Django check to see if all migrations have been applied correctly.
def convert_layer_to_pil(layer, apply_icc=True, **kwargs): """Convert Layer to PIL Image.""" from PIL import Image header = layer._psd._record.header if header.color_mode == ColorMode.BITMAP: raise NotImplementedError width, height = layer.width, layer.height channels, alpha = [], None ...
Convert Layer to PIL Image.
def _close(self, fd): """ Close the descriptor used for a path regardless of mode. """ if self._mode == WF_INOTIFYX: try: pynotifyx.rm_watch(self._inx_fd, fd) except: pass else: try: os.close(fd) except: pass
Close the descriptor used for a path regardless of mode.
def _concatenate_file(self, file_list, output): ''' Call unix "cat" to concatenate a list of files Parameters ---------- file_list: list List of strings, each leading to a file. These files are the ones to be concatenate together. E.g.: ["...
Call unix "cat" to concatenate a list of files Parameters ---------- file_list: list List of strings, each leading to a file. These files are the ones to be concatenate together. E.g.: ["/path/to/file1", "/path/to/file2"] output: str P...
def _clone_vm(image=None, name=None, session=None): ''' Create VM by cloning This is faster and should be used if source and target are in the same storage repository ''' if session is None: session = _get_session() log.debug('Creating VM %s by cloning %s', name, image) source ...
Create VM by cloning This is faster and should be used if source and target are in the same storage repository
def make_meetup_blueprint( key=None, secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): """ Make a blueprint for authenticating with Meetup using OAuth 2. This requires an OAuth consumer ...
Make a blueprint for authenticating with Meetup using OAuth 2. This requires an OAuth consumer from Meetup. You should either pass the key and secret to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`MEETUP_OAUTH_CLIENT_ID` and :envvar:`MEETU...
def match_file(apikey, path, metadata=None): """Uses the audioread library to decode an audio file and match it. """ import audioread with audioread.audio_open(path) as f: return match(apikey, iter(f), f.samplerate, int(f.duration), f.channels, metadata)
Uses the audioread library to decode an audio file and match it.
def most_common_nucleotides(partitioned_read_sequences): """ Find the most common nucleotide at each offset to the left and right of a variant. Parameters ---------- partitioned_read_sequences : list of tuples Each tuple has three elements: - sequence before mutant nucleotid...
Find the most common nucleotide at each offset to the left and right of a variant. Parameters ---------- partitioned_read_sequences : list of tuples Each tuple has three elements: - sequence before mutant nucleotides - mutant nucleotides - sequence after muta...
def handle_init(args): """usage: cosmic-ray init <config-file> <session-file> Initialize a mutation testing session from a configuration. This primarily creates a session - a database of "work to be done" - which describes all of the mutations and test runs that need to be executed for a full mutat...
usage: cosmic-ray init <config-file> <session-file> Initialize a mutation testing session from a configuration. This primarily creates a session - a database of "work to be done" - which describes all of the mutations and test runs that need to be executed for a full mutation testing run. The configura...
def render_diagram(out_base): """Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot'...
Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot' executable from the GraphViz package...
def cmd(self, tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', jid='', full_return=False, kwarg=None, **kwargs): ''' Synchronously execute a command on targeted minions ...
Synchronously execute a command on targeted minions The cmd method will execute and wait for the timeout period for all minions to reply, then it will return all minion data at once. .. code-block:: python >>> import salt.client >>> local = salt.client.LocalClient() ...
def staticdir(): """Return the location of the static data directory.""" root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(root, "static")
Return the location of the static data directory.
def fix_pin(self, line): """ Fix dependency by removing post-releases from versions and loosing constraints on internal packages. Drop packages from ignore set Also populate packages set """ dep = Dependency(line) if dep.valid: if dep.package ...
Fix dependency by removing post-releases from versions and loosing constraints on internal packages. Drop packages from ignore set Also populate packages set
def classdef__30(self, class_loc, name_tok, arglist_opt, colon_loc, body): """(3.0) classdef: 'class' NAME ['(' [testlist] ')'] ':' suite""" arglist, lparen_loc, rparen_loc = [], None, None bases, keywords, starargs, kwargs = [], [], None, None star_loc, dstar_loc = None, None if...
(3.0) classdef: 'class' NAME ['(' [testlist] ')'] ':' suite
def setButton(self, which, button): """ Sets the button for this wizard for the inputed type. :param which | <XOverlayWizard.WizardButton> button | <QtGui.QPushButton> """ try: self._buttons[which].deleteLater() except KeyError: ...
Sets the button for this wizard for the inputed type. :param which | <XOverlayWizard.WizardButton> button | <QtGui.QPushButton>
def _extract_pynn_components_to_neuroml(nl_model, nml_doc=None): """ Parse the NeuroMLlite description for cell, synapses and inputs described as PyNN elements (e.g. IF_cond_alpha, DCSource) and parameters, and convert these to the equivalent elements in a NeuroMLDocument """ if nml_doc =...
Parse the NeuroMLlite description for cell, synapses and inputs described as PyNN elements (e.g. IF_cond_alpha, DCSource) and parameters, and convert these to the equivalent elements in a NeuroMLDocument
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the encoding of the LongInteger to the output stream. Args: ostream (stream): A buffer to contain the encoded bytes of a LongInteger. Usually a BytearrayStream object. Required. ...
Write the encoding of the LongInteger to the output stream. Args: ostream (stream): A buffer to contain the encoded bytes of a LongInteger. Usually a BytearrayStream object. Required. kmip_version (KMIPVersion): An enumeration defining the KMIP version wi...
def rename(self, columns): """Returns a new DataFrame with renamed columns. Currently a simplified version of Pandas' rename. Parameters ---------- columns : dict Old names to new names. Returns ------- DataFrame With columns ren...
Returns a new DataFrame with renamed columns. Currently a simplified version of Pandas' rename. Parameters ---------- columns : dict Old names to new names. Returns ------- DataFrame With columns renamed, if found.
def main(args=None): """Entry point for `fuel-download` script. This function can also be imported and used from Python. Parameters ---------- args : iterable, optional (default: None) A list of arguments that will be passed to Fuel's downloading utility. If this argument is not sp...
Entry point for `fuel-download` script. This function can also be imported and used from Python. Parameters ---------- args : iterable, optional (default: None) A list of arguments that will be passed to Fuel's downloading utility. If this argument is not specified, `sys.argv[1:]` will...
def raw_to_delimited(header: Header, raw_payload: RawPayload) -> DelimitedMsg: """\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. """ return tuple(header) + (b'',) + tuple(raw_payload)
\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s.
def get_handler(self): """Create a fully configured CloudLoggingHandler. Returns: (obj): Instance of `google.cloud.logging.handlers. CloudLoggingHandler` """ gcl_client = gcl_logging.Client( project=self.project_id, credentials=se...
Create a fully configured CloudLoggingHandler. Returns: (obj): Instance of `google.cloud.logging.handlers. CloudLoggingHandler`
def get_channel_image(self, channel, img_size=300, skip_cache=False): """Get the logo for a channel""" from bs4 import BeautifulSoup from wikipedia.exceptions import PageError import re import wikipedia wikipedia.set_lang('fr') if not channel: _LOGGER...
Get the logo for a channel
def _get_keyid_by_gpg_key(key_material): """Get a GPG key fingerprint by GPG key material. Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded or binary GPG key material. Can be used, for example, to generate file names for keys passed via charm options. :param key_material: A...
Get a GPG key fingerprint by GPG key material. Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded or binary GPG key material. Can be used, for example, to generate file names for keys passed via charm options. :param key_material: ASCII armor-encoded or binary GPG key material ...
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (...
Re-raise the currently-handled TypeError with the field name added.
def mod_watch(name, sfun=None, **kwargs): ''' The docker_image watcher, called to invoke the watch command. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should...
The docker_image watcher, called to invoke the watch command. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered.
def forget(self): """ Remove memory of state variables set in the command processor """ self.stack = [] self.curindex = 0 self.curframe = None self.thread_name = None self.frame_thread_name = None return
Remove memory of state variables set in the command processor
def __closely_associated_score(self, normalized_sentences, top_n_words): ''' Scoring the sentence with closely associations. Args: normalized_sentences: The list of sentences. top_n_words: Important sentences. Returns: The list of scores...
Scoring the sentence with closely associations. Args: normalized_sentences: The list of sentences. top_n_words: Important sentences. Returns: The list of scores.
def _from_yang_library(self, yang_lib: Dict[str, Any]) -> None: """Set the schema structures from YANG library data. Args: yang_lib: Dictionary with YANG library data. Raises: BadYangLibraryData: If YANG library data is invalid. FeaturePrerequisiteError: If ...
Set the schema structures from YANG library data. Args: yang_lib: Dictionary with YANG library data. Raises: BadYangLibraryData: If YANG library data is invalid. FeaturePrerequisiteError: If a pre-requisite feature isn't supported. Multip...
def type_to_string(t): """Get string representation of memory type""" if t == MemoryElement.TYPE_I2C: return 'I2C' if t == MemoryElement.TYPE_1W: return '1-wire' if t == MemoryElement.TYPE_DRIVER_LED: return 'LED driver' if t == MemoryElement.T...
Get string representation of memory type
def complete(self): """ Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the sample.general.bestassemblyfile != 'NA' """ # Boolean to store the completeness of the analyses allcomplete = True # Clear the list of samp...
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the sample.general.bestassemblyfile != 'NA'
def set_route_name(self, ip_dest, next_hop, **kwargs): """Set the route_name value for the specified route Args: ip_dest (string): The ip address of the destination in the form of A.B.C.D/E next_hop (string): The next hop interface or ip address **kwa...
Set the route_name value for the specified route Args: ip_dest (string): The ip address of the destination in the form of A.B.C.D/E next_hop (string): The next hop interface or ip address **kwargs['next_hop_ip'] (string): The next hop address on ...
def DemoDB(keys_per_column=None, **kwargs): """ Provides an instance of DB that hooks up to the Chinook DB See http://chinookdatabase.codeplex.com/ for more info. """ _ROOT = os.path.abspath(os.path.dirname(__file__)) chinook = os.path.join(_ROOT, 'data', 'chinook.sqlite') return DB(filename...
Provides an instance of DB that hooks up to the Chinook DB See http://chinookdatabase.codeplex.com/ for more info.
def _sync_params_from_devices(self): """Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sp...
Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sparse parameters on devices, ther are pulled from...
def check_answer(self, task_input, language): """ Verify the answers in task_input. Returns six values 1st: True the input is **currently** valid. (may become invalid after running the code), False else 2nd: True if the input needs to be run in the VM, False else ...
Verify the answers in task_input. Returns six values 1st: True the input is **currently** valid. (may become invalid after running the code), False else 2nd: True if the input needs to be run in the VM, False else 3rd: Main message, as a list (that can be join with \n or <br/> for ex...
def store_checksums(dataset_name, sizes_checksums): """Store given checksums and sizes for specific dataset. Content of file is never disgarded, only updated. This is to ensure that if process is killed right after first download finishes, checksums registered during previous runs aren't lost. It is the res...
Store given checksums and sizes for specific dataset. Content of file is never disgarded, only updated. This is to ensure that if process is killed right after first download finishes, checksums registered during previous runs aren't lost. It is the responsibility of the caller not to call function multiple t...