code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def sync(self): 'Update state of folder from Jottacloud server' log.info("syncing %r" % self.path) self.folder = self.jfs.get(self.path) self.synced = True
Update state of folder from Jottacloud server
def get_submissions_multiple_assignments_by_sis_id( self, is_section, sis_id, students=None, assignments=None, **params): """ List submissions for multiple assignments by course/section sis id and optionally student https://canvas.instructure.com/doc/api/submissi...
List submissions for multiple assignments by course/section sis id and optionally student https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.for_students
def is_group(value): """ Check whether groupname or gid as argument exists. if this function recieved groupname, convert gid and exec validation. """ if type(value) == str: try: entry = grp.getgrnam(value) value = entry.gr_gid except KeyError: err...
Check whether groupname or gid as argument exists. if this function recieved groupname, convert gid and exec validation.
def configure(logstash_host=None, logstash_port=None, logdir=None): '''Configuration settings.''' if not (logstash_host or logstash_port or logdir): raise ValueError('you must specify at least one parameter') config.logstash.host = logstash_host or config.logstash.host config.logstash.port = l...
Configuration settings.
def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, ...
.. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (...
def add_sync_methods(cls): """Class decorator to add synchronous methods corresponding to async methods. This modifies the class in place, adding additional methods to it. If a synchronous method of a given name already exists it is not replaced. Args: cls: A class. Returns: The same class, modif...
Class decorator to add synchronous methods corresponding to async methods. This modifies the class in place, adding additional methods to it. If a synchronous method of a given name already exists it is not replaced. Args: cls: A class. Returns: The same class, modified in place.
def to_download(): """ Build interval of urls to download. We always get the first file of the next day. Ex: 2013-01-01 => 2013-01-02.0000 """ first_day = parse(interval_first) last_day = parse(interval_last) format_change = parse('2010-06-14') one_day = datetime.timedelt...
Build interval of urls to download. We always get the first file of the next day. Ex: 2013-01-01 => 2013-01-02.0000
def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/newFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder """ return DXHTTPRequest('/%s/newF...
Invokes the /project-xxxx/newFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder
def parent_frame_arguments(): """Returns parent frame arguments. When called inside a function, returns a dictionary with the caller's function arguments. These are positional arguments and keyword arguments (**kwargs), while variable arguments (*varargs) are excluded. When called at global scope, this will...
Returns parent frame arguments. When called inside a function, returns a dictionary with the caller's function arguments. These are positional arguments and keyword arguments (**kwargs), while variable arguments (*varargs) are excluded. When called at global scope, this will return an empty dictionary, since ...
def _generate_annotation_type_class(self, ns, annotation_type): # type: (ApiNamespace, AnnotationType) -> None """Defines a Python class that represents an annotation type in Stone.""" self.emit('class {}(bb.AnnotationType):'.format( class_name_for_annotation_type(annotation_type, ns...
Defines a Python class that represents an annotation type in Stone.
def G(self, T): """Calculate the heat capacity of the compound phase at the specified temperature. :param T: [K] temperature :returns: [J/mol] The Gibbs free energy of the compound phase. """ h = self.DHref s = self.Sref for Tmax in sorted([float(TT) f...
Calculate the heat capacity of the compound phase at the specified temperature. :param T: [K] temperature :returns: [J/mol] The Gibbs free energy of the compound phase.
def create(ctx, name, description, tags, private, init): """Create a new project. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon project create --name=cats-vs-dogs --description="Image Classification with DL" ``` """ try: tags = tags.split...
Create a new project. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon project create --name=cats-vs-dogs --description="Image Classification with DL" ```
def _write_source_data(self, sources): """ See src/jjk/measure3 """ for i, source in enumerate(sources): self._write_source(source)
See src/jjk/measure3
def join_pretty_tensors(tensors, output, join_function=None, name='join'): """Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A functio...
Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A function to join the tensors, defaults to concat on the last dimension. name:...
def _add_error(self, *args, **kwargs): # type: () -> None """Convenience function to add an error to this object, with line numbers An error title or description should not accidentally leak self._value, for privacy/redaction purposes. :rtype: None """ if kwargs.get('node', No...
Convenience function to add an error to this object, with line numbers An error title or description should not accidentally leak self._value, for privacy/redaction purposes. :rtype: None
def set_weather_from_metar( metar: typing.Union[Metar.Metar, str], in_file: typing.Union[str, Path], out_file: typing.Union[str, Path] = None ) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]: """ Applies the weather from a METAR object to a MIZ file Args: ...
Applies the weather from a METAR object to a MIZ file Args: metar: metar object in_file: path to MIZ file out_file: path to output MIZ file (will default to in_file) Returns: tuple of error, success
def SensorsTriggersNotificationsDelete(self, sensor_id, trigger_id, notification_id): """ Disconnect a notification from a sensor-trigger combination. @param sensor_id (int) - Sensor id if the sensor-trigger combination. @param trigger_id (int) - Trigger id ...
Disconnect a notification from a sensor-trigger combination. @param sensor_id (int) - Sensor id if the sensor-trigger combination. @param trigger_id (int) - Trigger id of the sensor-trigger combination. @param notification_id (int) - Notification id of the notificati...
def write_users(dburl): """Write users to the DB.""" data = { 'username': 'admin', 'realname': 'Website Administrator', 'email': 'coil@example.com', 'password': r'$bcrypt-sha256$2a,12$NNtd2TC9mZO6.EvLwEwlLO$axojD34/iE8x' r'QitQnCCOGPhofgmjNdq', } ...
Write users to the DB.
def to_dict(self): """Return a dictionary containing Atom data.""" data = {'aid': self.aid, 'number': self.number, 'element': self.element} for coord in {'x', 'y', 'z'}: if getattr(self, coord) is not None: data[coord] = getattr(self, coord) if self.charge is ...
Return a dictionary containing Atom data.
def _disappeared(self, fd, path, **params): """ Called when an open path is no longer acessible. This will either move the path to pending (if the 'missing' param is set for the file), or fire an exception. """ log = self._getparam('log', self._discard, **params) lo...
Called when an open path is no longer acessible. This will either move the path to pending (if the 'missing' param is set for the file), or fire an exception.
def set_timestamp_to_current(self): """ Set timestamp to current time utc :rtype: None """ # Good form to add tzinfo self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow())
Set timestamp to current time utc :rtype: None
def seat_button_count(self): """The total number of buttons pressed on all devices on the associated seat after the the event was triggered. For events that are not of type :attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property raises :exc:`AttributeError`. Returns: int: The seat wide p...
The total number of buttons pressed on all devices on the associated seat after the the event was triggered. For events that are not of type :attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property raises :exc:`AttributeError`. Returns: int: The seat wide pressed button count for the key of...
def replace_pipe(self, name, component): """Replace a component in the pipeline. name (unicode): Name of the component to replace. component (callable): Pipeline component. DOCS: https://spacy.io/api/language#replace_pipe """ if name not in self.pipe_names: ...
Replace a component in the pipeline. name (unicode): Name of the component to replace. component (callable): Pipeline component. DOCS: https://spacy.io/api/language#replace_pipe
def sendNotification(snmpDispatcher, authData, transportTarget, notifyType, *varBinds, **options): """Creates a generator to send SNMP notification. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`). The...
Creates a generator to send SNMP notification. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ...
def swo_set_emu_buffer_size(self, buf_size): """Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkExc...
Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error
async def fetch(self, *args, timeout=None): r"""Execute the statement and return a list of :class:`Record` objects. :param str query: Query text :param args: Query arguments :param float timeout: Optional timeout value in seconds. :return: A list of :class:`Record` instances. ...
r"""Execute the statement and return a list of :class:`Record` objects. :param str query: Query text :param args: Query arguments :param float timeout: Optional timeout value in seconds. :return: A list of :class:`Record` instances.
def _get_crawled_urls(self, handle, request): """ Main method where the crawler html content is parsed with beautiful soup and out of the DOM, we get the urls """ try: content = six.text_type(handle.open(request).read(), "utf-8", er...
Main method where the crawler html content is parsed with beautiful soup and out of the DOM, we get the urls
def get_account_db_class(cls) -> Type[BaseAccountDB]: """ Return the :class:`~eth.db.account.BaseAccountDB` class that the state class uses. """ if cls.account_db_class is None: raise AttributeError("No account_db_class set for {0}".format(cls.__name__)) retur...
Return the :class:`~eth.db.account.BaseAccountDB` class that the state class uses.
def encodeValue(value): """ TODO """ if isinstance(value, (list, tuple)): return [common.AttributeValue(string_value=str(v)) for v in value] else: return [common.AttributeValue(string_value=str(value))]
TODO
def breadth_first(problem, graph_search=False, viewer=None): ''' Breadth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal. ''' return _search(problem, FifoList(), ...
Breadth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal.
def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None): """ Converts between content body representations. Not all representations can be converted to/from other formats. Supported conversions: Source Representation | Destinatio...
Converts between content body representations. Not all representations can be converted to/from other formats. Supported conversions: Source Representation | Destination Representation Supported -------------------------------------------------------------- "storage" | ...
def type_to_string(f, map_types): """ Convert type info to pretty names, based on numbers from from FieldDescriptorProto https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor.pb """ if f.type in [1]: return "double" elif f.type in [2]: retur...
Convert type info to pretty names, based on numbers from from FieldDescriptorProto https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor.pb
def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]: """ Returns only the tokens present in the sentence that are in labels.""" if labels: return [tok for tok in sent if tok in labels] return list(sent)
Returns only the tokens present in the sentence that are in labels.
def update_function_code(FunctionName, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Publish=False, region=None, key=None, keyid=None, profile=None): ''' Upload the given code to the named lambda function. Returns {updated: true} if the fun...
Upload the given code to the named lambda function. Returns {updated: true} if the function was updated and returns {updated: False} if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip
def _validate_min(self, proposal): """Enforce min <= value <= max""" min = proposal['value'] if min > self.max: raise TraitError('Setting min > max') if min > self.value: self.value = min return min
Enforce min <= value <= max
def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8', **logs_kwargs): """ Wait for logs matching the given matcher. """ wait_for_logs_matching( self.inner(), matcher, timeout=timeout, encoding=encoding, **logs_kwarg...
Wait for logs matching the given matcher.
def _to_chimera(M, N, L, q): "Converts a qubit's linear index to chimera coordinates." return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L)
Converts a qubit's linear index to chimera coordinates.
def from_credentials(cls: Type[SigningKeyType], salt: Union[str, bytes], password: Union[str, bytes], scrypt_params: Optional[ScryptParams] = None) -> SigningKeyType: """ Create a SigningKey object from credentials :param salt: Secret salt passphrase credential ...
Create a SigningKey object from credentials :param salt: Secret salt passphrase credential :param password: Secret password credential :param scrypt_params: ScryptParams instance
def _write_entries(self, stream, entries, converter, properties=None): """Write iterable of entries as YAML object to stream. Args: stream: File-like object. entries: Iterable of entries. converter: Conversion function from entry to YAML object. propertie...
Write iterable of entries as YAML object to stream. Args: stream: File-like object. entries: Iterable of entries. converter: Conversion function from entry to YAML object. properties: Set of compartment properties to output (or None to output all)...
async def scroll(self, value, mode='relative'): """Scroll the cursor in the result set to a new position according to mode . Same as :meth:`Cursor.scroll`, but move cursor on server side one by one row. If you want to move 20 rows forward scroll will make 20 queries to move cursor. Curre...
Scroll the cursor in the result set to a new position according to mode . Same as :meth:`Cursor.scroll`, but move cursor on server side one by one row. If you want to move 20 rows forward scroll will make 20 queries to move cursor. Currently only forward scrolling is supported. ...
def var_added(self, v): """ var was added in the bot while it ran, possibly by livecoding :param v: :return: """ self.add_variable(v) self.window.set_size_request(400, 35 * len(self.widgets.keys())) self.window.show_all()
var was added in the bot while it ran, possibly by livecoding :param v: :return:
def mmGetCellActivityPlot(self, title="", showReset=False, resetShading=0.25, activityType="activeCells"): """ Returns plot of the cell activity. @param title (string) an optional title for the figure @param showReset (bool) if true, the first set of cell acti...
Returns plot of the cell activity. @param title (string) an optional title for the figure @param showReset (bool) if true, the first set of cell activities after a reset will have a gray background @param resetShading (float) if showReset is true, this fl...
def get_matching_indexes(self, possible_hash, possible_range): """ Get all indexes that could be queried on using a set of keys. If any indexes match both hash AND range keys, indexes that only match the hash key will be excluded from the result. Parameters ---------- ...
Get all indexes that could be queried on using a set of keys. If any indexes match both hash AND range keys, indexes that only match the hash key will be excluded from the result. Parameters ---------- possible_hash : set The names of fields that could be used as th...
def do_transform(self): """Apply the transformation (if it exists) to the latest_value""" if not self.transform: return try: self.latest_value = utils.Transform( expr=self.transform, value=self.latest_value, timedelta=self.time_between_upda...
Apply the transformation (if it exists) to the latest_value
def links(xmrs): """Return the list of Links for the *xmrs*.""" # Links exist for every non-intrinsic argument that has a variable # that is the intrinsic variable of some other predicate, as well # as for label equalities when no argument link exists (even # considering transitivity). links = ...
Return the list of Links for the *xmrs*.
def brightness_prob(self, clip=True): """The brightest water may have Band 5 reflectance as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11 Equation 10 (Zhu and Woodcock, 2012) Parameters ---------- nir: ndarray clip: boolean Output ...
The brightest water may have Band 5 reflectance as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11 Equation 10 (Zhu and Woodcock, 2012) Parameters ---------- nir: ndarray clip: boolean Output ------ ndarray: brightness p...
def put( self, path_or_tuple, folder_id='me/skydrive', overwrite=None, downsize=None, bits_api_fallback=True ): '''Upload a file (object), possibly overwriting (default behavior) a file with the same "name" attribute, if it exists. First argument can be either path to a local file or tuple of "(name, f...
Upload a file (object), possibly overwriting (default behavior) a file with the same "name" attribute, if it exists. First argument can be either path to a local file or tuple of "(name, file)", where "file" can be either a file-like object or just a string of bytes. overwrite option can be set to F...
def export_image3d(input, output, size=(800, 600), pcb_rotate=(0, 0, 0), timeout=20, showgui=False): ''' Exporting eagle .brd file into 3D image file using Eagle3D and povray. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displayed) the...
Exporting eagle .brd file into 3D image file using Eagle3D and povray. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception. Problem can be investigated by setting 'showgui' flag. ...
def stdout_avail(self): """Data is available in stdout, let's empty the queue and write it!""" data = self.interpreter.stdout_write.empty_queue() if data: self.write(data)
Data is available in stdout, let's empty the queue and write it!
def removeOutliers(points, radius): """ Remove outliers from a cloud of points within the specified `radius` search. .. hint:: |clustering| |clustering.py|_ """ isactor = False if isinstance(points, vtk.vtkActor): isactor = True poly = points.GetMapper().GetInput() else: ...
Remove outliers from a cloud of points within the specified `radius` search. .. hint:: |clustering| |clustering.py|_
def get(self, key, env=None): """ Returns the config setting for the specified environment. If no environment is specified, the value for the current environment is returned. If an unknown key or environment is passed, None is returned. """ if env is None: env...
Returns the config setting for the specified environment. If no environment is specified, the value for the current environment is returned. If an unknown key or environment is passed, None is returned.
async def strings(self, request: Optional['Request']=None) \ -> List[Tuple[Text, ...]]: """ For the given request, find the list of strings of that intent. If the intent does not exist, it will raise a KeyError. """ if request: locale = await request.get_...
For the given request, find the list of strings of that intent. If the intent does not exist, it will raise a KeyError.
def collect(self): """ Walks self.migration_home and load all potential migration modules """ for root, dirname, files in walk(self.migration_home): for file_name in file_filter(files, "*.py"): file_name = file_name.replace('.py', '') file = No...
Walks self.migration_home and load all potential migration modules
def result(self,num): """result(N) -> return the result of job N.""" try: return self.all[num].result except KeyError: error('Job #%s not found' % num)
result(N) -> return the result of job N.
def reporter(self): """ Creates the metadata report by pulling specific attributes from the metadata objects """ logging.info('Creating summary report') header = '{}\n'.format(','.join(self.headers)) # Create a string to store all the results data = str() ...
Creates the metadata report by pulling specific attributes from the metadata objects
def cfg_to_dot(self, filename): """ Export the function to a dot file Args: filename (str) """ with open(filename, 'w', encoding='utf8') as f: f.write('digraph{\n') for node in self.nodes: f.write('{}[label="{}"];\n'.format(...
Export the function to a dot file Args: filename (str)
def _and_join(self, terms): """ Joins terms using AND operator. Args: terms (list): terms to join Examples: self._and_join(['term1']) -> 'term1' self._and_join(['term1', 'term2']) -> 'term1 AND term2' self._and_join(['term1', 'term2', 'term3']) -...
Joins terms using AND operator. Args: terms (list): terms to join Examples: self._and_join(['term1']) -> 'term1' self._and_join(['term1', 'term2']) -> 'term1 AND term2' self._and_join(['term1', 'term2', 'term3']) -> 'term1 AND term2 AND term3' R...
def log_source(self, loglevel='INFO'): """Logs and returns the entire html source of the current page or frame. The `loglevel` argument defines the used log level. Valid log levels are `WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging). """ ll = loglevel.up...
Logs and returns the entire html source of the current page or frame. The `loglevel` argument defines the used log level. Valid log levels are `WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging).
def _population_load_script(work_bams, names, chrom, pairmode, items): """Prepare BAMs for assessing CNVs in a population. """ bed_file = _get_regional_bed_file(items[0]) if bed_file: return _population_prep_targeted.format(bam_file_str=",".join(work_bams), names_str=",".join(names), ...
Prepare BAMs for assessing CNVs in a population.
def _chain_future(source, dest): """Chain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future. """ i...
Chain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future.
def shutdown(self): """ Called by the server to commence a graceful shutdown. """ if self.cycle is None or self.cycle.response_complete: self.transport.close() else: self.cycle.keep_alive = False
Called by the server to commence a graceful shutdown.
def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"): """VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottl...
VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottleneck object hparams: optional hparams name: an optional string Returns: gates: a Tensor with shape [batch_size, num_experts] loa...
def _set_pg(self, v, load=False): """ Setter method for pg, mapped from YANG variable /rbridge_id/ag/pg (list) If this variable is read-only (config: false) in the source YANG file, then _set_pg is considered as a private method. Backends looking to populate this variable should do so via callin...
Setter method for pg, mapped from YANG variable /rbridge_id/ag/pg (list) If this variable is read-only (config: false) in the source YANG file, then _set_pg is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_pg() directly.
def topology_mdtraj(traj): '''Generate topology spec for the MolecularViewer from mdtraj. :param mdtraj.Trajectory traj: the trajectory :return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj. ''' import mdtraj as md top = {} top['atom_types'] = [a.elemen...
Generate topology spec for the MolecularViewer from mdtraj. :param mdtraj.Trajectory traj: the trajectory :return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
def bulk_history_create(self, objs, batch_size=None): """Bulk create the history for the objects specified by objs""" historical_instances = [ self.model( history_date=getattr(instance, "_history_date", now()), history_user=getattr(instance, "_history_user", ...
Bulk create the history for the objects specified by objs
def get_changed_files(self) -> List[str]: """Get the files changed on one git branch vs another. Returns: List[str]: File paths of changed files, relative to the git repo root. """ out = shell_tools.output_of( 'git', 'diff', ...
Get the files changed on one git branch vs another. Returns: List[str]: File paths of changed files, relative to the git repo root.
def stage_http_response1(self, conn_id, version, status, reason, headers): """Set response http info including headers, status, etc. conn_id unused here. Used in log""" # pylint: disable=attribute-defined-outside-init self._http_response_version = version self._http_response_s...
Set response http info including headers, status, etc. conn_id unused here. Used in log
def str_numerator(self): """Returns the numerator with formatting.""" if not self.undefined: return None unit_numerator, unit = self._unit_class(self.numerator).auto formatter = '%d' if unit_numerator == self.numerator else '%0.2f' numerator = locale.format(formatter,...
Returns the numerator with formatting.
def mount(name=None, **kwargs): ''' Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount opt...
Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount options to use temporarily for the dura...
def _act(self, utterance: str) -> list: """Infers DeepPavlov agent with raw user input extracted from Alexa request. Args: utterance: Raw user input extracted from Alexa request. Returns: response: DeepPavlov agent response. """ if self.stateful: ...
Infers DeepPavlov agent with raw user input extracted from Alexa request. Args: utterance: Raw user input extracted from Alexa request. Returns: response: DeepPavlov agent response.
def find_by_tag(self, tag, params={}, **options): """Returns the compact task records for all tasks with the given tag. Parameters ---------- tag : {Id} The tag in which to search for tasks. [params] : {Object} Parameters for the request """ path = "/tags/%s/tas...
Returns the compact task records for all tasks with the given tag. Parameters ---------- tag : {Id} The tag in which to search for tasks. [params] : {Object} Parameters for the request
def urlvoid_check(name, api_key): """Checks URLVoid.com for info on a domain""" if not is_fqdn(name): return None url = 'http://api.urlvoid.com/api1000/{key}/host/{name}'.format(key=api_key, name=name) response = requests.get(url) tree = ET.fromstring(response.text) if tree.find('./dete...
Checks URLVoid.com for info on a domain
def _validate_readonly(self, readonly, field, value): """ {'type': 'boolean'} """ if readonly: if not self._is_normalized: self._error(field, errors.READONLY_FIELD) # If the document was normalized (and therefore already been # checked for readonly fie...
{'type': 'boolean'}
def remove_sub(self, sub): """ Remove all references to a specific Subject ID :param sub: A Subject ID """ for _sid in self.get('sub2sid', sub): self.remove('sid2sub', _sid, sub) self.delete('sub2sid', sub)
Remove all references to a specific Subject ID :param sub: A Subject ID
def convert_pronouns( mrf_lines ): ''' Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to syntactic analyzer's mrf format; Uses the set of predefined pronoun conversion rules from _pronConversions; _pronConversions should be a list of lists, where each outer list ...
Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to syntactic analyzer's mrf format; Uses the set of predefined pronoun conversion rules from _pronConversions; _pronConversions should be a list of lists, where each outer list stands for a single conversion rul...
def K_value(P=None, Psat=None, phi_l=None, phi_g=None, gamma=None, Poynting=1): r'''Calculates the equilibrium K-value assuming Raoult's law, or an equation of state model, or an activity coefficient model, or a combined equation of state-activity model. The calculation procedure will use the most adva...
r'''Calculates the equilibrium K-value assuming Raoult's law, or an equation of state model, or an activity coefficient model, or a combined equation of state-activity model. The calculation procedure will use the most advanced approach with the provided inputs: * If `P`, `Psat`, `phi_l`, `phi...
def run(self, i_str, start_count=0, start_chunk_time=None): '''Run the pipeline. This runs all of the steps described in the pipeline constructor, reading from some input and writing to some output. :param str i_str: name of the input file, or other reader-specific descriptio...
Run the pipeline. This runs all of the steps described in the pipeline constructor, reading from some input and writing to some output. :param str i_str: name of the input file, or other reader-specific description of where to get input :param int start_count: index of the fi...
def next(self) -> Future: """Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs. """ self._running_future = Future() if self._finished: self._return_result(self._finished.p...
Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs.
def all_after_notification(self, model, prop_name, info): """ The method logs all changes that notified recursively trough the hierarchies of the states after the change occurs in the rafcon.core object. The method register as observer of observable StateMachineModel.state_machine of any observe...
The method logs all changes that notified recursively trough the hierarchies of the states after the change occurs in the rafcon.core object. The method register as observer of observable StateMachineModel.state_machine of any observed StateMachineModel. :param model: StateMachineModel that is r...
def alien_filter(name, location, size, unsize): """Fix to avoid packages include in slackbuilds folder """ (fname, flocation, fsize, funsize) = ([] for i in range(4)) for n, l, s, u in zip(name, location, size, unsize): if "slackbuilds" != l: fname.append(n) flocation.app...
Fix to avoid packages include in slackbuilds folder
def _check_triple(self, triple): """compare triple to ontology, return error or None""" subj, pred, obj = triple if self._should_ignore_predicate(pred): log.info("Ignoring triple with predicate '{}'" .format(self._field_name_from_uri(pred))) return ...
compare triple to ontology, return error or None
def _get_pos_name(pos_code, names='parent', english=True, pos_map=POS_MAP): """Gets the part of speech name for *pos_code*.""" pos_code = pos_code.lower() # Issue #10 if names not in ('parent', 'child', 'all'): raise ValueError("names must be one of 'parent', 'child', or " ...
Gets the part of speech name for *pos_code*.
def keys_present(name, number, save_dir, region=None, key=None, keyid=None, profile=None, save_format="{2}\n{0}\n{3}\n{1}\n"): ''' .. versionadded:: 2015.8.0 Ensure the IAM access keys are present. name (string) The name of the new user. number (int) Number of key...
.. versionadded:: 2015.8.0 Ensure the IAM access keys are present. name (string) The name of the new user. number (int) Number of keys that user should have. save_dir (string) The directory that the key/keys will be saved. Keys are saved to a file named according to t...
def get_installed_distributions(local_only=True, skip=('setuptools', 'pip', 'python')): """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower...
Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also skip...
def draw_points_heatmap_array(self, image_shape, alpha=1.0, size=1, raise_if_out_of_image=False): """ Draw the points of the line string as a heatmap array. Parameters ---------- image_shape : tuple of int The shape of the image onto...
Draw the points of the line string as a heatmap array. Parameters ---------- image_shape : tuple of int The shape of the image onto which to draw the point mask. alpha : float, optional Opacity of the line string points. Higher values denote a more v...
def validate_args(f): """ Ensures that *args consist of a consistent type :param f: any client method with *args parameter :return: function f """ def wrapper(self, args): arg_types = set([type(arg) for arg in args]) if len(arg_types) > 1: raise TypeError("Mixed inp...
Ensures that *args consist of a consistent type :param f: any client method with *args parameter :return: function f
def get_tmaster(self, topologyName, callback=None): """ get tmaster """ isWatching = False # Temp dict used to return result # if callback is not provided. ret = { "result": None } if callback: isWatching = True else: def callback(data): """ Custom ca...
get tmaster
def to_primitive(self, value, context=None): """ Schematics serializer override If epoch_date is true then convert the `datetime.datetime` object into an epoch `int`. """ if context and context.get('epoch_date'): epoch = dt(1970, 1, 1) value = (value - e...
Schematics serializer override If epoch_date is true then convert the `datetime.datetime` object into an epoch `int`.
def configure(self): """Configure the device. Send the device configuration saved inside the MCP342x object to the target device.""" logger.debug('Configuring ' + hex(self.get_address()) + ' ch: ' + str(self.get_channel()) + ' res: ' + str(self.get_reso...
Configure the device. Send the device configuration saved inside the MCP342x object to the target device.
def get_id(date=None, project: str = 'sip', instance_id: int = None) -> str: """Get a SBI Identifier. Args: date (str or datetime.datetime, optional): UTC date of the SBI project (str, optional ): Project Name instance_id (int, optional): SBI instance ...
Get a SBI Identifier. Args: date (str or datetime.datetime, optional): UTC date of the SBI project (str, optional ): Project Name instance_id (int, optional): SBI instance identifier Returns: str, Scheduling Block Instance (SBI) ID.
def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path, num_debug_videos=1, random_starts_step_limit=None, report_fn=None, report_metric=None ): """Evaluate.""" if eval_with_learner: assert...
Evaluate.
def get_word_id (root): """ lookup/assign a unique identify for each word root """ global UNIQ_WORDS # in practice, this should use a microservice via some robust # distributed cache, e.g., Redis, Cassandra, etc. if root not in UNIQ_WORDS: UNIQ_WORDS[root] = len(UNIQ_WORDS) ret...
lookup/assign a unique identify for each word root
def user_has_permission(self, user, name): """ verify user has permission """ targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return False for group in targetRecord.groups: if self.has_permission(group.role, name)...
verify user has permission
def _handle_union(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_union. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling union") union_cls = StructUnionDef("union", self, node) ...
TODO: Docstring for _handle_union. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
def generate_all(sumlevel, d): """Generate a dict that includes all of the available geoid values, with keys for the most common names for those values. """ from geoid.civick import GVid from geoid.tiger import TigerGeoid from geoid.acs import AcsGeoid sumlevel = int(sumlevel) d = dict(d....
Generate a dict that includes all of the available geoid values, with keys for the most common names for those values.
def plate_exchanger_identifier(self): '''Method to create an identifying string in format 'L' + wavelength + 'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and amplitude are specified in units of mm and rounded to two decimal places. ''' s = ('L' + str(round(se...
Method to create an identifying string in format 'L' + wavelength + 'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and amplitude are specified in units of mm and rounded to two decimal places.
def _process_wave_param(self, pval): """Process individual model parameter representing wavelength.""" return self._process_generic_param( pval, self._internal_wave_unit, equivalencies=u.spectral())
Process individual model parameter representing wavelength.
def safe_int_conv(number): """Safely convert a single number to integer.""" try: return int(np.array(number).astype(int, casting='safe')) except TypeError: raise ValueError('cannot safely convert {} to integer'.format(number))
Safely convert a single number to integer.
def is_for_driver_task(self): """See whether this function descriptor is for a driver or not. Returns: True if this function descriptor is for driver tasks. """ return all( len(x) == 0 for x in [self.module_name, self.class_name, self.function_name])
See whether this function descriptor is for a driver or not. Returns: True if this function descriptor is for driver tasks.
def list(self, **filters): """ Returns a queryset filtering object by user permission. If you want, you can specify filter arguments. See https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter for more details """ LOG.debug(u'Querying %s by filters=%s', self.model_cl...
Returns a queryset filtering object by user permission. If you want, you can specify filter arguments. See https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter for more details