Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,900
def set_xtick_labels(self, row, column, labels): subplot = self.get_subplot_at(row, column) subplot.set_xtick_labels(labels)
Manually specify the x-axis tick labels. :param row,column: specify the subplot. :param labels: list of tick labels.
358,901
def branch_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 branch rate of the coverage report. If the `filename` file is given, return the branch rate of the file.
358,902
def socket_handler(name, logname, host, port): return wrap_log_handler(logging.handlers.SocketHandler(host, port))
A Bark logging handler logging output to a stream (TCP) socket. The server listening at the given 'host' and 'port' will be sent a pickled dictionary. Similar to logging.handlers.SocketHandler.
358,903
def pl_resolution(KB, alpha): "Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]" clauses = KB.clauses + conjuncts(to_cnf(~alpha)) new = set() while True: n = len(clauses) pairs = [(clauses[i], clauses[j]) for i in range(n) for j in range(i+1, n)]...
Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]
358,904
def batch( baba, ipyclient=None, ): handle = baba.data taxdicts = baba.tests mindicts = baba.params.mincov nboots = baba.params.nboots sims = 0 if isinstance(handle, types.GeneratorType): handle = list(handle) sims = 1 else: handl...
distributes jobs to the parallel client
358,905
def getsourcefile(object): filename = getfile(object) if string.lower(filename[-4:]) in [, ]: filename = filename[:-4] + for suffix, mode, kind in imp.get_suffixes(): if in mode and string.lower(filename[-len(suffix):]) == suffix: return None if os.path.ex...
Return the Python source file an object was defined in, if it exists.
358,906
def start(self): self.connections(True) binding_keys = sys.argv[1:] if not binding_keys: print(sys.stderr, .format(sys.argv[0])) sys.exit(0) for binding_key in binding_keys: self.channel.queue_bind(exchange=, ...
start the channel listener and start consuming messages
358,907
def check_order(self, order): own_order = self.order for item in order: if item not in own_order: raise ValueError(f) return order
order must be a subset of self.order
358,908
def rawsql(query, ec=None): if isinstance(query, Result): query = query.get_query() ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): engine = engine_manager[ec] dialect = engine.engine.dialect else: dialect = ec.dialect if isinstance(query, (str,...
ec could be engine name or engine instance
358,909
def update_indel(self, nucmer_snp): s an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False' new_variant = Variant(nucmer_snp) if self.var_type not in [INS, DEL] \ or self.var_type != new_variant.var_type \ or s...
Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False
358,910
def doFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP=, **params): self._preFind(WHAT, SORT, SKIP, MAX, LOP) for key in params: self._addDBParam(key, params[key]) try: return self._doAction() except FMServerError as e: if e.args[0] in [401, 8]: return []
This function will perform the command -find.
358,911
def set_name(self, name): if name is None: if self.xmlnode.hasProp("name"): self.xmlnode.unsetProp("name") return name = unicode(name) self.xmlnode.setProp("name", name.encode("utf-8"))
Set the name of the item. :Parameters: - `name`: the new name or `None`. :Types: - `name`: `unicode`
358,912
def load_extra(cls, filename): try: with open(filename, ) as configuration_file: cls.load_extra_data(configuration_file.read()) sys.stderr.write("Config successfully loaded from {0:s}\n".format( filename)) return True except IOError: return False
Loads extra JSON configuration parameters from a file on the filesystem. Args: filename: str, the filename to open. Returns: bool: True if the extra configuration parameters were read.
358,913
def default(self, obj): if obj is None: return [] elif isinstance(obj, list): return [i.as_dictionary() for i in obj] elif isinstance(obj, dict): return self._keys_to_camel_case(obj) else: return obj.as_dictionary()
Convert an object to a form ready to dump to json. :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class. :return: List of dictionaries, each representing a physi...
358,914
def get_unique_name(self, name): if name not in self._db: self._db[name] = 0 return name else: index = self._db[name] self._db[name] = index + 1 return f"{name}_{index}"
returns an available unique name Parameters ---------- name : str name to be made unique Returns ------- unique_name : str new unique name
358,915
async def unban(self, user, *, reason=None): await self._state.http.unban(user.id, self.id, reason=reason)
|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to unban. reason:...
358,916
def packed_checksum(self, data): self.field.setval(self.algo(data[self.start:self.end])) sio = BytesIO() self.field.pack(sio) return sio.getvalue()
Given the data of the entire packet return the checksum bytes
358,917
def humanize_seconds(total_seconds, frmt=, negative_frmt=None): if negative_frmt is None: negative_frmt = .format(frmt) seconds = abs(int(total_seconds)) mapping = { : seconds // 3600, : seconds % 3600 // 60, : seconds % 3600 % 6...
Given time in int(seconds), return a string representing the time. If negative_frmt is not given, a negative sign is prepended to frmt and the result is wrapped in a <span> with the "negative-time" class.
358,918
def depth_july_average_ground_temperature(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._depth_july_average_ground_tem...
Corresponds to IDD Field `depth_july_average_ground_temperature` Args: value (float): value for IDD Field `depth_july_average_ground_temperature` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missin...
358,919
def _format_text(self, title, text, color, ellide=False): template = font-family: "{font_family}"; font-size: {title_size}pt; color: {color}\ if text: template += font-family: "{font_family}"; font-size: ...
Create HTML template for calltips and tooltips. This will display title and text as separate sections and add `...` if `ellide` is True and the text is too long.
358,920
def sample(self, bqm, **kwargs): tkw = self._truncate_kwargs if self._aggregate: return self.child.sample(bqm, **kwargs).aggregate().truncate(**tkw) else: return self.child.sample(bqm, **kwargs).truncate(**tkw)
Sample from the problem provided by bqm and truncate output. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Parameters for the sampling method, specified by the child sampler. ...
358,921
def getscale(self): status, dim_name, dim_size, data_type, n_attrs = _C.SDdiminfo(self._id) _checkErr(, status, ) if data_type == 0: raise HDF4Error("no scale set on that dimension") if dim_size == 0: dim_size = self....
Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimscale()' method was called. ...
358,922
def get_all_parsers(self, strict_type_matching: bool = False) -> List[Parser]: matching = self.find_all_matching_parsers(strict=strict_type_matching)[0] if len(matching[1]) > 0: raise Exception() return matching[0] + matching[2]
Returns the list of all parsers in order of relevance. :return:
358,923
def read(self, pk=None, fail_on_no_results=False, fail_on_multiple_results=False, **kwargs): url = self.endpoint if pk: url += % pk queries = kwargs.pop(, []) self._pop_none(kwargs) for field in self.fields: ...
=====API DOCS===== Retrieve and return objects from the Ansible Tower API. :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read that object if ``pk`` is provided (not ``None``). :type pk: int :param fail_on_no_results: Flag that if se...
358,924
def _SR(cpu, insn_id, dest, op, *rest): assert insn_id in (cs.arm.ARM_INS_ASR, cs.arm.ARM_INS_LSL, cs.arm.ARM_INS_LSR) if insn_id == cs.arm.ARM_INS_ASR: if rest and rest[0].type == : srtype = cs.arm.ARM_SFT_ASR else: srtype = cs.arm.ARM_S...
Notes on Capstone behavior: - In ARM mode, _SR reg has `rest`, but _SR imm does not, its baked into `op`. - In ARM mode, `lsr r1, r2` will have a `rest[0]` - In Thumb mode, `lsr r1, r2` will have an empty `rest` - In ARM mode, something like `lsr r1, 3` will not have `rest` and op will b...
358,925
def rel_url_to_id(url): yearRegex = r playerRegex = r boxscoresRegex = r teamRegex = r coachRegex = r stadiumRegex = r refRegex = r collegeRegex = r hsRegex = r bsDateRegex = r leagueRegex = r awardRegex = r regexes = [ yearRegex, playerRegex, ...
Converts a relative URL to a unique ID. Here, 'ID' refers generally to the unique ID for a given 'type' that a given datum has. For example, 'BradTo00' is Tom Brady's player ID - this corresponds to his relative URL, '/players/B/BradTo00.htm'. Similarly, '201409070dal' refers to the boxscore of the SF ...
358,926
def nl_send_simple(sk, type_, flags, buf=None, size=0): msg = nlmsg_alloc_simple(type_, flags) if buf is not None and size: err = nlmsg_append(msg, buf, size, NLMSG_ALIGNTO) if err < 0: return err return nl_send_auto(sk, msg)
Construct and transmit a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L549 Allocates a new Netlink message based on `type_` and `flags`. If `buf` points to payload of length `size` that payload will be appended to the message. Sends out the message using `nl_send_auto()...
358,927
def config(self): config = {} if self.config_file.exists(): with open(self.config_file.as_posix(), ) as f: config = {k:self._override[k] if k in self._override else v for k, v in yaml.safe_load(f).items()} ...
Allows changing the config on the fly
358,928
def precision(classifier, testset): hit = 0 total = 0 for example in testset: if classifier.classify(example)[0] == classifier.target(example): hit += 1 total += 1 if total == 0: raise ValueError("Empty testset!") return hit / float(total)
Runs the classifier for each example in `testset` and verifies that the classification is correct using the `target`. Returns a number between 0.0 and 1.0 with the precision of classification for this test set.
358,929
def ekgc(selidx, row, element, lenout=_default_len_out): selidx = ctypes.c_int(selidx) row = ctypes.c_int(row) element = ctypes.c_int(element) lenout = ctypes.c_int(lenout) null = ctypes.c_int() found = ctypes.c_int() cdata = stypes.stringToCharP(lenout) libspice.ekgc_c(selidx, row,...
Return an element of an entry in a column of character type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgc_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row to fetch from. :type row: int :param element: Index ...
358,930
def autodiscover(path=None, plugin_prefix=): plugins = {} for importer, name, ispkg in pkgutil.iter_modules(path=path): if name.startswith(plugin_prefix): t = time.time() new_plugins = load_plugins_from_module(name) for plugin_name, plugin in new_plugins.items...
Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin. Any subclasses found will be instantiated and returned...
358,931
def splitFile(inputFileName, linePerFile, outPrefix): nbTmpFile = 1 nbLine = 0 tmpFile = None try: with open(inputFileName, "r") as inputFile: for line in inputFile: row = line.rstrip("\r\n").split(" ") nbLine += 1 if tmpFile is N...
Split a file. :param inputFileName: the name of the input file. :param linePerFile: the number of line per file (after splitting). :param outPrefix: the prefix of the output files. :type inputFileName: str :type linePerFile: int :type outPrefix: str :returns: the number of created tempora...
358,932
def read_csv(path, fieldnames=None, sniff=True, encoding=, *args, **kwargs): return list(r for r in read_csv_iter(path, fieldnames=fieldnames, sniff=sniff, encoding=encoding, *args, **kwargs))
Read CSV rows as table from a file. By default, csv.reader() will be used any output will be a list of lists. If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead. CSV sniffing (dialect detection) is enabled by default, set sniff=False to switch it off.
358,933
def path_to_str(path): try: from pathlib import Path as _Path except ImportError: class _Path: pass if isinstance(path, _Path): return str(path) return path
Convert pathlib.Path objects to str; return other objects as-is.
358,934
def _start_of_week(self): dt = self if self.day_of_week != pendulum._WEEK_STARTS_AT: dt = self.previous(pendulum._WEEK_STARTS_AT) return dt.start_of("day")
Reset the date to the first day of the week and the time to 00:00:00. :rtype: DateTime
358,935
def shap_values(self, X, **kwargs): phi = None if self.mimic_model_type == "xgboost": if not str(type(X)).endswith("xgboost.core.DMatrix'>"): X = xgboost.DMatrix(X) phi = self.trees.predict(X, pred_contribs=True) if phi is not None: ...
Estimate the SHAP values for a set of samples. Parameters ---------- X : numpy.array or pandas.DataFrame A matrix of samples (# samples x # features) on which to explain the model's output. Returns ------- For a models with a single output this returns a mat...
358,936
def get_fast_scanner(self): v0 = self.v0 v1 = self.v1 QS = (self._QS[0], v0 * self._QS[1]) return FastScanner(self._y, self.X, QS, v1)
Return :class:`.FastScanner` for association scan. Returns ------- fast-scanner : :class:`.FastScanner` Instance of a class designed to perform very fast association scan.
358,937
def p_casecontent_statement(self, p): p[0] = Case(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
casecontent_statement : casecontent_condition COLON basic_statement
358,938
def gt(self, key, value, includeMissing=False): s value is greater (>). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", ...
Return entries where the key's value is greater (>). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 1500...
358,939
def describe_connection(self): if self.device==None: return "%s [disconnected]" % (self.name) else: return "%s connected to %s %s version: %s [serial: %s]" % (self.name, self.vendor_name, self.product_name, self.version_number, self.seria...
Return string representation of the device, including the connection state
358,940
def post(request): data = request.POST or json.loads(request.body)[] key = data.get(, None) val = data.get(, None) res = Result() if key is not None and val is not None: obj, created = UserPref.objects.get_or_create(user=request.user) if created: obj.data = json.dump...
Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json
358,941
def dfs_absent(path): * cmd_return = _hadoop_cmd(, , path) match = return True if match in cmd_return else False
Check if a file or directory is absent on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_absent /some_random_file Returns True if the file is absent
358,942
def handle_update_search_space(self, data): search_space = data cs = CS.ConfigurationSpace() for var in search_space: _type = str(search_space[var]["_type"]) if _type == : cs.add_hyperparameter(CSH.CategoricalHyperparameter( va...
change json format to ConfigSpace format dict<dict> -> configspace Parameters ---------- data: JSON object search space of this experiment
358,943
def to_curve25519_private_key(self): sk = self._signing_key raw_private = nacl.bindings.crypto_sign_ed25519_sk_to_curve25519(sk) return _Curve25519_PrivateKey(raw_private)
Converts a :class:`~nacl.signing.SigningKey` to a :class:`~nacl.public.PrivateKey` :rtype: :class:`~nacl.public.PrivateKey`
358,944
def on_block_received(self, block_id): _libexec(, self.pointer, ctypes.c_char_p(block_id.encode()))
This is exposed for unit tests, and should not be called directly.
358,945
def logSE(x1, x2=-1): e = get_valid_error(x1, x2) return 10*np.log10(e**2)
10 * log10(e**2) This function accepts two series of data or directly one series with error. **Args:** * `x1` - first data series or error (1d array) **Kwargs:** * `x2` - second series (1d array) if first series was not error directly,\\ then this should be the second series ...
358,946
def votes(self, req) -> int: try: votes = len(self[req.key].propagates) except KeyError: votes = 0 return votes
Get the number of propagates for a given reqId and identifier.
358,947
def _Assign(self, t): self._fill() for target in t.nodes: self._dispatch(target) self._write(" = ") self._dispatch(t.expr) if not self._do_indent: self._write()
Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately.
358,948
def check_s3_url(self, s3url): bucket, key = S3Hook.parse_s3_url(s3url) if not self.s3_hook.check_for_bucket(bucket_name=bucket): raise AirflowException( "The input S3 Bucket {} does not exist ".format(bucket)) if key and not self.s3_hook.check_for_key(key=ke...
Check if an S3 URL exists :param s3url: S3 url :type s3url: str :rtype: bool
358,949
def add_contig_to_header_cl(ref_file, out_file): header_file = "%s-contig_header.txt" % utils.splitext_plus(out_file)[0] with open(header_file, "w") as out_handle: for region in ref.file_contigs(ref_file, {}): out_handle.write(" return ("grep -v ^
Add update ##contig lines to VCF header, required for bcftools/GATK compatibility.
358,950
def know(self, what, confidence): if confidence > self.confidence: self.best = what self.confidence = confidence return self
Know something with the given confidence, and return self for chaining. If confidence is higher than that of what we already know, replace what we already know with what you're telling us.
358,951
def output_barplot(df, figformat, path, title=None, palette=None): logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.") read_count = Plot(path=path + "NanoComp_number_of_reads." + figformat, title="Comparing number of reads") ax = sns.countplot(...
Create barplots based on number of reads and total sum of nucleotides sequenced.
358,952
def create_was_invalidated_by_relation(self, activity_id, entity_kind, entity_id): return self._create_activity_relation(activity_id, entity_kind, entity_id, ActivityRelationTypes.WAS_INVALIDATED_BY)
Create a was invalidated by relationship between an activity and a entity(file). :param activity_id: str: uuid of the activity :param entity_kind: str: kind of entity('dds-file') :param entity_id: str: uuid of the entity :return: requests.Response containing the successful result
358,953
def regex_in(pl,regex): b1c3dxab15cxx1xy2b1c3dxab15cxx1xy2 def cond_func(ele,regex): m = regex.search(ele) if(m == None): return(False) else: return(True) cond = some(pl,cond_func,regex)[] return(cond)
regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex)
358,954
def histogram(self, column=, filename=None, log10=False, **kwargs): return_dict = HS.plot_histograms(self.data, column) if filename is not None: return_dict[].savefig(filename, dpi=300) return return_dict
Plot a histogram of one data column
358,955
def draw(self): if __debug__: verbose.report(, ) self.renderer = self.get_renderer(cleared=True) RendererAgg.lock.acquire() try: self.figure.draw(self.renderer) finally: RendererAgg.lock.release()
Draw the figure using the renderer
358,956
def _generate_examples(self, file_id, extracted_dirs): filedir = os.path.join(extracted_dirs["img_align_celeba"], "img_align_celeba") img_list_path = extracted_dirs["list_eval_partition"] landmarks_path = extracted_dirs["landmarks_celeba"] attr_path = extracted_dirs["list...
Yields examples.
358,957
def wrapped_setups(self): lst = [] for group in self.all_groups: if not group.root: if group.has_after_each: lst.extend(self.tokens.wrap_after_each(group.kls_name, group.async_after_each)) if group.has_before_each: ...
Create tokens for Described.setup = noy_wrap_setup(Described, Described.setup) for setup/teardown
358,958
def get_dir(path, dest, saltenv=): src = __context__[].cache_dir( path, saltenv, cachedir=os.path.join(, __salt__.kwargs[])) src = .join(src) single = salt.client.ssh.Single( __opts__, , **__salt__.kwargs) ret = single.shell.send(src, dest...
Transfer a directory down
358,959
def rn_theory(af, b): if b==0: return pow(af,-1) elif b==-1: avar = (1.038+3*np.log(2*np.pi*0.5*af)) / (4.0*pow(np.pi,2)) mvar = 3*np.log(256.0/27.0)/(8.0*pow(np.pi,2)) return mvar/avar else: ...
R(n) ratio expected from theory for given noise type alpha = b + 2
358,960
def set_scale(self, scale): register = self.MMA8452Q_Register[] self.board.i2c_read_request(self.address, register, 1, Constants.I2C_READ | Constants.I2C_END_TX_MASK, self.data_val, Constants.CB_TYPE_DIRECT) confi...
Set the device scale register. Device must be in standby before calling this function @param scale: scale factor @return: No return value
358,961
def update_rel_to(self, klass): if isinstance(self.remote_field.to, basestring): relation = self.remote_field.to try: app_label, model_name = relation.split(".") except ValueError: app_label = klass._meta.app_label ...
If we have a string for a model, see if we know about it yet, if so use it directly otherwise take the lazy approach. This check is needed because this is called before the main M2M field contribute to class is called.
358,962
def _set_date_tuple(self, mediafile, year, month=None, day=None): if year is None: self.__delete__(mediafile) return date = [u.format(int(year))] if month: date.append(u.format(int(month))) if month and day: date.append(u.format(i...
Set the value of the field given a year, month, and day number. Each number can be an integer or None to indicate an unset component.
358,963
def messageReceived(self, message): if len(message) == 2: self.gotMessage(message[1], message[0]) else: self.gotMessage(*reversed(message[0].split(b, 1)))
Overridden from :class:`ZmqConnection` to process and unframe incoming messages. All parsed messages are passed to :meth:`gotMessage`. :param message: message data
358,964
def dict_strip(d): _d = deepcopy(d) for k, v in iteritems(d): if isinstance(v, str): _d[k] = v.strip() elif isinstance(v, dict): _d[k] = dict_strip(v) return _d
Strips whitespace from the string values of the given dictionary (recursively). Args: d: A dictionary object. Returns: A new dictionary object, whose string values' whitespace has been stripped out.
358,965
def overview(): search = Service.search() search = search.filter("term", state=) search.aggs.bucket(, , field=, order={: }, size=100) \ .metric(, , field=) response = search.execute() print_line("Port Count") print_line("---------------") for entry in response.aggregations.p...
Function to create an overview of the services. Will print a list of ports found an the number of times the port was seen.
358,966
def prettify(string): string = emojize(string, use_aliases=True) if emojize else string string = progressed(string) return string
replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ```
358,967
def cmd(send, msg, args): parser = arguments.ArgParser(args[]) parser.add_argument(, choices=[, , ], nargs=) try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return api_output = get( % args[][][]).json() commit, version = m...
Check the git revison. Syntax: {command} [check|master]
358,968
def cmd(send, *_): words = [[verb, noun, abbrev, noun, adj, abbrev, noun], [verb, adj, abbrev, noun], [verb, abbrev, noun, verb, adj, noun], [verb, noun, ingverb, adj, abbrev, noun], [adj, abbrev, noun, verb, adj, noun], [abbrev, noun, verb, adj, noun, verb, abbrev, noun], [ingverb, n...
Causes the bot to generate some jargon. Syntax: {command}
358,969
def formatSubclassOf(fmt, cls, ontology, visited): if URIRef(fmt) == URIRef(cls): return True if ontology is None: return False if fmt in visited: return False visited.add(fmt) uriRefFmt = URIRef(fmt) for s, p, o in ontology.triples((uriRefFmt, RDFS.subCla...
Determine if `fmt` is a subclass of `cls`.
358,970
def get_document( self, collection_id, ref=None, mimetype="application/tei+xml, application/xml"): parameters = { "id": collection_id } _parse_ref_parameters(parameters, ref) return self.call( "documents", parameters, ...
Make a navigation request on the DTS API :param collection_id: Id of the collection :param ref: If ref is a tuple, it is treated as a range. String or int are treated as single ref :param mimetype: Media type to request :return: Response :rtype: requests.Response
358,971
def createissue(accountable, options): issue = accountable.issue_create(options) headers = sorted([, , ]) rows = [headers, [itemgetter(header)(issue) for header in headers]] print_table(SingleTable(rows))
Create new issue.
358,972
def get_tags_of_letter_per_page(self, letter_id, per_page=1000, page=1): return self._get_resource_per_page( resource=LETTER_TAGS, per_page=per_page, page=page, params={: letter_id}, )
Get tags of letter per page :param letter_id: the letter id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
358,973
def rgb2hex(rgb, force_long=False): hx = .join(["%02x" % int(c * 255 + 0.5 - FLOAT_ERROR) for c in rgb]) if not force_long and hx[0::2] == hx[1::2]: hx = .join(hx[0::2]) return "
Transform RGB tuple to hex RGB representation :param rgb: RGB 3-uple of float between 0 and 1 :rtype: 3 hex char or 6 hex char string representation Usage ----- >>> from colour import rgb2hex >>> rgb2hex((0.0,1.0,0.0)) '#0f0' Rounding try to be as natural as possible: >>> rgb2h...
358,974
def get_projects(): conn, c = open_data_base_connection() try: c.execute() project_names = np.array(c.fetchall()).squeeze(axis=1) project_names = convert_list_to_dict(project_names) return project_names except sqlite3.OperationalError: logging.info("{} not found"...
Returns a dict of projects present in the database. :return: dict -> {<int_keys>: <project_name>}
358,975
def say(self, txt, lang=None): lang = lang or self.classify(txt) self.get_engine_for_lang(lang).say(txt, language=lang)
Says the text. if ``lang`` is ``None``, then uses ``classify()`` to detect language.
358,976
def adapt(obj, to_cls): if obj is None: return obj elif isinstance(obj, to_cls): return obj errors = [] if hasattr(obj, ) and obj.__adapt__: try: return obj.__adapt__(to_cls) except (AdaptError, TypeError) as e: ex_type, ex, tb = sys.exc_inf...
Will adapt `obj` to an instance of `to_cls`. First sees if `obj` has an `__adapt__` method and uses it to adapt. If that fails it checks if `to_cls` has an `__adapt__` classmethod and uses it to adapt. IF that fails, MRO is used. If that fails, a `TypeError` is raised.
358,977
def get(self, list_id=None, email_address=None, include_tracking_preference=False): params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response = self._get("/subscribers/%s.json" % ...
Gets a subscriber by list ID and email address.
358,978
def post_chat_message(self, merchant_id, channel_id, message): return self.do_req(, self.base_url + % (merchant_id, channel_id), message)
post a chat message Arguments: channel_id: Scan token
358,979
def get_books_containing_page(cursor, uuid, version, context_uuid=None, context_version=None): with db_connect() as db_connection: with db_connection.cursor( cursor_factory=psycopg2.extras.RealDictCursor ) as real_dict_cursor: ...
Return a list of book names and UUIDs that contain a given module UUID.
358,980
def assign_from_ast(node, expr): if isinstance(expr, str): expr = ast.Name(id=expr, ctx=ast.Load()) mod = ast.Module([ast.Assign(targets=[node], value=expr)]) ast.fix_missing_locations(mod) return compile(mod, "<assignment_script>", "exec")
Creates code to assign name (or tuple of names) node from expr This is useful for recreating destructuring assignment behavior, like a, *b = [1,2,3].
358,981
def enumerate_imports(tokens): imported_modules = [] import_line = False from_import = False for index, tok in enumerate(tokens): token_type = tok[0] token_string = tok[1] if token_type == tokenize.NEWLINE: import_line = False from_import = False ...
Iterates over *tokens* and returns a list of all imported modules. .. note:: This ignores imports using the 'as' and 'from' keywords.
358,982
def __pred_for_np2d(self, mat, num_iteration, predict_type): if len(mat.shape) != 2: raise ValueError() def inner_predict(mat, num_iteration, predict_type, preds=None): if mat.dtype == np.float32 or mat.dtype == np.float64: data = np.array(mat.reshape(ma...
Predict for a 2-D numpy matrix.
358,983
def locate_range(self, key, start=None, stop=None): loc1 = self.l1.locate_key(key) if start is None and stop is None: loc = loc1 elif isinstance(loc1, slice): offset = loc1.start idx = SortedIndex(self.l2[loc1], copy=False) try: ...
Locate slice of index containing all entries within the range `key`:`start`-`stop` **inclusive**. Parameters ---------- key : object Level 1 key value. start : object, optional Level 2 start value. stop : object, optional Level 2 stop ...
358,984
def makebunches_alter(data, commdct, theidf): bunchdt = {} dt, dtls = data.dt, data.dtls for obj_i, key in enumerate(dtls): key = key.upper() objs = dt[key] list1 = [] for obj in objs: bobj = makeabunch(commdct, obj, obj_i) list1.append(bobj) ...
make bunches with data
358,985
def copy( self ): cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy
Make a copy of this :class:`ParserElement`. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParse...
358,986
def tsne(self, data_view_id): analysis = self._data_analysis(data_view_id) projections = analysis[] tsne = Tsne() for k, v in projections.items(): projection = Projection( xs=v[], ys=v[], responses=v[], ...
Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne`
358,987
def column_list(string): try: columns = list(map(int, string.split())) except ValueError as e: raise argparse.ArgumentTypeError(*e.args) for column in columns: if column < 1: raise argparse.ArgumentTypeError( .format(column)) retu...
Validate and convert comma-separated list of column numbers.
358,988
def Fierz_to_JMS_chrom(C, qq): if qq[0] in dflav: s = dflav[qq[0]] + 1 b = dflav[qq[1]] + 1 return {.format(s, b): C[ + qq], .format(s, b): C[ + qq], .format(b, s): C[ + qq].conjugate(), .format(b, s): C[ + qq].conjugate(), ...
From chromomagnetic Fierz to JMS basis for Class V. qq should be of the form 'sb', 'ds' etc.
358,989
def pip_installer_url(version=None): version = version or hpcbench.__version__ version = str(version) if in version: git_rev = if in os.environ: git_rev = version.split(, 1)[-1] if in git_rev: git_rev = git_rev.split(, 1)[0] git_...
Get argument to give to ``pip`` to install HPCBench.
358,990
def load_mnist_data(args): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = (np.expand_dims(x_train, -1).astype(np.float) / 255.)[:args.num_train] x_test = (np.expand_dims(x_test, -1).astype(np.float) / 255.)[:args.num_test] y_train = keras.utils.to_categorical(y_train, NUM_CLASS...
Load MNIST dataset
358,991
def _default_conflict_solver(match, conflicting_match): if len(conflicting_match.initiator) < len(match.initiator): return conflicting_match if len(match.initiator) < len(conflicting_match.initiator): return match return None
Default conflict solver for matches, shorter matches if they conflicts with longer ones :param conflicting_match: :type conflicting_match: :param match: :type match: :return: :rtype:
358,992
def set_focus(self, pos): "Set the focus in the underlying body widget." logging.debug(, pos) self.body.set_focus(pos)
Set the focus in the underlying body widget.
358,993
def convert(isbn, code=): isbn = _isbn_cleanse(isbn) if len(isbn) == 10: isbn = code + isbn[:-1] return isbn + calculate_checksum(isbn) else: if isbn.startswith(): return isbn[3:-1] + calculate_checksum(isbn[3:-1]) else: raise IsbnError( ...
Convert ISBNs between ISBN-10 and ISBN-13. Note: No attempt to hyphenate converted ISBNs is made, because the specification requires that *any* hyphenation must be correct but allows ISBNs without hyphenation. Args: isbn (str): SBN, ISBN-10 or ISBN-13 code (str): EAN Bo...
358,994
def dump_yaml(data, clean_up=False, long_form=False): return yaml.dump( data, Dumper=get_dumper(clean_up, long_form), default_flow_style=False, allow_unicode=True )
Output some YAML
358,995
def add_single(self, address, rank=1, nodeid=1, ospf_area=None, **kwargs): lb = self.create(address, rank, nodeid, ospf_area, **kwargs) self._engine.nodes[0].data[self.typeof].append(lb.data) self._engine.update()
Add a single loopback interface to this engine. This is used for single or virtual FW engines. :param str address: ip address for loopback :param int nodeid: nodeid to apply. Default to 1 for single FW :param str, Element ospf_area: ospf area href or element :raises Upda...
358,996
def rotate(file_name, rotation, suffix=, tempdir=None, method=): return str(Rotate(file_name, rotation, suffix, tempdir, method))
Rotate PDF by increments of 90 degrees.
358,997
def CorrectWrongEmails(self, askInput=True): for email in self.wrong_emails: corrected_email = self.CorrectEmail(email) self.emails[self.emails.index(email)] = corrected_email self.wrong_emails = []
Corrects Emails in wrong_emails
358,998
def get_EOL(file): f = open(file, ) firstline = f.read(350) EOL = "" for k in range(350): if firstline[k:k + 2] == "\r\n": print(file, ) EOL = break if EOL == "": for k in range(350): if firstline[k] == "\r": print...
find EOL of input file (whether mac,PC or unix format)
358,999
def _updateMetadata(self, variantFile): metadata = self._getMetadataFromVcf(variantFile) if self._metadata is None: self._metadata = metadata
Updates the metadata for his variant set based on the specified variant file