content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def seconds_to_str(value: int) -> str: """Convert seconds to a simple simple string describing the amount of time.""" mins, secs = divmod(value, 60) hours, mins = divmod(mins, 60) if value < 60: return f"{secs} second{'s' if secs != 1 else ''}" elif value < 3600: return f"{mins} minute{'s' if mins != 1 else ''}" else: return f"{hours} hour{'s' if hours != 1 else ''} and {mins} minute{'s' if mins != 1 else ''}"
64fb7d97ee1a914aa47edce5d478c3c763b11756
387,145
def count_None(seq): """Returns the number of `None` in a list or tuple Parameters ---------- seq : list or tuple input sequence Returns ------- num : integer number of `None` in the sequence """ return sum(i is None for i in seq)
f3d6621175ad60de4a6c9a007d241cad95367064
433,455
def filter_code_block(inp: str) -> str: """Returns the content inside the given Markdown code block or inline code.""" if inp.startswith("```") and inp.endswith("```"): inp = inp[3:][:-3] elif inp.startswith("`") and inp.endswith("`"): inp = inp[1:][:-1] return inp
2ed3eb692d251b526b21f858d4d8e72634f63758
174,146
def payloadDictionary(payload, lst): """creates payload dictionary. Args: payload: String SQL query lst: List of Strings keywords for payload dictionary Returns: dikt: dictionary dictionary using elements of lst as keys and payload as value for each key """ dikt = {} for i in lst: dikt[i] = payload return dikt
2b674dde0cbb8e898d821c28c92f54cab891dbf1
433,898
from datetime import datetime def parse_timestamp(timestamp): """ :param timestamp: float (common timestamp) :return: datetime--object that is computed using the passed timestamp """ dt_object = datetime.fromtimestamp(timestamp) return dt_object
fcf770711cf0c747ae1dfd6004e6b5388707def0
80,414
def calculate_maximum_speedup(n: int, f: float) -> float: """ Utilizes Amdahl's Law to calculate the maximum possible speedup. Parameters ---------- n: int The number of processors on the specific machine. f: float The fraction of the program/code/calculation that must be executed serially/sequentially. Raises ---------- ValueError If f < 0 or f > 1, or if n <= 0. """ if n <= 0: raise ValueError("n must be positive!") elif (f < 0) or (f > 1): raise ValueError("f must be within the closed unit interval!") max_speedup = 1 / (f + ((1 - f) / n)) return max_speedup
6cf320aa95320a9f3e9633c1a93fb0fc5f4b3224
500,414
def parse_time(timestring): """ Given a string of the format YYYY-MM-DDTHH:MM:SS.SS-HH:MM (and optionally a DST flag), convert to and return a numeric value for elapsed seconds since midnight (date, UTC offset and/or decimal fractions of second are ignored). """ date_time = timestring.split('T') # Separate into date and time hour_minute_second = date_time[1].split('+')[0].split('-')[0].split(':') return (int(hour_minute_second[0]) * 3600 + int(hour_minute_second[1]) * 60 + int(hour_minute_second[2].split('.')[0]))
7b4adbe36fbd5fd8f484b1e0b346c9673183e555
613,562
def python_3000_has_key(logical_line): """ The {}.has_key() method will be removed in the future version of Python. Use the 'in' operation instead, like: d = {"a": 1, "b": 2} if "b" in d: print d["b"] """ pos = logical_line.find('.has_key(') if pos > -1: return pos, "W601 .has_key() is deprecated, use 'in'"
1be1f91c6f52960b138ae05297b0b7f9b5123dc0
645,301
def is_file_format(file_name, file_extensions): """ Checks whether the extension of the given file is in a list of file extensions. :param file_name: Filename to check :param file_extensions: File extensions as a list :returns: True if the list contains the extension of the given file_name """ file_extension = file_name.split('.')[-1] return file_extension in file_extensions
5d8afd55cb618662e5db9e619252d50cd88a4d81
562,217
def is_leap_year(year): """Returns whether a given year was a leap year""" # "There is a leap year every year whose number is perfectly divisible by four - # except for years which are both divisible by 100 and not divisible by 400." # quoted from Western Washington University # https://www.wwu.edu/astro101/a101_leapyear.shtml if year % 100 == 0: # if year is a century year, an additional check is required (see above) if year % 400 == 0: # centuries must also be divisible by 400 return True return False if year % 4 == 0: return True return False
658106b2151bbdd4c126517472ee9c8147a3e8a8
236,598
def variance(rv, *args, **kwargs): """ Returns the variance `rv`. In general computed using `mean` but may be overridden. :param rv: RandomVariable """ return rv.variance(*args, **kwargs)
479175f7c101612ea14cef7caf3c5876c2714987
42,828
def argparse_bool(s): """ parse the string s to boolean for argparse :param s: :return: bool or None by default example usage: parser.add_argument("--train", help="train (finetune) the model or not", type=mzutils.argparse_bool, default=True) """ if not isinstance(s, str): return s if s.lower() in ('yes', 'y', 't', 'true', 1): return True elif s.lower() in ('no', 'n', 'f', 'false', 0): return False else: return None
3c2c0a45d58fe5aa693647b3023644b8ca1047ad
349,593
def norm_filters(weights, p=1): """Compute the p-norm of convolution filters. Args: weights - a 4D convolution weights tensor. Has shape = (#filters, #channels, k_w, k_h) p - the exponent value in the norm formulation """ assert weights.dim() == 4 return weights.view(weights.size(0), -1).norm(p=p, dim=1)
036c9af69aa2bf930911cdc1775fd0aafd980a93
117,190
import io def is_file_obj(o): """Test if an object is a file object""" return isinstance(o, (io.TextIOBase, io.BufferedIOBase, io.RawIOBase, io.IOBase))
94437b1bd758ae0fcc8a274a7366f01c93c8ee85
80,568
def update_max_depth(depth_node_dict): """ Maximum tree depth update. Input: - depth_node_dict: A map from node depth to node ids as a python dictionary. Output: - max_depth: The maximum depth of the tree. """ max_depth = max(depth_node_dict.keys()) return max_depth
0ab7fd3bfca6f3ea70c374e113adcc3d65b541e0
550,363
def merge_dict_tree(a, b): """Merge two dictionaries recursively. The following rules applied: - Dictionaries at each level are merged, with `b` updating `a`. - Lists at the same level are combined, with that in `b` appended to `a`. - For all other cases, scalars, mixed types etc, `b` replaces `a`. Parameters ---------- a, b : dict Two dictionaries to merge recursively. Where there are conflicts `b` takes preference over `a`. Returns ------- c : dict Merged dictionary. """ # Different types should return b if type(a) != type(b): return b # From this point on both have the same type, so we only need to check # either a or b. if isinstance(a, list): return a + b # Dict's should be merged recursively if isinstance(a, dict): keys_a = set(a.keys()) keys_b = set(b.keys()) c = {} # Add the keys only in a... for k in keys_a - keys_b: c[k] = a[k] # ... now the ones only in b for k in keys_b - keys_a: c[k] = b[k] # Recursively merge any common keys for k in keys_a & keys_b: c[k] = merge_dict_tree(a[k], b[k]) return c # All other cases (scalars etc) we should favour b return b
b3822fb59706bad679bd6e9370ad68cbc66039b1
374,045
def _dms2dd(degrees, minutes, seconds): """Helper method for converting degrees, minutes, seconds to decimal. Args: degrees (int): Lat/Lon degrees. minutes (int): Lat/Lon minutes. seconds (int): Lat/Lon seconds. Returns: float: Lat/Lon in decimal degrees """ decimal = degrees + float(minutes) / 60.0 + float(seconds) / 3600.0 return decimal
88a576b47184b274e5ee820238675ce0190a8248
190,621
from dateutil import tz def dt_as_utc(dt): """Convenience wrapper, converting the datetime object dt to UTC.""" if dt is None: return None return dt.astimezone(tz.tzutc())
c148d2dc3d8164324661ff6f4f070c49b6406ac7
57,721
def _label_suffix(label: str, suffix: str) -> str: """Returns (label + suffix) or a truncated version if it's too long. Parameters ---------- label : str Label name suffix : str Label suffix """ if len(label) > 50: nhead = 25 return "".join([label[:nhead], "..", suffix]) else: return label + suffix
de2ea748c97af55b96cb81eca47c94ab1f712125
375,965
def wrap_commands_in_shell(ostype, commands): """Wrap commands in a shell :param list commands: list of commands to wrap :param str ostype: OS type, linux or windows :rtype: str :return: a shell wrapping commands """ if ostype.lower() == 'linux': return '/bin/bash -c \'set -e; set -o pipefail; {}; wait\''.format( ';'.join(commands)) elif ostype.lower() == 'windows': return 'cmd.exe /c "{}"'.format('&'.join(commands)) else: raise ValueError('unknown ostype: {}'.format(ostype))
abc8a72494e1ed24aefd46f0a7ed7ae79bc97d40
525,359
def concat_name(first_name: str, last_name: str) -> str: """Return new string 'last_name, first_name'.""" return f"{last_name}, {first_name}"
981ab94041f53a5eacda6f0386d30c751fc2c5b4
348,956
def sse_pack(event_id: int, event: str, data: int, retry: str = "2000") -> str: """Pack data in Server-Sent Events (SSE) format.""" return f"retry: {retry}\nid: {event_id}\nevent: {event}\ndata: {data}\n\n"
075d7f58248b72a5835c6b9b65332fbcb799f2a8
689,427
import re def processed_string_data(sentence): """replace " with ' Args: sentence (str): string of characters Returns: str: original string put in "" with all internal " replaced with ' """ return '"{}"'.format(re.sub("\"", "'", sentence))
5e7b3301413b42ab3dbf38d568d5d19736617596
243,670
from bs4 import BeautifulSoup def find_forms(soup: BeautifulSoup): """ Returns a list of forms found on a particular webpage """ return soup.findAll('form')
2e6922b57f33a42d8cbe98c33a8507b26bf4026b
289,240
def impute_loan_term(data): """ Imputes loan term value with the mean loan term. """ data['Loan_Amount_Term'] = data['Loan_Amount_Term'].fillna(data['Loan_Amount_Term'].mean()) data['Loan_Amount_Term'] = data['Loan_Amount_Term']/12 return data
6810360dfb88a54dba1af37287c32c5e3a618a8b
280,345
from typing import List def flatten_list(my_list: List[List]) -> List: """ Flatten a list of list :param l: list of list :return: list """ return [item for sublist in my_list for item in sublist]
0c33e3ca968d3038e13a4949f70e2de5b0f2521a
469,947
def is_reply(tweet: dict): """Return True if the passed tweet is a reply. :param tweet: JSON dict for tweet """ if tweet["tweet"]["in_reply_to_screen_name"]: return True return False
b486eac4c38af91e9972af3799f7c6984082bc41
338,917
def get_vm_resource_id(subscription_id=None, resource_group=None, vm_name=None): """ Return full resource ID given a VM's name. """ return "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}".format(subscription_id, resource_group, vm_name)
ab6ae0b9142c4ae6ffc228e7adc3fc63acdf44d7
377,310
def recursive_binomial_coefficient(n, k): """Calculates the binomial coefficient, C(n,k), with n>=k using recursion Time complexity is O(k), so can calculate fairly quickly for large values of k. >>> recursive_binomial_coefficient(5,0) 1 >>> recursive_binomial_coefficient(8,2) 28 >>> recursive_binomial_coefficient(500,300) 5054949849935535817667719165973249533761635252733275327088189563256013971725761702359997954491403585396607971745777019273390505201262259748208640 """ if k > n: raise ValueError("Invalid Inputs, ensure that n >= k") # function is only defined for n>=k if k == 0 or n == k: # C(n,0) = C(n,n) = 1, so this is our base case. return 1 if k > n / 2: # C(n,k) = C(n,n-k), so if n/2 is sufficiently small, we can reduce the problem size. return recursive_binomial_coefficient(n, n - k) else: # else, we know C(n,k) = (n/k)C(n-1,k-1), so we can use this to reduce our problem size. return int((n / k) * recursive_binomial_coefficient(n - 1, k - 1))
07af2d622d91228eb370d6074c43702c10fdede6
665,572
def map_url_to_job_config(url, config_mapping): """Return job name and config of the longest matching URL in the config mapping.""" job_name, job_config = (None, None) match_length = 0 for candidate_url, match in config_mapping.items(): if url.startswith(candidate_url) and len(candidate_url) > match_length: job_name, job_config = match match_length = len(candidate_url) return job_name, job_config
3922157307debf5401160aa00dfa42e36d562775
536,397
from networkx import get_edge_attributes def uninformative_prediction(G, required_links): """ Function to predict links in an uninformative manner, i.e., the majority parity. So, if there are more positive links that negative links, then a positive link is predicted and vice-versa Args: G : Graph to consider as training data required_links : List of tuples (a, b) where (a, b) denotes the outgoing edge from `a` to `b`. Returns: List of {+1, -1} based on the properties of the graph """ edges_weights = list(get_edge_attributes(G, 'weight').values()) edges_parity = [1 if w > 0 else -1 for w in edges_weights] if sum(edges_parity) > 0: return [1 for _ in required_links] else: return [-1 for _ in required_links]
6f89b6703f8df7c42c3b03c85efea6b2d4318d81
666,617
def _operation_to_pooling_shape(operation): """Takes in the operation string and returns the pooling kernel shape.""" splitted_operation = operation.split('_') shape = splitted_operation[-1] assert 'x' in shape filter_height, filter_width = shape.split('x') assert filter_height == filter_width return int(filter_height)
997dad0b4613c3ca9a3bf21cd54c8b6344758235
382,773
import json import codecs def encode_blob(data): """ Encode a dictionary to a base64-encoded compressed binary blob. :param data: data to encode into a blob :type data: dict :returns: The data as a compressed base64-encoded binary blob """ blob_data = json.dumps(data).encode('utf8') for codec in ('zlib', 'base64'): blob_data = codecs.encode(blob_data, codec) return blob_data.replace(b'\n', b'')
266f0b6440adfae165a9d8d6877a111736e22488
678,060
def _nan_div(numerator, denominator): """Performs division, returning NaN if the denominator is zero.""" return numerator / denominator if denominator != 0 else float('NaN')
e3537b8f1721cddfd6e38e3628f0e19d94d966c9
337,616
def metalicity_jk_v_band(period, phi31_v): """ Returns the JK96 caclulated metalicity of the given RRab RR Lyrae. (Jurcsik and Kovacs, 1996) (3) (Szczygiel et al., 2009) (6) (Skowron et al., 2016) (1) Parameters ---------- period : float64 The period of the star. phi31_v : float64 The V band phi31 of the star. Returns ------- metalicity_jk_v : float64 The JK96 metalicity of the star. """ return -5.038 - 5.394 * period + 1.345 * phi31_v
fddd8e895372a68f1aaf96b4879155adb2cf0a8e
568,909
from operator import truediv def toratio(s): """Converts a pandas series of string to numeric ratios. Parameters -------------- s: pandas.Series of string Returns ---------- panda.Series of float """ return s.apply(lambda x: truediv(*[int(y) for y in x.split('/')]))
14594ea84478d0b2cbd8eab28f6810c628b02464
193,059
def optimal_noverlap(win_name,win_len): """ This function is intended to support scipy.signal.stft calls with noverlap parameter. :param win_name: (str) name of the window (has to follow scipy.signal.windows naming) :param win_len: (int) lenght of the FFT window :return : (int) optimal overlap in points for the given window type """ window_to_overlap_coef = {'hann': 0.5, 'hamming': 0.75, 'blackmanharris': 0.75, 'blackman': 2/3, 'flattop': 0.75, 'boxcar': 0} try: noverlap = int(win_len*window_to_overlap_coef[win_name]) except KeyError as exc: print(exc) print('The window you have selected is not recognized or does not have optimal overlap. Setting window overlap to default 75%.') noverlap = int(win_len*0.75) return noverlap
d98db08a9e08b6639a38a324799d1141e65b1eb4
19,554
import random def get_random_variant(variants): """ selects a random element from the 'variants' list """ return random.sample(variants,1)[0] # string #return get_1st_variant(variants)
505c098761fda5c0fb66c531dc5ccda4ebeea2e0
325,968
import functools def RequireAuth(handler): """Decorator for webapp2 request handler methods. Only use on webapp2.RequestHandler methods (e.g. get, post, put), and only after using a 'Check____Auth' decorator. Expects the handler's self.request.authenticated to be not False-ish. If it doesn't exist or evaluates to False, 403s. Otherwise, passes control to the wrapped handler. """ @functools.wraps(handler) def wrapper(self, *args, **kwargs): """Does the real legwork and calls the wrapped handler.""" if not getattr(self.request, 'authenticated', None): self.abort(403) else: handler(self, *args, **kwargs) return wrapper
edb8f223318d0b22511d6307ed6c35bc83a4ae4a
19,259
from typing import Tuple def __check_for_newline(line: str, pos: int) -> Tuple[bool, int]: """Check if line is newline. Args: line: line. pos: current position. Returns: bool and current position. """ saw_newline = False while pos < len(line) and line[pos].isspace(): if line[pos] == '\n': saw_newline = True pos += 1 return saw_newline, pos
461adcf7d37be95a41df073e474544c1891ae8b3
597,263
import ast def string_to_dictionary(string): """ Converts a dictionary string representation into a dictionary :param string: str :return: dict """ return ast.literal_eval(string)
3024a15ebcb615500bff7f5cc2728e1d71adae04
188,205
import re def stripXML(text): """ Remove XML annotation from a string. """ text = re.sub(r'<[^>]*>', '', text) text = re.sub(r'\s+', ' ', text) text = text.strip() return text
41204d697bd986a51c9b1bf28ac0fae1813b0a33
606,556
def ext_valid_update_path(cursor, ext, current_version, version): """ Check to see if the installed extension version has a valid update path to the given version. A version of 'latest' is always a valid path. Return True if a valid path exists. Otherwise return False. Args: cursor (cursor) -- cursor object of psycopg2 library ext (str) -- extension name current_version (str) -- installed version of the extension. version (str) -- target extension version to update to. A value of 'latest' is always a valid path and will result in the extension update command always being run. """ valid_path = False params = {} if version != 'latest': query = ("SELECT path FROM pg_extension_update_paths(%(ext)s) " "WHERE source = %(cv)s " "AND target = %(ver)s") params['ext'] = ext params['cv'] = current_version params['ver'] = version cursor.execute(query, params) res = cursor.fetchone() if res is not None: valid_path = True else: valid_path = True return (valid_path)
68cab905811904d6f8a8421fc409efe7f7e8703f
396,779
def runtime_enabled_function(name): """Returns a function call of a runtime enabled feature.""" return 'RuntimeEnabledFeatures::%sEnabled()' % name
7269952d9a5b2f343e985b6c571a3a8cb896cb15
278,939
def remove_managed_variant(store, managed_variant_id): """Remove a managed variant.""" removed_variant = store.delete_managed_variant(managed_variant_id) return removed_variant
b6e4af712b276d30d7b27ba0210316132fcf8ba4
114,409
from typing import Any import torch def move_to(obj: Any, device: torch.device): """Credit: https://discuss.pytorch.org/t/pytorch-tensor-to-device-for-a-list-of-dict/66283 Arguments: obj {dict, list} -- Object to be moved to device device {torch.device} -- Device that object will be moved to Raises: TypeError: object is of type that is not implemented to process Returns: type(obj) -- same object but moved to specified device """ if torch.is_tensor(obj) or isinstance(obj, torch.nn.Module): return obj.to(device) if isinstance(obj, dict): res = {k: move_to(v, device) for k, v in obj.items()} return res if isinstance(obj, list): return [move_to(v, device) for v in obj] if isinstance(obj, tuple): return tuple(move_to(list(obj), device)) return obj
9ed0ee66d2976aa0b17c0c0c060d6f29cf19f03f
110,254
import requests def request_issues(url): """Request issues from the given GitHub project URL. Parameters ---------- url : str URL of GitHub project. Returns ------- response : Response Response data. """ response = requests.get(url) return response
9f33675d687941873d9b401ddd381894b8cdb3e2
668,527
import math def ang_threep(a,b,c): """ Measures the angle formed by three points. The angle goes from 0 to 360. Point 'a' it's the anchord, and the measured angle it's the one that goes from 'b' to 'c' clockwise. """ ang = math.degrees(math.atan2(b[1]-a[1], b[0]-a[0]) - math.atan2(c[1]-a[1], c[0]-a[0])) return ang + 360 if ang < 0 else ang
79b449509b83c484f1192c3947563844f1e51a5c
370,594
import math def approx_atmospheric_refraction(solar_elevation_angle): """Returns Approximate Atmospheric Refraction in degrees with Solar Elevation Angle, solar_elevation_angle.""" if solar_elevation_angle > 85: approx_atmospheric_refraction = 0 elif solar_elevation_angle > 5: approx_atmospheric_refraction = ( 58.1 / math.tan(math.radians(solar_elevation_angle)) - 0.07 / pow(math.tan(math.radians(solar_elevation_angle)), 3) + 0.000086 / pow(math.tan(math.radians(solar_elevation_angle)), 5) ) / 3600 elif solar_elevation_angle > -0.575: approx_atmospheric_refraction = ( 1735 + solar_elevation_angle * ( -518.2 + solar_elevation_angle * ( 103.4 + solar_elevation_angle * (-12.79 + solar_elevation_angle * 0.711) ) ) ) / 3600 else: approx_atmospheric_refraction = ( -20.772 / math.tan(math.radians(solar_elevation_angle)) ) / 3600 return approx_atmospheric_refraction
7c447bee72d385113c3e9d749c74e9e5788429e6
162,683
def NeededPaddingForAlignment(value, alignment=8): """Returns the padding necessary to align value with the given alignment.""" if value % alignment: return alignment - (value % alignment) return 0
e7e9cb58fc43b4c249758acf54a49a344c3d8034
600,523
def inner_p_s(u, v): """ Calculate the inner product space of the 2 vectors. """ s = 0 if len(u) != len(v): s = -1 else: for i in range(len(u)): s += u[i]*v[i] return s
cee6fa97ea8604d911985eba67570b6887a42b7e
330,256
def _first_paragraph(doc: str) -> str: """Get the first paragraph from a docstring.""" paragraph, _, _ = doc.partition("\n\n") return paragraph
4d20e54eba1068e76e59d30316aada9d1c600e6d
196,474
def scale_to_range(min_max_old, element, min_max_new=[0, 10]): """Scale element from min_max_new to the new range, min_max_old. Args: min_max_old: Original range of the data, [min, max]. element: Integer that will be scaled to the new range, must be within the old_range. min_max_new: New range of the data. Returns: element scaled to the new range. """ new_range = min_max_new[1] - min_max_new[0] old_range = min_max_old[1] - min_max_old[0] return ((element - min_max_old[0]) * new_range) / old_range
263f08a7247af4feea9f498bd2ac2a129f949556
670,526
def chocolate_feast(n, c, m): """Hackerrank Problem: https://www.hackerrank.com/challenges/chocolate-feast/problem Function that calculates how many chocolates Bobby can purchase and eat. Problem stated below: Little Bobby loves chocolate. He frequently goes to his favorite 5&10 store, Penny Auntie, to buy them. They are having a promotion at Penny Auntie. If Bobby saves enough wrappers, he can turn them in for a free chocolate. For example, Bobby has n = 15 to spend on bars of chocolate that cost c = 3 each. He can turn in m = 2 wrappers to receive another bar. Initially, he buys 5 bars and has 5 wrappers after eating them. He turns in 4 of them, leaving him with 1, for 2 more bars. After eating those two, he has 3 wrappers, turns in 2 leaving him with 1 wrapper and his new bar. Once he eats that one, he has 2 wrappers and turns them in for another bar. After eating that one, he only has 1 wrapper, and his feast ends. Overall, he has eaten 5 + 2 + 1 + 1 = 9 bars. Args: n (int): Int representing Bobby's initial amount of money c (int): Int representing the cost of a chocolate bar m (int): Int representing the number of wrappers he can turn in for a free bar Returns: int: The number of chocolate bars Bobby can purchase and eat """ # We look for the candies + wrappers candies = n // c wrappers = n // c while wrappers >= m: wrappers -= m wrappers += 1 candies += 1 return candies
be400b13b15fbed6d21a95a7cbc35fd474ed7fb7
60,708
def first_not_none(*args): """Return first item from given arguments that is not None.""" for item in args: if item is not None: return item raise ValueError("No not-None values given.")
009619994339b3e7593cb8343e8d3e2eae959f0b
206,097
def _write_swift_version(repository_ctx, swiftc_path): """Write a file containing the current Swift version info This is used to encode the current version of Swift as an input for caching Args: repository_ctx: The repository context. swiftc_path: The `path` to the `swiftc` executable. Returns: The written file containing the version info """ result = repository_ctx.execute([swiftc_path, "-version"]) contents = "unknown" if result.return_code == 0: contents = result.stdout.strip() filename = "swift_version" repository_ctx.file(filename, contents, executable = False) return filename
55eae8cc8e5aa52ed35d0f3a564372292c2cc664
89,449
def X1X2_to_Xs(X1, X2): """Convert dimensionless spins X1, X2 to symmetric spin Xs""" return (X1+X2)/2.
9938f188d766d7895986b8796bb8eeeafe3b5b7d
29,174
import math def _toexponent(number): """ Formats exponent to PENELOPE format (E22.15) Args: number (Float): Number to format Returns: str: number to PENELOPE format (E22.15) """ if number == 0.0: exponent = 0 else: exponent = int(math.log10(abs(number))) if exponent >= 0: exponent_str = "+{:2d}".format(abs(exponent)) else: exponent_str = "-{:2d}".format(abs(exponent)) exponent_str = exponent_str.replace(" ", "0") # Replace white space in the exponent coefficient = float(abs(number)) / 10 ** exponent if number >= 0: number_str = "+{0:17.15f}E{1}".format(coefficient, exponent_str) else: number_str = "-{0:17.15f}E{1}".format(coefficient, exponent_str) # The number should not be longer than 22 characters assert len(number_str) == 22 return number_str
4f17f6c467ad309e372a506d5917cd9ed44c9e0e
540,174
def rotate_point(point: tuple, rotation: int, axis: int) -> tuple: """Rotate the point around the given axis, from the origin. Args: point (tuple): Coordinate tuple in the form (x,y,z) rotation (int): rotation ID. Indicating counter-clockwise rotation. 0 = no rotation, 1 = 90, 2 = 180, 3 = 270 axis (int): axis ID. 0 = x, 1 = y, 2 = z """ x, y, z = point if rotation == 0: pass elif rotation == 1: # 90 if axis == 0: # x y, z = -z, y # Rotation according to RH rule elif axis == 1: # y x, z = z, -x elif axis == 2: # z x, y = -y, x elif rotation == 2: # 180 if axis == 0: y, z = -y, -z elif axis == 1: x, z = -x, -z elif axis == 2: x, y = -x, -y elif rotation == 3: # 270 if axis == 0: y, z = z, -y elif axis == 1: x, z = -z, x elif axis == 2: x, y = y, -x return (x, y, z)
7d4c259049bd2b797c3e41fe8b84f5300f0c4817
233,812
from typing import Union from typing import Optional from pathlib import Path def check_for_project(path: Union[str, "Path"] = ".") -> Optional["Path"]: """Checks for a Brownie project.""" path = Path(path).resolve() for folder in [path] + list(path.parents): if folder.joinpath("brownie-config.json").exists(): return folder return None
026ccf715c7dbf9f1e7f3add2d84f7e661996928
674,590
import base64 def _decode(elem): """ Modifies transaction data with decoded version """ elem["tx_result"]["log"] = eval(elem["tx_result"]["log"]) events = elem["tx_result"]["events"] for event in events: for kv in event["attributes"]: k, v = kv["key"], kv["value"] kv["key"] = base64.b64decode(k).decode() kv["value"] = base64.b64decode(v).decode() return elem
06ae1243a0554509fa85742ecc9e388383071055
224,666
def delta_days(t0, t1): """Returns: time from `t0` to `t1' in days where t0 and t1 are Timestamps Returned value is signed (+ve if t1 later than t0) and fractional """ return (t1 - t0).total_seconds() / 3600 / 24
6a4c8a69fe1931454e77d2d684002600ca0525ed
425,273
def cget(mat, *i): """ Returns the column(s) '*i' of a 2D list 'mat' mat: matrix or 2D list *i: columns to extract from matrix NOTE: If one column is given, the column is returned as a list. If multiple columns are given, a list of columns (also lists) is returned """ if len(i) == 1: return [row[i[0]] for row in mat] else: return [[row[index] for row in mat] for index in i]
596e4ae985c55fe3046b84627138668e266e6707
544,857
import random def _random_tiebreak(winners, n=1): """ Given an iterable of possibly tied `winners`, select one at random. """ if len(winners) == 1: return winners else: return random.sample(winners, n)
0d24678a0eea7df9a880dfbdd0fba2d809f78894
226,374
def safe_get(mapping: dict, key, default=None): """ :param mapping: dictionary of key values :param key: key being searched for :param default: default value in case key was not present in the dict :return: default value if the key is not present in the mapping dictionary, else the value in the dict for the key """ if mapping is None or key not in mapping: return default return mapping[key]
e337f82958a0d384b963874298d870ec8e4cb5be
570,563
def get_int(db,key): """ Get integer value from redis database """ value_str = str(db.get(key)) return int(value_str)
b64bb2d74a3e4cc56b467989ee14f9beed47238d
143,404
def harmonic(n): """ Compute the n-th Harmonic number Compute Hn where Hn = 1 + 1/2 + 1/3 + ... + 1/n Parameters ---------- n : int n-th number Returns ------- hn harmonic number """ hn = 0 for i in range(1, n): hn += 1 / i return hn
cd4d870b66b5fc037c3b3c11b3c735e91c476c6b
51,077
import torch def toHWC(bchw : torch.Tensor): """ Converts a tensor in BxCxHxW to BxHxWxC """ return bchw.movedim((0,2,3,1), (0,1,2,3))
2f5c8a915dbef752392edd3d5f7e0e0fd512b813
246,655
import copy def even_spliter(total, inRange=[250, 500]): """ Splits the total into chunks where they are the size inRange ------ total: The value that needs to be split ------ inRange: List(min, max) min: The minimum value the split size needs to be max: The maximum split size before it needs to split more The algorithm is biased to the max split and will start to evenly split at the max first. """ splitRange = copy.deepcopy(inRange) while splitRange[1] >= splitRange[0]: if (total + splitRange[1]-1) % splitRange[1] >= splitRange[0]-1: splitList = [splitRange[1] for i in range(total//splitRange[1])] if total % splitRange[1] != 0: splitList.append(total % splitRange[1]) return splitList else: splitRange[1] -= 1 return [total]
6a0b94de1a1fb25766c09cab51801d8c8c173e42
471,940
def parse_range(entry, valid, default): """ parsing entries entry - value to check default - value if entry is invalid valid - valid range return - entry or default if entry is out of range """ if valid[0] <= entry <= valid[1]: result = entry else: result = default return result
0ddf60748c5b7c53e3861560e0262f6b763e5f7f
546,519
import inspect def get_unbound_fn(method_or_fn): """Return an unbound function from a bound method.""" if inspect.ismethod(method_or_fn): return method_or_fn.__func__ elif callable(method_or_fn): return method_or_fn else: raise ValueError('Expect a function or method.')
b82c279ac419df4278d4da4ec9c4ad903bd92e0b
124,966
def get_time(value): """Get a generic time in second and stored on a float value, with the 2 integer values Arguments: value -- Time to convert: [time sec, time microsecond] Return: float time in second """ return float(value[0]) + float(value[1])*0.000001
003ade1cb06a2f617541474d5e0d60546c786492
534,069
def get_class_def(class_name): """ Returns the definition for the given class name. """ parts = class_name.split('.') module = ".".join(parts[:-1]) mdl = __import__(module, globals=globals()) for comp in parts[1:]: mdl = getattr(mdl, comp) return mdl
e2e7c5bbf808815a5357a40f6d879f5043997cff
335,367
import torch def initial_inducing_points( train_data_loader, feature_extractor, args ): """ Initialises inducing points Shape: num_tasks X num_inducing_points X hidden_size """ inducing_points = [] for batch in train_data_loader: if len(inducing_points) > args.num_inducing_points: break mol_batch = batch.batch_graph() inducing_points.extend(feature_extractor(mol_batch)) inducing_points = torch.stack(inducing_points)[:args.num_inducing_points] print('number of inducing points =') print(len(inducing_points)) inducing_points = inducing_points.repeat(args.num_tasks,1,1) return inducing_points
fa0e74cc394d6ea05a89a3dc9906e7d65e79728c
519,820
from typing import Tuple def size2shape(size: int) -> Tuple[int, int]: """convert a plate size (number of wells) to shape (y, x)""" assert size in [384, 1536] return (16, 24) if size == 384 else (32, 48)
81795acc3992ff0d1b8b39997e8d60b19ea43db0
665,401
def get_accuracy(predictions, targets): """ Calculates the accuracy for a set of prediction and targets. predictions Softmax'ed output values of the network. targets One hot target vectors """ accuracy = (predictions.argmax(1).cpu().numpy() == targets.cpu().numpy()).sum()/(predictions.shape[0]) return accuracy
ea53cd79913b08cd10d4f1263890f82c662d1c60
198,020
from typing import Optional from typing import Mapping from typing import Any def _set_dut(tb_params: Optional[Mapping[str, Any]], dut_lib: str, dut_cell: str ) -> Optional[Mapping[str, Any]]: """Returns a copy of the testbench parameters dictionary with DUT instantiated. This method updates the testbench parameters dictionary so that the DUT is instantiated statically in the inner-most wrapper. """ if tb_params is None: return tb_params ans = {k: v for k, v in tb_params.items()} dut_params: Optional[Mapping[str, Any]] = tb_params.get('dut_params', None) if dut_params is None: ans['dut_lib'] = dut_lib ans['dut_cell'] = dut_cell else: ans['dut_params'] = _set_dut(dut_params, dut_lib, dut_cell) return ans
763c8e6836bd1bdd9db19648b4c6cbeaf33a7fd4
204,324
def format_value(val): """ A helper function to format fields for table output. Converts nested dicts into multilist strings. """ if isinstance(val, dict): return "\n".join([ f"{k}: {val[k]}" for k in val.keys()]) return val
c42dea3a5687c0ca32e27ddb4ddc2cf86a666d1c
499,580
def case(bin_spec: str, default: str = "nf") -> str: """ Return the case specified in the bin_spec string """ c = default if "NF" in bin_spec: c = "nf" elif "ÞF" in bin_spec: c = "þf" elif "ÞGF" in bin_spec: c = "þgf" elif "EF" in bin_spec: c = "ef" return c
b2fdab5d1a48e1d20c3a561707033970cac55356
16,097
import smtplib def get_email_server(host): """Return an SMTP server using the specified host. Abandon attempts to connect after 8 seconds. """ return smtplib.SMTP(host, timeout=8)
eccc3a2e4bf2ca8a3ea7ca2899876da9a8d464c6
331,885
def oxygen_cost_v(v): """Effectively defines Daniels' pace-power relationship. AKA speed-to-vdot. Assumed to be the same for all runners. Args: v (float): velocity in m/min. Returns: float: oxygen cost to cover distance in mL/kg/min. """ a1 = 0.182258 a2 = 0.000104 c = -4.60 return a1 * v + a2 * v ** 2 + c
685ba9c4fdef898f312f2cfbd0aacb374b541ea1
86,720
import json def getProcessedCloudtrailRecords(cloudtrailRecords=None): """ This function accepts the 'Records' portion of a cloudtrail monitoring report as a json object and extracts records to build a valid json string that can be stored in s3 and read by snowflake. The json string will be an array of records objects. """ # validate input if not cloudtrailRecords : raise ValueError('cannot accept None / empty values') # get initialize processed records list processedRecords = [cloudtrailRecord for cloudtrailRecord in cloudtrailRecords] return json.dumps(processedRecords)
2b25717d5e63dd1f63bb9fa772d310763c71eb49
198,278
def pixel_color_checker(data, row_index, pixel_index, R, G, B): """ :param data: image data as array :param row_index: index of image row to be checked :param pixel_index: index of pixel to be checked :param R: value (in range [0, 255]) at the R (red) value of the RGB notation :param G: value (in range [0, 255]) at the G (green) value of the RGB notation :param B: value (in range [0, 255]) at the B (blue) value of the RGB notation :return: boolean specifying whether the pixel of interest is colored as specified by the RGB values """ if (data[row_index][pixel_index][0] == R) and (data[row_index][pixel_index][1] == G) \ and (data[row_index][pixel_index][2] == B): return True else: return False
c188eca743b67dcf27456b3d7375507f6007f816
51,826
import pathlib def derive_filepath(filepath, append_string='', suffix=None, path=None): """Generate a file path based on the name and potentially path of the input file path. Parameters ---------- filepath: str of pathlib.Path Path to file. append_string: str String to append to file name stem. Default: ''. suffix: str or None File extension to use. If None, the same as video file. path: str or pathlib.Path or None Path to use. If None use same path as video file. Returns ------- pathlib.Path Path derived from video file path. """ stem = filepath.stem if suffix is None: suffix = filepath.suffix filename = f'{stem}_{append_string}{suffix}' if path is None: dpath = filepath.parent / filename else: dpath = pathlib.Path(path) / filename return dpath
174c439a5285441fcca7902bfd1c542348f6fb3d
681,942
def is_in_list(obj, obj_list): """ Check if obj is in obj_list explicitly by id Using (obj in obj_list) has false positives if the object overrides its __eq__ operator """ for o in obj_list: if(id(o) == id(obj)): return(True) else: return(False)
93676c25d4bb5fd77e1402467c69218c36db554b
141,179
def get_matrix_as_list(matrix): """ Retu9rns the given mamtrix as list of components :param matrix: OpenMaya.MMatrix :return: list(float) """ return [ matrix(0, 0), matrix(0, 1), matrix(0, 2), matrix(0, 3), matrix(1, 0), matrix(1, 1), matrix(1, 2), matrix(1, 3), matrix(2, 0), matrix(2, 1), matrix(2, 2), matrix(2, 3), matrix(3, 0), matrix(3, 1), matrix(3, 2), matrix(3, 3) ]
d17b81e764c53189037dd4bcd5e59abb03257d77
247,863
def update_max_for_sim(m, init_max, max_allowed): """ updates the current maximal number allowed by a factor :param m: multiplication factor :param init_max: initial maximum chromosome number allowed :param max_allowed: previous maximum chromosome number allowed :return: the current updated maximum for next iteration """ max_for_sim = 200 * m + init_max if max_for_sim < max_allowed: max_for_sim = max_allowed return max_for_sim
cf7f662d4bc817328e04ad28b2dfcf853bad9079
148,716
import random def random_from_alphabet(size, alphabet): """ Takes *size* random elements from provided alphabet :param size: :param alphabet: """ return list(random.choice(alphabet) for _ in range(size))
aeb8e4f1609ab799dd2dd6d66b8bf266fcb34f20
673,883
import math def PKCS1(message : int, size_block : int) -> int: """ PKCS1 padding function the format of this padding is : 0x02 | 0x00 | [0xFF...0xFF] | 0x00 | [message] """ # compute the length in bytes of the message length = math.ceil(math.ceil(math.log2(message-1)) / 8) template = "0200" # generate a template 0xFFFFF.....FF of size_block bytes for i in range(size_block-2): template = template + 'FF' template = int(template,16) # Add the 00 of the end of the padding to the template for i in range(length+1) : template = template ^ (0xFF << i*8) # add the padding to the original message message = message | template return message
33b65d1a0304f3d205d0fd2e4c52d4675d5b6ca0
100,578
def resample_factor_str(sig_sample_rate_hz: float, wav_sample_rate_hz: float) -> str: """ Compute file string for oversample and downsample options :param sig_sample_rate_hz: input signal sample rate :param wav_sample_rate_hz: wav sample rate; supports permitted_wav_fs_values :return: string with resample factor """ resample_factor = wav_sample_rate_hz / sig_sample_rate_hz # If resample factor is unity, no change resample_str = '_preserve' if resample_factor > 1: resample_str = '_upsample_' + str(int(10.*resample_factor)/10) + 'x_to' elif 1 > resample_factor > 0: resample_str = '_decimate_' + str(int(10./resample_factor)/10) + 'x_to' elif resample_factor < 0: print("Resample factor is negative: address") return resample_str
1f6f1e9b87d45112f47bdb6570b76ee03248cc8a
367,218
import re def _uses_settings(file): """Check if file imports AppSettings class. Returns: bool: True if it does, False otherwise. """ with open(file) as src_file: return bool(re.search('AppSettings', src_file.read()))
f77013b36974e00d75e0a99b0b761a942de6f94b
168,680
def smart_split(line): """ split string like: "C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'" in the list like: ['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'] """ flag_in = False l_val, val = [], [] for hh in line.strip(): if (hh == " ") & (not flag_in): if val != []: l_val.append("".join(val)) val = [] elif (hh == " ") & (flag_in): val.append(hh) elif ((hh == "'")|(hh == "\"")): flag_in = not flag_in else: val.append(hh) if val != []: l_val.append("".join(val)) return l_val
7249b6598f93c93ba17f668e5d0554ebae31a100
632,857
from pathlib import Path import hashlib def md5_hash_file(path: Path) -> str: """ Get md5 hash of a file. Args: path (Path): Absolute path or relative to current directory of the file. Returns: str: The md5 hash of the file. """ m = hashlib.md5() with path.open("rb") as f: m.update(f.read()) return m.hexdigest()
de398edd1476bf03cd78a3ddfd3e3c4ce8e14e1e
72,728
import struct def path_pack(data, pack = struct.pack, len = len): """ Given a sequence of point data, pack it into a path's serialized form. [px1, py1, px2, py2, ...] Must be an even number of numbers. """ return pack("!l%dd" %(len(data),), len(data), *data)
b1482633220f7649512d51165789011f1092fb40
516,922
def __m_rs(soup): """ Gets the most read news from the Rolling Stone page :param soup: the BeautifulSoup object :return: a list with the most read news from the Rolling Stone page """ news = [] anchors = soup.find('ol', class_='c-trending__list').find_all('a') for a in anchors: title = a.text link = a['href'] news.append(dict(title=title, link=link)) return news
5142ce2a441a7512f641008cc8755a3a45444d0c
608,152
def perform_PCA_inverse(pca, dataset_pca): """ Transform n-D array to back to original feature space Args: pca (object): Scikit-learn PCA object (n-D array) : n-D NumPy array of transformed dataset Returns: (n-D array) : n-D NumPy array of dataset inversely transformed back to original number of dimension """ return pca.inverse_transform(dataset_pca)
c3286178e055a869fd98b71fb7a25fcc1c7187a9
199,080
import yaml def get_options(option_fname): """Load options from YAML file""" with open(option_fname) as opt_file: options = yaml.full_load(opt_file) return options
4cdf099b8802e385bb82cc36ad0f404df50e0980
423,293
def parse_arguments(parser): """Read user arguments""" parser.add_argument( "--arxiv_id", type=str, required=True, help="arxiv paper ID to use to produce a new paper", ) args = parser.parse_args() return args
d3c80bf88bdb9e647d890d63f7050555e1940d0f
224,398
import torch import math def pose_error(R0: torch.Tensor, t0: torch.Tensor, R1: torch.Tensor, t1: torch.Tensor): """Compute the rotation and translation error. Adapted from PixLoc (author: Paul-Edouard Sarlin) https://psarlin.com/pixloc/ Args: * R0: The [3 x 3] first rotation matrix. * t0: The [3] first translation vector. * R1: The [3 x 3] second rotation matrix. * t1: The [3] second translation vector. Returns: * The rotation (in degrees) and translation error. """ dt = torch.norm(t0.ravel() - t1.ravel(), p=2, dim=-1) trace = torch.diagonal(R0.transpose(-1, -2) @ R1, dim1=-1, dim2=-2).sum(-1) cos = torch.clamp((trace - 1) / 2, -1, 1) dr = torch.acos(cos).abs() / math.pi * 180.0 return dr, dt
b1079781a3426ded29496bcff02097fb7f0a08ab
686,964
def length(iterable): """ Return number of items in the iterable. Attention: this function consumes the whole iterable and can never return if iterable has infinite number of items. :Example: >>> length(iter([0, 1])) 2 >>> length([0, 1, 2]) 3 """ try: return len(iterable) except TypeError: return sum(1 for item in iterable)
1c2963290d22b9076d3f8f51dd84e586de711b11
680,171