code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def id_request(self): if in self.oauth: url = self.oauth[] else: url = self.urls_request()[] ret = self.handle_api_exceptions(, url) return ret.json()
The Force.com Identity Service (return type dict of text_type)
def endpoint(self, endpoint): def decorator(f): def register_endpoint(state): state.app.view_functions[endpoint] = f self.record_once(register_endpoint) return f return decorator
Like :meth:`Flask.endpoint` but for a blueprint. This does not prefix the endpoint with the blueprint name, this has to be done explicitly by the user of this method. If the endpoint is prefixed with a `.` it will be registered to the current blueprint, otherwise it's an application in...
def delete_user(self, recipient_email): emailid_list = self.list_user_emails() if recipient_email not in emailid_list: raise Exception("User {0} not present!".format(recipient_email)) else: emailid_list.remove(recipient_email) self.y = self.decrypt() ...
Remove user from encryption
def some(args): from jcvi.formats.base import SetFile from jcvi.utils.cbook import gene_name p = OptionParser(some.__doc__) p.add_option("-v", dest="inverse", default=False, action="store_true", help="Get the inverse, like grep -v [default: %default]") p.set_outfile() p.se...
%prog some bedfile idsfile > newbedfile Retrieve a subset of bed features given a list of ids.
def running(name, **kwargs): rrootvirtualbox if in name or in name: return _vagrant_call(name, , , "Machine has been restarted", "running") else: ret = {: name, : {}, : True, : .format(name) } ...
r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each mac...
def solve_venn2_circles(venn_areas): (A_a, A_b, A_ab) = list(map(float, venn_areas)) r_a, r_b = np.sqrt(A_a / np.pi), np.sqrt(A_b / np.pi) radii = np.array([r_a, r_b]) if A_ab > tol: coords = np.zeros((2, 2)) coords[1][0] = find_distance_by_area(radii[0], radii[1], A_ab) ...
Given the list of "venn areas" (as output from compute_venn2_areas, i.e. [A, B, AB]), finds the positions and radii of the two circles. The return value is a tuple (coords, radii), where coords is a 2x2 array of coordinates and radii is a 2x1 array of circle radii. Assumes the input values to be nonneg...
def send(self, data, room=None, skip_sid=None, namespace=None, callback=None): return self.server.send(data, room=room, skip_sid=skip_sid, namespace=namespace or self.namespace, callback=callback)
Send a message to one or more connected clients. The only difference with the :func:`socketio.Server.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is used.
def build_rects(tmxmap, layer, tileset=None, real_gid=None): if isinstance(tileset, int): try: tileset = tmxmap.tilesets[tileset] except IndexError: msg = "Tileset logger.debug(msg.format(tileset, tmxmap)) raise IndexError elif isinstance(ti...
generate a set of non-overlapping rects that represents the distribution of the specified gid. useful for generating rects for use in collision detection Use at your own risk: this is experimental...will change in future GID Note: You will need to add 1 to the GID reported by Tiled. :param tm...
def add_item(self, query_params=None): return self.fetch_json( uri_path=self.base_uri + , http_method=, query_params=query_params or {} )
Add an item to this checklist. Returns a dictionary of values of new item.
def _parse_config_file_impl(filename): try: doc = yaml.load(file(filename).read()) project_id = doc["credentials"]["project_id"] access_token = doc["credentials"]["access_token"] api_domain = doc["credentials"]["api_domain"] return project_id, access_to...
Format for the file is: credentials: project_id: ... access_token: ... api_domain: ... :param filename: The filename to parse :return: A tuple with: - project_id - access_token - api_domain
def AddEventSource(self, event_source): self._RaiseIfNotWritable() self._AddAttributeContainer( self._CONTAINER_TYPE_EVENT_SOURCE, event_source)
Adds an event source. Args: event_source (EventSource): event source. Raises: IOError: when the storage file is closed or read-only. OSError: when the storage file is closed or read-only.
def shift_by_n_processors(self, x, mesh_axis, offset, wrap): n = self.shape[mesh_axis].size source_pcoord = [] for i in xrange(n): c = i - offset if c != c % n: if wrap: c = c % n else: c = None source_pcoord.append(c) return self.receive(x, mes...
Receive the slice from processor pcoord - offset. Args: x: a LaidOutTensor mesh_axis: an integer offset: an integer wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
def _create_search_filter(filter_by): return ",".join( [ "{0}:{1}".format(key, value) for key, value in filter_by.items() if value is not None ] )
:param filter_by: :return: dict
def _get_area(self): from fontTools.pens.areaPen import AreaPen pen = AreaPen(self.layer) self.draw(pen) return abs(pen.value)
Subclasses may override this method.
def get_pfam(pdb_id): out = get_info(pdb_id, url_root = ) out = to_dict(out) if not out[]: return dict() return remove_at_sign(out[])
Return PFAM annotations of given PDB_ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing the PFAM annotations for the specified PDB ID Examples -------- >>> pfam_info = g...
def db_group(self): if self._db_group is None: self._db_group = self.db_user return self._db_group
str: database system group (defaults to :attr:`db_user <tmdeploy.config.AnsibleHostVariableSection.db_user>`)
def openlines(image, linelength=10, dAngle=10, mask=None): nAngles = 180//dAngle openingstack = np.zeros((nAngles,image.shape[0],image.shape[1]),image.dtype) for iAngle in range(nAngles): angle = dAngle * iAngle se = strel_line(linelength,angle) openingstack[iAngle,:,:] = openi...
Do a morphological opening along lines of different angles. Return difference between max and min response to different angles for each pixel. This effectively removes dots and only keeps lines. image - pixel image to operate on length - length of the structural element angluar_resolution - angle ...
def _get_event_source_obj(awsclient, evt_source): event_source_map = { : event_source.dynamodb_stream.DynamoDBStreamEventSource, : event_source.kinesis.KinesisEventSource, : event_source.s3.S3EventSource, : event_source.sns.SNSEventSource, : event_source.cloudwatch.Cloud...
Given awsclient, event_source dictionary item create an event_source object of the appropriate event type to schedule this event, and return the object.
def _altair_line_num_(self, xfield, yfield, opts, style, encode): try: c = self._altair_chart_num_("line", xfield, yfield, opts, style, encode) except Exception as e: self.err(e, "Can not draw a line num chart") retu...
Get a line + text number chart
def epochs(steps=None, epoch_steps=1): try: iter(epoch_steps) except TypeError: epoch_steps = itertools.repeat(epoch_steps) step = 0 for epoch, epoch_steps in enumerate(epoch_steps): epoch_steps = min(epoch_steps, steps - step) yield (epoch + 1, epoch_steps) step += epoch_steps if st...
Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id, epoch_steps: int, number of steps in this ...
def config_prov(config): try: providers = [e.strip() for e in (config[] []).split()] except KeyError as e: print("Error reading config item: {}".format(e)) sys.exit() providers = list(OrderedDict.fromkeys(providers)) return providers
Read providers from configfile and de-duplicate it.
def update(self, friendly_name=values.unset, unique_name=values.unset): return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, )
Update the FieldTypeInstance :param unicode friendly_name: A string to describe the resource :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Updated FieldTypeInstance :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTy...
def czdivide(a, b, null=0): s divide function or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy if null == 0: return a.multiply(zinv(b)) if sps.issparse(a) else a * zinv(b) elif sps.issparse(b): b = b.toarray() else: b = np.asarray(b) ...
czdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy's divide, czdivide works with sparse matrices. Additionally, czdivide multiplies a by the zinv of b, so divide-by-zero en...
def _post_run_hook(self, runtime): self._anat_file = self.inputs.in_file self._mask_file = self.aggregate_outputs(runtime=runtime).mask_file self._seg_files = [self._mask_file] self._masked = True NIWORKFLOWS_LOG.info( , self._anat_file, self._m...
generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid
def _determine_ctxt(self): rel = os_release(self.pkg, base=) version = if CompareOpenStackReleases(rel) >= : version = service_type = .format(version=version) service_name = .format(version=version) endpoint_type = if config(): ...
Determines the Volume API endpoint information. Determines the appropriate version of the API that should be used as well as the catalog_info string that would be supplied. Returns a dict containing the volume_api_version and the volume_catalog_info.
def sample_less_than_condition(choices_in, condition): output = np.zeros(min(condition.shape[0], choices_in.shape[0])) choices = copy.deepcopy(choices_in) for i, _ in enumerate(output): avail_inds = np.where(choices < condition[i])[0] selected_ind = np.random.choice(avail_inds)...
Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order.
def transform_folder(args): command, (transform, src, dest) = args try: print(progress.value, "remaining") data = [] data_dir = os.path.join(src, command) for filename in os.listdir(data_dir): path = os.path.join(data_dir, filename) data.append(transform({: path})) pic...
Transform all the files in the source dataset for the given command and save the results as a single pickle file in the destination dataset :param args: tuple with the following arguments: - the command name: 'zero', 'one', 'two', ... - transforms to apply to wav file - ...
def _set_statistics_oam(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=statistics_oam.statistics_oam, is_container=, presence=False, yang_name="statistics-oam", rest_name="statistics-oam", parent=self, path_helper=self._path_helper, extmethods=self._...
Setter method for statistics_oam, mapped from YANG variable /mpls_state/statistics_oam (container) If this variable is read-only (config: false) in the source YANG file, then _set_statistics_oam is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
def delete(self, **kwargs): url = self.base_url + % kwargs[] resp = self.client.delete(url=url) return resp
Delete a notification.
def close(self): if self.closed: return super().close() if not self.upload_on_close: return local_loc = os.path.join(self.local_base, self.log_relative_path) remote_loc = os.path.join(self.remote_base, self.l...
Close and upload local log file to remote storage Wasb.
def upsert_pending_licensors(cursor, document_id): cursor.execute(, (document_id,)) uuid_, metadata = cursor.fetchone() acceptors = set([uid for uid, type_ in _dissect_roles(metadata)]) cursor.execute(, (uuid_,)) existing_acceptors_mapping = dict(cursor.fetchall()) existing_acce...
Update or insert records for pending license acceptors.
def get_ipv4(hostname): addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET, socket.SOCK_STREAM) return [addrinfo[x][4][0] for x in range(len(addrinfo))]
Get list of ipv4 addresses for hostname
def set_api_version(self, major, minor): if not self._is_byte(major) or not self._is_byte(minor): raise ArgumentError("Invalid API version number with component that does not fit in 1 byte", major=major, minor=minor) self.api_version = (major, minor...
Set the API version this module was designed for. Each module must declare the mib12 API version it was compiled with as a 2 byte major.minor number. This information is used by the pic12_executive to decide whether the application is compatible.
def show_more(context, label=None, loading=settings.LOADING): data = utils.get_data_from_context(context) page = data[] if page.has_next(): request = context[] page_number = page.next_page_number() querystring_key = data[] querystring = utils.get_...
Show the link to get the next page in a Twitter-like pagination. Usage:: {% show_more %} Alternatively you can override the label passed to the default template:: {% show_more "even more" %} You can override the loading text too:: {% show_more "even more" "working" %} Must...
def remove_group(self, name, swap_group=None): log.warning() url = if swap_group is not None: params = {: name, : swap_group} else: params = {: name} return self.delete(url, params=params)
Delete a group by given group parameter If you delete a group and content is restricted to that group, the content will be hidden from all users To prevent this, use this parameter to specify a different group to transfer the restrictions (comments and worklogs only) to :param name: str...
def enable_process_breakpoints(self, dwProcessId): for bp in self.get_process_code_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_code_breakpoint(dwProcessId, bp.get_address()) for bp in self.get_process_page_breakpoints(dwProcessId): ...
Enables all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID.
def get_base(self, option): if option: if option.isupper(): if len(option) > 3: return getattr(settings, option), True elif len(option) == 3: return option, True raise ImproperlyConfigured("Invalid currency ...
Parse the base command option. Can be supplied as a 3 character code or a settings variable name If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]: mapper = obj.__mapper__ assert mapper, "gen_columns called on {!r} which is not an " \ "SQLAlchemy ORM object".format(obj) colmap = mapper.columns if not colmap: return for attrname, column in colm...
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?" Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object instance. Also works with the corresponding SQLAlchemy ORM class. Examples: .. code-block:: python from sqlalchemy.ext.declarative import declarative_base ...
def generate_output_csv(evaluation_results, filename=): with open(filename, ) as f: for result in evaluation_results: for i, entry in enumerate(result[]): if entry[] == : result[][] = f.write("%s, " % result[]) f.write(", ".join([...
Generate the evaluation results in the format Parameters ---------- evaluation_results : list of dictionaries Each dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionaries. Each of the results has the keys 'latex' and 'probability' ...
def T(self, T): self._T = T self._Hfr = self._calculate_Hfr(T)
Set the temperature of the stream to the specified value, and recalculate it's enthalpy. :param T: Temperature. [°C]
def update_payload(self, fields=None): payload = super(DiscoveryRule, self).update_payload(fields) if in payload: payload[] = payload.pop() return {u: payload}
Wrap submitted data within an extra dict.
def line_rate(self, filename=None): if filename is None: el = self.xml else: el = self._get_class_element_by_filename(filename) return float(el.attrib[])
Return the global line rate of the coverage report. If the `filename` file is given, return the line rate of the file.
def uifile(self): output = if zipfile.is_zipfile(self.source()): zfile = zipfile.ZipFile(self.source(), ) if in zfile.namelist(): tempdir = tempfile.gettempdir() output = os.path.join(tempdir, ...
Returns the uifile for this scaffold. :return <str>
def uninstall_handler(self, event_type, handler, user_handle=None): self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle)
Uninstalls handlers for events in this resource. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application. :param user_handle: The user handle (ctypes object or None) returned by install_handler.
def view(tilesets): from .server import Server from .client import View curr_view = View() server = Server() server.start(tilesets) for ts in tilesets: if (ts.track_type is not None and ts.track_position is not None): curr_view.add_track(ts.track_type, ...
Create a higlass viewer that displays the specified tilesets Parameters: ----------- Returns ------- Nothing
def get_info( self, userSpecifier, **kwargs ): request = Request( , ) request.set_path_param( , userSpecifier ) response = self.ctx.request(request) if response.content_type is None...
Fetch the user information for the specified user. This endpoint is intended to be used by the user themself to obtain their own information. Args: userSpecifier: The User Specifier Returns: v20.response.Response containing the results from submi...
def tree_diff(a, b, n=5, sort=False): a = dump(a) b = dump(b) if not sort: a = vformat(a).split("\n") b = vformat(b).split("\n") else: a = vformat(recursive_sort(a)).split("\n") b = vformat(recursive_sort(b)).split("\n") return "\n".join(difflib.unified_diff(a, b...
Dump any data-structure or object, traverse it depth-first in-order and apply a unified diff. Depth-first in-order is just like structure would be printed. :param a: data_structure a :param b: data_structure b :param n: lines of context :type n:...
def _temporary_filenames(total): temp_files = [_get_temporary_filename() for i in range(total)] yield temp_files for temp_file in temp_files: try: os.remove(temp_file) except OSError: pass
Context manager to create temporary files and remove them after use.
def get_compound_afrs(self): result = self._compound_mfrs * 1.0 for compound in self.material.compounds: index = self.material.get_compound_index(compound) result[index] = stoich.amount(compound, result[index]) return result
Determine the amount flow rates of all the compounds. :returns: List of amount flow rates. [kmol/h]
def show(self): off = 0 for n, i in enumerate(self.get_instructions()): print("{:8d} (0x{:08x}) {:04x} {:30} {}".format(n, off, i.get_op_value(), i.get_name(), i.get_output(self.idx))) off += i.get_length()
Display (with a pretty print) this object
def histogram_cumulative(data,**kwargs): r return_edges = kwargs.pop(, True) norm = kwargs.pop(, False) P, edges = np.histogram(data, **kwargs) P = np.cumsum(P) if norm: P = P/P[-1] if not return_edges: edges = np.diff(edges) / 2. + edges[:-1] return P, edges
r''' Compute cumulative histogram. See `numpy.histrogram <https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html>`_ :extra options: **return_edges** ([``True``] | [``False``]) Return the bin edges if set to ``True``, return their midpoints otherwise. **normalize** ([``False``] | ``True``) ...
def unindent(self): _logger().debug() cursor = self.editor.textCursor() _logger().debug(, cursor.hasSelection()) if cursor.hasSelection(): cursor.beginEditBlock() self.unindent_selection(cursor) cursor.endEditBlock() self.editor.s...
Un-indents text at cursor position.
def process_json_response(self, response): response_json = response.json() code_key = "code" if code_key in response_json and response_json[code_key] != constants.HTTP_CODE_OK: code = response_json[code_key] message = response_json if "mes...
For a json response, check if there was any error and throw exception. Otherwise, create a housecanary.response.Response.
def destroy(self): dialog = self.dialog if dialog: dialog.setOnDismissListener(None) dialog.dismiss() del self.dialog super(AndroidDialog, self).destroy()
A reimplemented destructor that cancels the dialog before destroying.
def _get_fully_qualified_name(self): "return full parents name + self name (useful as key)" parent_name = self._get_parent_name() if not parent_name: return self._name else: return "%s.%s" % (parent_name, self._name)
return full parents name + self name (useful as key)
def _resolve_hostname(name): if env.ssh_config is None: return name elif not os.path.exists(os.path.join("nodes", name + ".json")): resolved_name = env.ssh_config.lookup(name)[] if os.path.exists(os.path.join("nodes", resolved_name + ".json")): name = resolved_name r...
Returns resolved hostname using the ssh config
def set_bn_eval(m:nn.Module)->None: "Set bn layers in eval mode for all recursive children of `m`." for l in m.children(): if isinstance(l, bn_types) and not next(l.parameters()).requires_grad: l.eval() set_bn_eval(l)
Set bn layers in eval mode for all recursive children of `m`.
def __get_award_emoji(self, item_type, item_id): emojis = [] group_emojis = self.client.emojis(item_type, item_id) for raw_emojis in group_emojis: for emoji in json.loads(raw_emojis): emojis.append(emoji) return emojis
Get award emojis for issue/merge request
def process_response(self, request, response): if hasattr(threadlocal, ): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog[]) return response
Disconnects the signal receiver to prevent it from staying active.
def get_reference_end_from_cigar(reference_start, cigar): s reference_end method ' reference_end = reference_start for i in xrange(len(cigar)): k, n = cigar[i] if k in (0,2,3,7,8): reference_end += n return reference_end
This returns the coordinate just past the last aligned base. This matches the behavior of pysam's reference_end method
def resolve_redirection(self, request, context): current_page = context[] lang = context[] if current_page.redirect_to_url: return HttpResponsePermanentRedirect(current_page.redirect_to_url) if current_page.redirect_to: return HttpResponsePermanentRedire...
Check for redirections.
def get_projected_player_game_stats_by_team(self, season, week, team_id): result = self._method_call("PlayerGameProjectionStatsByTeam/{season}/{week}/{team_id}", "projections", season=season, week=week, team_id=team_id) return result
Projected Player Game Stats by Team
def _shuffle(y, labels, random_state): if labels is None: ind = random_state.permutation(len(y)) else: ind = np.arange(len(labels)) for label in np.unique(labels): this_mask = (labels == label) ind[this_mask] = random_state.permutation(ind[this_mask]) ret...
Return a shuffled copy of y eventually shuffle among same labels.
def radiance2tb(rad, wavelength): from pyspectral.blackbody import blackbody_rad2temp as rad2temp return rad2temp(wavelength, rad)
Get the Tb from the radiance using the Planck function rad: Radiance in SI units wavelength: Wavelength in SI units (meter)
def led_changed(self, addr, group, val): _LOGGER.debug("Button %d LED changed from %d to %d", self._group, self._value, val) led_on = bool(val) if led_on != bool(self._value): self._update_subscribers(int(led_on))
Capture a change to the LED for this button.
def server_poweroff(host=None, admin_username=None, admin_password=None, module=None): return __execute_cmd(, host=host, admin_username=admin_username, admin_password=admin_password, module=module)
Powers down the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to power off on the chassis such as a blade. If not provided, the chassis ...
def _apply_replace_backrefs(m, repl=None, flags=0): if m is None: raise ValueError("Match is None!") else: if isinstance(repl, ReplaceTemplate): return repl.expand(m) elif isinstance(repl, (str, bytes)): return _bregex_parse._ReplaceParser().parse(m.re, repl...
Expand with either the `ReplaceTemplate` or compile on the fly, or return None.
def buildMaskImage(rootname, bitvalue, output, extname=, extver=1): maskname = output if fileutil.findFile(maskname): fileutil.removeFile(maskname) fdq = fileutil.openImage(rootname, mode=, memmap=False) try: _extn = fileutil.findExtname(f...
Builds mask image from rootname's DQ array If there is no valid 'DQ' array in image, then return an empty string.
def visitEncapsulatedShape(self, ctx: ShExDocParser.EncapsulatedShapeContext): enc_shape = ShexOneOfShapeParser(self.context) enc_shape.visit(ctx.innerShape()) self.expression = enc_shape.expression self._card_annotations_and_semacts(ctx)
encapsulatedShape: '(' innerShape ')' cardinality? annotation* semanticActions
def iter_blobs(self, predicate=lambda t: True): for entry in mviter(self.entries): blob = entry.to_blob(self.repo) blob.size = entry.size output = (entry.stage, blob) if predicate(output): yield output
:return: Iterator yielding tuples of Blob objects and stages, tuple(stage, Blob) :param predicate: Function(t) returning True if tuple(stage, Blob) should be yielded by the iterator. A default filter, the BlobFilter, allows you to yield blobs only if they match a given list ...
def main(arguments=None): result = _parse_arguments(arguments) linter_funcs = _ordered(linter_functions_from_filters, result.whitelist, result.blacklist) global_options = vars(result) tool_options = tool_options_from_global(global_options, ...
Entry point for the linter.
def schedule_telegram_message(message, to, sender=None, priority=None): schedule_messages(message, recipients(, to), sender=sender, priority=priority)
Schedules Telegram message for delivery. :param str message: text to send. :param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes. :param User sender: User model heir instance :param int priority: number describing message priority. If set overri...
def classify(self, dataset, missing_value_action=): return super(RandomForestClassifier, self).classify(dataset, missing_value_action=missing_value_action)
Return a classification, for each example in the ``dataset``, using the trained random forest model. The output SFrame contains predictions as class labels (0 or 1) and probabilities associated with the the example. Parameters ---------- dataset : SFrame Dataset of n...
def __check_command_completion(self, testsemicolon=True): if not self.__curcommand.iscomplete(): return True ctype = self.__curcommand.get_type() if ctype == "action" or \ (ctype == "control" and not self.__curcommand.accept_children): ...
Check for command(s) completion This function should be called each time a new argument is seen by the parser in order to check a command is complete. As not only one command can be ended when receiving a new argument (nested commands case), we apply the same work to parent comm...
def unirange(a, b): if b < a: raise ValueError("Bad character range") if a < 0x10000 or b < 0x10000: raise ValueError("unirange is only defined for non-BMP ranges") if sys.maxunicode > 0xffff: return u % (unichr(a), unichr(b)) else: ...
Returns a regular expression string to match the given non-BMP range.
def calculate_activity_rate(self, strain_data, cumulative=False, in_seconds=False): self.strain = strain_data self.strain.target_magnitudes = self.target_magnitudes for key in STRAIN_VARIABLES: self.strain.data[key] = self.strain.data...
Main function to calculate the activity rate (for each of the magnitudes in target_magnitudes) for all of the cells specified in the input strain model file :param strain_data: Strain model as an instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain ...
def is_twss(self, phrase): featureset = self.extract_features(phrase) return self.classifier.classify(featureset)
The magic function- this accepts a phrase and tells you if it classifies as an entendre
def stub_main(): from google.apputils import run_script_module import butcher.main run_script_module.RunScriptModule(butcher.main)
setuptools blah: it still can't run a module as a script entry_point
def update(self, client=None, unique_writer_identity=False): client = self._require_client(client) resource = client.sinks_api.sink_update( self.project, self.name, self.filter_, self.destination, unique_writer_identity=unique_writer_i...
API call: update sink configuration via a PUT request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed,...
def _template(node_id, value=None): "Check if a template is assigned to it and render that with the value" result = [] select_template_from_node = fetch_query_string() try: result = db.execute(text(select_template_from_node), node_id=node_id) template_result = result.fetchone() r...
Check if a template is assigned to it and render that with the value
def _set_bcpIn(self, value): x, y = absoluteBCPIn(self.anchor, value) segment = self._segment if segment.type == "move" and value != (0, 0): raise FontPartsError(("Cannot set the bcpIn for the first " "point in an open contour.") ...
Subclasses may override this method.
def set_(key, value, profile=None): conn = salt.utils.memcached.get_conn(profile) time = profile.get(, DEFAULT_EXPIRATION) return salt.utils.memcached.set_(conn, key, value, time=time)
Set a key/value pair in memcached
async def connect(self, conn_id, connection_string): self._ensure_connection(conn_id, False) msg = dict(connection_string=connection_string) await self._send_command(OPERATIONS.CONNECT, msg, COMMANDS.ConnectResponse) self._setup_connection(conn_id, connection_string)
Connect to a device. See :meth:`AbstractDeviceAdapter.connect`.
def process_results(self, results=None, **value): channels = [] for res in results: channels.extend(res.pop(, ).split()) value.update(res) value[] = channels value[] = value.get() == return value
take results list of all events and put them in a dict
def new_output(output_type=None, output_text=None, output_png=None, output_html=None, output_svg=None, output_latex=None, output_json=None, output_javascript=None, output_jpeg=None, prompt_number=None, etype=None, evalue=None, traceback=None): output = NotebookNode() if output_type is not None:...
Create a new code cell with input and output
def parse_qualifier(parser, event, node): name = _get_required_attribute(node, ) cim_type = _get_required_attribute(node, ) propagated = _get_attribute(node, ) (next_event, next_node) = six.next(parser) if _is_end(next_event, next_node, ): return CIMQualifier(name, None, type=c...
Parse CIM/XML QUALIFIER element and return CIMQualifier
def digital_write(pin_num, value, hardware_addr=0): _get_pifacedigital(hardware_addr).output_pins[pin_num].value = value
Writes the value to the input pin specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``output_pins`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(hardware_addr) >>> pfd.output_pins[pin_num].value = 1 ...
def color(self, key=None): if key is not None: return self._colorMap.get(nativestring(key), self._color) return self._color
Returns the color for this data set. :return <QColor>
def get_downloader(session, class_name, args): external = { : WgetDownloader, : CurlDownloader, : Aria2Downloader, : AxelDownloader, } for bin, class_ in iteritems(external): if getattr(args, bin): return class_(session, bin=getattr(args, bin), ...
Decides which downloader to use.
def _verify_sector_identifier(self, request): si_url = request["sector_identifier_uri"] try: res = self.endpoint_context.httpc.get(si_url) except Exception as err: logger.error(err) res = None if not res: raise InvalidSectorIdenti...
Verify `sector_identifier_uri` is reachable and that it contains `redirect_uri`s. :param request: Provider registration request :return: si_redirects, sector_id :raises: InvalidSectorIdentifier
def traverse_nodes(self, qids, up=True, down=False, **args): g = self.get_filtered_graph(**args) nodes = set() for id in qids: nodes.add(id) if down: nodes.update(nx.descendants(g, id)) if up: nodes.update(...
Traverse (optionally) up and (optionally) down from an input set of nodes Arguments --------- qids : list[str] list of seed node IDs to start from up : bool if True, include ancestors down : bool if True, include descendants relations ...
def __draw_canvas_cluster(self, ax, dimension, cluster_descr): cluster = cluster_descr.cluster data = cluster_descr.data marker = cluster_descr.marker markersize = cluster_descr.markersize color = cluster_descr.color for item in cluster: ...
! @brief Draw canvas cluster descriptor. @param[in] ax (Axis): Axis of the canvas where canvas cluster descriptor should be displayed. @param[in] dimension (uint): Canvas dimension. @param[in] cluster_descr (canvas_cluster_descr): Canvas cluster descriptor that should be displayed....
def from_dict(input_dict, data=None): import GPy m = GPy.core.model.Model.from_dict(input_dict, data) from copy import deepcopy sparse_gp = deepcopy(m) return SparseGPClassification(sparse_gp.X, sparse_gp.Y, sparse_gp.Z, sparse_gp.kern, sparse_gp.likelihood, sparse_gp.i...
Instantiate an SparseGPClassification object using the information in input_dict (built by the to_dict method). :param data: It is used to provide X and Y for the case when the model was saved using save_data=False in to_dict method. :type data: tuple(:class:`np.ndarray`, :class:`np....
def update_repository(self, repository_form=None): if repository_form is None: raise NullArgument() if not isinstance(repository_form, abc_repository_objects.RepositoryForm): raise InvalidArgument() if not repository_form.is_for_update(): raise Invali...
Updates an existing repository. :param repository_form: the form containing the elements to be updated :type repository_form: ``osid.repository.RepositoryForm`` :raise: ``IllegalState`` -- ``repository_form`` already used in an update transaction :raise: ``InvalidArgument`` -- the form ...
def list_cmd(argv=sys.argv[1:]): docopt(list_cmd.__doc__, argv=argv) initialize_config(__mode__=) list()
\ List information about available models. Uses the 'model_persister' from the configuration to display a list of models and their metadata. Usage: pld-list [options] Options: -h --help Show this screen.
def extend_selection_to_next(self, what=, direction=): self.__move_cursor_anchor(what, direction, QTextCursor.KeepAnchor)
Extend selection to next *what* ('word' or 'character') toward *direction* ('left' or 'right')
def draw_rivers_on_image(world, target, factor=1): for y in range(world.height): for x in range(world.width): if world.is_land((x, y)) and (world.layers[].data[y, x] > 0.0): for dx in range(factor): for dy in range(factor): target...
Draw only the rivers, it expect the background to be in place
def _shru16(ins): op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op = int16(op2) if op == 0: return [] output = _16bit_oper(op1) if op == 1: output.append() output.append() output.append() return output ou...
Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic
def append_known_secrets(self): for file_name in self.files: if "~" in file_name: file_name = os.path.expanduser(file_name) if not os.path.isfile(file_name): print( "Dont use." ) continue ...
Read key-value pair files with secrets. For example, .conf and .ini files. :return:
def p_do_loop_while(p): if len(p) == 6: q = make_block(p[2], p[3]) r = p[5] else: q = p[2] r = p[4] if p[1] == : gl.LOOPS.append((,)) p[0] = make_sentence(, r, q) gl.LOOPS.pop() if is_number(r): api.errmsg.warning_condition_is_always(p.line...
statement : do_start program_co label_loop WHILE expr | do_start label_loop WHILE expr | DO label_loop WHILE expr