Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
380,600
def insertBefore(self, child: Node, ref_node: Node) -> Node: if self.connected: self._insert_before_web(child, ref_node) return self._insert_before(child, ref_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.
380,601
def buglist(self, from_date=DEFAULT_DATETIME): if not self.version: self.version = self.__fetch_version() if self.version in self.OLD_STYLE_VERSIONS: order = else: order = date = from_date.strftime("%Y-%m-%d %H:%M:%S") params = { ...
Get a summary of bugs in CSV format. :param from_date: retrieve bugs that where updated from that date
380,602
def get_ports(self, id_or_uri, start=0, count=-1): uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path="ports") return self._client.get_all(start, count, uri=uri)
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: ...
380,603
def _update_console(self, value=None): if self._total == 0: frac = 1.0 else: frac = float(value) / float(self._total) file = self._file write = file.write if frac > 1: bar_fill = int(self._bar_length) else: bar_f...
Update the progress bar to the given value (out of the total given to the constructor).
380,604
def contains_non_repeat_actions(self): 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
380,605
def udf(f=None, returnType=StringType()): if f is None or isinstance(f, (str, DataType)): return_type = f or returnType return functools.partial(_create_udf, returnT...
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...
380,606
def _cmp(self, other): if self is other: return 0 try: assert isinstance(other, CIMParameter) except AssertionError: raise TypeError( _format("other must be CIMParameter, but is: {0}", type(other))) ret...
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` * ...
380,607
def zip(self, *items): 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
380,608
def funnel_rebuild(psg_trm_spec): param_score_gen, top_result_model, specification = psg_trm_spec params, score, gen = param_score_gen model = specification(*params) rmsd = top_result_model.rmsd(model) return rmsd, score, gen
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 ...
380,609
def most_recent_common_ancestor(self, *ts): if len(ts) > 200: res = self._large_mrca(ts) else: res = self._small_mrca(ts) if res: (res,), = res else: raise NoAncestor() return res
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.
380,610
def build_sdk_span(self, span): custom_data = CustomData(tags=span.tags, logs=self.collect_logs(span)) sdk_data = SDKData(name=span.operation_name, custom=custom_data, Type=self.get_span_kind_as_string(span...
Takes a BasicSpan and converts into an SDK type JsonSpan
380,611
def _load_github_repo(): if in os.environ: raise RuntimeError( ) try: with open(os.path.join(config_dir, ), ) as f: return f.read() except (OSError, IOError): raise RuntimeError( )
Loads the GitHub repository from the users config.
380,612
def get(self): open_tracking = {} if self.enable is not None: open_tracking["enable"] = self.enable if self.substitution_tag is not None: open_tracking["substitution_tag"] = self.substitution_tag.get() return open_tracking
Get a JSON-ready representation of this OpenTracking. :returns: This OpenTracking, ready for use in a request body. :rtype: dict
380,613
def handle(client, request): formaters = request.get(, None) if not formaters: formaters = [{: }] logging.debug( + json.dumps(formaters, indent=4)) data = request.get(, None) if not isinstance(data, str): return send(client, , None) max_line_length = None for formater i...
Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict }, ... # formaters ] } if no f...
380,614
def has_perm(self, user_obj, perm, obj=None): if not is_authenticated(user_obj): return False change_permission = self.get_full_permission_string() delete_permission = self.get_full_permission_string() if obj is 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). This behavior is based on the django system. http...
380,615
def get(zpool, prop=None, show_source=False, parsable=True): * ret = OrderedDict() value_properties = [, , , ] res = __salt__[]( __utils__[]( command=, flags=[], property_name=prop if prop else , target=zpool, ), python_shell=...
.. 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 ...
380,616
def cluster_application_attempts(self, application_id): path = .format( appid=application_id) return self.request(path)
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`
380,617
def page(self, course, task, submission): submission = self.submission_manager.get_input_from_submission(submission) submission = self.submission_manager.get_feedback_from_submission( submission, show_everything=True, translation=self.app._translations.get(se...
Get all data and display the page
380,618
def graph_loads(graph_json): layers = [] for layer in graph_json[]: layer_info = Layer(layer[], layer[], layer[], layer[]) layer_info.is_delete = layer[] layers.append(layer_info) graph = Graph(graph_json[], [], [], []) graph.layers = layers return graph
Load graph
380,619
def _decompose_vectorized_indexer(indexer, shape, indexing_support): assert isinstance(indexer, VectorizedIndexer) if indexing_support is IndexingSupport.VECTORIZED: return indexer, BasicIndexer(()) backend_indexer = [] np_indexer = [] indexer = [np.where(k < 0, k + s, k) if isin...
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...
380,620
def log(self, text, level=logging.INFO): self._fileStore.logToMaster(text, level)
convenience wrapper for :func:`fileStore.logToMaster`
380,621
def desired_destination(self, network, edge): n = len(network.out_edges[edge[1]]) if n <= 1: return network.out_edges[edge[1]][0] u = uniform() pr = network._route_probs[edge[1]] k = _choice(pr, u, n) return network.out_edges[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:`QueueNetwork's<.QueueNetwork>` transition matrix...
380,622
def com_google_fonts_check_family_equal_glyph_names(ttFonts): 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] = [] available[glyphname] = [] ...
Fonts have equal glyph names?
380,623
def write_data(self, variable_id, value): i = 0 j = 0 while i < 10: try: self.inst.query() i = 12 j = 1 except: self.connect() time.sleep(1) i += 1 ...
write values to the device
380,624
def purge_db(self): with self.engine.begin() as db: purge_user(db, self.user_id)
Clear all matching our user_id.
380,625
def get_projects(session, query): response = make_get_request(session, , params_data=query) json_data = response.json() if response.status_code == 200: return json_data[] else: raise ProjectsNotFoundException( message=json_data[], error_code=json_data[],...
Get one or more projects
380,626
def get_area_def(self, dsid): geocoding = self.root.find() epsg = geocoding.find().text rows = int(geocoding.find( + str(dsid.resolution) + ).text) cols = int(geocoding.find( + str(dsid.resolution) + ).text) geoposition = geocoding.find( + str(dsid.resolution) + ) ...
Get the area definition of the dataset.
380,627
def extant_item(arg, arg_type): if arg_type == "file": if not os.path.isfile(arg): raise argparse.ArgumentError( None, "The file {arg} does not exist.".format(arg=arg)) else: return arg elif arg_type == "directory": ...
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...
380,628
def validate_slice_increment(dicoms): first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) increment = first_image_position - previous_image_position for dicom_ in dicoms[2:]: current_image_position = numpy...
Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms
380,629
def hot(self, limit=None): 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
380,630
def copy(self): 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
380,631
def score_group(group_name=None): warnings.warn() def _inner(func): def _dec(s, ds): ret_val = func(s, ds) if not isinstance(ret_val, list): ret_val = [ret_val] def dogroup(r): cur_grouping = r.name ...
Warning this is deprecated as of Compliance Checker v3.2! Please do not using scoring groups and update your plugins if necessary
380,632
def inst_matches(self, start, end, instr, target=None, include_beyond_target=False): try: None in instr except: instr = [instr] first = self.offset2inst_index[start] result = [] for inst in self.insts[first:]: if inst.opcode in instr:...
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.
380,633
def fit_general(xy, uv): gxy = uv.astype(ndfloat128) guv = xy.astype(ndfloat128) Sx = gxy[:,0].sum() Sy = gxy[:,1].sum() Su = guv[:,0].sum() Sv = guv[:,1].sum() Sux = np.dot(guv[:,0], gxy[:,0]) Svx = np.dot(guv[:,1], gxy[:,0]) Suy = np.dot(guv[:,0], gxy[:,1]) Svy = np....
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. ...
380,634
def even_even(self): return self.select(lambda Z, N: not(Z % 2) and not(N % 2), name=self.name)
Selects even-even nuclei from the table
380,635
def copy_path(self): path = cairo.cairo_copy_path(self._pointer) result = list(_iter_path(path)) cairo.cairo_path_destroy(path) return result
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 ...
380,636
def plot_latent(self, labels=None, which_indices=None, resolution=60, legend=True, plot_limits=None, updates=False, kern=None, marker=, num_samples=1000, projection=, predict_kwargs={}, scatter_kwargs=None, *...
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'.
380,637
def order_by(self, *field_names): 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.
380,638
def _process_response(response, save_to): status_code = response.status_code if status_code == 200 and save_to: if save_to.startswith("~"): save_to = os.path.expanduser(save_to) if os.path.isdir(save_to) or save_to.endswith(os.path.sep): dirname = os.path...
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...
380,639
def save(self, *objs, condition=None, atomic=False): objs = set(objs) validate_not_abstract(*objs) for obj in objs: self.session.save_item({ "TableName": self._compute_table_name(obj.__class__), "Key": dump_key(self, obj), **re...
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...
380,640
def _read_mode_tsopt(self, size, kind): temp = struct.unpack(, self._read_fileng(size)) data = dict( kind=kind, length=size, val=temp[0], ecr=temp[1], ) return data
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]: +-------+-------+---------------------+-------------...
380,641
def entry_detail(request, slug, template=): entry = get_object_or_404(Entry.public, slug=slug) context = { : entry, } return render_to_response( template, context, context_instance=RequestContext(request), )
Returns a response of an individual entry, for the given slug.
380,642
def multi_send(self, template, emails, _vars=None, evars=None, schedule_time=None, options=None): _vars = _vars or {} evars = evars or {} options = options or {} data = {: template, : .join(emails) if isinstance(emails, list) else emails, : _vars....
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...
380,643
def draft_context(cls): previous_state = g.get() try: g.draft = True yield finally: g.draft = previous_state
Set the context to draft
380,644
def checkedItems( self ): if not self.isCheckable(): return [] return [nativestring(self.itemText(i)) for i in self.checkedIndexes()]
Returns the checked items for this combobox. :return [<str>, ..]
380,645
def load_var_files(opt, p_obj=None): 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
380,646
def interpolate(values, color_map=None, dtype=np.uint8): if color_map is None: cmap = linear_color_map else: from matplotlib.pyplot import get_cmap cmap = get_cmap(color_map) values = np.asanyarray(values, dtype=np.float64).ravel() colors = cmap((values - va...
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 --------...
380,647
def received_message(self, msg): logger.debug("Received message: %s", msg) if msg.is_binary: raise ValueError("Binary messages not supported") resps = json.loads(msg.data) cmd_group = _get_cmds_id(*resps) if cmd_group: (cmds, promise) = self._cmd...
Handle receiving a message by checking whether it is in response to a command or unsolicited, and dispatching it to the appropriate object method.
380,648
def ge(self, other): self._raise_if_null(other) return self.begin >= getattr(other, , 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
380,649
def shard_data(self, region): url, query = LolStatusApiV3Urls.shard_data(region=region) return self._raw_request(self.shard_data.__name__, region, url, query)
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
380,650
def remove_tiers(self, tiers): for a in tiers: self.remove_tier(a, clean=False) self.clean_time_slots()
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.
380,651
def close(self): keys = set(self._conns.keys()) for key in keys: self.stop_socket(key) self._conns = {}
Close all connections
380,652
def _do_packet_out(self, datapath, data, in_port, actions): 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) datapath.s...
send a packet.
380,653
def t384(args): 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: fw.write() fw.write(p) fw.write()
%prog t384 Print out a table converting between 96 well to 384 well
380,654
def read_adjacency_matrix(file_path, separator): file_row_generator = get_file_row_generator(file_path, separator) row = list() col = list() append_row = row.append append_col = col.append for file_row in file_row_generator: source_node = np.int64(file_row[0]) ...
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...
380,655
def reload_list(self): 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_view)
Press R in home view to retrieve quiz list
380,656
def _salt_send_event(opaque, conn, data): prefixobjectevent tag_prefix = opaque[] object_type = opaque[] event_type = opaque[] uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip() if path: ur...
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...
380,657
def set_context_suffix(self, name, suffix): data = self._context(name) data["suffix"] = suffix self._flush_tools()
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 ...
380,658
def _get_course_content(course_id, course_url, sailthru_client, site_code, config): cache_key = "{}:{}".format(site_code, course_url) response = cache.get(cache_key) if not response: try: sailthru_response = sailthru_client.api_get("content", {"id": course_url}) if ...
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...
380,659
def convert_epoch_to_timestamp(cls, timestamp, tsformat): return time.strftime(tsformat, time.gmtime(timestamp))
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 ...
380,660
def DbGetHostServersInfo(self, argin): self._log.debug("In DbGetHostServersInfo()") argin = replace_wildcard(argin) return self.db.get_host_servers_info(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
380,661
def rename_file(db, user_id, old_api_path, new_api_path): 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_filepath(new_api_path) if old_dir != new_dir: raise ValueErro...
Rename a file.
380,662
def generate_hash(data, algorithm=, 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_keys_per_b...
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...
380,663
def save(self, dolist=0): quoted = not dolist array_size = 1 for d in self.shape: array_size = d*array_size ndim = len(self.shape) fields = (7+2*ndim+len(self.value))*[""] fields[0] = self.name fields[1] = self.type fields[2] = self.mo...
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.
380,664
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray: def samp(x): return int(pr.sample_rate * x) inputs = [] for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(inhibit_hop_t)): if len(audio) - offset < samp(pr.buffer_t / 2.): break inputs.append(vec...
Returns an array of inputs generated from the wake word audio that shouldn't cause an activation
380,665
def get_definition(self, stmt: Statement, sctx: SchemaContext) -> Tuple[Statement, SchemaContext]: if stmt.keyword == "uses": kw = "grouping" elif stmt.keyword == "type": kw = "typedef" else: raise ValueError("not a or stateme...
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...
380,666
def clear_file(self): if (self.get_file_metadata().is_read_only() or self.get_file_metadata().is_required()): raise NoAccess() if in self.my_osid_object_form._my_map[]: rm = self.my_osid_object_form._get_provider_manager() catalog_id_str = ...
stub
380,667
def availabledirs(self) -> Folder2Path: directories = Folder2Path() for directory in os.listdir(self.basepath): if not directory.startswith(): path = os.path.join(self.basepath, directory) if os.path.isdir(path): directories.add(di...
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...
380,668
def _extract_secrets_from_file(self, f, filename): try: log.info("Checking file: %s", filename) for results, plugin in self._results_accumulator(filename): results.update(plugin.analyze(f, filename)) f.seek(0) except UnicodeDecodeError: ...
Extract secrets from a given file object. :type f: File object :type filename: string
380,669
def add_parent(self,node): if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ): raise CondorDAGNodeError, "Parent must be a CondorDAGNode or a CondorDAGManNode" self.__parents.append( 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.
380,670
def get_all_children(self): 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.
380,671
def is_valid_catalog(self, catalog=None): catalog = catalog or self return validation.is_valid_catalog(catalog, validator=self.validator)
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...
380,672
def projects(self): 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.
380,673
def get_instance_status(self): status_url = self._get_url() res = self.rest_client.session.get(status_url) _handle_http_errors(res) return res.json()
Get the status the instance for this Streaming Analytics service. Returns: dict: JSON response for the instance status operation.
380,674
def _retry(self, context, backoff): if not hasattr(context, ): context.count = 0 if self._should_retry(context): backoff_interval = backoff(context) context.count += 1 if self.retry_t...
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...
380,675
def recent(self, with_catalog=True, with_date=True): kwd = { : , : , : with_catalog, : with_date, } self.render(, kwd=kwd, view=MPost.query_recent(num=20), postrecs=MPost.query_re...
List posts that recent edited.
380,676
def create(self, throw_on_exists=False): if not throw_on_exists and self.exists(): return self resp = self.r_session.put(self.database_url, params={ : TYPE_CONVERTERS.get(bool)(self._partitioned) }) if resp.status_code == 201 or resp.status_code == 202: ...
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...
380,677
def before(method_name): def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): returns = getattr(self, method_name)(*args, **kwargs) if returns is None: return function(self, *args, **kwargs) else: if i...
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...
380,678
def to_report_json(self): return self.reporter.json(self.n_lines, self.n_assocs, self.skipped)
Generate a summary in json format
380,679
def execute(self, fn, *args, **kwargs): 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.
380,680
def _gen_exclusion_paths(): yield yield yield if not hasattr(imp, ): return base = os.path.join(, + imp.get_tag()) yield base + yield base + yield base + yield base +
Generate file paths to be excluded for namespace packages (bytecode cache files).
380,681
def autoencoder_residual_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_bottom, "targets": modalities.ident...
Residual autoencoder model for text.
380,682
def setDesigns(self, F, A): F = to_list(F) A = to_list(A) assert len(A) == len(F), n_terms = len(F) n_covs = 0 k = 0 l = 0 for ti in range(n_terms): assert F[ti].shape[0] == self._N, assert A[ti].shape[1] == self._P, ...
set fixed effect designs
380,683
def create_mod_site(self, mc): 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((site_name, mod_site_state), mc.mod_type, ...
Create modification site for the BaseAgent from a ModCondition.
380,684
def shortname(inputid): 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.
380,685
def maps_get_rules_output_rules_value(self, **kwargs): 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, "rules") value = ET.SubElemen...
Auto Generated Code
380,686
def cross_validation(scheme_class, num_examples, num_folds, strict=True, **kwargs): if strict and num_examples % num_folds != 0: raise ValueError(("{} examples are not divisible in {} evenly-sized " + "folds. To allow this, have a look at the " + ...
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...
380,687
def request_response(self): a, b, e = self.pmm[3] & 7, self.pmm[3] >> 3 & 7, self.pmm[3] >> 6 timeout = 302E-6 * (b + 1 + a + 1) * 4**e data = self.send_cmd_recv_rsp(0x04, , timeout, check_status=False) if len(data) != 1: log.debug("insufficient data received from ta...
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 ...
380,688
def compute_batch(self, duplicate_manager=None, context_manager=None): from ...acquisitions import AcquisitionLP assert isinstance(self.acquisition, AcquisitionLP) self.acquisition.update_batches(None,None,None) X_batch = self.acquisition.optimize()[0] k=1 ...
Computes the elements of the batch sequentially by penalizing the acquisition.
380,689
def filter_incomplete_spectra(self, flimit=1000, percAccept=85): assert percAccept > 0 and percAccept < 100 def _retain_only_complete_spectra(item, fmax, acceptN): frequencies = item[].loc[item[] < fmax] fN = frequencies.size if fN >= acceptN: ...
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!
380,690
def ExportClientsByKeywords(keywords, filename, token=None): r index = client_index.CreateClientIndex(token=token) client_list = index.LookupClients(keywords) logging.info("found %d clients", len(client_list)) if not client_list: return writer = csv.DictWriter([ u"client_id", u"hostname", ...
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...
380,691
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): success...
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...
380,692
def randbetween(lower: int, upper: int) -> int: if not isinstance(lower, int) or not isinstance(upper, int): raise TypeError() if lower < 0 or upper <= 0: raise ValueError() return randbelow(upper - lower + 1) + lower
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.
380,693
def read_frames(self, nframes, dtype=np.float64): return self._sndfile.read_frames(nframes, dtype)
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. - ...
380,694
def restore_catalog_to_ckan(catalog, origin_portal_url, destination_portal_url, apikey, download_strategy=None, generate_new_access_url=None): catalog[] = catalog.get() or origin_portal_url res = {} origin_portal = RemoteCKAN(origin_portal_url) ...
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...
380,695
def set_uint_info(self, field, data): _check_call(_LIB.XGDMatrixSetUIntInfo(self.handle, c_str(field), c_array(ctypes.c_uint, data), len(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
380,696
def resizeEvent(self, event): 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
380,697
def build(self, js_path): super(Script, self).build() self.source = js_path
:param js_path: Javascript source code.
380,698
def PublishMultipleEvents(cls, events, token=None): event_name_map = registry.EventRegistry.EVENT_NAME_MAP for event_name, messages in iteritems(events): if not isinstance(event_name, string_types): raise ValueError( "Event names should be string, got: %s" % type(event_name)) ...
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.
380,699
def isinstance(self, instance, class_name): if isinstance(instance, BaseNode): klass = self.dynamic_node_classes.get(class_name, None) if klass: return isinstance(instance, klass) return False else: raise TypeError("Th...
Check if a BaseNode is an instance of a registered dynamic class