content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import numbers def validate_float(datum, **kwargs): """ Check that the data value is a floating point number or double precision. conditional python types (int, float, numbers.Real) Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return isinstance(datum, (int, float, numbers.Real)) and not isinstance(datum, bool)
8ced3fd09f35dc485cc9848eb0c6bcac1e3e047b
182,332
def _generate_location(location, items, techs): """ Returns a dict for a given location. Dict keys for permitted technologies are the only ones that don't start with '_'. Args: location : (str) name of the location items : (AttrDict) location settings techs : (list) list of available technologies """ # Mandatory basics within = items.get('within', None) level = items.get('level', None) d = {'_location': location, '_level': level, '_within': str(within)} # Override if 'override' in items: for k in items.override.keys_nested(): target_key = '_override.' + k try: d[target_key] = items.override.get_key(k) except KeyError: # Allow locations to not define 'within' if k == 'within': d[target_key] = None # Permitted echnologies for y in techs: if y in items.techs: d[y] = 1 else: d[y] = 0 return d
6e9f371379eeb8c827c2c8b26a3f4e442fc4b341
488,054
def get_single_rank(child_node): """ Extract MPI info from IPM XML child node (corresponding to one MPI rank) child_node : xml.etree.ElementTree.Element child of root node, i.e. ET.parse(filename).getroot()[i] """ i_regions = 6 # "regions" block under root.child mpi_node = child_node[i_regions][0] # "region" block under root.child.regions record_list = [] for leaf in mpi_node[1:]: # skip the first "modules" tag record = {**leaf.attrib, 'time': float(leaf.text)} record_list.append(record) return record_list
a3352761baf6daef95830953cb5a2cdb7b302f11
271,561
def _arg_no_mixin(num): """Return FindArgNoMixin for num.""" class FindArgNoMixin(object): # suppress(too-few-public-methods) """Mixin that provides generate() for finding args by number.""" def generate(self, # suppress(no-self-use) sub, other_transform, match_transform): """Generate argument list of num size.""" # A cheap hack to ensure that we generate a few extra in the # list GET case gen_num = abs(num - 1 if sub is not None else num) args_before = (" ".join([other_transform("ARGUMENT")] * gen_num)) match_arg = match_transform("VALUE") subcommand = sub + " " if sub is not None else "" return subcommand + " ".join([args_before, match_arg]) return FindArgNoMixin
f918a05183f265750490e62303173525134eb3ca
634,961
import re def _split_numeric_sortkey( s, limit=10, reg=re.compile(r"[0-9][0-9]*\.?[0-9]*").search, join=" ".join ): """Separate numeric values from the string and convert to float, so it can be used for human sorting. Also removes all extra whitespace.""" result = reg(s) if not result or not limit: text = join(s.split()) return (text,) if text else tuple() else: start, end = result.span() return ( join(s[:start].split()), float(result.group()), _split_numeric_sortkey(s[end:], limit - 1), )
08023c180b74a066eaafe9726657e2c03d7d7c4c
452,788
def add_shift_steps_unbalanced( im_label_list_all, shift_step=0): """ Appends a fixed shift step to each large image (ROI) Args: im_label_list_all - list of tuples of [(impath, lblpath),] Returns: im_label_list_all but with an added element to each tuple (shift step) """ return [(j[0], j[1], shift_step) for j in im_label_list_all]
63fc45bc14e54ec5af473ec955bd45602f3c7041
6,894
def parse_dhm_response(msg: str) -> int: """Parse server's DHM key exchange request :param msg: server's DHMKE message :return: number in the server's message """ return int(msg.split(':')[1])
065d16e8ae317d49ee2e29743b3004f8d79aadd2
587,132
def limit(value, limits): """ :param <float> value: value to limit :param <list>/<tuple> limits: (min, max) limits to which restrict the value :return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to that boundary. """ if value < limits[0]: value = limits[0] elif value > limits[1]: value = limits[1] else: pass return value
55fb603edb478a26b238d7c90084e9c17c3113b8
6,485
from typing import Dict from typing import Any def keyword_format(**kwargs: Dict[str, Any]) -> str: """formats kwargs as comma joined key=value pairs. Example: >>> from torforce.utils.repr_utils import keyword_format >>> >>> keyword_format(a=1, b=2, c=3) 'a=1, b=2, c=3' """ return ', '.join([f'{k}={v}' for k, v in kwargs.items()])
f87677ffdb57eadca873ee52ea7321ee1c196bad
408,488
from typing import Union from typing import List def remove_prefix_suffix( x: str, prefix: Union[str, List[str]], suffix: Union[str, List[str]] ) -> str: """ Remove the prefix and suffix from a string, prefix and suffix can be a string or a list of strings. :param x: input string :param prefix: a string or a list of strings, will check prefix one by one :param suffix: a string or a list of strings, will check suffix one by one :return: the string without prefix/suffix """ if isinstance(prefix, str): prefix = [prefix] if isinstance(suffix, str): suffix = [suffix] for s in prefix: if x.startswith(s): x = x[len(s) :] break for s in suffix: if x.endswith(s): x = x[: -len(s)] break return x
17e44f24a361eb4f821221b2bef8b4c429f443a5
214,885
def __wrap_string_vales(_where_value): """This function wraps values going in the WHERE clause in single-quotes if they are not integers. :param _where_value: The value to be evaluated and potentially wrapped in single-quotes :returns: The value in int or string format """ try: _where_value = int(_where_value) except (TypeError, ValueError): _where_value = f"'{_where_value}'" return _where_value
7431cfd57caf3af9bc92ba8b559394136b21efe8
320,674
def is_float(value): """Check if value is a float.""" return isinstance(value, float)
a0b52166c42b6bceaffa18e8057f0408196acaab
640,275
def mapify_iterable(iter_of_dict, field_name): """Convert an iterable of dicts into a big dict indexed by chosen field I can't think of a better name. 'Tis catchy. """ acc = dict() for item in iter_of_dict: acc[item[field_name]] = item return acc
e2b21fcd9bb311f467f81888becc2e8f1ad84444
79,852
def get_scope(scope): """Get scope for the labeler Args: scope (list): combination of issue_body, issue_comments, pull_requests or ["all"] Returns: list: list of scopes """ if "all" in scope: scope = ["issue_body", "issue_comments", "pull_requests"] return scope
43467bc2d4ab6838dfa9a264b92e871119ec7ce3
433,289
def job(priority, properties): """Creates a new job with the given priority and properties.""" return { "priority": priority, "properties": properties, }
2ad8130d5a6c4c36f3010329b15f4e9f3e826e26
158,583
def converts(*args): """ A convenient decorator for the ModelConverter used to mark which method should be used to convert which MongoEngine field. """ def _inner(func): func._converter_for = frozenset(args) return func return _inner
cd999d76c896630d9afa87244a195029dec75281
58,715
def rmod(denom, result, num_range): """ Calculates the inverse of a mod operation. The *denom* parameter specifies the denominator of the original mod (%) operation. In this implementation, *denom* must be greater than 0. The *result* parameter specifies the result of the mod operation. For obvious reasons this value must be in the range ``[0, denom)`` (greater than or equal to zero and less than the denominator). Finally, *num_range* specifies the range that the numerator of the original mode operation can lie in. This must be an iterable sorted in ascending order with unique values (e.g. most typically a :func:`range`). The function returns the set of potential numerators (guaranteed to be a subset of *num_range*). """ if denom <= 0: raise ValueError('invalid denominator') if not (0 <= result < denom): return set() if len(num_range) == 0: return set() assert num_range[-1] >= num_range[0] start = num_range[0] + (result - num_range[0] % denom) % denom stop = num_range.stop return range(start, stop, denom)
f3f62f70802d6a62c17e0feabbcb56790a8b43aa
195,256
def redis_string_to_list(value, sep=','): """convert a comma (or sep) separated string to list. Args: value: byte, a redis string. sep: string, which separator is used to separator items Return: a list of strings. Could be empty list if original string is None or empty. """ return value.decode('utf-8').split(sep) if value else []
e81106294d1a87104e003ffe5827683c0c49036d
561,694
import math def calc_bragg_angle(d, energy_eV, n=1): """Calculate Bragg angle from the provided energy and d-spacing. Args: d (float): interplanar spacing (d-spacing) [A]. energy_eV (float): photon energy [eV]. n (int): number of diffraction peak. Returns: dict: the resulted dictionary with: lamda (float): wavelength [nm]. bragg_angle (float): Bragg angle [rad]. bragg_angle_deg (float): Bragg angle [deg]. """ # Check/convert types first: d = float(d) energy_eV = float(energy_eV) n = int(n) lamda = 1239.84193 / energy_eV # lamda in [nm] bragg_angle = math.asin(n * lamda / (2 * d * 0.1)) # convert d from [A] to [nm]. bragg_angle_deg = 180. / math.pi * bragg_angle return { 'lamda': lamda, 'bragg_angle': bragg_angle, 'bragg_angle_deg': bragg_angle_deg, }
2271fde28a30609dd41c1c3618132bfb368a122b
470,384
def b_to_mb(byts: int, decimals: int = 1) -> float: """Convert a count of bytes into a count of megabytes. Arguments: byts {int} -- The count of bytes. Keyword Arguments: decimals {int} -- The number of decimal points to include in the count of megabytes. (default: {1}) Returns: float -- The count of megabytes. """ return round(byts / 1000 / 1000, decimals)
412711c6db8e30701c3de5db251e9686cbf91aa2
510,067
def read_topology_file(data_path) -> str: """Reads the topology and returns the contents of the data file as a string.""" with open(data_path, "r") as f: data_string = f.read() return data_string
6e3ea30cc11cb6f0e77ef3e3f34fe74bfbc59cfb
469,808
def ocircle2(circle1, circle1_radius, circle2, circle2_radius): """ detects collision between two circles """ if (circle1.distance_to(circle2) <= (circle1_radius+circle2_radius)): return True else: return False
a3811f83f99eeccedfea32bcbf99f1e518c644a4
80,604
import math def obrien_fleming_cutoff(K, current_k, alpha): """ Returns the cutoff value for O'Brien and Fleming's Test Arguments: K: An integer less than 10. current_k: The current interm analysis number alpha: The alpha level of the overall trial (0.01, 0.05 or 0.1). Returns: cutoff: The value of \(C_B(K, \alpha)\) for the study. Note: Since there is no closed source formula for the cutoff value, a lookup table is used. """ if not isinstance(K, int) or K < 1 or K > 10: raise ValueError('K must be an integer between 1 and 10.') if not isinstance(current_k, int) or current_k < 1 or current_k > 10: raise ValueError('current_k must be an integer between 1 and 10.') if current_k > K: raise ValueError('current_k must be less than k.') if alpha not in [0.01, 0.05, 0.1]: raise ValueError('alpha must be 0.01, 0.05, or 0.1.') cutoffs = { "0.01": [2.576, 2.580, 2.595, 2.939, 2.986, 3.023, 3.053, 3.078, 3.099, 3.117], "0.05": [1.960, 2.178, 2.289, 2.361, 2.413, 2.453, 2.485, 2.512, 2.535, 2.555], "0.1": [1.645, 1.875, 1.992, 2.067, 2.122, 2.164, 2.197, 2.225, 2.249, 2.270], } return cutoffs[str(alpha)][K - 1] * math.sqrt(K / current_k)
411f91aa7d70265018f2e157cee22d31c90a0abb
337,877
def expected(df, ts): """Modify *df* with the 'model' and 'scenario' name from *ts.""" return df.assign(model=ts.model, scenario=ts.scenario)
742255d9b69d3ae27a0726402a46f8bdea525826
127,868
def readFile(fPath): """ Reads the Santander text file which is a bank statement file encoded in ISO-8859-1. :param fPath: The fPath to the input text file. :return: A list containing all the lines of the file read correctly. """ with open(fPath, "r", encoding="ISO-8859-1") as inF: # Replacing non-breaking space in Latin1 with a UTF-8 space ls = inF.readlines() ls = [l.replace("\xa0", " ") for l in ls] return ls
38af6361ff80557fd5cc1e5b0466394e6729b8c8
184,037
def factorial(n): """Calculate the factorial for N.""" t = 1 for i in range(1, n + 1): t *= i return t
1cebbd139e1e7be177eb81455439913220775dc4
391,216
def calculate_curvature(fit, yeval, ym_per_pix): """ Calculate the curvature of the road given a fit to one of the lane lines """ # Get the parameters of the fit A = fit[0] B = fit[1] # calculate the curvature curv = (1+(2*A*yeval*ym_per_pix+B)**2)**1.5/abs(2*A) return curv
20964502ca451408d3d5d4761321ad172e4b4989
229,819
from typing import Any def index() -> Any: """Basic HTML response.""" return ( "<html>" "<body style='padding: 10px;'>" "<h1>Welcome to the API</h1>" "<div>" "Check the docs: <a href='/docs'>here</a>" "</div>" "</body>" "</html>" )
03be914dc51ea9ae237ea71ff19daf0f5a0a936d
211,164
def _create_signature_key(signature, rev): """Given a signature ID and revision, build the key we use to look up the signature in the redis db.""" return f'{signature}:{rev}'
d0c790bcd9a3ddfbbc45c5fc439513b310241685
245,260
def fst(xs): """Returns the first element from a list.""" return xs[0]
acbd8e6cacfd6b679621d14f5d959571dd4c1fdc
487,314
import importlib def import_modules(modules, path, attribute=None, fetch_attribute=False): """Import and return modules from a path if they have a given attribute :param modules: Collection of modules to import or collection of tuples containing (module, attribute). :param path: import path to get modules from :param attribute: attribute to filter modules by or None if tuples are used :param fetch_attribute: True to create module, attribute tuples, False to only return modules :exception AttributeError: When attribute does not exist for a given module :exception ImportError: If path + module does not exist :return: Collection of imported modules or collection of (module, attribute) tuples when fetch_attribute is True. """ imported_modules = [] # If attribute is not set modules should be collection of tuples if not attribute: module_filters = modules else: # Generate a list of tuples were each module_name is associated with # the specified attribute. module_filters = list() for module_name in modules: module_filters.append((module_name, attribute)) for modname, attrib in module_filters: mod = importlib.import_module(path + '.' + modname) if not hasattr(mod, attrib): msg = "The module '%s.%s' should have a '%s' "\ "attribute." % (path, modname, attrib) raise AttributeError(msg) elif fetch_attribute: imported_modules.append((mod, attrib)) else: imported_modules.append(mod) return imported_modules
235734bdb293c1f4a8db8ceea47bdd447c38332e
604,035
import warnings def filt(signal, synapse, dt, axis=0, x0=None, copy=True): """Filter ``signal`` with ``synapse``. .. note:: Deprecated in Nengo 2.1.0. Use `.Synapse.filt` method instead. """ warnings.warn("Use ``synapse.filt`` instead", DeprecationWarning) return synapse.filt(signal, dt=dt, axis=axis, y0=x0, copy=copy)
8d2a8968599ebf70c23f0453a81427ce130a11c7
482,715
def filter_to_transform(filter_fn, df_name='atoms'): """Create transform function (which operates on dataset items) from filter function (which operates on dataframes). By default, applies filter_fn to ``atoms`` dataframe, but a different dataframe can be specified optionally. :param filter_fn: Arbitrary filter function that takes in a dataframe and returns filtered dataframe :type filter_fn: filter function :param df_name: Name of dataframe to apply filter_fn to, defaults to 'atoms' :type df_name: str, optional """ def transform_fn(item): item[df_name] = filter_fn(item['atoms']) return item return transform_fn
a1435a495bcee19ee42985a653d6d8d18515a3e2
288,997
import math def oersted_to_amps_per_meter(oersted): """Converts Oersted to \(\\frac{A}{m}\)""" return (oersted*1e3)/(4*math.pi)
d964a86649da9fede19227f977af2384d6d84858
530,935
import re def _version_from_tag(tag): """ Extracts the semver from the given tag (e.g: v0.1.0 -> 0.1.0) :param tag: :return: """ pattern = re.compile('v\d+.\d+.\d+') if not pattern.match(tag): raise Exception(f"{tag} is not valid semver") return tag[1:]
f9364c189401673b9033ae38945b9e9c93adf005
516,672
def bitcount(num, length, value=1): """Counts the bits in num that are set to value (1 or 0, default 1).""" one_count = 0 curr_length = length while num and curr_length: one_count += 1 & num num >>= 1 curr_length -= 1 if value: return one_count else: return length - one_count
6666c3a42a24316bd2952cc32477f0141807277d
258,265
def ieplc(mapping): """ Returns the statistics for the number of inter-process logical communications (IePLC). :param mapping: process-to-node mapping :return: IePLC statistics """ weights = [d['weight'] for u, v, d in mapping.process_graph.edges(data=True)] return sum(weights), sum(weights)//len(weights) + 1, min(weights), max(weights)
803846d2fdf3a1a696c53572a9019a18de6ebf9f
560,238
def normalized_device_coordinates_to_image(image): """Map normalized value from [-1, 1] -> [0, 255]. """ return (image + 1.0) * 127.5
39f244b32c18807f7eb87f529ebccf14adc895ad
397,787
def keys_from_hash(hexdigest): """ Return a cache keys triple for a hash hexdigest string. NOTE: since we use the first character and next two characters as directories, we create at most 16 dir at the first level and 16 dir at the second level for each first level directory for a maximum total of 16*16 = 256 directories. For a million files we would have about 4000 files per directory on average with this scheme which should keep most file systems happy and avoid some performance issues when there are too many files in a single directory. For example: >>> expected = ('f', 'b', '87db2bb28e9501ac7fdc4812782118f4c94a0f') >>> assert expected == keys_from_hash('fb87db2bb28e9501ac7fdc4812782118f4c94a0f') """ return hexdigest[0], hexdigest[1], hexdigest[2:]
ffa4a1685e92a1b9768ccf1efa206c4b7f8b0e85
617,115
def point_judge(center, bbox): """ 用于将矩形框的边界按顺序排列 :param center: 矩形中心的坐标[x, y] :param bbox: 矩形顶点坐标[[x1, y1], [x2, y2], [x3, y3], [x4, y4]] :return: 矩形顶点坐标,依次是 左下, 右下, 左上, 右上 """ left = [] right = [] for i in range(4): if bbox[i][0] > center[0]: # 只要是x坐标比中心点坐标大,一定是右边 right.append(bbox[i]) else: left.append(bbox[i]) if right[0][1] > right[1][1]: # 如果y点坐标大,则是右上 right_down = right[1] right_up = right[0] else: right_down = right[0] right_up = right[1] if left[0][1] > left[1][1]: # 如果y点坐标大,则是左上 left_down = left[1] left_up = left[0] else: left_down = left[0] left_up = left[1] return left_down, right_down, left_up, right_up
bb0d8eb6c4b056f8dc95493aa35c775045e0df90
597,058
def traffic_light(load): """Returns green, amber or red depending on the value of load.""" if load < 0.7: return "green" elif load < 0.9: return "amber" else: return "red"
5a0b3f29052ee52ec260899dbe817af15b042ede
334,640
def create_multi_feedforward_parser(parser): """Add the multi-agent policy hyperparameters to the parser.""" parser.add_argument( "--shared", action="store_true", help="whether to use a shared policy for all agents") parser.add_argument( "--maddpg", action="store_true", help="whether to use an algorithm-specific variant of the MADDPG " "algorithm") return parser
3d3f16c077e37d775764626f8f8a43bb8351441e
379,589
def get_aggregation_func(path, aggregation_functions): """Lookup aggregation function for path, if any. Defaults to 'mean'. :param path: Path to lookup :type path: str :param aggregation_functions: Aggregation function configuration :type aggregation_functions: dict(<pattern>: <compiled regex>) """ if not aggregation_functions: return 'mean' for pattern in aggregation_functions: if pattern.search(path): return aggregation_functions[pattern] return 'mean'
c305e26e77fedd9b8b19845bb5fcd422be6f3542
441,154
def is_abs(field): """ Check if field is absolute value. Parameters ---------- field : str Field name. Returns ------- (bool, str) Whether the field is absolute or not along with the basic field itself. """ if field[:4] == 'ABS(' and field[-1] == ')': return field[4:-1], True else: return field, False
808d2e7d5531be1aba57fd68e8c17de3116b3649
327,732
def make_readable_pythonic(value: int) -> str: """Make readable time (pythonic). Examples: >>> assert make_readable(359999) == "99:59:59" """ return f"{value / 3600:02d}:{value / 60 % 60:02d}:{value % 60:02d}"
a091ef99b94cb2b4c3e0d657805a9e7b6418dd3a
656,404
import math def smaller2k(n): """ Returns power of 2 which is smaller than n. Handles negative numbers. """ if n == 0: return 0 if n < 0: return -2**math.ceil(math.log2(-n)) else: return 2**math.floor(math.log2(n))
0d0bbbf95cb22bf1b9ffb29012075534bcc9646d
709,493
def _get_excluded_pids(exclude_file): """Reads the exclusion list and returns a dict of lists of excluded patients""" exclude_pids = { 'NCP': [], 'CP': [], 'Normal': [] } with open(exclude_file, 'r') as f: for line in f.readlines(): cls, pid = line.strip('\n').split() exclude_pids[cls].append(pid) return exclude_pids
7c07615231896120373a1723db6901857502a68c
209,596
import requests def get_dnb_token(username, password, url="https://maxcvservices.dnb.com/rest/Authentication"): """Get a new authentication token. See http://developer.dnb.com/docs/2.0/common/authentication-process :param username: D&B username :type username: str :param password: D&B password :type password: str :returns: authentication token or "INVALID CREDENTIALS" :rtype: str """ r = requests.post( url, headers={ "x-dnb-user": username, "x-dnb-pwd": password, } ) return r.headers["Authorization"]
b847c3e777811abc00aaf9fefce90784b90f6614
272,872
def runpath(tmp_path): """ Return a temporary runpath for testing. The path will not be automatically removed after the test for easier investigation. It takes a form like: /tmp/pytest-of-userid/pytest-151/test_sub_pub_unsub0 """ return str(tmp_path)
df2d0caa4f4e834fb9f0577f143d79aa17649939
582,508
def _find_in_columncollection(columns, name): """ Find a column in a column collection by name or _label""" for col in columns: if col.name == name or getattr(col, "_label", None) == name: return col return None
d7d72cb6b13a51b51770fcac13d8166c0a87ace3
371,008
from pathlib import Path def input_custom_variables(string: str, dmvio_folder: str): """ Replace the following environment variables in the given string. if ${EVALPATH} is inside string it is replaced with the path to the evaltools (the folder where this file is located). ${DMVIO_PATH} is replaced with the path to DM-VIO. """ return string.replace('${EVALPATH}', str(Path(__file__).parent.parent.resolve())).replace('${DMVIO_PATH}', dmvio_folder)
0766874154192a885e49f50f14b5ab9038788ced
18,588
from typing import AnyStr def re_url_repl(sre) -> AnyStr: """Add space at the begging of the given URL. Argument sre is the result of re.match() and re.search()""" return ' ' + sre.group(0)
be0da8b1e2ce4fef1015671ec4c0729c1ab4c478
501,285
def _get_lines_from_file(filename, lines=None): """ If lines is None read the lines from the file with the filename filename. Args: filename (str): file to read lines from lines (list/ None): list of lines Returns: list: list of lines """ if lines is None: with open(filename, "r") as f: lines = f.readlines() return lines
4d4cf767bb5aaafc1ac2a396c1f4227e67268b99
336,870
import secrets def secure_random(low: int, high: int) -> int: """Generates a random number from low (inclusive) to high (inclusive) using the secrets module. DISCLAIMER: we are not security experts this may not be at all secure. Parameters ---------- low : int The inclusive lower bound high : int The inclusive upper bound Returns ------- int The generated number """ return secrets.randbelow(high) + low
8bb90113ef83382e5224637713ca5c860f419d70
399,344
def cost(candidate, grid, distances_mx): """ Calculate the cost of a (candidate) solution. Args: candidate: The solution (frozenset). grid: A list of MapBox objects. distances_mx: A NumPy array. Returns: The solution's cost (float). """ c = sorted(candidate) c_cost = 0 for i, sq in enumerate(grid): if i not in c and sq.demand > 0: j = c[distances_mx[c, i].argmin()] c_cost += sq.demand * distances_mx[j, i] return c_cost
636efedfb8b8751d09a55566c7d65223f85c36f8
157,264
def par2bool(s): """ Returns boolean (True, False) from given parameter. Accepts booleans, strings or integers. """ if isinstance(s, str): s = s.lower() return s in ["true", "1", "on", True, 1]
9f4d4c1e1de553b26cbfe0791d363fd00fc3b811
146,780
def get_last_id(file_name): """Retrieve last status ID from a file""" try: with open(file_name) as f: last_id = int(f.read()) return last_id except IOError: return 0
0395cb0134c6c032a87b7370e0fcc47a3ab33619
283,908
def get_sql_dialect(session): """Return the active SqlAlchemy dialect. Args: session (object): the session to check for SqlAlchemy dialect Returns: str: name of the SqlAlchemy dialect """ return session.bind.dialect.name
f2de63abcfdf443893f230904ae72716b4a8fffa
384,575
from typing import Dict from typing import Any import zlib import base64 def _serialize_bytes(data: bytes, compress: bool = True) -> Dict[str, Any]: """Serialize binary data. Args: data: Data to be serialized. compress: Whether to compress the serialized data. Returns: The serialized object value as a dict. """ if compress: data = zlib.compress(data) value = { "encoded": base64.standard_b64encode(data).decode("utf-8"), "compressed": compress, } return {"__type__": "b64encoded", "__value__": value}
c77236ef8d3e019d09d1c9de53627f87cb88b4b2
55,230
def visc(Tc, S, V = False): """ Calculate the viscosity of water or seawater Reference: Sharqawy et al. 2009 Thermophysical properties of seawater: a review of \ existing correlations and data https://doi.org/10.5004/dwt.2010.1079 Eq 22 and Eq 23 viscosity unit in kg/m/s Parameters ---------- Tc : scalar Temperature in °C. S : scalar Salinity in per mil (g/kg). V: Bool whether or not return calculated viscosity, default is False Returns ------- Viscosity or Seawater to water ratio. """ Sref = S/1000 #reference salinity is written in kg/kg A = 1.541 + 1.998e-2 * Tc - 9.52e-5 * Tc**2 B = 7.974 - 7.561e-2 * Tc + 4.724e-4 *Tc**2 Sw_w = 1 + A*Sref + B*Sref**2#seawater to water ratio if V: V_water = 4.2844e-5 + 1/( 0.157* (Tc+ 64.993)**2 -91.296) #water viscosity V_sw = V_water * Sw_w # seawater viscosity Sw_w = (Sw_w, V_sw) print("given viscosity is in kg/m/s, which is 1000 times of centipoise") return Sw_w
b58ac72bd2454b05aa8facbc6132fc72456e13fe
550,459
import hashlib def checksum(fpath, hasher=None, asbytes=False): """Returns the checksum of the file at the given path as a hex string (default) or as a bytes literal. Uses MD5 by default. **Attribution**: Based on code from `Stack Overflow <https://stackoverflow.com/a/3431835/789078>`_.""" def blockiter(fpath, blocksize=0x1000): with open(fpath, "rb") as afile: block = afile.read(blocksize) while len(block) > 0: yield block block = afile.read(blocksize) try: hasher = hasher or hashlib.md5() for block in blockiter(fpath): hasher.update(block) return (hasher.digest() if asbytes else hasher.hexdigest()) except: return None
76d6ffb2c91a6706564cdbb269e256dae51e3139
224,112
from typing import Optional import re import click def validate_version_string(ctx, param, value: Optional[str]) -> Optional[str]: """ Callback for click commands that checks that version string is valid """ if value is None: return None version_pattern = re.compile(r"\d+(?:\.\d+)+") if not version_pattern.match(value): raise click.BadParameter(value) return value
22e084403cfa2ff72c003de53fe6b17c5dc03319
629,587
def max_sequence(arr): """Find the largest sum of any contiguous subarray.""" best_sum = 0 # or: float('-inf') current_sum = 0 for x in arr: current_sum = max(0, current_sum + x) best_sum = max(best_sum, current_sum) return best_sum
d17f69534eda79649236438df7a1576ebbea789c
78,330
def _transform(point, reference, projection): """Transform on point from local coords to a proj4 projection.""" lat, lon, altitude = reference.to_lla(point[0], point[1], point[2]) easting, northing = projection(lon, lat) return [easting, northing, altitude]
17dc2c1cc0ac1c0f01f09a790a8b9521d7d605ec
467,617
from typing import List import hashlib def md5_hashsum(file_names: List[str]) -> str: """ Calculate md5 hash sum of files listed Args: file_names: list of file names Returns: hashsum string """ hash_md5 = hashlib.md5() for file_name in file_names: with open(file_name, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
f3a5b854af1dd89c33d9f129a1998df572d330b0
404,733
def make_keyword_html(keywords): """This function makes a section of HTML code for a list of keywords. Args: keywords: A list of strings where each string is a keyword. Returns: A string containing HTML code for displaying keywords, for example: '<strong>Ausgangsw&ouml;rter:</strong> Nature, Plants, Fauna' """ res_html = '<strong>Ausgangsw&ouml;rter:</strong> ' for word in keywords[:-1]: res_html += word + ', ' res_html += keywords[-1] return res_html
71e35245ad7b2fe2c67f6a4c27d53374945089bd
5,031
import math def sigmoid(x): """Sigmoid function f(x)=1/(1+e^(-x)) Args: x: float, input of sigmoid function Returns: y: float, function value """ # for x which is to large, the sigmoid returns 1 if x > 100: return 1.0 # for x which is very small, the sigmoid returns 0 if x < -100: return 1e-6 return 1.0 / (1.0 + math.exp(-x))
c65624784c34422ca41f14d118e3690990a05b47
688,818
from typing import List def quick_sort(source) -> List[int]: """クイックソート. 計算量: O(n log n)""" if len(source) <= 1: return source n = len(source) # いったん中央の値を求める median_value = source[n // 2] # 分割する領域を作成 smalls, bigs, middles = [], [], [] # データソースの値を、3つの領域に振り分ける for i in range(n): if source[i] < median_value: smalls.append(source[i]) elif source[i] > median_value: bigs.append(source[i]) else: middles.append(source[i]) # 大小が発生した領域を更に分割する if smalls: smalls = quick_sort(smalls) if bigs: bigs = quick_sort(bigs) # 極限まで分割した各領域を合成する return smalls + middles + bigs
0ce4eb05e8073d56e5134f5464b71317d0f0756b
165,026
def smooth_avg(data: list[int]) -> list[int]: """ Generate a smoothed version of a data set where each point is replaced by the average of itself and immeadiately adjacent points Args: data (list[int]): A list of continuous data points Returns: list[int]: A smoother list of continuous data points """ smoothed = [] for i, x in enumerate(data): if i == 0: smoothed.append((x + data[i + 1]) / 2) elif i == len(data) - 1: smoothed.append((x + data[i - 1]) / 2) else: smoothed.append((data[i - 1] + x + data[i + 1]) / 3) return smoothed
593d1b43216229874c7fb7148392d7c2c922640a
150,905
import re def get_active_port(flows): """Find the active port name based on knowledge that down stream traffic is only output to the 'nic' interface. Args: flows (dict): Open flow details of the mux, result returned from function get_flows Returns: string or None: Name of the active port or None if something is wrong. """ for in_port in flows.keys(): if not re.match(r"(m|mu|mux|muxy)-", in_port): return in_port return None
cfee2c86e0d22de37cf206249a91e565d328b875
81,394
from typing import Any def to_str(obj: "Any") -> str: """ Convert any object to a string. This simply calls ``str`` on the object to produce a string representation. """ return obj if isinstance(obj, str) else str(obj)
3d069f3d444a454eda610729b37ca8c9a9c1dcf9
310,365
def getROI(img,x,y,ROI_size): """ crop square ROI from image with center x, y coordinate Parameters: -img: input image -x,y: center coordinate of ROI -ROI_size: size of ROI in pixel Returns: -imCrop: image of ROI -x1,y1: coordinate of top left corner of the ROI -x2,y2: coordinate of botton right corner of the ROI """ x1 = int(x-(ROI_size/2)) y1 = int(y-(ROI_size/2)) x2 = int(x+(ROI_size/2)) y2 = int(y+(ROI_size/2)) imCrop = img[y1:y2,x1:x2] return imCrop,x1,y1,x2,y2
a501944996a786fa16cfc1e0c41168178c9837d5
480,464
def default_selection(random, population, args): """Return the population. This function acts as a default selection scheme for an evolutionary computation. It simply returns the entire population as having been selected. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments """ return population
b1aedf4ae4835c745128ef0c93689821ee5a671a
191,242
def extract_qa_bits(band_data, bit_location): """Get bit information from given position. Args: band_data (numpy.ma.masked_array) - The QA Raster Data bit_location (int) - The band bit value """ return band_data & (1 << bit_location)
d911e75230e46f8571a0926b11c92a74e5da5496
270,363
def halt_after_time(time,at_node,node_data,max_time=100): """ Halts after a fixed duration of time. """ return time>=max_time
c1d2b82d5a8b2019be8ea845bf5b135ed7c5209f
690,127
import copy def revise_unanswerable(preds, na_probs, na_prob_thresh): """ Revise the predictions results and return a null string for unanswerable question whose unanswerable probability above the threshold. Parameters ---------- preds: dict A dictionary of full prediction of spans na_probs: dict A dictionary of unanswerable probabilities na_prob_thresh: float threshold of the unanswerable probability Returns ------- revised: dict A dictionary of revised prediction """ revised = copy.deepcopy(preds) for q_id in na_probs.keys(): if na_probs[q_id] > na_prob_thresh: revised[q_id] = "" return revised
e8e6b008445421b3b226db56d8b61113d46d1ac5
238,943
def snake2camel(snake_str): """Convert a string from snake case to camel case.""" first, *others = snake_str.split('_') return ''.join([first.lower(), *map(str.title, others)])
428cb49438bacb44f4fcfb05a3b0ea82cb5b65de
141,028
import re def countMultiQuestionMarks(text): """ Count repetitions of question marks """ return len(re.findall(r"(\?)\1+", text))
5c0a1dd3838e414aae9a537add7fb120b29adf0b
551,835
def join_host_port(host, port): """Joins a host and port""" if ":" in host or "%" in host: host = "[" + host + "]" return "%s:%d" % (host, port)
bc1b7d76cbc61910402f1187c9723d6d23d03b3a
601,280
def makeWennerArray(numElectrodes=32, id0=0): """ creates a schedule (A,B,M, N) for a Wenner array of length numElectrodes """ schedule=[] for a in range(1, (numElectrodes+2)//3): for k in range(0, numElectrodes-3*a): schedule.append((k+id0, k+3*a+id0, k+1*a+id0, k+2*a+id0)) return schedule
d95adba2679d812fed4b6d2a46b46a8a93868d34
512,526
def merge_var(*a): """Return a sorted list of the symbols in the arguments""" result = [] for var in a: for sym in var: if not sym in result: result.append(sym) result.sort() return result
aac4d02b63f3d02cf97e2f479c5c831b5174d208
170,868
def get_byte(buffer: bytes, offset: int) -> int: """ Gets the byte at the given offset. :param buffer: The buffer to get from. :param offset: The offset from the start of the buffer. :return: The byte value. """ return buffer[offset]
ab37cc2dfa28669dca3e2b4482423bfad009994a
396,352
def reverse_edge(edge): """Switches u and v in an edge tuple. """ reverse = list(edge) reverse[0] = edge[1] reverse[1] = edge[0] return tuple(reverse)
0690bac37188a38baf5cb56fe73dfff8187ff12a
544,326
import requests from bs4 import BeautifulSoup def get_ansible_modules(url): """ This function returns a dictionary which each key is the name of an ansible module and the value is its description """ response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') span_list = soup.find_all('span', class_='std std-ref') module_dict = {} for span in span_list: span_text = span.text split_text = span_text.split(' – ', 1) key = split_text[0] value = split_text[1] module_dict[key] = value return module_dict
453163c3fa01895ec8ed04331fd57c717f5454a9
575,265
def bytes_to_hex_str(bytes_hex: bytes, prefix="") -> str: """Convert bytes to hex string.""" return prefix + bytes_hex.hex()
2ef7e57cbe0e96465543b966def31f5ce36bcbbe
62,513
def solution(l): """ Solution 4 again passes all but the last test case. Try to speed things up some using a dynamic programming-like approach. This solution wound up passing all of the test cases -- the key here is to uses a memorization/dynamic programming approach. A core component of this problem involves finding all multiples of a number after a given number in the list. In the brute force approach, we do the following: 0: for each li: 1: for each lj such that j > i: 2: if li divides lj: 3: for each lk such that k > j: 4: if lj divides lk: (li, lj, lk) is a valid solution Note that steps 3 and 4 involve counting the number of valid values of lk for a given lj. Since we are evaluating all possible values of lj for each possible value of li, this means that we would potentially repeat steps 3 and 4 multiple times for the *same value of lj*. Take the example: l = [1, 1, 1, 1, 3] In this case we would evaluate the number of valid lks for the final '1' 3 times. In the worst case, where l is of length N and consists of all 1's, we would be finding the valid lks for the penultimate lj (N-2) times. To improve on this, we can cache/memorize the values as we compute them. We'll store the smallest computation -- the number of possible values of lk for a given lj. Then, as we traverse the list, if we have already computed the values of lk for a given lj, we just use the value that we previously computed. This touches on the concept of Dynamic Programming. """ # Make sure no numbers are less than 1 or greater than 999999 for li in l: if li > 999999 or li < 1: return 0 # Get number of elements in the list n_l = len(l) # If there are fewer than 3 elements in the list, then there # can't be any lucky triples, so return 0 if n_l < 3 or n_l > 2000: return 0 # Initialize counts -- d_cts[j] corresponds to the number of valid values # of l[k] for l[j]. d_cts = [-1] * n_l ctr = 0 # First iterate over i for i in range(n_l-2): for j in range(i+1, n_l-1): if l[j] % l[i] == 0: # Check to see if we already computed this if d_cts[j] == -1: # Count the number of valid divisors for l[j] d_ctr = 0 for k in range(j+1, n_l): if l[k] % l[j] == 0: d_ctr += 1 d_cts[j] = d_ctr # Add the pre-computed value ctr += d_cts[j] return ctr
0387a39e6d087f381aece01db2718a9e90ba642c
50,836
from string import punctuation import re def normalize_text(text, method='str'): """ Parameters ---------- text : str method : {'str', 'regex'}, default 'str' str: cleans digits and puntuations only ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~') regex : clean digits and all special characters Returns ------- text : str """ # Conver to lower case text = text.lower() if method=='str': # Remove digits text = ''.join(c for c in text if not c.isdigit()) # Remove punctuation text = ''.join(c for c in text if c not in punctuation) # Remove extra spaces text = " ".join(text.split()) elif method=='regex': # Remove digits text = re.sub(r'\d+', ' ', text) # Remove all special characters text = re.sub(r'\W+', ' ', text) # Remove extra spaces text = re.sub('\s\s+', ' ', text) return text
6baae1a8e352b4d2ec608fe3091d3f11a20f5d5d
78,325
def isPrime(n: int)->bool: """ Give an Integer 'n'. Check if 'n' is Prime or Not :param n: :return: bool - True or False A no. is prime if it is divisible only by 1 & itself. 1- is neither Prime nor Composite We will use Naive approach. . Check Divisibity of n with all numbers smaller than n. within range 2 to sqrt(n). All divisors of n comes as pairs. Thus if n is not divisible by any no. within range 2 to sqrt(n), then it is Prime. WE reduce range from 2 to n to 2 to sqrt(n) """ if n==1 : return False i = 2 while (i * i <= n ): if ( n % i ==0): return False i = i+1 return True
57eddd0aba0d53faa6ee1f4f5ff566a1c3b3ef85
63,172
def modify_pred_classes(y_pred_proba, y_pred_classes, thresh=.9): """ Modifies predicted classes to account for words not in command words set. Based on prediction confidence. y_pred_proba: array of prediction probability output from Keras model y_pred_classes: array of prediction classes from Keras model thresh: threshold to predict anything less confident than as "unknown" """ probs = y_pred_proba.max(axis=1) is_unknown = probs < thresh y_pred_modified = y_pred_classes.copy() y_pred_modified[is_unknown] = 11 return y_pred_modified
137b1435a2cebe0d7d2169b0d6f1904ba6606fda
531,363
def unique_group(groups): """Find unique groups in list not including None.""" ugroups = set(groups) ugroups -= set((None,)) ugroups = list(ugroups) ugroups.sort() return ugroups
ef147e4bbccf32f8e9d85954aced914f13b5ba06
253,147
import textwrap def ftl(code): """Nicer indentation for FTL code. The code returned by this function is meant to be compared against the output of the FTL Serializer. The input code will be UTF8-decoded and will end with a newline to match the output of the serializer. """ # The FTL Serializer returns Unicode data so we use it as the baseline. code = code.decode('utf8') # The code might be triple-quoted. code = code.lstrip('\n') return textwrap.dedent(code)
94b5b0aff62cf91afd1831db2e83a07fe4d197d2
488,167
def string_to_array(str_val, separator): """ Args str_val : string value separator : string separator Return List as splitted string by separator after stripping whitespaces from each element """ if not str_val: return [] res = str_val.split(separator) return res
925e369c578b8aeb4943e02f1371c53c846cf888
131,575
def ms_to_htk(ms_time): """ Convert time in ms to HTK (100 ns) units """ if type(ms_time)==type("string"): ms_time = float(ms_time) return int(ms_time * 10000.0)
fe3854dedddbed8ddb31cd4f5a8b8f77c9afb1e2
594,507
def flatten_processes_response(response): """Helper function to extract only pids and paths from the list processes command""" return [{item['process_pid']: item['process_path']} for item in response]
bafa9b0368f78e69c6a40bf2234f585f24ec08c2
340,927
import requests def read_in_s3_json(url): """Reads in a json file from S3 and returns a Python object""" response = requests.get(url) return response.json()
c697889a03d20b07b248e770e3ee828ce7e120a5
154,685
import math def insertArrayShift(input_list, val): """Takes a list and a value and returns a new list with the value inserted at the middle index. The input list is sliced into its left half, then the value is appended, then the right half is added to the end. """ mid = math.ceil(len(input_list) / 2) return input_list[:mid] + [val] + input_list[mid:]
b6d5c5e583033a350ba7f8b4507244d66d504fc9
295,421
import math def lrs_round(floatNumber): """ rounding floats to integers in a way that python 2 did e.g. lrs_round(4.5) results in 5 :Parameters: floatNumber: float to be rounded to integer :Returns: rounded number """ return floatNumber/abs(floatNumber) * math.floor(abs(floatNumber)+0.5)
6c4ce0035d2d14f016fd17df8153edc6a3527071
527,955
import logging def metrics(time_dur, extremes, count, mean_hr, list_of_times, time, voltages): """Create a dictionary with the specified metrics Once all of the metrics have been determined, it is necessary to compile them all together. This is done through the generation of a dictionary. In the assignment, it is specified that the dictionary should contain the following information: duration: time duration of the ECG strip voltage_extremes: tuple in the form (min, max) where min and max are the minimum and maximum lead voltages found in the data file. num_beats: number of detected beats in the strip, as a numeric variable type. mean_hr_bpm: estimated average heart rate over the length of the strip beats: list of times when a beat occurred This function reads in each of these metrics and places each one into their respective keys as mentioned above. Then, once all of the information has been added to the dictionary, it is returned. Parameters ---------- time_dur : float Contains duration of ECG strip in seconds extremes : tuple Contains the minimum and maximum voltages from the ECG strip count : int Value containing the number of peaks present mean_hr : float Contains the average heart rate (beats per minute) list_of_times : list Contains floats that match the times at which peaks occurred Returns ------- dictionary Contains all of the metrics necessary """ logging.info("Dictionary being established") metrics_dict = {"duration": time_dur, "voltage_extremes": extremes, "num_beats": count, "mean_hr_bpm": mean_hr, "beats": list_of_times, "times": time, "voltages": voltages} logging.info("Dictionary filled") return metrics_dict
e9188d3b6119c44463a3403c570f6f1d567c50f7
31,196
from typing import Sequence def timestamp_to_ms(groups: Sequence[str]): """ Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds. Example: >>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups()) 420 """ h, m, s, frac = map(int, groups) ms = frac * 10**(3 - len(groups[-1])) ms += s * 1000 ms += m * 60000 ms += h * 3600000 return ms
2928a0b14876e3b14ad8056bafbab5d540ead686
631,067
def _collect_providers(provider, *all_deps): """Collects the requested providers from the given list of deps.""" providers = [] for deps in all_deps: for dep in deps: if provider in dep: providers.append(dep[provider]) return providers
98855ea9f4997202b3462a941c06508c42f93c5d
482,058