content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import time def toc(tic): """Returns the time since 'tic' was called.""" return time.perf_counter() - tic
976cdeb30a723a8667ae2e0d86a4270ad356d634
638,715
from typing import Optional import math def round_for_theta( v: float, theta: Optional[float] ) -> float: """ Round a value based on the precision of theta. :param v: Value. :param theta: Theta. :return: Rounded value. """ if theta is None: return v else: return round(v, int(abs(math.log10(theta)) - 1))
ef6d18df588df8a80be9dc6c9b7f9104e3109d69
11,514
def read_DDTpos(inhdr): """ Read reference wavelength and DDT-estimated position from DDTLREF and DDT[X|Y]P keywords. Will raise KeyError if keywords are not available. """ try: lddt = inhdr['DDTLREF'] # Ref. wavelength [A] xddt = inhdr['DDTXP'] # Predicted position [spx] yddt = inhdr['DDTYP'] except KeyError as err: raise KeyError("File has no DDT-related keywords (%s)" % err) # Some sanity check if not (abs(xddt) < 7 and abs(yddt) < 7): raise KeyError( "Invalid DDT position: %.2f x %.2f is outside FoV" % (xddt, yddt)) return lddt, xddt, yddt
39cce130305440f14db8e5378ae4e66b8e124b20
32,979
def markdown_list(url: str, title: str) -> str: """Return the Markdown list syntax for YouTube video.""" return f'* [{title}]({url})'
d6da7ea5bcef4fd4f6f1b6fe48521e7cf71772c6
327,034
def traverse_maze(network, part_two=False): """Traverse the maze collecting letters and counting the steps taken.""" x = network[0].index('|') y = 0 direction = 'D' letters = [] steps = 0 while network[y][x] != ' ': if direction == 'D': y += 1 elif direction == 'U': y -= 1 elif direction == 'R': x += 1 elif direction == 'L': x -= 1 if network[y][x] == '+': if direction in ('L', 'R'): if y != len(network) - 1 and network[y+1][x] != ' ': direction = 'D' else: direction = 'U' else: if x != len(network[0]) - 1 and network[y][x+1] != ' ': direction = 'R' else: direction = 'L' elif network[y][x].isalpha(): letters.append(network[y][x]) steps += 1 if not part_two: return ''.join(letters) return steps
eceda7d741a37db63784a708effefdf0f2908f05
379,708
import re def parse_jobs_list(cli_output): """ Parse Databricks CLI output of `databricks jobs list` to return a list of job ids and their names. """ jobs = cli_output.decode('utf-8').replace('\r\n','\n').split('\n') output = {} for job in jobs: matches = re.search('(\d+) +(.+)', job) if matches: output[matches.group(1)] = matches.group(2) return output
ca3970fca80e88bc7b9c376fdae0f8fed10ac9da
407,061
def scapy_layers_dot11_Dot11_find_elt_by_id(self, id): """Iterate over elt and return the first with a specific ID""" for elt in self.elts(): if elt.ID == id: return elt return None
a976e4a0487cc9d3e0cef0cf1a5730c710db95ba
564,923
def reduce_id(id_): """Reduce the SsODNet ID to a string with fewer free parameters.""" return id_.replace("_(Asteroid)", "").replace("_", "").replace(" ", "").lower()
8f6d236030bb6304af04808cdabc6a15c06aeb40
588,372
def reverse(s): """Returns the string s, reverse-videoed.""" return '\x16%s\x16' % s
c62fa89f9b50ee401482a2bcb1b4b2e56f792446
160,991
def Levenshtein_Distance(str1, str2): """ cal str1 and str2 edit distance. Args: str1: string A str2: string B Return: value of edit distance """ matrix = [[ i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)] for i in range(1, len(str1)+1): for j in range(1, len(str2)+1): if(str1[i-1] == str2[j-1]): d = 0 else: d = 1 matrix[i][j] = min(matrix[i-1][j]+1, matrix[i][j-1]+1, matrix[i-1][j-1]+d) return matrix[len(str1)][len(str2)]
89b8c6d761442bb514d798e650c87705e3126397
240,572
def get_menu_name(name): """Make any supplied string suitable/nice for menubar name. :arg name: Name need to make nice for menubar. :type name: str :return: Nice menu name for menubar. :rtype: str """ # get menu name and use it for menu identifier menu_name = "" for char in name: if char == '_' or char == '-': char = ' ' if char.isalpha() or char.isdigit() or char.isspace(): menu_name += char return menu_name
1e53113a99209e81b60e57846a27de1a7ec19959
187,457
import re def validate_hair_color(hcl): """ Validate Height - a # followed by exactly six characters 0-9 or a-f. """ match = re.search("#[0-9a-f]{6}", hcl) return bool(match)
96a63139b907861ffd29cff27b02842ba2d43e9b
492,178
def pivotCombinedInventories(combinedinventory_df): """Create a pivot table of combined emissions. :param combinedinventory_df: pandas dataframe returned from a 'combineInventories..' function :return: pandas pivot_table """ # Group the results by facility,flow,and compartment combinedinventory_df_pt = combinedinventory_df.pivot_table( values=['FlowAmount', 'DataReliability'], index=['FRS_ID', 'SRS_ID', 'Compartment'], columns='Source') return combinedinventory_df_pt
71d56bd546b5990c7b2658f0616ebaf8ed6f472f
628,390
def permutation_from_block_permutations(permutations): """Reverse operation to :py:func:`permutation_to_block_permutations` Compute the concatenation of permutations ``(1,2,0) [+] (0,2,1) --> (1,2,0,3,5,4)`` :param permutations: A list of permutation tuples ``[t = (t_0,...,t_n1), u = (u_0,...,u_n2),..., z = (z_0,...,z_nm)]`` :type permutations: list of tuples :return: permutation image tuple ``s = t [+] u [+] ... [+] z`` :rtype: tuple """ offset = 0 new_perm = [] for p in permutations: new_perm[offset: offset +len(p)] = [p_i + offset for p_i in p] offset += len(p) return tuple(new_perm)
3b6508c103e39051ccfa909b54aa9ec506b35f86
64,666
def lol_product(head, values): """List of list of tuple keys, similar to `itertools.product`. Parameters ---------- head : tuple Prefix prepended to all results. values : sequence Mix of singletons and lists. Each list is substituted with every possible value and introduces another level of list in the output. Examples -------- >>> lol_product(('x',), (1, 2, 3)) ('x', 1, 2, 3) >>> lol_product(('x',), (1, [2, 3], 4, [5, 6])) # doctest: +NORMALIZE_WHITESPACE [[('x', 1, 2, 4, 5), ('x', 1, 2, 4, 6)], [('x', 1, 3, 4, 5), ('x', 1, 3, 4, 6)]] """ if not values: return head elif isinstance(values[0], list): return [lol_product(head + (x,), values[1:]) for x in values[0]] else: return lol_product(head + (values[0],), values[1:])
bc48c9044ba30fd84347430cf42e4d31904a8d74
233,272
import random def max_weight_paths(k, weight_paths_dict, paths_to_edges, overlap=True, norev=False, rgen=None): """ Returns k largest-weight paths. The function proceeds in order through descending weight values to select paths, and if an entire weight class of paths is not to be included, applies a predictable order to the paths before checking them for inclusion (by sorting the (src,dst) pairs in the class and then applying rgen.shuffle). :param k: number of paths to select :param weight_paths_dict: a dict {weight: set} where keys are weight values, and corresponding values are sets of paths having that weight :param paths_to_edges: a dict {(src, dst): set} where the path with endpoints (src, dst) consists of the edges in the corresponding set :param overlap: True if max-weight paths selected can share links; False if selected paths should be disjoint :param norev: True if (dst,src) should be excluded if (src,dst) is chosen :param rgen: RNG object with .shuffle() method to use; random.shuffle() is used if not provided :return: (set, set): the set of (src,dst) pairs for paths selected, and the set of edges covered by those paths """ if rgen is None: rgen = random selected_paths = set() probed_edges = set() weight_list = sorted(weight_paths_dict, reverse=True) weight_index = -1 while k > 0 and weight_index < len(weight_list)-1: weight_index += 1 weight_class = weight_paths_dict[weight_list[weight_index]] l = len(weight_class) if k-l >= 0 and overlap and not norev: # in this case we will use all paths in the weight class, so no ordering is necessary selected_paths.update(weight_class) k -= l else: # in this case we may not use all paths in the weight class, either because: # (1) we don't need them all (including them all will result in more than k paths); or # (2) we have to check for reverses and/or overlap and thus may skip over some paths in the class # so we first sort the paths (deterministic) and then rgen.shuffle them so the weight tie is broken randomly but reproducibly given the RNG paths = sorted(weight_class) rgen.shuffle(paths) if overlap and not norev: selected_paths.update(paths[:k]) k = 0 elif overlap and norev: # paths is an ordered list, so iteration is deterministic for s, d in paths: if (d,s) not in selected_paths: selected_paths.add((s,d)) k -= 1 if k <= 0: break else: # paths is an ordered list, so iteration is deterministic for path in paths: if norev and (path[1],path[0]) in selected_paths: continue path_edges = paths_to_edges[path] if probed_edges.isdisjoint(path_edges): selected_paths.add(path) probed_edges |= path_edges k -= 1 if k <= 0: break # if overlap==True, then we didn't have to update probed_edges, so do it now if overlap: for path in selected_paths: probed_edges |= paths_to_edges[path] return selected_paths, probed_edges
50264effde7c0f7f97c6e5a4c6c34899ad5462db
669,326
def countit(objs): """Return a dict with counts for each item in a list.""" out = {} for el in objs: out[el] = 1 + out.get(el, 0) out = {k: v for k, v in out.items()} return out
f9909092180ccd1bf12bc96a972701cfbd6ff3c7
504,418
def dataframeToPaths(df): """ returns list of paths for given dataframe :param df: dataframe/segment of dataframe :return: gcp urls/paths for this segment/dataframe """ return df['gcp_url'].tolist()
c10bb462c350039631f631953da5fca18b82c031
143,639
def factorial( *, number: int, ) -> int: """Recursive Factorial Function Args: number (int): number Returns: int: factorial of the number """ if number <= 1: return 1 return number * factorial(number=number - 1)
0ab7323ebd6bd9df7a72a3b26abeddc46e8a5a37
643,881
def type_of_user(datum, city): """ Takes as input a dictionary containing info about a single trip (datum) and its origin city (city) and returns the type of system user that made the trip. Remember that Washington has different category names compared to Chicago and NYC. """ user_type = "" # 'usertype'(Subscriber or Customer) or 'Member Type'(Registered or Casual) if city is "Washington": user_type = "Subscriber" if datum.get("Member Type") == "Registered" else "Customer" else: user_type = datum.get("usertype") return user_type
63e21b544dab127043f46bab7956b056a3aa1058
407,445
import pathlib def get_message(message): """ get message from file or string format and return it. Args: message: str or Path.file path to the cleartext or cleartext itself. Returns: message: str.cleartext """ if not isinstance(message, str) and not isinstance(message, pathlib.Path): print("input str object or Path object.aborting...") exit() if isinstance(message, str): if message == "": print("message is empty.aborting...") exit() else: return message else: try: with message.open() as f: message = f.read() if message == "": print("message is empty.aborting...") exit() return message except UnicodeDecodeError: print("file is binary.aborting...") exit()
c00dfa1bda60445c605eddaa8a8e7df1a3802be0
98,357
def GitRemoteUrlFilter(url, patch): """Used with FilterFn to isolate a patch based on the url of its remote.""" return patch.git_remote_url == url
eb6e509c1966e5b9b9e6abf00a164b3a3f9cb1f2
74,302
import torch def region_mask(n, min_mask_size, max_mask_size, maskable_length, device=None): """Create a vector of ``n`` random region masks. Masks are returned in a vector with shape `(n, maskable_length)`. The mask vectors are boolean vectors of ``maskable_length`` with a continuous region of 1s between ``min_mask_size`` and ``max_mask_size`` (inclusive). """ # Generate the start & end positions for each mask, then compare these to # absolute indices to create the actual mask vectors. mask_sizes = ( torch.rand([n, 1], device=device) * (max_mask_size - min_mask_size) + min_mask_size ) mask_starts = torch.rand([n, 1], device=device) * (maskable_length - mask_sizes) mask_ends = mask_starts + mask_sizes indexes = torch.arange(0, maskable_length, device=device) return (mask_starts <= indexes) & (indexes < mask_ends)
ceedf548f1b9f25f579bff51d69cfb593ab2b7df
98,420
def mass_transfer_coefficient_OILTRANS(wind_speed, length, schmdt_nmbr): """ Return the mass transfert coefficien [m/s], formula derived from (Mackay and Matsugu, 1973) source : (Berry et al., 2012) Parameters ---------- wind_speed : Wind speed 10 meters above the surface [m/s] length : Downwind length of the oil slick axis [m] schmdt_nmbr : Schmidt number [] """ return (0.0048 * (wind_speed **(7/9)) * (length ** (-1/9)) * schmdt_nmbr ** (-2/3))
799a491fce669262c939a18da07dbb2a52750c43
298,582
async def ping(): """A test ping endpoint.""" return {"ping": "I'm alive!"}
3e12e2ec3b4d7fd26b64ca9e2269a24c5ab995e6
103,307
def sanitize_price(price_str): """ Normalise a price string and convert to float value. :param price_str: Price string to normalise. :return: Float price value. """ if price_str is None: return None price_str = price_str.strip('$ \t\n\r') price_str = price_str.replace(',', '') return float(price_str)
84af7c25c19bcbef690cc19554f01e6e284446f2
26,457
def indent(s, indentation=" "): """ helper function to indent text @param s the text (a string) @param indentation the desired indentation @return indented text """ return [indentation + _ for _ in s]
59ec5d6751f906b84c2d46a51777f0831116082a
35,074
def calculate_mean(some_list): """ Function to calculate the mean of a dataset. Takes the list as an input and outputs the mean. """ return (1.0 * sum(some_list) / len(some_list))
d0374fc5321f6caa05f546e274490e906bf60106
30,681
def enf_list(item): """ When a list is expected, this function can be used to ensure non-list data types are placed inside of a single entry list. :param item: any datatype :return list: a list type """ if not isinstance(item,list) and item: return [item] else: return item
b27bde2da0855ffa02837dda2f8dfb85f43db30a
150,151
def b_ord(byte): """Return the Unicode code point for a byte or iteration product \ of a byte string alike object (e.g. bytearray). :param byte: The single byte or iteration product of a byte string to \ convert :type byte: bytes or str or int :return: Unicode code point :rtype: int""" return byte if isinstance(byte, int) else ord(byte)
ba79752c7ee7cadde1e7a7323f88fcb46f2d8511
463,835
def get(isamAppliance, instance_id, id, check_mode=False, force=False): """ Retrieving the contents of a file in the administration pages root """ return isamAppliance.invoke_get("Retrieving the contents of a file in the administration pages root", "/wga/reverseproxy/{0}/management_root/{1}".format(instance_id, id))
7ced8fa881e2fe89da5a135f43f883d7e20f8f62
286,956
from typing import Any import yaml def parse_arg_value(val: str) -> Any: """Parse a string value into its Python representation.""" return yaml.safe_load(val)
dfa3a916f78360c7b8209abb573c5cdc17ef2d9d
169,617
def _is_sequence(obj): """Check if the object is a sequence (list, tuple etc.). Parameters ----------- object an object to be checked Returns -------- bool True if the object is iterable but is not a string, False otherwise """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
8733ec482df1b09e6051537524f9c69d5a4295da
291,597
def get_attribute_from_tag(tag, attribute): """Returns a xml attribute from a given tag""" element = None try: element = tag.attrib[attribute] except KeyError: pass # print("Error: attribute {} was not defined in this tag.".format(e)) return element
914e04f2e6441ffb5f42d71de49bd99fe5e3092b
27,207
import logging def getLogger(module_name=None): """ Returns a logger appropriate for use in the ocp_cd_tools module. Modules should request a logger using their __name__ """ logger_name = 'ocp_cd_tools' if module_name: logger_name = '{}.{}'.format(logger_name, module_name) return logging.getLogger(logger_name)
ff1f9e859332c7f0f7d9f734d63eaefdd766b491
94,704
import math def deg2rad(ang_deg): """ Converts degrees to radians """ return math.pi*ang_deg/180.0
190dbd8bfccba8ffe206ef5bb089145026bb9f07
103,596
def Dict(**entries): """Create a dct out of the argument=value arguments. Ex: Dict(a=1, b=2, c=3) ==> {'a':1, 'b':2, 'c':3}""" return entries
a7575cffcd6345b9402ca8ae21213d72f5e83775
237,933
def get_job_status(job): """Returns the status of the job(celery.result.ResultSet) as a percentage of completed tasks """ total = len(job.results) return (float(job.completed_count()) / total) * 100
5cc2bfd7cce4cd5aa3344bf52a99b6a8f48c8d6a
214,621
import math def _gain2db(gain): """ Convert linear gain in range [0.0, 1.0] to 100ths of dB. Power gain = P1/P2 dB = 10 log(P1/P2) dB * 100 = 1000 * log(power gain) """ if gain <= 0: return -10000 return max(-10000, min(int(1000 * math.log10(min(gain, 1))), 0))
1bd602e0db397b3730c4f2b3439aeb351e6bd854
9,041
def group_list(actions, agent_states, env_lens): """ Unflat the list of items by lens :param items: list of items :param lens: list of integers :return: list of list of items grouped by lengths """ grouped_actions = [] grouped_agent_states = [] cur_ofs = 0 for g_len in env_lens: grouped_actions.append(actions[cur_ofs: cur_ofs + g_len]) grouped_agent_states.append(agent_states[cur_ofs: cur_ofs + g_len]) cur_ofs += g_len return grouped_actions, grouped_agent_states
bc6199f5cc0efcdfde7e9c9085c1ccc95c535e30
662,003
import json import requests def check_aws(admin_api_key, env, cc_account_id): """ Checks if an account is an AWS Account with get_account API call """ api_url = env + "/api/account.json/get_account" get_account_info = json.dumps({"account_id": cc_account_id}) r7 = requests.post(api_url, headers = {"Content-Type": "application/json", "access_key": admin_api_key}, data = get_account_info) # checks for AWS (works for mav and non-mav) if "Provider" in r7.json(): if r7.json()["Provider"] == "Amazon Web Services": return True return False
fc69b72870dadb54b796e4206319f2181d252686
606,726
def is_input_op(node): """Return true when the node is the input of the graph.""" return node.WhichOneof("op_type") == "input_conf"
294f5f1b785bb4ac26be8f7d9cacde2a26e73ce6
373,155
def is_fq(name): """Return True if the supplied 'name' is fully-qualified, False otherwise. Usage examples: >>> is_fq('master') False >>> is_fq('refs/heads/master') True :name: string name of the ref to test :returns: bool """ return name.startswith('refs/')
e603920b192caa4e72d7f265dac72761cf2d6611
226,635
import time from datetime import datetime def format_date(timestamp, precision=0): """ Construct an ISO 8601 time from a timestamp. There are several possible sources for *timestamp*. - time.time() returns a floating point number of seconds since the UNIX epoch of Jan 1, 1970 UTC. - time.localtime(time.time()) returns a time tuple for the current time using the local time representation. - datetime.datetime.now() returns a datetime object for the current time using the local time representation, but with no information about time zone. - iso8601.parse_date(str) returns a datetime object for a previously stored time stamp which retains time zone information. In the first three cases the formatted date will use the local time representation but include the UTC offset for the local time. The fourth case the UTC offset of the time stamp will be preserved in formatting. If *precision* is given, encode fractional seconds with this many digits of precision. This only works if *timestamp* is datetime object or seconds since epoch. """ dt = None microsecond = 0 # Try converting from seconds to time_struct try: microsecond = int(1000000*(timestamp-int(timestamp))) timestamp = time.localtime(timestamp) except TypeError: # Not a floating point timestamp; could be datetime or time_struct pass # Try converting from datetime to time_struct if isinstance(timestamp, datetime): microsecond = timestamp.microsecond tz = timestamp.utcoffset() if tz is not None: dt = tz.days*86400 + tz.seconds timestamp = timestamp.timetuple() # Find time zone offset isdst = timestamp.tm_isdst if timestamp.tm_isdst >=0 else 0 if dt is None: dt = -(time.timezone,time.altzone)[isdst] # Do the formatting local = time.strftime('%Y-%m-%dT%H:%M:%S',timestamp) sign = "+" if dt >= 0 else "-" offset = "%02d:%02d"%(abs(dt)//3600,(abs(dt)%3600)//60) fraction = ".%0*d"%(precision,microsecond//10**(6-precision)) if precision else "" return "".join((local,fraction,sign,offset))
305e001bef5aa91d2524e152552073413d974577
75,768
from functools import reduce def rank(B, S): """Return the rank of the subset S in base set B.""" return reduce(lambda a,b: a | b, [1 << (i if type(B) == int else B[1][i]) for i in S], 0)
fa81b882f27bb3bd0505c00b05dbe16653ff1927
150,961
def typed_property(name, expected_type): """Common function used to creating arguments with forced type :param name: name of attribute :param expected_type: expected type of attribute value :return: property attribute """ private_name = '_' + name @property def prop(self): return getattr(self, private_name) @prop.setter def prop(self, value): if not isinstance(value, expected_type): raise TypeError('Expected {}'.format(expected_type)) setattr(self, private_name, value) return prop
d1cc4dd8ea01d2d32efeffe28dea3236b8ab30c2
33,156
def sign(l): """ :param l: ordered list of indices :type l: list (or similar) :return: sign of l Compute the sign of an ordered list (-1 for each flip needed to get to ascending order) """ res = 1 for i in range(len(l)): for j in range(i + 1, len(l)): if l[i] > l[j]: res *= -1 return res
f11a8ed5e8f6b01fb443c69aedb50e91e22dd4c5
458,802
import torch def attention_bias(inputs, mode, inf=-1e20): """ A bias tensor used in attention mechanism :param inputs: A tensor :param mode: either "causal" or "masking" :param inf: A float, denoting an inf value :returns: A tensor with shape [batch, heads, queries, memories] """ if mode == "causal": result = torch.triu(torch.ones([inputs, inputs]), diagonal=1) * inf return result.reshape([1, 1, inputs, inputs]) elif mode == "masking": result = (1.0 - inputs.float()) * inf return result.unsqueeze(1).unsqueeze(1) else: raise ValueError("Unknown mode %s" % mode)
c3e69d8c86b36d38ddc7fcad76013781f191223a
266,707
def iou(polygon_1,polygon_2): """ Calculate intercept over union for shapely polygons. Args: polygon_1 polygon_2 Returns: intercept over union """ area_intersection = polygon_1.intersection(polygon_2).area area_polygon_1_polygon_2 = polygon_1.union(polygon_2).area iou = area_intersection/(area_polygon_1_polygon_2) * 100 return iou
14d9bac353466abe1556393e2d33862e40e99225
534,474
def get_number(key, row): """Reads a number from a row (assume all as float).""" if key in row and row[key]: return float(row[key]) else: return None
b0519ef90cdce3da49588c14887dc74113d542a2
256,240
def get_test_object_names(obj): """ Returns all attribute names that starts with "test_" """ ret = [] for o in dir(obj): if o.startswith("test_"): ret.append(o) return ret
ca22389234fdf98c1ec0405fa4871926f0c7165c
547,944
def get_cpu_mask(cores): """Return a string with the hex for the cpu mask for the specified core numbers.""" mask = 0 for i in cores: mask |= 1 << i return '0x{0:x}'.format(mask)
8034506756c5db0706070cefd6f231586cc816e2
535,596
def interval_to_milliseconds(interval): """Convert a Binance interval string to milliseconds :param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: int value of interval in milliseconds None if interval prefix is not a decimal integer None if interval suffix is not one of m, h, d, w """ seconds_per_unit = { "m": 60, "h": 60 * 60, "d": 24 * 60 * 60, "w": 7 * 24 * 60 * 60, } try: return int(interval[:-1]) * seconds_per_unit[interval[-1]] * 1000 except (ValueError, KeyError): return None
ab1745a846f7536e4e2c0c91dc482d754fa3d7f3
282,594
def get_id(corpus, key): """ Get the corpus ID of a word (handle utf-8 encoding errors, following change https://github.com/vered1986/LexNET/pull/2 from @gossebouma) :param corpus: the corpus' resource object :param key: the word :return: the ID of the word or -1 if not found """ id = -1 # the index of the unknown word try: id = corpus.get_id_by_term(key.encode('utf-8')) except UnicodeEncodeError: pass return id
84cfd2a12952ef1be984001304ad5c7c3ce161f2
549,440
from typing import Any from typing import Literal def _return_true(*_: Any) -> Literal[True]: """Always return true, discarding any arguments""" return True
a72e74ecc942a36d472bae7e957a7a6fb0879403
48,682
def caption_fmt(caption): """ Format a caption """ if caption: return "\n== {} ==\n".format(caption) return ""
e6e94efa5f16f9b0590e912e68ee1e3acfb4d54a
41,712
def task_exists(twarrior, task_name: str) -> bool: """ Check if task exists before inserting it in Task Warrior. """ tasks = twarrior.load_tasks() for key in tasks.keys(): for task in tasks[key]: if task['description'] == task_name: return True return False
1a5dbd790b11492c7417b7611c7f62af544a7862
36,471
def result_to_metrics(result): """Specific for the result dictionary of simpletransformers binary classification, which is a dictionary including keys: `tp`, `fp`, `tn`, and `fn`. TP = True Positive FP = False Positive TN = True Negative FN = False Negative accuracy = (TP + TN) / (TP + FP + TN + FN) precision = TP / (TP + FP) recall = TP / (TP + FN) :returns accuracy, precision, recall """ accuracy = (result['tp'] + result['tn']) / (result['tp'] + result['fp'] + result['tn'] + result['fn']) positives = result['tp'] + result['fp'] if positives > 0: precision = result['tp'] / (result['tp'] + result['fp']) else: # If there are no positives, we set the precision to 1 precision = 1.0 labeled_positives = result['tp'] + result['fn'] if labeled_positives > 0: recall = result['tp'] / (result['tp'] + result['fn']) else: # If there are no labelled positives, we set the recall to 1 recall = 1.0 if precision + recall > 0: f1 = (2 * precision * recall) / (precision + recall) else: f1 = 0.0 return accuracy, precision, recall, f1
03fc76c88d3468d5ff518ae90ecba7db61ff947d
458,175
import click def detect_config_version(config): """Return version of an slo-generator config based on the format. Args: config (dict): slo-generator configuration. Returns: str: SLO config version. """ if not isinstance(config, dict): click.secho( 'Config does not correspond to any known SLO config versions.', fg='red') return None api_version = config.get('apiVersion', '') kind = config.get('kind', '') if not kind: # old v1 format return 'v1' return api_version.split('/')[-1]
26cb4d7ae7eba981e456dc8f9201df719f720896
16,407
import yaml def read_config(file_name="config.yaml"): """Read configurations. Args: file_name (str): file name Returns: configs (dict): dictionary of configurations """ with open(file_name, 'r') as f: config = yaml.safe_load(f) return config
51faf47b4c28d1cbf80631d743d9087430efb148
14,643
import json def _GenerateCopyCommand(from_path, to_path, comment=None): """Returns a Dockerfile entry that copies a file from host to container. Args: from_path: (str) Path of the source in host. to_path: (str) Path to the destination in the container. comment: (str) A comment explaining the copy operation. """ cmd = "COPY {}\n".format(json.dumps([from_path, to_path])) if comment is not None: formatted_comment = "\n# ".join(comment.split("\n")) return "# {}\n{}".format(formatted_comment, cmd) return cmd
c1c5fb832cbde60f4ebed675b231a15166159673
639,044
def dice_name_from_cost(cost: str) -> str: """Given a string like `magic:face` returns just `magic`""" return cost.split(":")[0]
e72a9ed41b257c17e38d7b46f1ca19856d8bdb43
531,429
import inspect def monkeypatch_methods(monkeypatch): """Monkeypatch all methods from `cls` onto `target`. This utility lets you easily mock multiple methods in an existing class. In case of classmethods the binding will not be changed, i.e. `cls` will keep pointing to the source class and not the target class. """ def _monkeypatch_methods(target, cls): for name, method in inspect.getmembers(cls, inspect.ismethod): if method.__self__ is None: # For unbound methods we need to copy the underlying function method = method.__func__ monkeypatch.setattr(f'{target}.{name}', method) return _monkeypatch_methods
d3139c55831e03bc7a66d93a8fa81b1d3abcca4b
425,724
def is_fittable(data_form, layers_form): """ Return True if a fit problem (comprised of all its forms) is fittable or not. To be fittable, refl1d requires at least one free parameter. """ has_free = data_form.has_free_parameter() for layer in layers_form: has_free = has_free or layer.has_free_parameter() return has_free
51b5375f7f56087f780079d44326b8c987048165
382,781
def specframe2sample(frame, hop_size=3072, win_len=4096): """ Takes frame index (int) and returns the corresponding central time (sec) """ return frame * hop_size + win_len / 2
cffe9aca5d290368145aba2d5cc29b0e84f9696a
444,546
def meta_command(name, bases, attrs): """ Look for attrs with a truthy attribute __command__ and add them to an attribute __commands__ on the type that maps names to decorated methods. The decorated methods' doc strings also get mapped in __docs__. Also adds a method run(command_name, *args, **kwargs) that will execute the method mapped to the name in __commands__. """ commands = {} docs = {} for attr, value in attrs.items(): if getattr(value, '__command__', False): commands[attr] = value # methods have always have a __doc__ attribute, sometimes empty docs[attr] = (getattr(value, '__doc__', None) or 'perform the %s command' % attr).strip() attrs['__commands__'] = commands attrs['__docs__'] = docs def run(self, command, *args, **kwargs): return self.__commands__[command](self, *args, **kwargs) attrs.setdefault('run', run) return type(name, bases, attrs)
39ca4b4b7ffd9a09ba1e0715976d5a8c4c4b2b58
398,560
def gen_params(guess): """Return dict of parameters with guess string.""" return {'file': 'foo', 'signature': guess}
be82c04d61b1bf5115d65acc5fe08c23a0136619
332,496
from typing import Tuple def is_parent(parent_key: Tuple[str], key: Tuple[str]) -> bool: """Determines if keys have parent:child relationship. Example using dot notation: is_parent(a.b, a.b.c) == True is_parent(a.b, a.b.c.d) == True is_parent(a.b, a.x.y) == False """ return len(key) > len(parent_key) and key[: len(parent_key)] == parent_key
10f13f05fac3495ace654528aa0bb249d235d6d4
134,405
def asint(value): """Coerce to integer.""" if value is None: return value return int(value)
d6372f0e545b6e4923c8fecf74a0817fb56a5699
548,416
def formatFieldEqVal(fieldNames, sepStr = " and "): """Format a (field1=value1) and (field2=value2)... clause in the form used with a data dictionary. This is intended to help generate select commands. Inputs: - fieldNames: a list or other sequence of field names - sepStr: the string to separate field=value pairs. Example: sqlCmd = "select * from %s where %s" % (tableName, formatFieldEqVal(fieldNames)) dbCursor.execute(sqlCmd, dataDict) """ fmtFieldList = ["(%s=%%(%s)s)" % (fieldName, fieldName) for fieldName in fieldNames] return sepStr.join(fmtFieldList)
abb1ee3f9b4d2fc145cc4b34094226d367821f13
439,311
def f2hex(flo): """Convert floating point value `flo` (`0 <= f <=1`) to a zero-padded hex string.""" if not 0 <= flo <= 1: raise ValueError("value must be between 0 and 1 (inclusive)", flo) intval = round(255 * flo) return f"{intval:X}".zfill(2)
96d5f7d1635b348c2224dcd11e6490770765b8bc
469,535
def do_steps_help(cls_list): """Print out the help for the given steps classes.""" for cls in cls_list: print(cls.help()) return 0
19ce1585f915183fcb38c2ea268a6f30780830bb
689,001
def normalise_spaces(text: str) -> str: """Normalise spaces of arbitrary length to single spaces""" return " ".join([s.strip() for s in text.split(" ")])
28c3ee96ddf57173335dea2271bf922ccf8174cb
155,789
def _pop_all(kind, universe, iterable, validate=True): """ Removes all elements of 'iterable' from 'universe' and returns them. If 'validate' is true, then a ValueError is raised if a element would be removed multiple times, or if an element of 'iterable' does not appear in 'universe' at all. """ members = set() for elem in iterable: if validate and elem in members: raise ValueError("%s '%s' specified multiple times" % (kind, elem)) if elem in universe: universe.remove(elem) members.add(elem) elif validate: raise ValueError("Unrecognized %s '%s'" % (kind, elem)) return members
19843d6855270c35de2ff9c6e8a91e4f49c1e82d
191,778
def get_model_name(obj): """ Returns the name of the model """ return obj._meta.model_name
2a74e19aa618e759c06459c2ca8b577dffeef646
150,794
def get_destination_filename(path, prefix="t", overwrite=False): """ Get the output file name. :param pathlib.Path path: Destination path :param str prefix: prefix of filename. :param bool overwrite: if True then :return: file name for output :rtype: str """ if overwrite: name = path.name else: name = "-".join([prefix, path.name]) return name
af57d27b04fa1040fa0584ca7e6250101a32d77f
17,687
def num_in_row(board, row, num): """True if num is already in the row, False otherwise""" return num in board[row]
ca9ab9de4514740e25e0c55f3613d03b2844cdb8
708,225
import textwrap import itertools def rewrap(text, width=None): """ Rewrap text for output to the console. Removes common indentation and rewraps paragraphs according to the console width. Line feeds between paragraphs preserved. Formatting of paragraphs that starts with additional indentation preserved. """ if width is None: width = 80 # Remove common indentation. text = textwrap.dedent(text) def needs_wrapping(line): # Line always non-empty. return not line[0].isspace() # Split text by lines and group lines that comprise paragraphs. wrapped_text = "" for do_wrap, lines in itertools.groupby(text.splitlines(True), key=needs_wrapping): paragraph = ''.join(lines) if do_wrap: paragraph = textwrap.fill(paragraph, width) wrapped_text += paragraph return wrapped_text
a327e1828941422daa6f1f94cbbee14bb7433559
102,305
import re def extract_sentence_id(tag): """ Extract the sentence ID of current sentence. Args: tag (str): Sentence tag Returns: str: sentence ID """ if "<s" not in tag: return "" pattern = re.compile('id="[a-z0-9]+?"(?=\s)') res = re.findall(pattern, tag) if len(res) == 0: return None return res[0].replace('"', "").replace("id=", "")
99a24d332e21b5861c74b00fdcb334892eda4b7c
32,550
import math def euclidean_distance(p1, p2): """ Precondition: p1 and p2 are same length :param p1: point 1 tuple coordinate :param p2: point 2 tuple coordinate :return: euclidean distance between two points p1 and p2 """ distance = 0 for dim in range(len(p1)): distance += (p1[dim] - p2[dim])**2 return math.sqrt(distance)
e284e97f4cd92de55ea15b37f819301df007580a
191,214
def get_exception_kwargs(e): """ Extracts extra info (attributes) from an exception object. """ kwargs = {} for attr, value in vars(e).items(): if not attr.startswith('_') and attr not in ('args', 'message'): kwargs[attr] = value return kwargs
45b5a78c766c02ee49a3af4ed793a61025e9424a
46,396
def _str_to_int_or_float(val): """helper function that tries to cast a str to int and if that fails then tries casting to float""" try: val = int(val) except ValueError: val = float(val) return val
7139ef92b0cc9f0db14e7ca0d0af24b272d6e50d
504,878
def clean_styles(widget, styles) -> dict: """ Ensures safety while passing styles to tkinter objects. Normally tkinter objects raise errors for declaring styles that are not allowed for a given widget. This function takes in the styles dictionary and removes invalid styles for the particular widget returning the cleaned styles dictionary. As a bonus, duplicate definitions are overwritten. :param widget: :param styles: :return: dict cleaned_styles """ allowed_styles = widget.config() or {} cleaned_styles = {} for style in styles: if style in allowed_styles: cleaned_styles[style] = styles[style] return cleaned_styles
efe325a0cc202ac5deff38547822156b8b40fae0
581,430
def catch(func, *args, **kwargs): """ Call the supplied function with the supplied arguments, catching and returning any exception that it throws. Arguments: func: the function to run. *args: positional arguments to pass into the function. **kwargs: keyword arguments to pass into the function. Returns: If the function throws an exception, return the exception. If the function does not throw an exception, return None. """ try: func(*args, **kwargs) except Exception as e: return e
23aa157713090c26d69f98599c9ce0b41c947ccc
411,333
def aln_abuts_unknown_bases(tx, fasta): """ Do any exons in this alignment immediately touch Ns? :param tx: a GenePredTranscript object :param fasta: pyfasta Fasta object for genome :return: boolean """ chrom = tx.chromosome for exon in tx.exon_intervals: if exon.start == 0: # we are at the edge of the contig left_base = None else: left_base = fasta[chrom][exon.start - 1] if exon.stop >= len(fasta[chrom]): # we are at the edge of the contig right_base = None else: right_base = fasta[chrom][exon.stop] if left_base == 'N' or right_base == 'N': return True return False
ceb31739be0091b3b52f763c0c0d6d15b1aebd19
22,188
def tartaglia(n): """ Funzione per generare un triangolo di tartaglia. Parametri --------- n: int Altezza del triangolo da generare Output ------ triangolo: list of lists [[],[],[],...] Lista di liste, corrispondenti alle righe del triangolo di tartaglia. Esempio ------- >>> triangolo = tartaglia(4) >>> triangolo [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] """ triangolo = [] # Scrivere il proprio codice quì return triangolo
1dbb18879e565feef3405e533da492936d4a4b20
630,373
def auto_str(cls): """ Add implementation of __str__ and __repr__ functions to a class """ def __str__(self): return type(self).__name__ + '{' + ','.join(f'{k}={str(v)}' for k, v, in vars(self).items()) + '}' def __repr__(self): return type(self).__qualname__ + '{' + ','.join(f'{k}={repr(v)}' for k, v, in vars(self).items()) + '}' cls.__str__ = __str__ cls.__repr__ = __repr__ return cls
7b03f04b7091fa32fb813fa6c04aac44815e2ff3
304,617
def _columns(cursor, table): """Return the columns of a table as a list.""" cursor.execute(''' SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = %s ''', (table, )) return [column['column_name'] for column in cursor.fetchall()]
03544abe0980dfa00b366b38687f4795707b9385
615,876
from typing import Sequence from typing import Optional def sequence_find(hay: Sequence, needle: Sequence) -> Optional[int]: """ Return the index for starting index of a sub-sequence within a sequence. The function is intended to work similarly to the built-in `.find()` method for Python strings, but accepting all types of sequences (including different types for `hay` and `needle`). Example ******** .. code-block:: python >>> seqsim.common.sequence_find([1, 2, 3, 4, 5], [2, 3]) 1 :param hay: The sequence to be searched within. :param needle: The sub-sequence to be located in the sequence. :return: The starting index of the sub-sequence in the sequence, or `None` if not found. """ # Cache `needle` length and have it as a tuple already len_needle = len(needle) t_needle = tuple(needle) # Iterate over all sub-lists (or sub-tuples) of the correct length and check # for matches for i in range(len(hay) - len_needle + 1): if tuple(hay[i : i + len_needle]) == t_needle: return i return None
2601e73c4230292f558db4ad54e346a503f7ee43
566,347
def is_boolean(op): """ Tests whether an operation requires conversion to boolean. """ return op in ['or', 'and', '!']
5989c5db1befe76e61baa22a313b2d2e8f201553
659,748
def table(custom_headings, col_headings_formatted, rows, spec): """ Create a LaTeX table Parameters ---------- custom_headings : None, dict optional dictionary of custom table headings col_headings_formatted : list formatted column headings rows : list of lists of cell-strings Data in the table, pre-formatted spec : dict options for the formatter Returns ------- dict : contains key 'latex', which corresponds to a latex string representing the table """ longtables = spec['longtables'] table = "longtable" if longtables else "tabular" if custom_headings is not None \ and "latex" in custom_headings: latex = custom_headings['latex'] else: latex = "\\begin{%s}[l]{%s}\n\hline\n" % \ (table, "|c" * len(col_headings_formatted) + "|") latex += ("%s \\\\ \hline\n" % (" & ".join(col_headings_formatted))) for formatted_rowData in rows: if len(formatted_rowData) > 0: formatted_rowData_latex = [ (formatted_cell['latex'] if isinstance(formatted_cell, dict) else formatted_cell) for formatted_cell in formatted_rowData] latex += " & ".join(formatted_rowData_latex) #MULTI-ROW support for *data* (non-col-header) rows of table. Currently # unused (unneeded) - see multirow formatter that is commented out in formatters.py #multirows = [ ("multirow" in el) for el in formatted_rowData_latex ] #if any(multirows): # latex += " \\\\ " # last = True; lineStart = None; col = 1 # for multi,data in zip(multirows,formatted_rowData_latex): # if last == True and multi == False: # lineStart = col #line start # elif last == False and multi == True: # latex += "\cline{%d-%d} " % (lineStart,col) #line end # last=multi # res = _re.search("multicolumn{([0-9])}",data) # if res: col += int(res.group(1)) # else: col += 1 # if last == False: #need to end last line # latex += "\cline{%d-%d} "%(lineStart,col-1) # latex += "\n" #else: latex += " \\\\ \hline\n" latex += "\end{%s}\n" % table return {'latex': latex}
0ca28fce26fc7476aa5b88a621c5476ae8d381ce
1,213
import pickle def load_ddata(path, num): """ Load data for defender. Input: - path: path to pickled file - num: number of (source,target) pairs Return: graph, target nodes, community assignment, source nodes """ with open(path, "rb") as f: data = pickle.load(f) graph = data["graph"] targets = { "random": data["targets_random"][:num], "degree": data["targets_degree"][:num], "community": data["targets_community"][:num], } sources = data["sources"][:num] node_com = data["node_com"] return graph, targets, sources, node_com
bbda82c773888b3534907f93f6312b55e7c34f4b
153,180
from datetime import datetime def better_time(text): """Convert the time format to a better format""" dt = datetime.strptime(text, '%a %b %d %H:%M:%S %z %Y') return dt.strftime('%c')
5b5f7efa94e07d32956cfbeee6536b8a55c4b1cd
431,525
def _convert_ketone_unit(raw_value): """Convert raw ketone value as read in the device to its value in mmol/L.""" return int((raw_value + 1) / 2.) / 10.
804d34ecc9d901f3d958ebee34282885248c3499
697,361
import torch from typing import Tuple def sigmoid_soft_top_k( logits: torch.Tensor, k: int, tau: float, ) -> Tuple[torch.Tensor, torch.Tensor]: """Calculate soft top k mask using a sigmoid function. Args: logits: Parameters used for weighting. k: Number of elements that should be selected. tau: Temperature that is used to vary steepness of sigmoid function. Returns: mask: Soft top k mask that can be used to select k elements. x0: Exactly k (normalized) logits are larger than x0. (Useful to gain insight in logits.) """ if k == len(logits): # Not doing anything return torch.ones_like(logits), torch.zeros( 1, device=logits.device, ) std, mean = torch.std_mean(logits) logits = (logits - mean) / torch.maximum(std, torch.tensor(1e-3)) # Find splitter value: k values are >=q q = 1 - k / len(logits) x0 = torch.quantile(logits, q).detach() # Center and stretch depending on temperature tau logits = (logits - x0) / tau return torch.sigmoid(logits), x0.detach()
e46726760d2c496e8eb34c34282a3bf9dd91f6d7
197,022
def _parse_restriction_split(source_object, restriction_split, search_low_dbnum, search_high_dbnum): """ Parses a split restriction string and sets some needed variables. Returns a tuple in the form of: (low dbnum, high dbnum) """ restriction_size = len(restriction_split) if restriction_size >= 2: try: search_low_dbnum = int(restriction_split[1].strip()) except ValueError: source_object.msg("Invalid value for low dbref limit.") return False if restriction_size >= 3: try: search_high_dbnum = int(restriction_split[2].strip()) except ValueError: source_object.msg("Invalid value for high dbref limit.") return False return search_low_dbnum, search_high_dbnum
bca959a7ab8a37f4c261e25fabfbd76e956f5cf6
352,522
def open_file(file_path, read_mode="r"): """ Opens a file from the OS and reads it to cast it to string. Args: file_path (str): OS file path of the archive; read_mode (str): read mode. Returns: (str): the file contents as a string. """ with open(file_path, read_mode) as myfile: file_txt = myfile.read() return file_txt
333297ed76b663872e6588dd5d495f27326d493d
449,912
def generate_bps(perturbator, t): """Generate a motion perturbation field by using the method described in :cite:`BPS2006`. Parameters ---------- perturbator : dict A dictionary returned by initialize_motion_perturbations_bps. t : float Lead time for the perturbation field (minutes). Returns ------- out : ndarray Array of shape (2,m,n) containing the x- and y-components of the motion vector perturbations, where m and n are determined from the perturbator. See also -------- pysteps.noise.motion.initialize_bps """ vsf = perturbator["vsf"] p_par = perturbator["p_par"] p_perp = perturbator["p_perp"] eps_par = perturbator["eps_par"] eps_perp = perturbator["eps_perp"] V_par = perturbator["V_par"] V_perp = perturbator["V_perp"] g_par = p_par[0] * pow(t, p_par[1]) + p_par[2] g_perp = p_perp[0] * pow(t, p_perp[1]) + p_perp[2] return (g_par * eps_par * V_par + g_perp * eps_perp * V_perp) / vsf
481ac1f8c48d06ef7b1e05eca7fa4b89e6c65238
320,553
from typing import Any def equals(check_value: Any, item: Any) -> bool: """Check if two values are equal. :param check_value: Value to check. :type check_value: Any :param item: Item to check against. :type item: Any :return: Bool of comparison. :rtype: bool """ return check_value == item
960fa68702f0ead68d6c64d55c863546db06e92a
315,668
def convert_adsorption_energy_units(AE): """Converts the adsorption energy into units of KJ/mol Parameters ---------- AE : :py:attr:`array_like` array of adsorption energies Returns ------- :py:attr:`array_like` array of adsorption energies in units of KJ/mol """ return (AE * 96.485 * 1000)
f447f6b1e5edae12e293a5c06983ee625cc67296
407,580