code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def insertBefore(self, child: Node, ref_node: Node) -> Node: """Insert new child node before the reference child node. If the reference node is not a child of this node, raise ValueError. If this instance is connected to the node on browser, the child node is also added to it. "...
Insert new child node before the reference child node. If the reference node is not a child of this node, raise ValueError. If this instance is connected to the node on browser, the child node is also added to it.
def buglist(self, from_date=DEFAULT_DATETIME): """Get a summary of bugs in CSV format. :param from_date: retrieve bugs that where updated from that date """ if not self.version: self.version = self.__fetch_version() if self.version in self.OLD_STYLE_VERSIONS: ...
Get a summary of bugs in CSV format. :param from_date: retrieve bugs that where updated from that date
def get_ports(self, id_or_uri, start=0, count=-1): """ Gets all interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. start: The first item to return, using 0-based indexing. If not specified, the ...
Gets all interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: ...
def _update_console(self, value=None): """ Update the progress bar to the given value (out of the total given to the constructor). """ if self._total == 0: frac = 1.0 else: frac = float(value) / float(self._total) file = self._file ...
Update the progress bar to the given value (out of the total given to the constructor).
def contains_non_repeat_actions(self): ''' Because repeating repeat actions can get ugly real fast ''' for action in self.actions: if not isinstance(action, (int, dynamic.RepeatCommand)): return True return False
Because repeating repeat actions can get ugly real fast
def udf(f=None, returnType=StringType()): """Creates a user defined function (UDF). .. note:: The user-defined functions are considered deterministic by default. Due to optimization, duplicate invocations may be eliminated or the function may even be invoked more times than it is present in the...
Creates a user defined function (UDF). .. note:: The user-defined functions are considered deterministic by default. Due to optimization, duplicate invocations may be eliminated or the function may even be invoked more times than it is present in the query. If your function is not deterministic, ca...
def _cmp(self, other): """ Comparator function for two :class:`~pywbem.CIMParameter` objects. The comparison is based on their public attributes, in descending precedence: * `name` * `type` * `reference_class` * `is_array` * `array_size` ...
Comparator function for two :class:`~pywbem.CIMParameter` objects. The comparison is based on their public attributes, in descending precedence: * `name` * `type` * `reference_class` * `is_array` * `array_size` * `qualifiers` * `value` * ...
def zip(self, *items): """ Zip the collection together with one or more arrays. :param items: The items to zip :type items: list :rtype: Collection """ return self.__class__(list(zip(self.items, *items)))
Zip the collection together with one or more arrays. :param items: The items to zip :type items: list :rtype: Collection
def funnel_rebuild(psg_trm_spec): """Rebuilds a model and compares it to a reference model. Parameters ---------- psg_trm: (([float], float, int), AMPAL, specification) A tuple containing the parameters, score and generation for a model as well as a model of the ...
Rebuilds a model and compares it to a reference model. Parameters ---------- psg_trm: (([float], float, int), AMPAL, specification) A tuple containing the parameters, score and generation for a model as well as a model of the best scoring parameters. Returns ...
def most_recent_common_ancestor(self, *ts): """Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found. """ if len(ts) > 200: res = self._large_mrca(ts) else: ...
Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found.
def build_sdk_span(self, span): """ Takes a BasicSpan and converts into an SDK type JsonSpan """ custom_data = CustomData(tags=span.tags, logs=self.collect_logs(span)) sdk_data = SDKData(name=span.operation_name, custom=custom_data, ...
Takes a BasicSpan and converts into an SDK type JsonSpan
def _load_github_repo(): """ Loads the GitHub repository from the users config. """ if 'TRAVIS' in os.environ: raise RuntimeError('Detected that we are running in Travis. ' 'Stopping to prevent infinite loops.') try: with open(os.path.join(config_dir, 'repo'), 'r')...
Loads the GitHub repository from the users config.
def get(self): """ Get a JSON-ready representation of this OpenTracking. :returns: This OpenTracking, ready for use in a request body. :rtype: dict """ open_tracking = {} if self.enable is not None: open_tracking["enable"] = self.enable if se...
Get a JSON-ready representation of this OpenTracking. :returns: This OpenTracking, ready for use in a request body. :rtype: dict
def handle(client, request): """ Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict }, ... # forma...
Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict }, ... # formaters ] } if no f...
def has_perm(self, user_obj, perm, obj=None): """ Check if user have permission of himself If the user_obj is not authenticated, it return ``False``. If no object is specified, it return ``True`` when the corresponding permission was specified to ``True`` (changed from v0.7.0)....
Check if user have permission of himself If the user_obj is not authenticated, it return ``False``. If no object is specified, it return ``True`` when the corresponding permission was specified to ``True`` (changed from v0.7.0). This behavior is based on the django system. http...
def get(zpool, prop=None, show_source=False, parsable=True): ''' .. versionadded:: 2016.3.0 Retrieves the given list of properties zpool : string Name of storage pool prop : string Optional name of property to retrieve show_source : boolean Show source of property ...
.. versionadded:: 2016.3.0 Retrieves the given list of properties zpool : string Name of storage pool prop : string Optional name of property to retrieve show_source : boolean Show source of property parsable : boolean Display numbers in parsable (exact) values ...
def cluster_application_attempts(self, application_id): """ With the application attempts API, you can obtain a collection of resources that represent an application attempt. :param str application_id: The application id :returns: API response object with JSON data :rtyp...
With the application attempts API, you can obtain a collection of resources that represent an application attempt. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
def page(self, course, task, submission): """ Get all data and display the page """ submission = self.submission_manager.get_input_from_submission(submission) submission = self.submission_manager.get_feedback_from_submission( submission, show_everything=True, ...
Get all data and display the page
def graph_loads(graph_json): ''' Load graph ''' layers = [] for layer in graph_json['layers']: layer_info = Layer(layer['type'], layer['input'], layer['output'], layer['size']) layer_info.is_delete = layer['is_delete'] layers.append(layer_info) graph = Graph(graph_json['m...
Load graph
def _decompose_vectorized_indexer(indexer, shape, indexing_support): """ Decompose vectorized indexer to the successive two indexers, where the first indexer will be used to index backend arrays, while the second one is used to index loaded on-memory np.ndarray. Parameters ---------- indexe...
Decompose vectorized indexer to the successive two indexers, where the first indexer will be used to index backend arrays, while the second one is used to index loaded on-memory np.ndarray. Parameters ---------- indexer: VectorizedIndexer indexing_support: one of IndexerSupport entries Ret...
def log(self, text, level=logging.INFO): """ convenience wrapper for :func:`fileStore.logToMaster` """ self._fileStore.logToMaster(text, level)
convenience wrapper for :func:`fileStore.logToMaster`
def desired_destination(self, network, edge): """Returns the agents next destination given their current location on the network. An ``Agent`` chooses one of the out edges at random. The probability that the ``Agent`` will travel along a specific edge is specified in the :class:...
Returns the agents next destination given their current location on the network. An ``Agent`` chooses one of the out edges at random. The probability that the ``Agent`` will travel along a specific edge is specified in the :class:`QueueNetwork's<.QueueNetwork>` transition matrix...
def com_google_fonts_check_family_equal_glyph_names(ttFonts): """Fonts have equal glyph names?""" fonts = list(ttFonts) all_glyphnames = set() for ttFont in fonts: all_glyphnames |= set(ttFont["glyf"].glyphs.keys()) missing = {} available = {} for glyphname in all_glyphnames: missing[glyphname] ...
Fonts have equal glyph names?
def write_data(self, variable_id, value): """ write values to the device """ i = 0 j = 0 while i < 10: try: self.inst.query('*IDN?') # logger.info("Visa-AFG1022-Write-variable_id : %s et value : %s" %(variable_id, value)) ...
write values to the device
def purge_db(self): """ Clear all matching our user_id. """ with self.engine.begin() as db: purge_user(db, self.user_id)
Clear all matching our user_id.
def get_projects(session, query): """ Get one or more projects """ # GET /api/projects/0.1/projects response = make_get_request(session, 'projects', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise Proje...
Get one or more projects
def get_area_def(self, dsid): """Get the area definition of the dataset.""" geocoding = self.root.find('.//Tile_Geocoding') epsg = geocoding.find('HORIZONTAL_CS_CODE').text rows = int(geocoding.find('Size[@resolution="' + str(dsid.resolution) + '"]/NROWS').text) cols = int(geocod...
Get the area definition of the dataset.
def extant_item(arg, arg_type): """Determine if parser argument is an existing file or directory. This technique comes from http://stackoverflow.com/a/11541450/95592 and from http://stackoverflow.com/a/11541495/95592 Args: arg: parser argument containing filename to be checked arg_type...
Determine if parser argument is an existing file or directory. This technique comes from http://stackoverflow.com/a/11541450/95592 and from http://stackoverflow.com/a/11541495/95592 Args: arg: parser argument containing filename to be checked arg_type: string of either "file" or "directory...
def validate_slice_increment(dicoms): """ Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms """ first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) inc...
Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms
def hot(self, limit=None): """GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`. :param limit: max number of links to return """ return self._reddit.hot(self.display_name, limit=limit)
GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`. :param limit: max number of links to return
def copy(self): """ Copy the instance and make sure not to use a reference """ return self.__class__( amount=self["amount"], asset=self["asset"].copy(), blockchain_instance=self.blockchain, )
Copy the instance and make sure not to use a reference
def score_group(group_name=None): ''' Warning this is deprecated as of Compliance Checker v3.2! Please do not using scoring groups and update your plugins if necessary ''' warnings.warn('Score_group is deprecated as of Compliance Checker v3.2.') def _inner(func): def _dec(s, ds): ...
Warning this is deprecated as of Compliance Checker v3.2! Please do not using scoring groups and update your plugins if necessary
def inst_matches(self, start, end, instr, target=None, include_beyond_target=False): """ Find all `instr` in the block from start to end. `instr` is a Python opcode or a list of opcodes If `instr` is an opcode with a target (like a jump), a target destination can be specified whi...
Find all `instr` in the block from start to end. `instr` is a Python opcode or a list of opcodes If `instr` is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found.
def fit_general(xy, uv): """ Performs a simple fit for the shift only between matched lists of positions 'xy' and 'uv'. Output: (same as for fit_arrays) ================================= DEVELOPMENT NOTE: Checks need to be put in place to verify that enough o...
Performs a simple fit for the shift only between matched lists of positions 'xy' and 'uv'. Output: (same as for fit_arrays) ================================= DEVELOPMENT NOTE: Checks need to be put in place to verify that enough objects are available for a fit. ...
def even_even(self): """ Selects even-even nuclei from the table """ return self.select(lambda Z, N: not(Z % 2) and not(N % 2), name=self.name)
Selects even-even nuclei from the table
def copy_path(self): """Return a copy of the current path. :returns: A list of ``(path_operation, coordinates)`` tuples of a :ref:`PATH_OPERATION` string and a tuple of floats coordinates whose content depends on the operation type: * :obj:`M...
Return a copy of the current path. :returns: A list of ``(path_operation, coordinates)`` tuples of a :ref:`PATH_OPERATION` string and a tuple of floats coordinates whose content depends on the operation type: * :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ...
def plot_latent(self, labels=None, which_indices=None, resolution=60, legend=True, plot_limits=None, updates=False, kern=None, marker='<>^vsd', num_samples=1000, projection='2d', predict_kwargs={}, scatter_kw...
see plotting.matplot_dep.dim_reduction_plots.plot_latent if predict_kwargs is None, will plot latent spaces for 0th dataset (and kernel), otherwise give predict_kwargs=dict(Yindex='index') for plotting only the latent space of dataset with 'index'.
def order_by(self, *field_names): """ Mark the filter as being ordered if search has occurred. """ if not self._search_ordered: self._search_ordered = len(self._search_terms) > 0 return super(SearchableQuerySet, self).order_by(*field_names)
Mark the filter as being ordered if search has occurred.
def _process_response(response, save_to): """ Given a response object, prepare it to be handed over to the external caller. Preparation steps include: * detect if the response has error status, and convert it to an appropriate exception; * detect Content-Type, and based on...
Given a response object, prepare it to be handed over to the external caller. Preparation steps include: * detect if the response has error status, and convert it to an appropriate exception; * detect Content-Type, and based on that either parse the response as JSON or return as plain tex...
def save(self, *objs, condition=None, atomic=False): """Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this condition holds. :param bool atomic: only perform each save if the local and DynamoDB versions of the object match. :r...
Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this condition holds. :param bool atomic: only perform each save if the local and DynamoDB versions of the object match. :raises bloop.exceptions.ConstraintViolation: if the condition (or...
def _read_mode_tsopt(self, size, kind): """Read Timestamps option. Positional arguments: * size - int, length of option * kind - int, 8 (Timestamps) Returns: * dict -- extracted Timestamps (TS) option Structure of TCP TSopt [RFC 7323]: +...
Read Timestamps option. Positional arguments: * size - int, length of option * kind - int, 8 (Timestamps) Returns: * dict -- extracted Timestamps (TS) option Structure of TCP TSopt [RFC 7323]: +-------+-------+---------------------+-------------...
def entry_detail(request, slug, template='djournal/entry_detail.html'): '''Returns a response of an individual entry, for the given slug.''' entry = get_object_or_404(Entry.public, slug=slug) context = { 'entry': entry, } return render_to_response( template, context, ...
Returns a response of an individual entry, for the given slug.
def multi_send(self, template, emails, _vars=None, evars=None, schedule_time=None, options=None): """ Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma sep...
Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma separated email string @param _vars: a key/value hash of the replacement vars to use in the send. Each var may be...
def draft_context(cls): """Set the context to draft""" previous_state = g.get('draft') try: g.draft = True yield finally: g.draft = previous_state
Set the context to draft
def checkedItems( self ): """ Returns the checked items for this combobox. :return [<str>, ..] """ if not self.isCheckable(): return [] return [nativestring(self.itemText(i)) for i in self.checkedIndexes()]
Returns the checked items for this combobox. :return [<str>, ..]
def load_var_files(opt, p_obj=None): """Load variable files, merge, return contents""" obj = {} if p_obj: obj = p_obj for var_file in opt.extra_vars_file: LOG.debug("loading vars from %s", var_file) obj = merge_dicts(obj.copy(), load_var_file(var_file, obj)) return obj
Load variable files, merge, return contents
def interpolate(values, color_map=None, dtype=np.uint8): """ Given a 1D list of values, return interpolated colors for the range. Parameters --------------- values : (n, ) float Values to be interpolated over color_map : None, or str Key to a colormap contained in: matplot...
Given a 1D list of values, return interpolated colors for the range. Parameters --------------- values : (n, ) float Values to be interpolated over color_map : None, or str Key to a colormap contained in: matplotlib.pyplot.colormaps() e.g: 'viridis' Returns --------...
def received_message(self, msg): """ Handle receiving a message by checking whether it is in response to a command or unsolicited, and dispatching it to the appropriate object method. """ logger.debug("Received message: %s", msg) if msg.is_binary: rais...
Handle receiving a message by checking whether it is in response to a command or unsolicited, and dispatching it to the appropriate object method.
def ge(self, other): """ Greater than or overlaps. Returns True if no part of this Interval extends lower than other. :raises ValueError: if either self or other is a null Interval :param other: Interval or point :return: True or False :rtype: bool """ ...
Greater than or overlaps. Returns True if no part of this Interval extends lower than other. :raises ValueError: if either self or other is a null Interval :param other: Interval or point :return: True or False :rtype: bool
def shard_data(self, region): """ Get League of Legends status for the given shard. Requests to this API are not counted against the application Rate Limits. :param string region: the region to execute this request on :returns: ShardStatus """ url, query = LolS...
Get League of Legends status for the given shard. Requests to this API are not counted against the application Rate Limits. :param string region: the region to execute this request on :returns: ShardStatus
def remove_tiers(self, tiers): """Remove multiple tiers, note that this is a lot faster then removing them individually because of the delayed cleaning of timeslots. :param list tiers: Names of the tier to remove. :raises KeyError: If a tier is non existent. """ for a in...
Remove multiple tiers, note that this is a lot faster then removing them individually because of the delayed cleaning of timeslots. :param list tiers: Names of the tier to remove. :raises KeyError: If a tier is non existent.
def close(self): """Close all connections """ keys = set(self._conns.keys()) for key in keys: self.stop_socket(key) self._conns = {}
Close all connections
def _do_packet_out(self, datapath, data, in_port, actions): """send a packet.""" ofproto = datapath.ofproto parser = datapath.ofproto_parser out = parser.OFPPacketOut( datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER, data=data, in_port=in_port, actions=actions...
send a packet.
def t384(args): """ %prog t384 Print out a table converting between 96 well to 384 well """ p = OptionParser(t384.__doc__) opts, args = p.parse_args(args) plate, splate = get_plate() fw = sys.stdout for i in plate: for j, p in enumerate(i): if j != 0: ...
%prog t384 Print out a table converting between 96 well to 384 well
def read_adjacency_matrix(file_path, separator): """ Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format. Inputs: - file_path: The path where the adjacency matrix is stored. - separator: The delimiter among values (e.g. ",", "\t", " ") Outp...
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format. Inputs: - file_path: The path where the adjacency matrix is stored. - separator: The delimiter among values (e.g. ",", "\t", " ") Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse...
def reload_list(self): '''Press R in home view to retrieve quiz list''' self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.home_view = self.make_listview(self.leetcode.quizzes) self.view_stack = [] self.goto_view(self.home_v...
Press R in home view to retrieve quiz list
def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt co...
Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict t...
def set_context_suffix(self, name, suffix): """Set a context's suffix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as 'foo<suffix>' in the suite's bin path. Args: name (str): Name of the context t...
Set a context's suffix. This will be applied to all wrappers for the tools in this context. For example, a tool called 'foo' would appear as 'foo<suffix>' in the suite's bin path. Args: name (str): Name of the context to suffix. suffix (str): Suffix to apply to ...
def _get_course_content(course_id, course_url, sailthru_client, site_code, config): """Get course information using the Sailthru content api or from cache. If there is an error, just return with an empty response. Arguments: course_id (str): course key of the course course_url (str): LMS u...
Get course information using the Sailthru content api or from cache. If there is an error, just return with an empty response. Arguments: course_id (str): course key of the course course_url (str): LMS url for course info page. sailthru_client (object): SailthruClient site_code...
def convert_epoch_to_timestamp(cls, timestamp, tsformat): """Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timesta...
Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp from UNIX epochs. For valid examples take a look into the ...
def DbGetHostServersInfo(self, argin): """ Get info about all servers running on specified host, name, mode and level :param argin: Host name :type: tango.DevString :return: Server info for all servers running on specified host :rtype: tango.DevVarStringArray """ self._l...
Get info about all servers running on specified host, name, mode and level :param argin: Host name :type: tango.DevString :return: Server info for all servers running on specified host :rtype: tango.DevVarStringArray
def rename_file(db, user_id, old_api_path, new_api_path): """ Rename a file. """ # Overwriting existing files is disallowed. if file_exists(db, user_id, new_api_path): raise FileExists(new_api_path) old_dir, old_name = split_api_filepath(old_api_path) new_dir, new_name = split_api_...
Rename a file.
def generate_hash(data, algorithm='chd_ph', hash_fns=(), chd_keys_per_bin=1, chd_load_factor=None, fch_bits_per_key=None, num_graph_vertices=None, brz_memory_size=8, brz_temp_dir=None, brz_max_keys_per_bucket=128, bdz_precomputed_rank=7, chd_avg_ke...
Generates a new Minimal Perfect Hash (MPH) Parameters ---------- data : list, array-like, file-like The input that is used to generate the minimal perfect hash. Be aware, in most cases the input is expected to be distinct, and many of the algorithms benefit from the input being sor...
def save(self, dolist=0): """Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file. """ quoted = not dolist array_size = 1 for d in self.shape: ...
Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file.
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray: """ Returns an array of inputs generated from the wake word audio that shouldn't cause an activation """ def samp(x): return int(pr.sample_rate * x) inputs = [] for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(i...
Returns an array of inputs generated from the wake word audio that shouldn't cause an activation
def get_definition(self, stmt: Statement, sctx: SchemaContext) -> Tuple[Statement, SchemaContext]: """Find the statement defining a grouping or derived type. Args: stmt: YANG "uses" or "type" statement. sctx: Schema context where the definition is used. ...
Find the statement defining a grouping or derived type. Args: stmt: YANG "uses" or "type" statement. sctx: Schema context where the definition is used. Returns: A tuple consisting of the definition statement ('grouping' or 'typedef') and schema context o...
def clear_file(self): """stub""" if (self.get_file_metadata().is_read_only() or self.get_file_metadata().is_required()): raise NoAccess() if 'assetId' in self.my_osid_object_form._my_map['fileId']: rm = self.my_osid_object_form._get_provider_manager('REPOS...
stub
def availabledirs(self) -> Folder2Path: """Names and paths of the available working directories. Available working directories are those beeing stored in the base directory of the respective |FileManager| subclass. Folders with names starting with an underscore are ignored (use ...
Names and paths of the available working directories. Available working directories are those beeing stored in the base directory of the respective |FileManager| subclass. Folders with names starting with an underscore are ignored (use this for directories handling additional data files...
def _extract_secrets_from_file(self, f, filename): """Extract secrets from a given file object. :type f: File object :type filename: string """ try: log.info("Checking file: %s", filename) for results, plugin in self._results_accumulator(filename)...
Extract secrets from a given file object. :type f: File object :type filename: string
def add_parent(self,node): """ Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent. """ if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ): raise CondorDAGNodeError, "Parent must be a Con...
Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent.
def get_all_children(self): """Return all children GO IDs.""" all_children = set() for parent in self.children: all_children.add(parent.item_id) all_children |= parent.get_all_children() return all_children
Return all children GO IDs.
def is_valid_catalog(self, catalog=None): """Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: ...
Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog (str o dict): Catálogo (dict, JSON...
def projects(self): """ Returns a set of all projects in this list. """ result = set() for todo in self._todos: projects = todo.projects() result = result.union(projects) return result
Returns a set of all projects in this list.
def get_instance_status(self): """Get the status the instance for this Streaming Analytics service. Returns: dict: JSON response for the instance status operation. """ status_url = self._get_url('status_path') res = self.rest_client.session.get(status_url) _h...
Get the status the instance for this Streaming Analytics service. Returns: dict: JSON response for the instance status operation.
def _retry(self, context, backoff): ''' A function which determines whether and how to retry. :param ~azure.storage.models.RetryContext context: The retry context. This contains the request, response, and other data which can be used to determine whether or not to retr...
A function which determines whether and how to retry. :param ~azure.storage.models.RetryContext context: The retry context. This contains the request, response, and other data which can be used to determine whether or not to retry. :param function() backoff: A func...
def recent(self, with_catalog=True, with_date=True): ''' List posts that recent edited. ''' kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, } self.render('list/post_list.h...
List posts that recent edited.
def create(self, throw_on_exists=False): """ Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op. :param bool throw_on_exis...
Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op. :param bool throw_on_exists: Boolean flag dictating whether or not to thro...
def before(method_name): """ Run the given method prior to the decorated view. If you return anything besides ``None`` from the given method, its return values will replace the arguments of the decorated view. If you return an instance of ``HttpResponse`` from the given method, Respite wil...
Run the given method prior to the decorated view. If you return anything besides ``None`` from the given method, its return values will replace the arguments of the decorated view. If you return an instance of ``HttpResponse`` from the given method, Respite will return it immediately without deleg...
def to_report_json(self): """ Generate a summary in json format """ return self.reporter.json(self.n_lines, self.n_assocs, self.skipped)
Generate a summary in json format
def execute(self, fn, *args, **kwargs): """Execute an operation and return the result.""" if self.in_executor_context(): corofn = asyncio.coroutine(lambda: fn(*args, **kwargs)) return corofn() future = self.submit(fn, *args, **kwargs) return future.result()
Execute an operation and return the result.
def _gen_exclusion_paths(): """ Generate file paths to be excluded for namespace packages (bytecode cache files). """ # always exclude the package module itself yield '__init__.py' yield '__init__.pyc' yield '__init__.pyo' if not hasattr(imp, 'ge...
Generate file paths to be excluded for namespace packages (bytecode cache files).
def autoencoder_residual_text(): """Residual autoencoder model for text.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 32 hparams.batch_size = 1024 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.bottom = { "inputs": modalities.identity...
Residual autoencoder model for text.
def setDesigns(self, F, A): """ set fixed effect designs """ F = to_list(F) A = to_list(A) assert len(A) == len(F), 'MeanKronSum: A and F must have same length!' n_terms = len(F) n_covs = 0 k = 0 l = 0 for ti in range(n_terms): assert F...
set fixed effect designs
def create_mod_site(self, mc): """Create modification site for the BaseAgent from a ModCondition.""" site_name = get_mod_site_name(mc) (unmod_site_state, mod_site_state) = states[mc.mod_type] self.create_site(site_name, (unmod_site_state, mod_site_state)) site_anns = [Annotation(...
Create modification site for the BaseAgent from a ModCondition.
def shortname(inputid): # type: (Text) -> Text """Returns the last segment of the provided fragment or path.""" parsed_id = urllib.parse.urlparse(inputid) if parsed_id.fragment: return parsed_id.fragment.split(u"/")[-1] return parsed_id.path.split(u"/")[-1]
Returns the last segment of the provided fragment or path.
def maps_get_rules_output_rules_value(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_rules = ET.Element("maps_get_rules") config = maps_get_rules output = ET.SubElement(maps_get_rules, "output") rules = ET.SubElement(output, "ru...
Auto Generated Code
def cross_validation(scheme_class, num_examples, num_folds, strict=True, **kwargs): """Return pairs of schemes to be used for cross-validation. Parameters ---------- scheme_class : subclass of :class:`IndexScheme` or :class:`BatchScheme` The type of the returned schemes. Th...
Return pairs of schemes to be used for cross-validation. Parameters ---------- scheme_class : subclass of :class:`IndexScheme` or :class:`BatchScheme` The type of the returned schemes. The constructor is called with an iterator and `**kwargs` as arguments. num_examples : int The...
def request_response(self): """Verify that a card is still present and get its operating mode. The Request Response command returns the current operating state of the card. The operating state changes with the authentication process, a card is in Mode 0 after power-up or a Polli...
Verify that a card is still present and get its operating mode. The Request Response command returns the current operating state of the card. The operating state changes with the authentication process, a card is in Mode 0 after power-up or a Polling command, transitions to Mode 1 with ...
def compute_batch(self, duplicate_manager=None, context_manager=None): """ Computes the elements of the batch sequentially by penalizing the acquisition. """ from ...acquisitions import AcquisitionLP assert isinstance(self.acquisition, AcquisitionLP) self.acquisition.upd...
Computes the elements of the batch sequentially by penalizing the acquisition.
def filter_incomplete_spectra(self, flimit=1000, percAccept=85): """Remove all data points that belong to spectra that did not retain at least **percAccept** percent of the number of data points. ..warning:: This function does not honor additional dimensions (e.g., time...
Remove all data points that belong to spectra that did not retain at least **percAccept** percent of the number of data points. ..warning:: This function does not honor additional dimensions (e.g., timesteps) yet!
def ExportClientsByKeywords(keywords, filename, token=None): r"""A script to export clients summaries selected by a keyword search. This script does a client search for machines matching all of keywords and writes a .csv summary of the results to filename. Multi-value fields are '\n' separated. Args: ke...
r"""A script to export clients summaries selected by a keyword search. This script does a client search for machines matching all of keywords and writes a .csv summary of the results to filename. Multi-value fields are '\n' separated. Args: keywords: a list of keywords to search for filename: the name...
def on_exception(wait_gen, exception, max_tries=None, jitter=full_jitter, giveup=lambda e: False, on_success=None, on_backoff=None, on_giveup=None, **wait_gen_kwargs): """Returns d...
Returns decorator for backoff and retry triggered by exception. Args: wait_gen: A generator yielding successive wait times in seconds. exception: An exception type (or tuple of types) which triggers backoff. max_tries: The maximum number of attempts to make before gi...
def randbetween(lower: int, upper: int) -> int: """Return a random int in the range [lower, upper]. Raises ValueError if any is lower than 0, and TypeError if any is not an integer. """ if not isinstance(lower, int) or not isinstance(upper, int): raise TypeError('lower and upper must be in...
Return a random int in the range [lower, upper]. Raises ValueError if any is lower than 0, and TypeError if any is not an integer.
def read_frames(self, nframes, dtype=np.float64): """Read nframes frames of the file. :Parameters: nframes : int number of frames to read. dtype : numpy dtype dtype of the returned array containing read data (see note). Notes ----...
Read nframes frames of the file. :Parameters: nframes : int number of frames to read. dtype : numpy dtype dtype of the returned array containing read data (see note). Notes ----- - read_frames updates the read pointer. - ...
def restore_catalog_to_ckan(catalog, origin_portal_url, destination_portal_url, apikey, download_strategy=None, generate_new_access_url=None): """Restaura los datasets de un catálogo original al portal pasado por parámetro. Si hay temas presentes en el ...
Restaura los datasets de un catálogo original al portal pasado por parámetro. Si hay temas presentes en el DataJson que no están en el portal de CKAN, los genera. Args: catalog (DataJson): El catálogo de origen que se restaura. origin_portal_url (str): La URL d...
def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set """ _check_call(_LIB.XGDMatrixSetUIntInfo(se...
Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set
def resizeEvent(self, event): """ Reimplements the :meth:`QWidget.resizeEvent` method. :param event: QEvent. :type event: QEvent """ LOGGER.debug("> Application resize event accepted!") self.size_changed.emit(event) event.accept()
Reimplements the :meth:`QWidget.resizeEvent` method. :param event: QEvent. :type event: QEvent
def build(self, js_path): super(Script, self).build() """ :param js_path: Javascript source code. """ self.source = js_path
:param js_path: Javascript source code.
def PublishMultipleEvents(cls, events, token=None): """Publishes multiple messages at once. Args: events: A dict with keys being event names and values being lists of messages. token: ACL token. Raises: ValueError: If the message is invalid. The message must be a Semantic ...
Publishes multiple messages at once. Args: events: A dict with keys being event names and values being lists of messages. token: ACL token. Raises: ValueError: If the message is invalid. The message must be a Semantic Value (instance of RDFValue) or a full GrrMessage.
def isinstance(self, instance, class_name): """Check if a BaseNode is an instance of a registered dynamic class""" if isinstance(instance, BaseNode): klass = self.dynamic_node_classes.get(class_name, None) if klass: return isinstance(instance, klass) #...
Check if a BaseNode is an instance of a registered dynamic class