Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
9,900
def _call_pyfftw(self, x, out, **kwargs): kwargs.pop(, None) kwargs.pop(, None) kwargs.pop(, None) if self.halfcomplex: preproc = self._preprocess(x) assert is_real_dtype(preproc.dtype) else: ...
Implement ``self(x[, out, **kwargs])`` for pyfftw back-end. Parameters ---------- x : `numpy.ndarray` Array representing the function to be transformed out : `numpy.ndarray` Array to which the output is written planning_effort : {'estimate', 'measure', 'p...
9,901
def get_full_pipe(sol, base=()): pipe, i = DspPipe(), len(base) for p in sol._pipe: n, s = p[-1] d = s.dsp p = {: p} if n in s._errors: p[] = s._errors[n] node_id = s.full_name + (n,) assert base == node_id[:i], % (node_id[:i], base) ...
Returns the full pipe of a dispatch run. :param sol: A Solution object. :type sol: schedula.utils.Solution :param base: Base node id. :type base: tuple[str] :return: Full pipe of a dispatch run. :rtype: DspPipe
9,902
def get_upstream_paths(self, port): base_paths = { : self.REPLAY_API % port, : self.CDX_API % port, } if self.recorder_path: base_paths[] = self.recorder_path return base_paths
Retrieve a dictionary containing the full URLs of the upstream apps :param int port: The port used by the replay and cdx servers :return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled]) :rtype: dict[str, str]
9,903
def _cromwell_debug(metadata): def get_failed_calls(cur, key=None): if key is None: key = [] out = [] if isinstance(cur, dict) and "failures" in cur and "callRoot" in cur: out.append((key, cur)) elif isinstance(cur, dict): for k, v in cur.items(): ...
Format Cromwell failures to make debugging easier.
9,904
def credentials_loader(self, in_credentials: str = "client_secrets.json") -> dict: accepted_extensions = (".ini", ".json") if not path.isfile(in_credentials): raise IOError("Credentials file doesninstalled' auth_settings = in_auth.get("installed") ...
Loads API credentials from a file, JSON or INI. :param str in_credentials: path to the credentials file. By default, look for a client_secrets.json file.
9,905
def addItem(self, item, message=None): if message is None: message = % item.path try: v = Version.new(repo=self) v.addItem(item) v.save(message) except VersionError, e: raise RepoError(e)
add a new Item class object
9,906
def elixir_decode(elixir_filename): import re, pyfits parts_RE=re.compile(r) dataset_name = parts_RE.findall(elixir_filename) if not dataset_name or len(dataset_name)<5 : raise ValueError( % elixir_filename ) comments={: , : , ...
Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits
9,907
def wrap(self, stream, name=None, filename=None): for lineno, token, value in stream: if token in ignored_tokens: continue elif token == : token = elif token == : token = elif token in (, ): ...
This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value.
9,908
def print_http_nfc_lease_info(info): print \ .format(info) device_number = 1 if info.deviceUrl: for device_url in info.deviceUrl: print \ \ \ \ \ .format(device_url, ...
Prints information about the lease, such as the entity covered by the lease, and HTTP URLs for up/downloading file backings. :param info: :type info: vim.HttpNfcLease.Info :return:
9,909
def _brace_key(self, key): if isinstance(key, six.integer_types): t = str key = t(key) else: t = type(key) return t(u) + key + t(u)
key: 'x' -> '{x}'
9,910
def clean(cls, path): for pth in os.listdir(path): pth = os.path.abspath(os.path.join(path, pth)) if os.path.isdir(pth): logger.debug( % pth) shutil.rmtree(pth) else: logger.debug( % pth) os.remove(pth)
Clean up all the files in a provided path
9,911
def _apply_sub_frames(cls, documents, subs): for path, projection in subs.items(): child_document = document keys = cls._path_to_keys(path) for key in keys[:-1]: child_document = child_document[key] ...
Convert embedded documents to sub-frames for one or more documents
9,912
def _getKeyForUrl(url, existing=None): (keyName, bucketName)) elif existing is None: pass else: assert False if key is None: key = bucket.new_key(keyName) except: ...
Extracts a key from a given s3:// URL. On return, but not on exceptions, this method leaks an S3Connection object. The caller is responsible to close that by calling key.bucket.connection.close(). :param bool existing: If True, key is expected to exist. If False, key is expected not to ...
9,913
def get_client_address(self): return "amqps://{}:{}@{}.{}:5671/{}".format( urllib.parse.quote_plus(self.policy), urllib.parse.quote_plus(self.sas_key), self.sb_name, self.namespace_suffix, self.eh_name)
Returns an auth token dictionary for making calls to eventhub REST API. :rtype: str
9,914
def sql_program_name_func(command): args = command.split() for prog in args: if not in prog: return prog return args[0]
Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str
9,915
def get_replacement_method(method_to_patch, side_effect=UNDEFINED, rvalue=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, context=UNDEFINED, subsequent_rvalue=UNDEFINED): def patch_with(*args, **kwargs): if side_effect != UNDEFINED: return execute_side_effect(side_effect, args, kwargs) ...
Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implements caching in place of the method_to_patch :param function method_to_patch: A reference to the method that will be patched. :param mixed side_effect: The side effect to exec...
9,916
def get_port(self, id_or_uri, port_id_or_uri): uri = self._client.build_subresource_uri(id_or_uri, port_id_or_uri, "ports") return self._client.get(uri)
Gets an interconnect port. Args: id_or_uri: Can be either the interconnect id or uri. port_id_or_uri: The interconnect port id or uri. Returns: dict: The interconnect port.
9,917
def list(): infos = manager.get_all() if not infos: print("No known TensorBoard instances running.") return print("Known TensorBoard instances:") for info in infos: template = " - port {port}: {data_source} (started {delta} ago; pid {pid})" print(template.format( port=info.port, ...
Print a listing of known running TensorBoard instances. TensorBoard instances that were killed uncleanly (e.g., with SIGKILL or SIGQUIT) may appear in this list even if they are no longer running. Conversely, this list may be missing some entries if your operating system's temporary directory has been cleared ...
9,918
def make_config_file(guided=False): config_path = _make_config_location(guided=guided) config_data = make_config_data(guided=guided) write_config_file(config_path, config_data)
Options: --auto, --guided, --manual Places for the file: --inplace, --user
9,919
def draw(self): self.screen.clear() x, y = 1, 1 max_y, max_x = self.screen.getmaxyx() max_rows = max_y - y lines, current_line = self.get_lines() scroll_top = getattr(self, , 0) if current_line <= scroll_top: scroll_top = 0 ...
draw the curses ui on the screen, handle scroll if needed
9,920
def saveJSON(g, data, backup=False): if not backup: fname = filedialog.asksaveasfilename( defaultextension=, filetypes=[(, ), ], initialdir=g.cpars[] ) else: fname = os.path.join(os.path.expanduser(), ) if not fname: g.clog.warn()...
Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename
9,921
def addvFunc(self,solution,EndOfPrdvP): self.makeEndOfPrdvFunc(EndOfPrdvP) solution.vFunc = self.makevFunc(solution) return solution
Creates the value function for this period and adds it to the solution. Parameters ---------- solution : ConsumerSolution The solution to this single period problem, likely including the consumption function, marginal value function, etc. EndOfPrdvP : np.array ...
9,922
def build_kal_scan_channel_string(kal_bin, channel, args): option_mapping = {"gain": "-g", "device": "-d", "error": "-e"} base_string = "%s -v -c %s" % (kal_bin, channel) base_string += options_string_builder(option_mapping, args) return(base_string)
Return string for CLI invocation of kal, for channel scan.
9,923
def previous_song(self): if self.current_song is None: return self._get_good_song(base=-1, direction=-1) if self.playback_mode == PlaybackMode.random: previous_song = self._get_good_song(direction=-1) else: current_index = self._songs.index(self.curr...
previous song for player to play NOTE: not the last played song
9,924
def finalize(self): self.global_scope.close() name_generator = NameGenerator(skip=self.reserved_keywords) self.global_scope.build_remap_symbols( name_generator, children_only=not self.obfuscate_globals, )
Finalize the run - build the name generator and use it to build the remap symbol tables.
9,925
def _run_get_data_background(macs, queue, shared_data, bt_device): run_flag = RunFlag() def add_data(data): if not shared_data[]: run_flag.running = False data[1][] = datetime.utcnow().isoformat() queue.put(data) RuuviTagSensor.get_datas(add_data, macs, run_flag,...
Background process function for RuuviTag Sensors
9,926
def get_arctic_lib(connection_string, **kwargs): m = CONNECTION_STR.match(connection_string) if not m: raise ValueError("connection string incorrectly formed: %s" % connection_string) library, host = m.group(1), m.group(2) return _get_arctic(host, **kwargs)[library]
Returns a mongo library for the given connection string Parameters --------- connection_string: `str` Format must be one of the following: library@trading for known mongo servers library@hostname:port Returns: -------- Arctic library
9,927
def filter(self, **kwargs): from sqlalchemy import or_ Statement = self.get_model() Tag = self.get_model() session = self.Session() page_size = kwargs.pop(, 1000) order_by = kwargs.pop(, None) tags = kwargs.pop(, []) exclude_text = kwargs.pop(,...
Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned.
9,928
def print_chain_summary(self, stream=sys.stdout, indent=""): stream.write("%sTotal files : %i\n" % (indent, len(self.file_dict))) stream.write("%s Input files : %i\n" % (indent, len(self.chain_input_files))) stream.write("%s Output fil...
Print a summary of the files in this file dict. This version uses chain_input_files and chain_output_files to count the input and output files.
9,929
def id_source(source, full=False): if source not in source_ids: return if full: return source_ids[source][1] else: return source_ids[source][0]
Returns the name of a website-scrapping function.
9,930
def check_path(path, create=False): if not os.path.exists(path): if create: os.makedirs(path) return os.path.exists(path) else: return False return True
Check for a path on filesystem :param path: str - path name :param create: bool - create if do not exist :return: bool - path exists
9,931
def create_page(self, **extra_kwargs): with translation.override(self.default_language_code): self.default_lang_name = dict( self.languages)[self.default_language_code] self.slug = self.get_slug(self.default_language_code, ...
Create page (and page title) in default language extra_kwargs will be pass to cms.api.create_page() e.g.: extra_kwargs={ "soft_root": True, "reverse_id": my_reverse_id, }
9,932
def rm_watch(self, wd, rec=False, quiet=True): lwd = self.__format_param(wd) if rec: lwd = self.__get_sub_rec(lwd) ret_ = {} for awd in lwd: wd_ = self._inotify_wrapper.inotify_rm_watch(self._fd, awd) if wd_ < 0: ...
Removes watch(s). @param wd: Watch Descriptor of the file or directory to unwatch. Also accepts a list of WDs. @type wd: int or list of int. @param rec: Recursively removes watches on every already watched subdirectories and subfiles. @type rec: bo...
9,933
def updateData(self, axeskey, x, y): if axeskey == : self.stimPlot.setData(x,y) ranges = self.viewRange() self.rangeChange(self, ranges) if axeskey == : self.clearTraces() if self._traceUnit == : y = y * se...
Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response' :type axeskey: str :param x: index values associated with y to plot :type x: numpy.ndarray :param y: values to plot at x :type y: numpy.ndarray
9,934
def _get_timestamp_tuple(ts): if isinstance(ts, datetime.datetime): return Timestamp.from_datetime(ts).tuple() elif isinstance(ts, Timestamp): return ts raise TypeError()
Internal method to get a timestamp tuple from a value. Handles input being a datetime or a Timestamp.
9,935
def _process_uniprot_ids(self, limit=None): LOG.info("Processing UniProt IDs") if self.test_mode: graph = self.testgraph else: graph = self.graph line_counter = 0 model = Model(graph) geno = Genotype(graph) raw = .join((self.rawdi...
This method processes the mappings from ZFIN gene IDs to UniProtKB IDs. Triples created: <zfin_gene_id> a class <zfin_gene_id> rdfs:label gene_symbol <uniprot_id> is an Individual <uniprot_id> has type <polypeptide> <zfin_gene_id> has_gene_product <uniprot_id> ...
9,936
def get_net(req): try: nxt, prev = map( int, (req.GET.get(, 0), req.GET.get(, 0)) ) net = nxt - prev except Exception: net = 0 return net
Get the net of any 'next' and 'prev' querystrings.
9,937
def calcAspectRatioFromCorners(corners, in_plane=False): q = corners l0 = [q[0, 0], q[0, 1], q[1, 0], q[1, 1]] l1 = [q[0, 0], q[0, 1], q[-1, 0], q[-1, 1]] l2 = [q[2, 0], q[2, 1], q[3, 0], q[3, 1]] l3 = [q[2, 0], q[2, 1], q[1, 0], q[1, 1]] a1 = line.length(l0) / line.length(l1) ...
simple and better alg. than below in_plane -> whether object has no tilt, but only rotation and translation
9,938
def validate_sceneInfo(self): if self.sceneInfo.prefix not in self.__satellitesMap: logger.error( % (self.sceneInfo.name, self.sceneInfo.prefix)) raise WrongSceneNameError( % (self.sceneInfo.name, self.sceneInfo.prefix))
Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong.
9,939
def in_scope(self, exclude_scopes=None, include_scopes=None): if include_scopes is not None and not isinstance(include_scopes, Scope): raise ValueError(.format( type(include_scopes) )) if exclude_scopes is not None and not isinstance(exclude_scopes, Scope): raise ValueError(.forma...
Whether this scope should be included by the given inclusion and exclusion rules. :param Scope exclude_scopes: An optional Scope containing scope names to exclude. None (the default value) indicates that no filtering should be done based on exclude_scopes. :param Scope include_scopes: An optional Scope c...
9,940
def current(self): if not has_request_context(): return self.no_req_ctx_user_stack.top user_stack = getattr(_request_ctx_stack.top, , None) if user_stack and user_stack.top: return user_stack.top return _get_user()
Returns the current user
9,941
def active_thresholds_value_maps(keywords, exposure_key): if in keywords: if keywords[] == layer_mode_continuous[]: return keywords[] else: return keywords[] if keywords[] == layer_mode_continuous[]: classifications = keywords[].get(exposure_key) else: ...
Helper to retrieve active value maps or thresholds for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: Active thresholds or value maps. :rtype: dict
9,942
def extract_audioclip_samples(d) -> dict: ret = {} if not d.data: return {} try: from fsb5 import FSB5 except ImportError as e: raise RuntimeError("python-fsb5 is required to extract AudioClip") af = FSB5(d.data) for i, sample in enumerate(af.samples): if i > 0: filename = "%s-%i.%s" % (d.name,...
Extract all the sample data from an AudioClip and convert it from FSB5 if needed.
9,943
def iter_variants(self): for idx, row in self.bim.iterrows(): yield Variant( row.name, CHROM_INT_TO_STR[row.chrom], row.pos, [row.a1, row.a2] )
Iterate over marker information.
9,944
def add_contig_to_header(line, ref_file): if line.startswith(" out = [line] for region in ref.file_contigs(ref_file): out.append(" return "\n".join(out) else: return line
Streaming target to add contigs to a VCF file header.
9,945
def ecg_hrv(rpeaks=None, rri=None, sampling_rate=1000, hrv_features=["time", "frequency", "nonlinear"]): if rpeaks is None and rri is None: raise ValueError("Either rpeaks or RRIs needs to be given.") if rpeaks is not None and rri is not None: raise ValueError("Either rpeaks or RRIs s...
Computes the Heart-Rate Variability (HRV). Shamelessly stolen from the `hrv <https://github.com/rhenanbartels/hrv/blob/develop/hrv>`_ package by Rhenan Bartels. All credits go to him. Parameters ---------- rpeaks : list or ndarray R-peak location indices. rri: list or ndarray RR interva...
9,946
def get_authority_key_identifier(self): try: ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) except x509.ExtensionNotFound: return x509.AuthorityKeyIdentifier.from_issuer_public_key(self.x509.public_key()) else: return x...
Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.
9,947
def _get_exc_info(self, exc_tuple=None): if exc_tuple is None: etype, value, tb = sys.exc_info() else: etype, value, tb = exc_tuple if etype is None: if hasattr(sys, ): etype, value, tb = sys.last_type, sys.last_value, \ ...
get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information
9,948
def get_schema(repo, content_type): try: with open( os.path.join(repo.working_dir, , % (content_type,)), ) as fp: data = fp.read() return avro.schema.parse(data) except IOError: raise NotFou...
Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict
9,949
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): return self.client.api.send_location(self.room_id, geo_uri, name, thumb_url, thumb_info)
Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of th...
9,950
def getprice(self): target = self.bot.get("target", {}) if target.get("reference") == "feed": assert self.market == self.market.core_quote_market(), "Wrong market for reference!" ticker = self.market.ticker() price = ticker.get("quoteSettlement_price") ...
Here we obtain the price for the quote and make sure it has a feed price
9,951
def iter_instances(self): for wrkey in set(self.keys()): obj = self.get(wrkey) if obj is None: continue yield wrkey, obj
Iterate over the stored objects Yields: wrkey: The two-tuple key used to store the object obj: The instance or function object
9,952
def get_csv_from_metadata(dsn, d): logger_csvs.info("enter get_csv_from_metadata") _csvs = OrderedDict() _d = copy.deepcopy(d) try: if "paleoData" in _d: _d["paleoData"], _csvs = _get_csv_from_section(_d["paleoData"], "{}.paleo".format(dsn), _csvs) if "chr...
Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files. :param str dsn: Dataset name :param dict d: Metadata :return dict _csvs: Csv
9,953
def barycentric_to_cartesian(tri, bc): bc = np.asarray(bc) tri = np.asarray(tri) if len(bc.shape) == 1: return barycentric_to_cartesian(np.transpose(np.asarray([tri]), (1,2,0)), np.asarray([bc]).T)[:,0] bc = bc if bc.shape[0] == 2 else bc.T if bc....
barycentric_to_cartesian(tri, bc) yields the d x n coordinate matrix of the given barycentric coordinate matrix (also d x n) bc interpolated in the n triangles given in the array tri. See also cartesian_to_barycentric. If tri and bc represent one triangle and coordinate, then just the coordinate and not a m...
9,954
def update_thread(cls, session, conversation, thread): data = thread.to_api() data[] = True return cls( % ( conversation.id, thread.id, ), data=data, request_type=RequestPaginator.PUT, singleton=True, ...
Update a thread. Args: session (requests.sessions.Session): Authenticated session. conversation (helpscout.models.Conversation): The conversation that the thread belongs to. thread (helpscout.models.Thread): The thread to be updated. Returns: ...
9,955
def format_all(self): res = + str(self.name) + res += + str(self.parent) + res += self._get_all_children() res += self._get_links() return res
return a trace of parents and children of the obect
9,956
def rtype_to_model(rtype): models = goldman.config.MODELS for model in models: if rtype.lower() == model.RTYPE.lower(): return model raise ValueError( % rtype)
Return a model class object given a string resource type :param rtype: string resource type :return: model class object :raise: ValueError
9,957
def get_repo(name, basedir=None, **kwargs): *** repos = list_repos(basedir) repofile = for repo in repos: if repo == name: repofile = repos[repo][] if repofile: filerepos = _parse_repo_file(repofile)[1] return filerepos[name] return {}
Display a repo from <basedir> (default basedir: all dirs in ``reposdir`` yum option). CLI Examples: .. code-block:: bash salt '*' pkg.get_repo myrepo salt '*' pkg.get_repo myrepo basedir=/path/to/dir salt '*' pkg.get_repo myrepo basedir=/path/to/dir,/path/to/another/dir
9,958
def _set_collection(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=collection.collection, is_container=, presence=False, yang_name="collection", rest_name="collection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register...
Setter method for collection, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection (container) If this variable is read-only (config: false) in the source YANG file, then _set_collection is considered as a private method. Backends looking to populate this variable should do so via c...
9,959
def save_cloud_optimized(self, dest_url, resampling=Resampling.gauss, blocksize=256, overview_blocksize=256, creation_options=None): src = self with tempfile.NamedTemporaryFile(suffix=) as tf: src.save(tf.name, overviews=False) convert_to...
Save as Cloud Optimized GeoTiff object to a new file. :param dest_url: path to the new raster :param resampling: which Resampling to use on reading, default Resampling.gauss :param blocksize: the size of the blocks default 256 :param overview_blocksize: the block size of the overviews, ...
9,960
def env(): ssh = cij.env_to_dict(PREFIX, REQUIRED) if "KEY" in ssh: ssh["KEY"] = cij.util.expand_path(ssh["KEY"]) if cij.ENV.get("SSH_PORT") is None: cij.ENV["SSH_PORT"] = "22" cij.warn("cij.ssh.env: SSH_PORT was not set, assigned: %r" % ( cij.ENV.get("SSH_PORT") ...
Verify SSH variables and construct exported variables
9,961
def cli(self, commands): cli_output = dict() if type(commands) is not list: raise TypeError() for command in commands: output = self._send_command(command) if in output: raise ValueError(.format(command)) cli_output.setde...
Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 'show clock': u'*22:01:51.165 UTC Thu Feb 18 20...
9,962
def run_review(*args): email_cnt = idx = 1 email_cnt = email_cnt + email_cnt, idx = __get_post_review(email_cnt, idx) email_cnt, idx = __get_page_review(email_cnt, idx) email_cnt, idx = __get_wiki_review(email_cnt, idx) diff_str = __get_diff_recent() if len(diff_s...
Get the difference of recents modification, and send the Email. For: wiki, page, and post.
9,963
def update_marker(self, iid, **kwargs): if iid not in self._markers: raise ValueError("Unknown iid passed as argument: {}".format(iid)) self.check_kwargs(kwargs) marker = self._markers[iid] marker.update(kwargs) self.delete_marker(iid) return self.cre...
Change the options for a certain marker and redraw the marker :param iid: identifier of the marker to change :type iid: str :param kwargs: Dictionary of options to update :type kwargs: dict :raises: ValueError
9,964
def failback_from_replicant(self, volume_id, replicant_id): return self.client.call(, , replicant_id, id=volume_id)
Failback from a volume replicant. :param integer volume_id: The id of the volume :param integer replicant_id: ID of replicant to failback from :return: Returns whether failback was successful or not
9,965
def make_error_response(self, cond): if self.stanza_type == "error": raise ValueError("Errors may not be generated in response" " to errors") stanza = Presence(stanza_type = "error", from_jid = self.from_jid, ...
Create error response for the any non-error presence stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :Types: - `cond`: `unicode` :return: new presence stanza. :returntype: `Presence`
9,966
def get(self, key: Text, count: Optional[int]=None, formatter: Formatter=None, locale: Text=None, params: Optional[Dict[Text, Any]]=None, flags: Optional[Flags]=None) -> List[Text]: if params is None: params = {} ...
Get the appropriate translation given the specified parameters. :param key: Translation key :param count: Count for plurals :param formatter: Optional string formatter to use :param locale: Prefered locale to get the string from :param params: Params to be substituted :p...
9,967
def get_entry_by_material_id(self, material_id, compatible_only=True, inc_structure=None, property_data=None, conventional_unit_cell=False): data = self.get_entries(material_id, compatible_only=compatible_only, ...
Get a ComputedEntry corresponding to a material_id. Args: material_id (str): Materials Project material_id (a string, e.g., mp-1234). compatible_only (bool): Whether to return only "compatible" entries. Compatible entries are entries that have been ...
9,968
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> : "Create a vocabulary from a set of `tokens`." freq = Counter(p for o in tokens for p in o) itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq] for o in reversed(defaults.text_spec_tok): if o in it...
Create a vocabulary from a set of `tokens`.
9,969
def get_mapping_from_db3_file( db_path ): import sqlite3 conn = sqlite3.connect(db_path) results = conn.cursor().execute() rosetta_residue_ids = [] mapping = {} for r in results: mapping["%s%s%s" % (r[0], str(r[1]).rjust(4), r[2])] = { : r[4], : r[5], : r[6]} roset...
Does the work of reading the Rosetta SQLite3 .db3 file to retrieve the mapping
9,970
def get_version(module): init_py = open(.format(module)).read() return re.search("__version__ = [\"]+)['\"]", init_py).group(1)
Return package version as listed in `__version__`.
9,971
def find_movers(choosers, rates, rate_column): logger.debug() relocation_rates = pd.Series( np.zeros(len(choosers)), index=choosers.index) for _, row in rates.iterrows(): indexes = util.filter_table(choosers, row, ignore={rate_column}).index relocation_rates.loc[indexes] = row[...
Returns an array of the indexes of the `choosers` that are slated to move. Parameters ---------- choosers : pandas.DataFrame Table of agents from which to find movers. rates : pandas.DataFrame Table of relocation rates. Index is unused. Other columns describe filters on the...
9,972
def render_mail(self, template_prefix, email, context): subject = render_to_string(.format(template_prefix), context) subject = " ".join(subject.splitlines()).strip() subject = self.format_email_subject(subject) bodies = {} fo...
Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation"
9,973
def upload_all_books(book_id_start, book_id_end, rdf_library=None): logger.info( "starting a gitberg mass upload: {0} -> {1}".format( book_id_start, book_id_end ) ) for book_id in range(int(book_id_start), int(book_id_end) + 1): cache = {} errors = 0 ...
Uses the fetch, make, push subcommands to mirror Project Gutenberg to a github3 api
9,974
def _restore_replace(self): if PyFunceble.path.isdir(self.base + ".git"): if "PyFunceble" not in Command("git remote show origin").execute(): return True return False retu...
Check if we need to replace ".gitignore" to ".keep". :return: The replacement status. :rtype: bool
9,975
def getattr(self, name, default: Any = _missing): return deep_getattr(self.clsdict, self.bases, name, default)
Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])``
9,976
def _fetch_stock_data(self, stock_list): pool = multiprocessing.pool.ThreadPool(len(stock_list)) try: res = pool.map(self.get_stocks_by_range, stock_list) finally: pool.close() return [d for d in res if d is not None]
获取股票信息
9,977
def Earth(pos=(0, 0, 0), r=1, lw=1): import os tss = vtk.vtkTexturedSphereSource() tss.SetRadius(r) tss.SetThetaResolution(72) tss.SetPhiResolution(36) earthMapper = vtk.vtkPolyDataMapper() earthMapper.SetInputConnection(tss.GetOutputPort()) earthActor = Actor(c="w") earthActor...
Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_
9,978
def _check_lock_permission( self, url, lock_type, lock_scope, lock_depth, token_list, principal ): assert lock_type == "write" assert lock_scope in ("shared", "exclusive") assert lock_depth in ("0", "infinity") _logger.debug( "checkLockPermission({}, {},...
Check, if <principal> can lock <url>, otherwise raise an error. If locking <url> would create a conflict, DAVError(HTTP_LOCKED) is raised. An embedded DAVErrorCondition contains the conflicting resource. @see http://www.webdav.org/specs/rfc4918.html#lock-model - Parent locks WILL NOT ...
9,979
def client_list(self, *args): if len(self._clients) == 0: self.log() else: self.log(self._clients, pretty=True)
Display a list of connected clients
9,980
def certify_enum(value, kind=None, required=True): if certify_required( value=value, required=required, ): return if not isinstance(value, kind): raise CertifierTypeError( message="expected {expected!r}, but value is of type {actual!r}".format( ...
Certifier for enum. :param value: The value to be certified. :param kind: The enum type that value should be an instance of. :param bool required: Whether the value can be `None`. Defaults to True. :raises CertifierTypeError: The type is invalid
9,981
def is_shortcut_in_use(self, shortcut): for path, actionName, action in foundations.walkers.dictionaries_walker(self.__categories): if action.shortcut() == QKeySequence(shortcut): return True return False
Returns if given action shortcut is in use. :param name: Action shortcut. :type name: unicode :return: Is shortcut in use. :rtype: bool
9,982
def line_spacing_rule(self): pPr = self._element.pPr if pPr is None: return None return self._line_spacing_rule( pPr.spacing_line, pPr.spacing_lineRule )
A member of the :ref:`WdLineSpacing` enumeration indicating how the value of :attr:`line_spacing` should be interpreted. Assigning any of the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or :attr:`ONE_POINT_FIVE` will cause the value of :attr:`line_spacing` to be updated ...
9,983
def dequeue(self, k): if self.j + k <= self.M: out = self.A[self.j:(self.j + k)] self.j += k elif k <= self.M: out = np.empty(k, ) nextra = self.j + k - self.M out[:(k - nextra)] = self.A[self.j:] self.enqueue() ...
Outputs *k* draws from the multinomial distribution.
9,984
def export(self, exclude=[]): fields = ( (key, self.get_field(key)) for key in self.schema if not key.startswith("_") and key not in exclude ) doc = {name: field.export() for name, field in fields} return doc
returns a dictionary representation of the document
9,985
def wait_for(self, pids=[], status_list=process_result_statuses): simple_shell_commandTest simple shell command servicefailureerror results={} pids = self._get_pids(pids) for pid in pids: while(True): try: stat = self._call_rest_api(, +pid+...
wait_for(self, pids=[], status_list=process_result_statuses) Waits for a process to finish :Parameters: * *pids* (`list`) -- list of processes waiting to be finished * *status_list* (`list`) -- optional - List of statuses to wait for processes to finish with :Example: ...
9,986
def _group_dict_set(iterator): d = defaultdict(set) for key, value in iterator: d[key].add(value) return dict(d)
Make a dict that accumulates the values for each key in an iterator of doubles. :param iter[tuple[A,B]] iterator: An iterator :rtype: dict[A,set[B]]
9,987
def profile(self, name): self.selected_profile = self.profiles.get(name) return self.profiles.get(name)
Return a specific profile.
9,988
def set_icon_data(self, base64_data, mimetype="image/png", rel="icon"): self.add_child("favicon", %(rel, base64_data, mimetype))
Allows to define an icon for the App Args: base64_data (str): base64 encoded image data (ie. "data:image/x-icon;base64,AAABAAEAEBA....") mimetype (str): mimetype of the image ("image/png" or "image/x-icon"...) rel (str): leave it unchanged (standard ...
9,989
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]: rlines: List[str] = [] slot = self.schema.slots[slotname] if slot.alias: slotname = slot.alias slotname = self.python_name_for(slotname) range_type_name = self.range_type_name(slot,...
Generate python post init rules for slot in class
9,990
def indent(self, space=4): if not isinstance(space,int): raise TypeError("space must be an int") if space < 0: raise ValueError("space must be a non-negative integer") space = *space; o = []; l = 0 for c in self.newick(): if c == : ...
Return an indented Newick string, just like ``nw_indent`` in Newick Utilities Args: ``space`` (``int``): The number of spaces a tab should equal Returns: ``str``: An indented Newick string
9,991
def minutes_from_utc(self): offset = 0 if self.__datetime is not None and \ self.__datetime.utcoffset() is not None: offset = self.__datetime.utcoffset().seconds / 60 if self.__datetime.utcoffset().days == -1: offset = -((60 * 24) - offset...
The timezone offset of this point in time object as +/- minutes from UTC. A positive value of the timezone offset indicates minutes east of UTC, and a negative value indicates minutes west of UTC. 0, if this object represents a time interval.
9,992
def handle_args_and_set_context(args): parser = argparse.ArgumentParser() parser.add_argument("env", help="environment") parser.add_argument("path_to_template", help="path to the config template to process") parser.add_argument("--no_params", help="disable loading values from params file", action="store_true...
Args: args: the command line args, probably passed from main() as sys.argv[1:] Returns: a populated Context object based on CLI args
9,993
def console_load_apf(con: tcod.console.Console, filename: str) -> bool: return bool( lib.TCOD_console_load_apf(_console(con), filename.encode("utf-8")) )
Update a console from an ASCII Paint `.apf` file.
9,994
def to_bytes(self): raw = b if not self._options: return raw for icmpv6popt in self._options: raw += icmpv6popt.to_bytes() return raw
Takes a list of ICMPv6Option objects and returns a packed byte string of options, appropriately padded if necessary.
9,995
def _generateModel0(numCategories): secondOrder[key] = probs return (initProb, firstOrder, secondOrder, 3)
Generate the initial, first order, and second order transition probabilities for 'model0'. For this model, we generate the following set of sequences: 1-2-3 (4X) 1-2-4 (1X) 5-2-3 (1X) 5-2-4 (4X) Parameters: ---------------------------------------------------------------------- numCate...
9,996
def adict(*classes): a = True for c in classes: if isclass(c) and _infer_dict(c): t = _dict_classes.get(c.__module__, ()) if c.__name__ not in t: _dict_classes[c.__module__] = t + (c.__name__,) else: a = False r...
Install one or more classes to be handled as dict.
9,997
def has_child(self, term): for parent in self.children: if parent.item_id == term or parent.has_child(term): return True return False
Return True if this GO object has a child GO ID.
9,998
def open511_convert(input_doc, output_format, serialize=True, **kwargs): try: output_format_info = FORMATS[output_format] except KeyError: raise ValueError("Unrecognized output format %s" % output_format) input_doc = ensure_format(input_doc, output_format_info.input_format) resul...
Convert an Open511 document between formats. input_doc - either an lxml open511 Element or a deserialized JSON dict output_format - short string name of a valid output format, as listed above
9,999
def FindLiteral(self, pattern, data): pattern = utils.Xor(pattern, self.xor_in_key) offset = 0 while 1: offset = data.find(pattern, offset) if offset < 0: break yield (offset, offset + len(pattern)) offset += 1
Search the data for a hit.