Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
356,800
def connect(self, addr=None, userinfo=None): if _debug: ProxyClientService._debug("connect addr=%r", addr) if addr: self.address = addr else: addr = self.address if userinfo: self.userinfo = userinfo conn ...
Initiate a connection request to the device.
356,801
def help(ctx, topic, **kw): if topic is None: click.echo(ctx.parent.get_help()) else: click.echo(main.commands[topic].get_help(ctx))
Show help for any command.
356,802
def OnHelpSize(self, event): size = event.GetSize() config["help_window_size"] = repr((size.width, size.height)) event.Skip()
Help window size event handler stores size in config
356,803
def query_by_expired(cls): lifetime = current_app.permanent_session_lifetime expired_moment = datetime.utcnow() - lifetime return cls.query.filter(cls.created < expired_moment)
Query to select all expired sessions.
356,804
def edit(self, name=None, description=None, **kwargs): update_dict = {: self.id} if name: if not isinstance(name, str): raise IllegalArgumentError("name should be provided as a string") update_dict.update({: name}) if description: ...
Edit the details of a part (model or instance). For an instance you can edit the Part instance name and the part instance description. To alter the values of properties use :func:`Part.update()`. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as ...
356,805
def notescan_main(options): filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = bool(options.postprocess_cmd) for input_filename in...
Main function for this program when run as script.
356,806
def _adjusted_rand_index(reference_indices, estimated_indices): n_samples = len(reference_indices) ref_classes = np.unique(reference_indices) est_classes = np.unique(estimated_indices) if (ref_classes.shape[0] == est_classes.shape[0] == 1 or ref_classes.shape[0] == est_classe...
Compute the Rand index, adjusted for change. Parameters ---------- reference_indices : np.ndarray Array of reference indices estimated_indices : np.ndarray Array of estimated indices Returns ------- ari : float Adjusted Rand index .. note:: Based on sklearn.met...
356,807
def index(): collection_names = request.values.getlist() collections = Collection.query if collection_names: collections = collections.filter( Collection.name.in_(collection_names)) assert len(collection_names) == collections.count() response = search.client.search( ...
Query Elasticsearch using "collection" param in query string.
356,808
def thellier_interpreter_BS_pars_calc(self, Grade_As): thellier_interpreter_pars = {} thellier_interpreter_pars[] = [] thellier_interpreter_pars[] = BOOTSTRAP_N = int(self.preferences[]) Grade_A_samples_BS = {} if len(list(Grade_As.keys())) >= self.acceptance_c...
calcualte sample or site bootstrap paleointensities and statistics Grade_As={}
356,809
def _extract_member(self, member, targetpath, pwd): arcname = member.filename.replace(, os.path.sep) if os.path.altsep: arcname = arcname.replace(os.path.altsep, os.path.sep) arcname = os.path.splitdrive(arcname)[1] invalid_path_p...
Extract the ZipInfo object 'member' to a physical file on the path targetpath.
356,810
def add_event_handler(self, full_usage_id, handler_function, event_kind = HID_EVT_ALL, aux_data = None): report_id = self.find_input_usage(full_usage_id) if report_id != None: self.__input_report_templates[report_id][full_usage_id].__value = None ...
Add event handler for usage value/button changes, returns True if the handler function was updated
356,811
def get_canonical_user_id(self, headers=None): rs = self.get_all_buckets(headers=headers) return rs.ID
Convenience method that returns the "CanonicalUserID" of the user who's credentials are associated with the connection. The only way to get this value is to do a GET request on the service which returns all buckets associated with the account. As part of that response, the canonical user...
356,812
def __updateNavButtons(self): navButtons = None for v in self.views: if v.getId() == : navButtons = v break if navButtons: self.navBack = self.findViewById(, navButtons) self.navHome = self.findViewById(, navButtons) ...
Updates the navigation buttons that might be on the device screen.
356,813
def get_input_grads(self, merge_multi_context=True): assert self.inputs_need_grad if merge_multi_context: return _merge_multi_context(self.input_grad_arrays, self.data_layouts) return self.input_grad_arrays
Get the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Defaults to ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A `True` value indicate that we ...
356,814
def _detect(self): results = [] for c in self.contracts: shadowing = self.detect_shadowing(c) if shadowing: for all_variables in shadowing: shadow = all_variables[0] variables = all_variables[1:] ...
Detect shadowing Recursively visit the calls Returns: list: {'vuln', 'filename,'contract','func', 'shadow'}
356,815
def compute_exports(exports): loc, glob = get_calling_namespaces() retval = {} try: for export in exports: if SCons.Util.is_Dict(export): retval.update(export) else: try: retval[export] = loc[export] e...
Compute a dictionary of exports given one of the parameters to the Export() function or the exports argument to SConscript().
356,816
def _print_returns_summary(self, ret): return_counter = 0 not_return_counter = 0 not_return_minions = [] not_response_minions = [] not_connected_minions = [] failed_minions = [] for each_minion in ret: minion_ret = ret[each_minion] ...
Display returns summary
356,817
def append_records(self, dataset_key, stream_id, body): owner_id, dataset_id = parse_dataset_key(dataset_key) try: return self._streams_api.append_records(owner_id, dataset_id, stream_id, body) except _swagger.rest.ApiExcep...
Append records to a stream. :param dataset_key: Dataset identifier, in the form of owner/id :type dataset_key: str :param stream_id: Stream unique identifier. :type stream_id: str :param body: Object body :type body: obj :raises RestApiException: If a server erro...
356,818
def revisions(self, path, max_revisions): if self.repo.is_dirty(): raise DirtyGitRepositoryError(self.repo.untracked_files) revisions = [] for commit in self.repo.iter_commits( self.current_branch, max_count=max_revisions ): rev = Revision( ...
Get the list of revisions. :param path: the path to target. :type path: ``str`` :param max_revisions: the maximum number of revisions. :type max_revisions: ``int`` :return: A list of revisions. :rtype: ``list`` of :class:`Revision`
356,819
def clear_calendars(self): self._calendars.clear() self._calendar_factories.clear() self._aliases.clear()
Deregisters all current registered calendars
356,820
def setup(self): super().setup() self._start_time = self.clock.time self.initialize_simulants()
Setup the simulation and initialize its population.
356,821
def _cstor_args_from_fields(self, fields, is_struct=False): if is_struct: args = [(fmt_var(f.name), fmt_type(f.data_type, tag=True, has_default=f.has_default)) for f in fields] else: args = [(fmt_var(f.name), fmt_type(f.data_type, tag=True)) for f in fiel...
Returns a string representing the properly formatted arguments for a constructor.
356,822
def send_email(self, msg, tag=None): try: return self._send_email(msg, tag) except: self.exceptions.append(straceback()) return -2
Send an e-mail before completing the shutdown. Returns 0 if success.
356,823
def fast_sync_inspect_snapshot( snapshot_path ): with open(snapshot_path, ) as f: info = fast_sync_inspect( f ) if in info: log.error("Failed to inspect snapshot {}: {}".format(snapshot_path, info[])) return {: } hash_hex = get_file_hash(f, hashlib.sha...
Inspect a snapshot Return useful information Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success Return {'error': ...} on error
356,824
def apply(self, points): if not isinstance(points, BagOfPoints): raise ValueError() if points.dim != 3: raise ValueError() if points.frame != self._from_frame: raise ValueError( %(points.frame, self._from_frame, self._to_frame)) if isinstance...
Applies the rigid transformation to a set of 3D objects. Parameters ---------- points : :obj:`BagOfPoints` A set of objects to transform. Could be any subclass of BagOfPoints. Returns ------- :obj:`BagOfPoints` A transformed set of objects of the...
356,825
def key_from_password(password): if isinstance(password, unicode): password = password.encode() if not isinstance(password, bytes): raise TypeError("password must be byte string, not %s" % type(password)) sha = SHA256.new() sha.update(password) return sha.digest()
This method just hashes self.password.
356,826
def get_user(user_or_username): user = None if isinstance(user_or_username, MemberData): user = user_or_username if isinstance(user_or_username, basestring): user = get_member_by_login_name(get_portal(), user_or_username, False) return user
Return Plone User :param user_or_username: Plone user or user id :returns: Plone MemberData
356,827
def delta_encode(data, axis=-1, out=None): if isinstance(data, (bytes, bytearray)): data = numpy.frombuffer(data, dtype=) diff = numpy.diff(data, axis=0) return numpy.insert(diff, 0, data[0]).tobytes() dtype = data.dtype if dtype.kind == : data = data.view( % dtype.item...
Encode Delta.
356,828
def exception(self, timeout=None): if not self._done.wait(timeout): raise Timeout() if self._state == self.S_EXCEPTION: return self._result
Wait for the async function to complete and return its exception. If the function did not raise an exception this returns ``None``.
356,829
async def reprompt_dialog(self): if self.active_dialog != None: dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogSet.reprompt_dialog(): Can%s'." % self.active_dialog.id) a...
Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior. :return:
356,830
def submit(self, job): script = self._printer.generate(job) stdin, stdout, stderr = self._ssh.exec_command() stdin.write(script) stdin.flush() stdin.channel.shutdown_write() return stdout.read()
Submits a given job :param job: The job to submit :type job: pyqueue.job.JobInterface
356,831
def allow_unregister(self, plugin_override=True): vals = self._hook_manager.call_hook(, course=self, default=self._allow_unregister) return vals[0] if len(vals) and plugin_override else self._allow_unregister
Returns True if students can unregister from course
356,832
def delete(self, alert_condition_id): return self._delete( url=.format(self.URL, alert_condition_id), headers=self.headers )
This API endpoint allows you to delete an alert condition :type alert_condition_id: integer :param alert_condition_id: Alert Condition ID :rtype: dict :return: The JSON response of the API :: { "condition": { "id": "integer", ...
356,833
def get_choices(field): empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] if hasattr(field.field, "_choices"): choices = field.field._choices elif hasattr(field.field, "_queryset"): queryset = field.field._queryset field_name = getattr(field.field, "to_f...
Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices
356,834
def load_locations(self, location_file=None): if location_file is None: contents = pkgutil.get_data(__package__, ) contents_string = contents.decode("ascii") locations = contents_string.split() else: from .cli import open_file with ope...
Load locations into this resolver from the given *location_file*, which should contain one JSON object per line representing a location. If *location_file* is not specified, an internal location database is used.
356,835
def get_root_books(self): if self._catalog_session is not None: return self._catalog_session.get_root_catalogs() return BookLookupSession( self._proxy, self._runtime).get_books_by_ids(list(self.get_root_book_ids()))
Gets the root books in the book hierarchy. A node with no parents is an orphan. While all book ``Ids`` are known to the hierarchy, an orphan does not appear in the hierarchy unless explicitly added as a root node or child of another node. return: (osid.commenting.BookList) - th...
356,836
def unset_logging(self): if self.logger_flag is True: return root_logger = logging.getLogger() for hndlr in root_logger.handlers: if hndlr not in self.prior_loghandlers: hndlr.setLevel(logging.ERROR) self.logger_flag = True
Mute newly added handlers to the root level, right after calling executor.status
356,837
async def remove(gc: GroupControl, slaves): click.echo("Removing from existing group: %s" % slaves) click.echo(await gc.remove(slaves))
Remove speakers from group.
356,838
def import_file(args): full_path, path_dict = Object.validate_full_path( args.full_path, vault=args.vault, path=args.path) if args.create_dataset: dataset = create_dataset(args) else: try: dataset = solvebio.Dataset.get_by_full_path(full_path) except so...
Given a dataset and a local path, upload and import the file(s). Command arguments (args): * create_dataset * template_id * full_path * vault (optional, overrides the vault in full_path) * path (optional, overrides the path in full_path) * commit_mode * capa...
356,839
def _update_scale_factor(self, accept_rate): if accept_rate > self.force_acceptance_max and self.covar_scale_factor < self.covar_scale_factor_max: self.covar_scale_factor *= self.covar_scale_multiplier elif accept_rate < self.force_acceptance_min and self.covar_scale_factor > self.c...
Private function. Updates the covariance scaling factor ``covar_scale_factor`` according to its limits
356,840
def anim_to_html(anim): if not hasattr(anim, ): with NamedTemporaryFile(suffix=) as f: anim.save(f.name, fps=20, extra_args=[, ]) video = open(f.name, "rb").read() anim._encoded_video = video.encode("base64") return VIDEO_TAG.format(anim._encoded_video)
adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/ This function converts and animation object from matplotlib into HTML which can then be embedded in an IPython notebook. This requires ffmpeg to be installed in order to build the intermediate mp4 file To get thes...
356,841
def set_extent_location(self, new_location): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() self.new_extent_loc = new_location
A method to set the location of this UDF File Set Descriptor. Parameters: new_location - The new extent this UDF File Set Descriptor should be located at. Returns: Nothing.
356,842
def _create_message(response, service_instance): respbody = response.body custom_properties = {} broker_properties = None message_type = None message_location = None for name, value in response.headers: if name.lower() == : broker_properties = json.loads(value) ...
Create message from response. response: response from Service Bus cloud server. service_instance: the Service Bus client.
356,843
def mount(self, volume): volume._make_mountpoint() try: self._call_mount(volume, volume.mountpoint, self._mount_type or self.type, self._mount_opts) except Exception: volume._clear_mountpoint() raise
Mounts the given volume on the provided mountpoint. The default implementation simply calls mount. :param Volume volume: The volume to be mounted :param mountpoint: The file system path to mount the filesystem on. :raises UnsupportedFilesystemError: when the volume system type can not be mounte...
356,844
def rmdir(self, directory, missing_okay=False): if message.find("OSError: [Errno 2] ENOENT") != -1: if not missing_okay: raise RuntimeError("No such directory: {0}".format(directory)) ...
Forcefully remove the specified directory and all its children.
356,845
def jacobian(expr, symbols): jac = [] for symbol in symbols: f = sympy.diff(expr, symbol) jac.append(f) return jac
Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector. :param expr: A sympy Expr. :param symbols: The symbols w.r.t. which to derive.
356,846
def alphanumeric_hash(s: str, size=5): import hashlib import base64 hash_object = hashlib.md5(s.encode()) s = base64.b32encode(hash_object.digest()) result = s[:size].decode().lower() return result
Short alphanumeric string derived from hash of given string
356,847
def _estimate_friedrich_coefficients(x, m, r): assert m > 0, "Order of polynomial need to be positive integer, found {}".format(m) df = pd.DataFrame({: x[:-1], : np.diff(x)}) try: df[] = pd.qcut(df.signal, r) except ValueError: return [np.NaN] * (m + 1) quantiles = df.groupby(...
Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) As described by Friedrich et al. (2000): Physics Letters A 271, p. 217-222 *Extracting model equations from experimental ...
356,848
def _M2_dense(X, Y, weights=None, diag_only=False): if weights is not None: if diag_only: return np.sum(weights[:, None] * X * Y, axis=0) else: return np.dot((weights[:, None] * X).T, Y) else: if diag_only: return np.sum(X * Y, axis=0) els...
2nd moment matrix using dense matrix computations. This function is encapsulated such that we can make easy modifications of the basic algorithms
356,849
def _iterate_through_pages(get_function, resource, **kwargs): request_data = True data = [] page = 1 while request_data: temp_response = get_function(page=page, **kwargs) if temp_response[resource][] != : data.append(temp_response) ...
Iterate through all pages and return the collected data :rtype: list
356,850
def get_grade_system_admin_session_for_gradebook(self, gradebook_id, proxy): if not self.supports_grade_system_admin(): raise errors.Unimplemented() return sessions.GradeSystemAdminSession(gradebook_id, proxy, self._runtime)
Gets the ``OsidSession`` associated with the grade system admin service for the given gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.GradeSystemAdminSession) - ``a GradeSystemAdminSession`...
356,851
def url_fix_host (urlparts): if not urlparts[1]: urlparts[2] = urllib.unquote(urlparts[2]) return False userpass, netloc = urllib.splituser(urlparts[1]) if userpass: userpass = urllib.unquote(userpass) netloc, is_idn = idna_encode(urllib.unquote(netloc).lower()) ...
Unquote and fix hostname. Returns is_idn.
356,852
def find(name): if op.exists(name): return name path = op.dirname(__file__) or paths = [path] + config[] for path in paths: filename = op.abspath(op.join(path, name)) if op.exists(filename): return filename for d in os.listdir(path): ful...
Locate a filename into the shader library.
356,853
def cli(env, identifier, a_record, aaaa_record, ptr, ttl): items = [, , , , , , , ] mask = "mask[%s]" % .join(items) dns = SoftLayer.DNSManager(env.client) vsi = SoftLayer.VSManager(env.client) vs_id = ...
Sync DNS records.
356,854
def select(self, sql_string, cols, *args, **kwargs): working_columns = None if kwargs.get() is not None: working_columns = kwargs.pop() query = self._assemble_select(sql_string, cols, *args, *kwargs) return self._execute(query, working_columns=working_columns)
Execute a SELECT statement :sql_string: An SQL string template :columns: A list of columns to be returned by the query :*args: Arguments to be passed for query parameters. :returns: Psycopg2 result
356,855
def get_audiences(self): audience_nodes = self.__query_assertion() return [OneLogin_Saml2_XML.element_text(node) for node in audience_nodes if OneLogin_Saml2_XML.element_text(node) is not None]
Gets the audiences :returns: The valid audiences for the SAML Response :rtype: list
356,856
def tag_(name, repository, tag=, force=False): if not isinstance(repository, six.string_types): repository = six.text_type(repository) if not isinstance(tag, six.string_types): tag = six.text_type(tag) image_id = inspect_image(name)[] response = _client_wrapper(, ...
.. versionchanged:: 2018.3.0 The repository and tag must now be passed separately using the ``repository`` and ``tag`` arguments, rather than together in the (now deprecated) ``image`` argument. Tag an image into a repository and return ``True``. If the tag was unsuccessful, an error wi...
356,857
def _run_soft_delete(self): query = self.new_query().where(self.get_key_name(), self.get_key()) time = self.fresh_timestamp() setattr(self, self.get_deleted_at_column(), time) query.update({self.get_deleted_at_column(): self.from_datetime(time)})
Perform the actual delete query on this model instance.
356,858
def get(self, deviceId): measurementsByName = self.measurements.get(deviceId) if measurementsByName is None: return [] else: return list(measurementsByName.values())
lists all known active measurements.
356,859
def parse_transcripts(transcript_lines): LOG.info("Parsing transcripts") if isinstance(transcript_lines, DataFrame): transcripts = parse_ensembl_transcript_request(transcript_lines) else: transcripts = parse_ensembl_transcripts(transcript_lines) parsed_transcripts = ...
Parse and massage the transcript information There could be multiple lines with information about the same transcript. This is why it is necessary to parse the transcripts first and then return a dictionary where all information has been merged. Args: transcript_lines(): This could be an itera...
356,860
def SetWeight(self, path_segment_index, weight): if path_segment_index not in self._weight_per_index: raise ValueError() self._weight_per_index[path_segment_index] = weight if weight not in self._indexes_per_weight: self._indexes_per_weight[weight] = [] self._indexes_per_weight[weigh...
Sets a weight for a specific path segment index. Args: path_segment_index: an integer containing the path segment index. weight: an integer containing the weight. Raises: ValueError: if the path segment weights do not contain the path segment index.
356,861
def remove(self, *nonterminals): for nonterm in set(nonterminals): _NonterminalSet._control_nonterminal(nonterm) if nonterm not in self: raise KeyError( + nonterm.__name__ + ) self._grammar.rules.remove(*self._assign_map[nonterm], _validate=F...
Remove nonterminals from the set. Removes also rules using this nonterminal. Set start symbol to None if deleting nonterminal is start symbol at the same time. :param nonterminals: Nonterminals to remove.
356,862
def auth_list(): * auths = {} with salt.utils.files.fopen(, ) as auth_attr: for auth in auth_attr: auth = salt.utils.stringutils.to_unicode(auth) auth = auth.split() if len(auth) != 6: continue if auth[...
List all available authorization CLI Example: .. code-block:: bash salt '*' rbac.auth_list
356,863
def firstvalue(self, *fieldspecs, **kwargs): default = kwargs.get(, None) values = [val for val in self.itervalues(*fieldspecs, **kwargs)] if values: return values[0] else: return default
Return the [first] [v]alue or the value given by the keyword argument `default` if not value exists. `default` defaults to `None`.
356,864
def get_security_error(node): assert node.name() == and not node.isArray() if node.hasElement(): secid = XmlHelper.get_child_value(node, ) err = XmlHelper.as_security_error(node.getElement(), secid) return err else: return None
return a SecurityError if the specified securityData element has one, else return None
356,865
def authenticateRequest(self, service_request, username, password, **kwargs): authenticator = self.getAuthenticator(service_request) if authenticator is None: return True args = (username, password) if hasattr(authenticator, ): http_request = kwargs.ge...
Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will stop processing the request and return an error to the client. @rtype: C{bool}
356,866
def update_templates(self, body): return self.client.put(self._url(), data=body)
Update enrollment and verification SMS templates. Useful to send custom messages on sms enrollment and verification Args: body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guardian/put_templates
356,867
async def remove_pump_async(self, partition_id, reason): if partition_id in self.partition_pumps: captured_pump = self.partition_pumps[partition_id] if not captured_pump.is_closing(): await captured_pump.close_async(reason) del self.parti...
Stops a single partiton pump. :param partition_id: The partition ID. :type partition_id: str :param reason: A reason for closing. :type reason: str
356,868
def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None): base_config = items[0]["config"] for x in align_bams: bam.index(x, base_config) params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_CIGAR_READS"] paired = vcfuti...
Preparation work for SomaticIndelDetector.
356,869
def post(self, request, *args, **kwargs): queryset = self.get_selected(request) if request.POST.get(): response = self.process_action(request, queryset) if not response: url = self.get_done_url() return self.render(request, redirect_url=u...
Method for handling POST requests. Checks for a modify confirmation and performs the action by calling `process_action`.
356,870
def bgzip_and_index(in_file, config=None, remove_orig=True, prep_cmd="", tabix_args=None, out_dir=None): if config is None: config = {} out_file = in_file if in_file.endswith(".gz") else in_file + ".gz" if out_dir: remove_orig = False out_file = os.path.join(out_dir, os.path.bas...
bgzip and tabix index an input file, handling VCF and BED.
356,871
def set_root(self, index): if not index.isValid(): self.setModel(None) self.setCurrentIndex(QtCore.QModelIndex()) self.new_root.emit(QtCore.QModelIndex()) return if self.model() != index.model(): self.setModel(index.model()) s...
Set the given index as root index of list :param index: the new root index :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None
356,872
def html_scientific_notation_rate(rate): precision = if rate * 100 > 0: decimal_rate = Decimal(precision % (rate * 100)) if decimal_rate == Decimal((precision % 0)): decimal_rate = Decimal(str(rate * 100)) else: decimal_rate = Decimal(str(rate * 100)) if decimal...
Helper for convert decimal rate using scientific notation. For example we want to show the very detail value of fatality rate because it might be a very small number. :param rate: Rate value :type rate: float :return: Rate value with html tag to show the exponent :rtype: str
356,873
def _collapse_language_array(language_array): language_dict = {} for language in language_array.item: key = language.key[0] value = language.value[0] language_dict[key] = value return language_dict
Convert the Ideone language list into a Python dictionary.
356,874
def histogram_stretch(self, use_bands, **kwargs): data = self._read(self[use_bands,...], **kwargs) data = np.rollaxis(data.astype(np.float32), 0, 3) return self._histogram_stretch(data, **kwargs)
entry point for contrast stretching
356,875
def login_student(request): if not get_config(, , default=False): return render_json(request, { : _(), : }, template=, help_text=login_student.__doc__, status=403) if request.method == : return render(request, , {}, help_text=login_student.__doc__) elif...
Log in student POST parameters (JSON): student: profile id of the student
356,876
def to_root(df, path, key=, mode=, store_index=True, *args, **kwargs): if mode == : mode = elif mode == : mode = else: raise ValueError(.format(mode)) from root_numpy import array2tree df_ = df.copy(deep=False) if store_index: name = df_.index.name ...
Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: string, {'w', 'a'} Mode that the file should be opened in (default: 'w') store_index: bo...
356,877
def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}): if infix_operator and not (len(pos_args)==2 and keyword_args==[]): raise Exception( ) (kwargs,_,_,_) = self._pprint_args self._pprint_args = (keyword_args + kwarg...
Method to define the positional arguments and keyword order for pretty printing.
356,878
def cli(ctx, oldversion): path = ctx.home bubble_file_name = path + config_file = path + if file_exists(bubble_file_name): pass else: with open(bubble_file_name, ) as dot_bubble: dot_bubble.write( + metadata.version) dot_bubble.write( + config_fil...
Upgrade the current bubble, should mimic init as much as possible(experimental)
356,879
def deleteItemAtIndex(self, itemIndex): if not itemIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return item = self.getItem(itemIndex, "<no item>") logger.debug("deleteItemAtIndex: removing {}".format(item)) parentIndex...
Removes the item at the itemIndex. The item's finalize method is called before removing so it can close its resources.
356,880
def match(self, fpath): for pat in self.pats: if fnmatch.fnmatch(fpath, pat): return True return False
Does `fpath` match one of our filename patterns?
356,881
def fit(self, X, y=None): subset_df = pd.read_csv(self.subset_list, header=0, index_col=0) if isinstance(self.sel_subset, int): self.sel_subset_name = subset_df.index[self.sel_subset] elif isinstance(self.sel_subset, str): self.sel_subset_name = self.sel_subset ...
Fit FeatureSetSelector for feature selection Parameters ---------- X: array-like of shape (n_samples, n_features) The training input samples. y: array-like, shape (n_samples,) The target values (integers that correspond to classes in classification, real numbers ...
356,882
def all_keys(self, uppercase_keys=False): d = {} for k in self._override.keys(): d[k.upper() if uppercase_keys else k.lower()] = {} for k in self._args.keys(): d[k.upper() if uppercase_keys else k.lower()] = {} for k in self._env.keys(): d[...
Return all keys regardless where they are set.
356,883
def delete_brand_by_id(cls, brand_id, **kwargs): kwargs[] = True if kwargs.get(): return cls._delete_brand_by_id_with_http_info(brand_id, **kwargs) else: (data) = cls._delete_brand_by_id_with_http_info(brand_id, **kwargs) return data
Delete Brand Delete an instance of Brand by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_brand_by_id(brand_id, async=True) >>> result = thread.get() :param async boo...
356,884
def update_mim_version(self, new_genes, new_panel, old_version): LOG.info() version = new_panel[] for gene in new_panel[]: gene_symbol = gene[] if gene_symbol in new_genes: gene[] = version continue ...
Set the correct version for each gene Loop over the genes in the new panel Args: new_genes(set(str)): Set with the new gene symbols new_panel(dict)
356,885
def get_player_summaries(self, steamids=None, **kwargs): if not isinstance(steamids, collections.Iterable): steamids = [steamids] base64_ids = list(map(convert_to_64_bit, filter(lambda x: x is not None, steamids))) if not in kwargs: kwargs[] = base64_ids ...
Returns a dictionary containing a player summaries :param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice that api will convert if ``32-bit`` are given :return: dictionary of player summaries, see :doc:`responses </responses>`
356,886
def save_bank(self, bank_form, *args, **kwargs): if bank_form.is_for_update(): return self.update_bank(bank_form, *args, **kwargs) else: return self.create_bank(bank_form, *args, **kwargs)
Pass through to provider BankAdminSession.update_bank
356,887
def get_feature_names(self, always_signed=True): return self.unhasher.get_feature_names( always_signed=always_signed, always_positive=self._always_positive(), )
Return feature names. This is a best-effort function which tries to reconstruct feature names based on what it has seen so far. HashingVectorizer uses a signed hash function. If always_signed is True, each term in feature names is prepended with its sign. If it is False, signs a...
356,888
def convert_to_record(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if result is not None: if isinstance(result, dict): return _record(result) return (_record(i) for i in result) return...
Wrap mongodb record to a dict record with default value None
356,889
def _flush_events(self): if self._sink is not None: for event in self._pending_events: self._sink.receive(event) self._pending_events = []
! @brief Send all pending events to event sink.
356,890
def check_args(arguments, data_frame): stripped_args = [a[0] for a in arguments] df = data_frame.df for a in arguments: if a[0] not in df.index: print("-I- ignoring invalid argument: {}".format(a[0])) print("-") condition = df[] reqd_args = df[condition...
check arguments against a command_line_dataframe. checks that: all arguments are valid all required arguments are present default values are used where needed
356,891
def _getPWMFrequency(self, device, message): result = self._getConfig(self.PWM_PARAM, device) freq, msg = self._CONFIG_PWM.get(result, (result, )) if message: result = msg else: result = freq return result
Get the PWM frequency stored on the hardware device. :Parameters: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. message : `bool` If set to `True` a text message will be returned, if s...
356,892
def finish(self): if self._has_responded: raise NSQException() self._has_responded = True self.on_finish.send(self)
Respond to nsqd that you’ve processed this message successfully (or would like to silently discard it).
356,893
def translate_opcodes(code_obj, target): target = get_py_internals(target) src_ops = code_obj.disassemble() dst_opmap = target[] dst_ops = [] op_iter = enumerate(src_ops) for i, op in op_iter: if isinstance(op, pwnypack.bytecode.Label): dst_ops.append(op) ...
Very crude inter-python version opcode translator. Raises SyntaxError when the opcode doesn't exist in the destination opmap. Used to transcribe python code objects between python versions. Arguments: code_obj(pwnypack.bytecode.CodeObject): The code object representation to translate. ...
356,894
def add_kb(self, issuer, kb): try: self.issuer_keys[issuer].append(kb) except KeyError: self.issuer_keys[issuer] = [kb]
Add a key bundle and bind it to an identifier :param issuer: Owner of the keys in the key bundle :param kb: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance
356,895
def save(unique_keys, data, table_name=): _set_table(table_name) connection = _State.connection() if isinstance(data, Mapping): data = [data] elif not isinstance(data, Iterable): raise TypeError("Data must be a single mapping or an iterable " "of ...
Save the given data to the table specified by `table_name` (which defaults to 'swdata'). The data must be a mapping or an iterable of mappings. Unique keys is a list of keys that exist for all rows and for which a unique index will be created.
356,896
def best_kmers(dt, response, sequence, k=6, consider_shift=True, n_cores=1, seq_align="start", trim_seq_len=None): y = dt[response] seq = dt[sequence] if trim_seq_len is not None: seq = pad_sequences(seq, align=seq_align, maxlen=trim_seq_len) seq = [s.replace("N", "") fo...
Find best k-mers for CONCISE initialization. Args: dt (pd.DataFrame): Table containing response variable and sequence. response (str): Name of the column used as the reponse variable. sequence (str): Name of the column storing the DNA/RNA sequences. k (int): Desired k-mer length. ...
356,897
def get_json(self, path, **kwargs): url = self._make_url(path) headers = kwargs.setdefault(, {}) headers.update({: }) response = self._make_request("GET", url, **kwargs) return json.loads(response.text)
Perform an HTTP GET request with JSON headers of the specified path against Device Cloud Make an HTTP GET request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library `request method <htt...
356,898
def import_modules(names, src, dst): for name in names: module = importlib.import_module(src + + name) setattr(sys.modules[dst], name, module)
Import modules in package.
356,899
def synteny(args): from jcvi.assembly.geneticmap import bed as geneticmap_bed from jcvi.apps.align import blat from jcvi.formats.blast import bed as blast_bed, best p = OptionParser(synteny.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) ...
%prog synteny mstmap.out novo.final.fasta reference.fasta Plot MSTmap against reference genome.