content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import requests def get_filterjs(url): """ Get filter.js file :param url: base url for timetabling system :return: filter.js text """ url = url + 'js/filter.js' source = requests.get(url).text return source
1a1d330c4e2ddf16fc30710096d51e7207fe2e25
646,900
def parseBands(band, allBands, error): """Parses a string that specifies bands. Bands are horizontal rectangles defined with respect to lines. They correspond with regions of interest where we try to find specific marks, such as commas and accents. Parameters ---------- band: string or Non...
f502ddc4107d2440e914166866168c700fd5a6e2
646,901
def GeojsonCheck(filename): """ Checks if filename is of type geojson :param str filename: filename to check :returns: bool - True if filename ends with geojson; otherwise False """ if filename.endswith('.geojson'): return True else: return False
28738d580c849fcfab1572dea70d8928817042ba
646,904
def volume_bars(df, volume_column, threshold): """ Computes volume bars (index) :param df: pd.DataFrame() :param volume_column: (str) name for the column with volume data :param m: (int) threshold for volume :return idx: returns list of indices """ t = df[volume_column] ts = 0 ...
dfac4717cb6bec3776b4b5617e4db40393d067bd
646,905
def multiply_by_u(x, u=(9, 4), d=5): """ Multiply x with u, interpreting as numbers from the field sqrt(d). Where u is a fundamental solution. Args: x: <tuple> (a,b) to be interpreted as (a+b*sqrt(d)) u: <tuple> (u1,u2) to be interpreted as (u1+u2*sqrt(d)) d: <int> Returns: (x,y...
21ffab64599033ce3942ad67e681e97e98f2255e
646,907
def zeroth_order(t: float, q: list, k: float) -> float: """Simple zeroth-order rate function. :param t: model time :param q: Vector (list) of mass distribution through compartments (not actually used but required argument for ODE solver) :param k: Time constant of the rate function. :returns:...
71a46a200beeae60f6fa73372b08539672b24d3b
646,908
def construct_conn_msg(stream, lines=None, protocol_opts=None): """Return a connnection message :param stream: stream name :param lines: number of messages to consume :param protocol_opts: optional arguments """ connection_msg = stream if lines: connection_msg += ' {0}'.format(lines...
823411a327e8c6fe0e6cd99d0479b2b4ba8d15cb
646,909
def MultipleReplace(Text, ReplaceDict): """ Perform multiple replacements in one go using the replace dictionary in format: { 'search' : 'replace' } """ NewText = Text for Search, Replace in ReplaceDict.items(): NewText = NewText.replace(Search, str(Replace)) return NewText
1c1ff4a1395ca6553855025d369140ec088f18ae
646,911
import logging def check_proc_type(image_proc_type): """ check_proc_type function checks to make sure image_proc_type is a string :param image_proc_type: user selected processing technique :raises ValueError: if image_proc_type is not a string :returns True: if pass test """ if isins...
77ec8e9ac1aacef3cdeb0473406081d44ca43590
646,913
def gcd(n1, n2): """ Recursive function to return the GCD of n1 and n2 """ if n1 == 0: return n2 return gcd(n2 % n1, n1)
7e63371859191bd5179dd2a275f870ad97e10208
646,914
def wrap_with_links(obj, links, val, root_path, many=False): """Adds links key to object (first argument) based on links dictionary and value""" if many: for item in obj: item['links'] = {} for key in links: item['links'][key] = root_path + links[key].format(item[...
ea42bff363fe131a423501b8442449f03c3eccb7
646,921
def GetNegativeResult(line): """Extract the name of the negative result from line.""" line = line[len("@remove "):] return line.strip()
fc9c1ddbd6c84bd535f1651c74825a2fa4adb380
646,924
import logging def bases_to_complete_previous_codon(phase): # pylint: disable=invalid-name """ Return the bases at exon start that completes the previous codon. >>> bases_to_complete_previous_codon(0) # e.g. -----XXX 0 >>> bases_to_complete_previous_codon(2) # e.g. XX-----X 1 >>> bases_t...
a5b77dc0468ae9144f6f4250c7d3cc49bfce68a6
646,928
import random import string def generate_key(num_chars=32): """ Generate a unique key. :param num_chars: Number of characters. :return: Key of num_chars length """ return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(num_chars))
688deb94ddfef5d2a5e5e8f44171bca43c1429ed
646,929
def is_palindrome(s): """check if a string is a palindrome""" return s == s[::-1]
0e5e89f54374c16800da6785e81260c63b9e5317
646,930
def best_case_name(obj): """Take an object and return the highest quality case name possible. In general, this means returning the fields in an order like: - case_name - case_name_full - case_name_short Assumes that the object passed in has all of those attributes. """ if ...
a2c792a2fab02d9783cf56ca97b1c3848698f5de
646,931
def merge_dict(d1, d2): """Merge two dictionaries The second dictionary `d2` overwrites values in `d1` if they have common keys. This is equivilent to return {**d1, **2} in python3. Using this function improves python2--3 compatibility. """ out = d1.copy() out.update(d2) ...
f6833203264315da8a7efac3e1b21133cc6f6738
646,932
import textwrap def get_docstring(target) -> str: """ Retrieves the documentation string from the target object and returns it after removing insignificant whitespace :param target: The object for which the doc string should be retrieved :return: The cleaned documentation string f...
3c52831c612513ae39d4173194a3b98ba2fbb4f8
646,933
import typing def filter_line( line: str, filters: typing.Optional[typing.Iterable[str]] ) -> typing.Optional[str]: """ Filters out line that contain substring Args: line: line to filter filters: filter strings to apply Returns: line if not filter are found in line, e...
859477b209ad8e5cfd444fb0e172068f94df1596
646,934
def parse_item(item): """ Parse a CVE item from the NVD database """ parsed_items = {} cve = item.get('cve', {}) CVE_data_meta = cve.get('CVE_data_meta', {}) ID = CVE_data_meta.get('ID', '') parsed_items['id'] = ID affects = cve.get('affects', {}) vendor = affects.get('vendor'...
26d03e5054ceb33d071273d6894cfba0bed58ec5
646,935
from typing import Dict def convert_to_instruction_dict(installation_str: str) -> Dict[str, str]: """Convert given string to dict. Args: installation_str (str): The string to be converted. Returns: Dict[str, str]: Expected dict """ return {"cmd": installation_str}
d5c384b9203208b1a9294a7c000602314cf08a02
646,938
def fix_aspect_providers(lib_providers): """Change a list of providers to be returnable from an aspect. Args: lib_providers: A list of providers, e.g., as returned from forward_deps(). Returns: A list of providers which is valid to return from an aspect. """ # The DefaultInfo provider...
2a0cfc5465cb89be3f8375997b7a5bcef61c9b82
646,940
def pairs_to_dict(items: list) -> dict: """Example: ['MESSAGES', '3', 'UIDNEXT', '4'] -> {'MESSAGES': '3', 'UIDNEXT': '4'}""" if len(items) % 2 != 0: raise ValueError('An even-length array is expected') return dict((items[i * 2], items[i * 2 + 1]) for i in range(len(items) // 2))
591449759e8794693403abdd3f2207abcef4f0c0
646,944
def fig(fig, include_plotlyjs='cdn', full_html:bool=False)->str: """Returns html for a plotly figure. By default the plotly javascript is not included but imported from the plotly cdn, and the full html wrapper is not included. Args: include_plotlyjs (bool, str): how to import the necessary javascr...
3447c3b460220afa0bc58285d4b1765f2831e080
646,947
def _triangles(dg): """ Return a list of all oriented triangles in the digraph ``dg``. EXAMPLES:: sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _triangles sage: Q = ClusterQuiver(['A',3]) sage: _triangles(Q.digraph()) [] sage: Q.mutate([0,1]) ...
eb9260b4079d60747ab701aae624a03d70612c5c
646,948
from datetime import datetime def wrf_times_to_datetime(wrfdata,timename='Times',format='%Y-%m-%d_%H:%M:%S'): """Convert WRF times to datetime format""" timestrs = wrfdata.variables['Times'][:] if hasattr(timestrs[0],'values'): # xarray return [ datetime.strptime(s.values.tostring().decode...
f3ffe736d2847582ef0fc684a50f20ec352ff799
646,950
def get_higher_closing_price(df): """returns the exchange with the higher closing price""" # exchange 1 has higher closing price if (df['close_exchange_1'] - df['close_exchange_2']) > 0: return 1 # exchange 2 has higher closing price elif (df['close_exchange_1'] - df['close_exchange_2']) <...
8002c1124ab2257032f259c72e7a37f6e075562e
646,959
import torch def normalize(clip, mean, std): """ Normalise clip by subtracting mean and dividing by standard deviation Parameters ---------- clip : torch.tensor video clip mean : tuple Tuple of mean values for each channel std : tuple Tuple of standard deviation va...
6949d643c870f39899bd4b876a0ee8301507806d
646,960
import re def fix_varptr_calls(vba_code): """ Change calls like VarPtr(foo(0)) to VarPtr(foo) so we can report on the whole byte array. """ # Do we have any VarPtr() calls? if ("VarPtr(" not in vba_code): return vba_code vba_code = re.sub(r"(VarPtr\(\w+)\(0\)\)", r'\1)', vba_code)...
0461395fba611c054dc5b0c44b19879f0b3e6aef
646,961
import hashlib def checksum(file, method='sha1', chunk_size=4096): """Calculate the checksum of a file. """ h = hashlib.new(method) with open(file, 'rb') as f: for chunk in iter(lambda: f.read(chunk_size), b""): h.update(chunk) return h.hexdigest()
5acca91e4cf45f4684f5e8bf07a95eb1a4c7e201
646,964
def _exist_key(key, **kwargs): """ check whether key is exsit in the kwargs and kwargs[key] is not None. """ is_exist = key in kwargs is_not_none = kwargs[key] is not None if is_exist else None return is_exist and is_not_none
0fadd75a5bc735a0a0ed7e387ddd4d9842db8c37
646,965
def duration_to_string(duration): """Format a duration in seconds as a string. Args: duration (float): The duration in seconds. Return: A more human-readable version of the string (for example, "3.5 hours" or "93 milliseconds"). """ if duration > 3600 * 24: duration_str = "{0:0.1f} days".f...
ce643d44b0436083f0b039ce3f0b7f4085c7f043
646,967
def cli(ctx, quota_id, deleted=False): """Display information on a quota Output: A description of quota. For example:: {'bytes': 107374182400, 'default': [], 'description': 'just testing', 'display_amount': '100.0 GB', 'groups': [], ...
1ba978b422817b36b6124235cd49ff665e299069
646,968
def rank_results(results): """Ranks the results of the hyperparam search, prints the ranks and returns them. Args: results (list): list of model configs and their scores. Returns: list: the results list reordered by performance. """ ranking = sorted(results, key=lambda k: k["score"...
a3878446280e1d006c409c9391a8d9962e447651
646,969
def indent(unindented, n_spaces=2): """ Indent a multi-line string using spaces. """ indent = " " * n_spaces newline = "\n" + indent return indent + newline.join(unindented.split("\n"))
4f501b77ab55a3af12b19330a2a7e8af548baec3
646,977
def getAverageRGBOld(image): """ Given PIL Image, return average value of color as (r, g, b) """ # no. of pixels in image npixels = image.size[0] * image.size[1] # get colors as [(cnt1, (r1, g1, b1)), ...] cols = image.getcolors(npixels) # get [(c1*r1, c1*g1, c1*g2),...] sumRGB = [(x...
eb28dd84af9531a39ea12c11d1300d097a45a5a4
646,978
def match(cmd, s): """ Check if cmd has the required parts of s and any of the optional part. """ parts = s.split('-') start = parts[0] if len(parts) > 1: end = parts[1] else: end = "" return cmd.startswith(start) and (start+end).startswith(cmd)
9a92f31a0f463a4a0215fdc82e0ce29a804ebffc
646,982
def has_failed(node): """ Check whether status is "failed". To avoid false positives check whether status is one of "pass" or "none". :param node: XML node holding status as text. :returns: Whether the status is reported as "failed". """ return (node.text.strip() not in ['pass', 'none'])
ff72db0d6ce2e8dd11cd2167ee23fd49fb4679ec
646,984
def _has_active_network_in_vlan(vlan): """ Check if there are any other active network in the vlan this is used because some equipments remove all the L3 config when applying some commands, so they can only be applyed at the first time or to remove interface vlan configuration :param vlan: vlan...
d271796451aeef5953b4b60d11f9513d1b18f659
646,985
def func(x, a, b, c): """ Second degree polynomial function of the form f(x) = ax^2 + bx + c :param x: input variable :param a: second deg coeff :param b: first deg coeff :param c: zeroth deg coeff :return: f(x) """ return a*x**2 + b*x + c
bedc9b41013e47aecfee779589b6e3e7b22b96cd
646,988
import torch def describe(x: torch.Tensor): """ Describe the distribution of numbers in the input tensor. This function mimics the behavior of DataFrame and Series describe method in pandas. Parameters ---------- x : torch.Tensor Input tensor to be described Returns ----...
fa1d9a2d711d9668235e49480c6a94f2c0e96093
646,990
def checkNewFollowers(new_list, old_list): """ Checks if elements in the new list are present in the old one if not present, saves it into a list of new users (that is, new followers) :param new_list: A list of followers generated in this execution :param old_list: A list of followers generated ...
db46dd9c05dc08836aab57ca8a5d020fa2cc05ac
646,993
import torch def average_aggregator(embedding_batch, embed_dim=0): """ aggregates by averaging embedding lists in each of the n batch entries :param embedding_batch: python list of n tensors of m x K-dim embedding vectors (m can vary) :param embed_dim: K, used if the embedding_lists is empty (n = 0) t...
c4fbb0e67035246a6f585ce140c99f1dfc6cc7c0
646,994
def is_property_rel(rel_type): # type: (str) -> bool """Test for string indicating a property relationship Arguments: rel_type {str} -- relationship type Returns: bool -- relationship is a property """ return rel_type.endswith('-properties')
b8258ab602f0b3e6dffc7bb29727b3177cc0b349
646,995
def int_to_roman(input): """ Convert an integer to a Roman numeral. """ if not isinstance(input, type(1)): raise TypeError("expected integer, got %s" % type(input)) if not 0 < input < 4000: raise ValueError("Argument must be between 1 and 4000") ints = (1000, 900, 500, 400, 100, 90, 50,...
35bdebee545660a5c3608e3fc32de998813c0393
646,998
import torch def box_nms(boxes, scores, threshold): """Non maximum suppression. Args: boxes: (tensor) bounding boxes, sized [N,4]. scores: (tensor) bbox scores, sized [N,]. threshold: (float) overlap threshold. Returns: keep: (tensor) selected indices. Reference: https://...
bf877bdd9640facdfc59fea6c25728e6d810ec58
647,002
def valid(guess): """ This is a predicate function to check whether a user input is a letter and with only one letter. :param guess: :return: bool """ if guess.isalpha() and len(guess) == 1: return True return False
c66e1a4b0da64ac53644f23099077955a942bd71
647,004
def findall_with(node, path, func): """Find all func(n) for n in node.findall(path). """ return [func(n) for n in node.findall(path)]
f1ca028013078c47923f3a62ee2691a6bec6bb2d
647,007
def _split_table_name(table_name): """Split 'schema_name.table_name' to (schema_name, table_name).""" table_name_items = table_name.split(".") if len(table_name_items) == 1: schema_name = None elif len(table_name_items) == 2: schema_name, table_name = table_name_items else: r...
9538acb70b7d6bd5f035481d164e5fce0fe3e68b
647,008
def ell_max_from_resolution(resolution): """Returns the maximum degree for a spherical input of given resolution.""" return resolution // 2 - 1
7ef887fa4dfacff0476a1d5f4d98a49f5db076c1
647,009
def buscar_vuelos_escala(vuelos: dict, origen: str, destino: str) -> list: """ Buscar vuelos (con escala) Parámetros: vuelos (dict): Es un diccionario de diccionarios con la información de los vuelos. origen (str): El código del aeropuerto de origen destino (str): El código del aeropuerto de d...
2231d18c60b1bf6d0553e75dc449ea27688ba21d
647,012
import torch def normalize(x, eps=1e-6): """Apply min-max normalization.""" x = x.contiguous() N, C, H, W = x.size() x_ = x.view(N*C, -1) max_val = torch.max(x_, dim=1, keepdim=True)[0] min_val = torch.min(x_, dim=1, keepdim=True)[0] x_ = (x_ - min_val) / (max_val - min_val + eps) out ...
738311825bb64c562c018acd1bdaa0500ea4fee8
647,015
def filter_par(name): """Filter parenthesis away from a name.""" if name.endswith(")"): return name.split("(")[0] else: return name
a72967b2bc8e3c52aa17169aa69cbad74605dbf5
647,020
def fermi_energy_parser(vasp_dir): """ Parses fermi energy from DOSCAR file. :param vasp_dir: string containing path to VASP-file. :return: float containing fermi energy. """ # Open DOSCAR file. outcar_file = vasp_dir + '/DOSCAR' try: with open(outcar_file, "r") as f: ...
07297e5194d59b8d78a852524ac9c63502a423e0
647,021
def vocab(name): """ Given a property such as 'rel', get its fully-qualified URL in our JSON-LD vocabulary. """ return "http://api.conceptnet.io/ld/conceptnet5.7/context.ld.json#" + name
e46dcdc8648eb8b8a6085f7fa1a2a51eafca3987
647,022
def unconvert_from_RGB_255(colors): """ Return a tuple where each element gets divided by 255 Takes a (list of) color tuple(s) where each element is between 0 and 255. Returns the same tuples where each tuple element is normalized to a value between 0 and 1 """ un_rgb_color = (colors[0]/(2...
637f9e03e17f4fae17f0f023f486e24d5ca6e745
647,023
def get_total_nodes(load_bal): """ Returns the number of nodes attached to the load balancer. Regardless if they are in the scaling group or not. """ return len(load_bal.nodes)
570809488bd800d8bfc41ce564929e13b1d3f013
647,025
def convert_to_int(s): """Convert any object to int if possible, otherwise return original object.""" try: return int(s) except (ValueError, TypeError): return s
aec494493aba265ea91cf11225a2a09aeda3fa4e
647,028
def superpack_name(pyver, numver): """Return the filename of the superpack installer.""" return 'numpy-%s-win32-superpack-python%s.exe' % (numver, pyver)
5c234119923961c98b6f036df21cc9cd9a8ca0d8
647,034
def riffle(*args): """riffle(*args) Riffles lists of equal length. The resulting list alternates between elements of each of the input lists. """ n = len(args) # Verify that all lists are the same length for i in range(1, n): if len(args[0]) != len(args[i]): raise Val...
3cb156c2d42479ced434438effee614908e08a0a
647,035
from typing import Any def is_false(expression: Any): """Returns true if the input expression evaluates to false""" return expression is False
1ddda5f3d3ea0666598a6562d2dae2d7ff8e1533
647,036
def get_gazed_at_multiplier(person_of_interest, looking_at, add_to_multiply=.5, base_multiple=1): """Creates a 'per-frame' multiplier based on the # of people looking at the person_of_interest frame_multiplier = base_multiple + (add_to_multiply * [# of people looking at that person]) note: Doesn't include...
b9b14cd3ecd735cb6ea0f1d77aebf20b7d1571b9
647,041
import math def gen_gaussian_list(a, b, n=1000): """gen_gaussian_list(a, b, n=1000) Generate a discrete approximation of a Gaussian function, including its domain and range, stored as a pair of vanilla python lists. Args: a (float) : Lower bound of domain b (float) : Upper bound o...
babea372bb98c659b54ef20ca043f27bb14365e2
647,050
def is_panchromatic_product(xml_node): """Checks whether a satellite product is panchromatic.""" for child in xml_node: if child.text == 'Pan': return True return False
81c61c84955aab5984fb4a391ae44991a8db00e4
647,051
def center_kernel_low_rank(G): """ Center a the feature matrix such that :math:`\mathbf{G}_c \mathbf{G}_c^T` is centered. .. math:: \mathbf{G}_c = (\mathbf{I} - \dfrac{\mathbf{11}^T}{n})\mathbf{G} :param G: (``numpy.ndarray``) Low-rank approximation of the feature matrix of shape ``(n, k)``. ...
200a3aed74b8b3aff7ac88a0daeb03f31159a2f8
647,052
def quota_parse(quota_dict): """ Parse the output of ``SESConnection.get_send_quota()`` to just the results. """ return quota_dict['GetSendQuotaResponse']['GetSendQuotaResult']
36d44e539b969b8e4ef26b738ad59fc47ce12f66
647,054
from unittest.mock import patch def class_mock(q_class_name, request, autospec=True, **kwargs): """ Return a mock patching the class with qualified name *q_class_name*. The mock is autospec'ed based on the patched class unless the optional argument *autospec* is set to False. Any other keyword argumen...
448ab8aff578bbdb6ab8a9b3130fdf0fac1f113b
647,058
def abstractmethod(funcobj): """Decorator used to identify an abstract method that must be implemented in any subclasses.""" funcobj.__isabstractmethod__ = True return funcobj
755cda1b6a58c6cda7a6dd7828148951302db0d8
647,061
from typing import Type from enum import Enum from typing import Sequence def create_choices(enum_type: Type[Enum]) -> Sequence[str]: """Create choice strings. Args: enum_type: enum Returns: a collection of strings describing the choices in enum. """ # mypy wants type annotation...
4a3dda90048bebeafeb71049cfb7e28a530f0461
647,062
def p_maxlh(n,k): """ Calculates the maximum likelihood estimator for the kth sample of n total samples. Args: n: the number of samples from the random variable, X k: the hierarchical position of the sample when ordered k in [0,n) Returns: the maximum likelih...
29d709124b6bd8d86ef01cb7603297b8cfc774c5
647,063
def try_config(config, heading, key): """Attempt to extract config[heading][key], with error handling. This function wraps config access with a try-catch to print out informative error messages and then exit.""" try: section = config[heading] except KeyError: exit("Missing config se...
6c10fd8ec356cf5ad2b6c09314a3ea00e7af08f5
647,064
import re def humanize(word): """ Capitalize the first word and turn underscores into spaces and strip a trailing ``"_id"``, if any. Like :func:`titleize`, this is meant for creating pretty output. Examples:: >>> humanize("employee_salary") "Employee salary" >>> humanize(...
22ef47a7112a2ac2b0ae14ce1822f3de3c3477c6
647,069
def total_heat_sum_error(spf_heat_data): """Total values for heating and overall heating spf. Uses heating operational data. Calculate total heat extracted from ground and absolute error. Also calculates spf and fractional error. Parameters ---------- spf_heat_data : pd.Dateframe Heatp...
c15c07c984a11b2732ee7ed47c6263db18156e10
647,073
def get_download_url_from_commit(package, commit): """ Return the download URL for this commit @package - :user/:repo combination @commit - commit hash """ return "https://codeload.github.com/%s/legacy.tar.gz/%s" % (package, commit)
cb1a7b60f7bb6ba873644b2914cffc67a758f85e
647,077
def OR(bools): """Logical OR.""" if True in bools: return True return False
200e78e6ef1ce91ad36301cea0b8f56dc7301219
647,078
import math def Magnitude(a): """Magnitude returns the square root of the sum of the numbers of a list squared.""" c = 0 for i in range(len(a)): c = c + a[i]**2 return math.sqrt(c)
b4b28190f41a7c52ff0446fe551b665f06db5299
647,079
import torch def make_directed(nbr_list): """ Check if a neighbor list is directed, and make it directed if it isn't. Contributed by saxelrod Args: nbr_list (torch.LongTensor): neighbor list Returns: new_nbrs (torch.LongTensor): directed neighbor list directed (...
d6d1de47b01b0e74d23785325d1d8a7d0dcfb738
647,080
import uuid def get_guid(path): """ Return a GUID which is reproducibly tied to a file path """ return uuid.uuid5(uuid.NAMESPACE_DNS, 'quantiphyse.org/' + path)
d63fa9a35f36ddc9bac248bddb235ee3614e035b
647,081
def list2dict(lst): """Takes a list of (key,value) pairs and turns it into a dict.""" dic = {} for k,v in lst: dic[k] = v return dic
55c6bb953ee5e0341f25bd1e2a0994ef73fd1ca5
647,085
def min_max_normalize(X): """Min-Max normalization function X = (X - Xmin)/(Xmax - Xmin)""" samples, features = X.shape for i in range(features): xmin = X[:, i].min() xmax = X[:, i].max() X[:, i] = (X[:, i] - xmin)/(xmax - xmin) return X
cf23a0254559487a77010a6c8942e52959afa4aa
647,086
def calc_percentages(df): """ Build dataframe with percent changes day to day. """ df_pct = df[df.columns.difference(['date', 'stato', 'note', 'note_it', 'note_en', 'note_test', 'note_casi', 'casi_da_sospetto_diagnostico', 'casi_da_s...
b74bb4dd549494ff602a173c99a220fb7f83f7ac
647,090
import yaml def load_config(path): """ Loads config file: Args: path (str): path to the config file Returns: config (dict): dictionary of the configuration parameters, merge sub_dicts """ with open(path, 'r') as f: cfg = yaml.safe_load(f) config = dict() for...
7ab52ac2180ad3d688e12e275d7e7ad1a5aa0814
647,094
def get_routing_segmentation_security_policy( self, source_zone: str, destination_zone: str, ) -> dict: """Get all security policies configured on Orchestrator for a particular pair source and destination segments .. list-table:: :header-rows: 1 * - Swagger Section - ...
0506035b6de993bd6ca6ce9948f34eeb2fe6b54e
647,099
def sel_dou_1(input_data): """ Use hard-coded criteria to pre-select articles from DOU section 1. Input and output are Pandas DataFrames. """ identifica_regex = '(?:portaria|decreto|resolu|medida provisória|lei )' veto_orgao_regex = '(?:universidade|instituto federal|superintendência regional|su...
5f3f5d78ade1153d811ccd56c1f1d323fc1713ae
647,102
import six def key_not_string(d): """Helper function to recursively determine if any key in a dictionary is not a string. """ for k, v in d.items(): if not isinstance(k, six.string_types) or (isinstance(v, dict) and key_not_string(v)): return True
5121fc184c2d0164dd9288652e8e586a746d5cde
647,105
def _get_truncated_setting_value(value, max_length=None): """ Returns the truncated form of a setting value. Returns: truncated_value (object): the possibly truncated version of the value. was_truncated (bool): returns true if the serialized value was truncated. """ if isinstance(va...
59d16f03e542e41fd4c62e986631c7c6e5211be7
647,106
def get_offset_map(doc, options): """Return mapping from original to cut document text offsets or None if the text is not cut.""" if options.cut == 'tiab': # restrict to title and abstract sections = doc.text.split('\t') if len(sections) <= 2: return None else: ...
2d639b1633486bfd3b0410a1dac9ca0ee9835612
647,107
def psmid_to_charge(psmid): """ Extract charge from Percolator PSMId. Expects the following formatted PSMId: `run` _ `SII` _ `MSGFPlus spectrum index` _ `PSM rank` _ `scan number` _ `MSGFPlus-assigned charge` _ `rank` See https://github.com/percolator/percolator/issues/147 """ psmid = ...
4695daabfd10f055c459239f4cc7e1bbb328aa50
647,108
import string def camel_to_snake(s: str) -> str: """Returns a new str in snake_case, given an str in camelCase. Raises: ValueError: When original str is not in camelCase Examples: >>> camel_to_snake('camelToSnake') 'camel_to_snake' >>> camel_to_snake('already_snake') ...
8b483ea0d4002b231076f0ff921eba6d745ee199
647,109
import re def object_id_from_uri(uri): """ from a sciety.org uri extract the DOI portion to be an id value e.g. from https://sciety.org/articles/activity/10.1101/865006 return 10.1101/865006 """ if uri: id_match_pattern = re.compile(r".*?/(10\..*)") matches = id_match_pattern.m...
79a0acb84da99c54206edcc3f33d224b764051f1
647,111
def get_array_alpha(rgba): """Return alpha values of an RGBA 3D-array.""" return rgba[...,3]
e6a227c004497b3b346cdf627818289fb4c63a50
647,113
from typing import Any def get_pitch(note: Any) -> float: """Get pitch for a given nbs note.""" key = note.key + note.pitch / 100 if key < 33: key -= 9 elif key > 57: key -= 57 else: key -= 33 return 2 ** (key / 12) / 2
6984ef56c1eb55c3de3dff95613171c38be7c156
647,122
def sample_sequentials(sequential_keys, exp, idx): """ Samples sequentially from the "from" values specified in each key of the experimental configuration which have sample == "sequential" Unlike `cartesian` sampling, `sequential` sampling iterates *independently* over each keys Args: s...
ce6d4a4e5238f1e10e26beae7898a79aca4c6268
647,123
def parse(string: str, delimiter: str = ' ', nest_open: str = '(', nest_close: str = ')') -> list: """ This function is for parsing a nested string structure into a nested list >>>parse("hello world") ["hello", "world"] >>>parse("a b (c d (e f)) g") ["a", "b", ["c", "d", ["e", "f"]], "g"] ...
e038a671e6ed30dfae2bb770e5c3d41d304bfee2
647,132
def executable(pytestconfig) -> str: """Returns the path to the lightgbm executable.""" return pytestconfig.getoption('execfile')
820ca9231810d6a8f17637e3f639f46dadb9260e
647,133
def sql_name(raw_name): """ Cleaned column name. Args: raw_name: raw column name Returns: cleaned name suitable for SQL column """ sql_name = raw_name for to_replace in ['"', ' ', '\\', '/', '(', ')', '.']: sql_name = sql_name.replace(to_replace, '_') return...
faa72162ed8e048833972f93a155dc002f44a1a8
647,135
def _split(text): """Split a line of text into two similarly sized pieces. >>> _split("Hello, world!") ('Hello,', 'world!') >>> _split("This is a phrase that can be split.") ('This is a phrase', 'that can be split.') >>> _split("This_is_a_phrase_that_can_not_be_split.") ('This_is_a_phrase...
cc1ce276dad54a9b954bc6453d96adaeb2e85a64
647,136
def get_bboxes_intersection(roiA, roiB): """ Computes the intersection area of two bboxes :param roiA: the first bbox :param roiB: the second bbox :return: the area of the intersection """ xInter = min(roiA[3], roiB[3]) - max(roiA[1], roiB[1]) yInter = min(roiA[2], roiB[2]) - max(roiA[0]...
85cde64b0b6d490aea5bf2c5fffda50fca502220
647,139
def linear(t0, t1, y0, y1, t): """ Helper function for linear interpolation between two points .. math:: z = \\frac{y_1-y_0}{t_1-t_0} \\left( t - t_0 \\right) Args: t0 (torch.tensor): first "x" point t1 (torch.tensor): second "x" point y0 (torch.tensor): first "y" ...
d4587bb3847acad076f6b2465c1b91009318e62f
647,140
def set_material(item, material): """Set the material on an item. Args: item (bpy.Object): The Blender object to assign the material to. material (bpy.Material): The material to assign. Returns: bpy.Material: The Blender material. """ # Don't bother if we can't ...
86c892f407faaa31988ac4f3491071f1826977d5
647,141