content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def split(inp,n): """ Splits an input list into a list of lists. Length of each sub-list is n. :param inp: :param n: :return: """ if len(inp) % n != 0: raise ValueError i = j = 0 w = [] w2 = [] while i<len(inp): # print(i,j) if j==n: j = 0 w2.append(w.copy()) w = [] w.append(inp[i]) i += 1 j += 1 w2.append(w.copy()) return w2
72feefc7ab6dc5288f12f5defb1d44ea2c7d95e8
60,701
def _fullname(obj): """Get the fully qualified class name of an object.""" if isinstance(obj, str): return obj cls = obj.__class__ module = cls.__module__ if module == "builtins": # no need for builtin prefix return cls.__qualname__ return module + "." + cls.__qualname__
8923c1de66ba50b6bfb340839ec1c8239f313688
60,704
def adjusted_classes(y_scores, threshold): """ This function adjusts class predictions based on the prediction threshold (t). Will only work for binary classification problems. Inputs: y_scores (1D array): Values between 0 and 1. threshold (float): probability threshold Returns: array of 0s and 1s """ return (y_scores >= threshold).astype(int)
84a1c33fa10141ca8c7b16bb194e46fd5254856f
60,706
def get_ec2_instance(cloud_connection, region, instance_filters): """ Find and return an EC2 object based on criteria given via `instance_filters` parameter. :param cloud_connection: object: Cloud Connection object :param region: string: The AWS region where the instances are located. :param instance_filters: string: If we need to filter on an EC2 :return EC2 object """ conn = cloud_connection.get_connection(region, ["ec2"]) found_instances = conn.get_only_instances(filters=instance_filters) return found_instances[0] if len(found_instances) else None
3b0a9d536114cb1769a3f758df7df1fcf904b365
60,707
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
import math def calc_angle_between_two_locs(lon1_deg, lat1_deg, lon2_deg, lat2_deg): """ This function reads in two coordinates (in degrees) on the surface of a sphere and calculates the angle (in degrees) between them. """ # Import modules ... # Convert to radians ... lon1_rad = math.radians(lon1_deg) # [rad] lat1_rad = math.radians(lat1_deg) # [rad] lon2_rad = math.radians(lon2_deg) # [rad] lat2_rad = math.radians(lat2_deg) # [rad] # Calculate angle in radians ... distance_rad = 2.0 * math.asin( math.hypot( math.sin((lat1_rad - lat2_rad) / 2.0), math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin((lon1_rad - lon2_rad) / 2.0) ) ) # [rad] # Return angle ... return math.degrees(distance_rad)
1ffa72e64696fc800de3fbf93bfb01a13ce14d22
60,709
def parse_time(value: str) -> int: """ Parses the string into a integer representing the number of milliseconds. """ if value.endswith("ms"): return int(float(value.replace("ms", ""))) return int(float(value.replace("s", "")) * 1000)
99dde4ccf874ec73d5785715ca5367b9d2535491
60,711
import re def parse_macro_spec(macro_spec): """ Parse a macro specification and return a dictionary of key-value pairs :param macro_spec: Macro string in the format "key=value,key=value,..." """ if macro_spec: return dict(re.findall("(\w+)=([^,]*)", macro_spec)) else: return {}
0bd6ecbbb35e4214900b2f2b818a95672fb2cdd3
60,712
import importlib def get_member(member_path: str): """ Import a module and retrieve a member from a module dot notation path separated by an ``:`` with the instance name. (eg: ``package.module:instance``) :param member_path: A string path with pattern ``package.module:member`` :return: """ split = member_path.split(':') if len(split) != 2: raise ImportError( 'Invalid instance path syntax ' '(eg: `package.module:instance`)' ) module_name, instance_name = split module = importlib.import_module(module_name) return getattr(module, instance_name, None)
835ae6dd7c30bd1b435c2e8d5172dc04c0b19a5a
60,715
import hashlib def compute_text_md5(text): """ Compute md5sum as hexdigest :param text: the input string :rtype string """ m = hashlib.md5() m.update(text) return m.hexdigest()
8d6b0b9484fd28beff6cc6fccdedd7ab0570470b
60,718
from datetime import datetime def make_timestamp(minutes_ago): """Make POSIX timestamp representing now minutes `minutes_ago`.""" minute_1 = 60 return datetime.now().timestamp() - (minutes_ago * minute_1)
8ede4844dceade1c121c3d582e1d3a8e33c46d00
60,719
def save(context, key, value): """ Saves any value to the template context. Usage:: {% save "MYVAR" 42 %} {{ MYVAR }} """ context.dicts[0][key] = value return ''
4623d867a91941abe9b4d9b80944d80831187669
60,720
import re def match(string, patterns): """Given a string return true if it matches the supplied list of patterns. Parameters ---------- string : str The string to be matched. patterns : None or [pattern, ...] The series of regular expressions to attempt to match. """ if patterns is None: return True else: return any(re.match(pattern, string) for pattern in patterns)
7477412a3619e19d24885adfa56c451c92c74f4d
60,722
def get_gettext(o): """ In python 2 return the ugettext attribute. In python 3 return gettext. """ return o.gettext
ba74557088e90bbf7a69ce7e1b466728aa13375f
60,729
def require_model(f): """Decorator to perform check that the model handle exists in the service. """ def wrapper(*args, **kwargs): """Function wrapper to perform model handle existence check.""" if args[0].config.handle(): return f(*args, **kwargs) raise Exception("API requires model to be set") return wrapper
a38d0afb4cb68e2f2d8b651493f72dbf30c6d713
60,730
def _getHierBenchNameFromFullname(benchFullname): """ Turn a bench name that potentially looks like this: 'foodir/bench_algos.py::BenchStuff::bench_bfs[1-2-False-True]' into this: 'foodir.bench_algos.BenchStuff.bench_bfs' """ benchFullname = benchFullname.partition("[")[0] # strip any params (modName, _, benchName) = benchFullname.partition("::") if modName.endswith(".py"): modName = modName.partition(".")[0] modName = modName.replace("/", ".") benchName = benchName.replace("::", ".") return "%s.%s" % (modName, benchName)
c9bbc6882f2c702a110d1b81b8c47eace72409b9
60,731
def hostname( location ): """Extracts the hostname.""" end = location.find(':') if -1 == end: host = location else: host = location[0:end] return host
80245838573d480bdc57b8c16a28f3522e7b2cfa
60,732
import re def error_065_image_desc_with_br(text): """Fix the error and return (new_text, replacements_count) tuple.""" return re.subn(r"(\[\[Файл:[^\]]+)\s*<br>\s*(\]\])", "\\1\\2", text)
36a69c6c7951480b6642b69db1c465c273545811
60,733
import copy def subj_or_obj_in_annotations(annotations, item, rel, item_in_mod): """ Looks for item in the second pos of annotations AND rel in the first pos of the annotation. If both are found, it creates a new annotation [rel, item, item_in_mod] and returns it. Otherwise, it returns None""" annotations_copy = copy.deepcopy(annotations) for annotation in annotations_copy: if annotation[1] == item_in_mod and annotation[0] == rel: # For add_object, we have already switched the direction of # rel. So the annotation is going to be the same whether this # function was called from add_subject or add_object. new_annotation = [rel, item, item_in_mod] return new_annotation return None
03cfd197dc878536e6f697adf59e6107f1015699
60,738
import json def refresh(series_id): """ Params: series_id [int] - id for the series as designated by apple Returns: JSON object with keys "success" (either 0 or 1) and "episode" that contains the entire episode object. Given a series_id, checks to see if we should request apple to get new episodes. If there are new episodes, returns the new episode object. """ episode = {"series_id": series_id, "episode-id": 420, "description":"testing"} response = {"success": 0, "episode": episode} return json.dumps(response)
119428af519400d77777bd1418b6ce3eeba0e112
60,739
def _obj_exists(r, queue, obj): """Returns whether the obj exists in the given queue.""" size = r.llen(queue) # No reason to call lrange if we aren't even dealing with a list, for # example. if size == 0: return False ### # Hopefully this isn't so wildly inefficient that it blows up in our # face later. ### contents = r.lrange(queue, 0, size) # Make sure to use bytes so that comparisons work. return True if bytes(obj) in contents else False
c621c03331db60ae2105d094410e10c4a48e678d
60,743
def year_type(s): """Validate the type of year argument. Args: s (str): The parsed argument. Returns: int: Year if valid. Raises: ValueError: If `s` is not a valid year. """ y = int(s) if y < 1950: raise ValueError('Year should be provided in four-digit format and greater than 1950.') return y
d18848a60582e877867c7032030d36e3d35d78bf
60,748
def _next_page_state(page_state, took): """Move page state dictionary to the next page""" page_state['page_num'] = page_state['page_num'] + 1 page_state['took'] = page_state['took'] + took return page_state
edf4a4d0540683fe4b92c6428200c418b5bf41b9
60,752
def to_month_only_dob(date): """ Convert dates of birth into month and year of birth starting from 1st of each month for anonymity return blank if not in the right format """ try: date = date.strftime("%Y-%m-01") except ValueError: date = "" except TypeError: date = "" except AttributeError: date = "" return date
d6e38593cb5f636c5d93e7cf5901056196d712c2
60,753
import functools import operator def combine_probability_matrices(matrices): """given a sequence of probability matrices, combine them into a single matrix with sum 1.0 and return it""" distribution = functools.reduce(operator.mul, matrices) # normalize return distribution / distribution.sum()
e27e702226188238d49fd285e5171af06a40bead
60,754
def makebinstr(binning): """Return a string for the binning""" binning=binning.strip().split() return '%sx%s' % (binning[0], binning[1])
59b59a368eea95418a22b2898f3c2fa8f34f37f2
60,755
import json def toJSON(py_object): """Convert an object to JSON string using its __dict__ :param py_object: object to create a JSON string of """ return json.dumps(py_object, default=lambda o: o.__dict__)
ef6a5ab78bb96ad7e3ad29cabf02811fcf16aa6b
60,759
def is_european(point): """Returns true if the continent code for the given point is Europe.""" return point['AddressInfo']['Country']['ContinentCode'] == 'EU'
16132f97416c7cd36202a1462956f5a5cc345ddc
60,762
def attr(*args, **kwargs): """ Set the given attributes on the decorated test class, function or method. Replacement for nose.plugins.attrib.attr, used with pytest-attrib to run tests with particular attributes. """ def decorator(test): """ Apply the decorator's arguments as arguments to the given test. """ for arg in args: setattr(test, arg, True) for key in kwargs: setattr(test, key, kwargs[key]) return test return decorator
6091c81a24fe549bc6e7cd8a4b98c94f4617157a
60,769
from typing import List from typing import Optional from typing import Tuple def merge_template_tokens( template_ids: List[int], token_ids: List[int], max_length: Optional[int] = None ) -> Tuple[List[int], List[int]]: """ Merge template and token ids Args: - template_ids: List[int], template ids - token_ids: List[int], token ids - max_length: int, max length Return: - token_ids: List[int], merged token ids - template_mask: List[int], template mask """ token_ids = [token_ids[0]] + template_ids + token_ids[1:-1] if max_length: token_ids = token_ids[:max_length - 1] + [token_ids[-1]] template_mask = [0] + [1] * len(template_ids) + [0] * (len(token_ids) - len(template_ids) - 1) return token_ids, template_mask
2286be670b7856ee4e82ac80a6d649ca2511eb47
60,770
def run_model(model): """Run a BCMD Model. Parameters ---------- model : :obj:`bayescmd.bcmdModel.ModelBCMD` An initialised instance of a ModelBCMD class. Returns ------- output : :obj:`dict` Dictionary of parsed model output. """ model.create_initialised_input() model.run_from_buffer() output = model.output_parse() return output
c08fe4b0f90f07ee1f9a77062fd09822a1fec477
60,773
import platform def get_python_version() -> str: """Find and format the python implementation and version. :returns: Implementation name, version, and platform as a string. """ return "{} {} on {}".format( platform.python_implementation(), platform.python_version(), platform.system(), )
8daf0b8e2153e37dcdfca396f9af32699a42d81d
60,776
def __call_cls_method_if_exists(cls, method_name): """Returns the result of calling the method 'method_name' on class 'class' if the class defined such a method, otherwise returns None. """ method = getattr(cls, method_name, None) if method: return method()
a078c004c8852c562ef0b8cff8096e34bf4e9f80
60,780
def avg_polysemy(polysemy_dict): """ compute average polysemy .. doctest:: >>> avg_polysemy(defaultdict(int, {1: 2, 2: 2})) 1.5 :param collections.defaultdict polysemy_dict: mapping from polysemy class to number of instances in that class :rtype: float :return: average polysemy """ numerator = sum([key * value for key, value in polysemy_dict.items()]) denominator = sum(polysemy_dict.values()) return numerator / denominator
7582e2e422fe6556c2bf573dec93c81241eb7643
60,783
def recalc_dhw_vol_to_energy(vol, delta_t=35, c_p_water=4182, rho_water=995): """ Calculates hot water energy in kWh/a from input hot water volume in liters/apartment*day Parameters ---------- vol : float Input hot water volume in liters/apartment*day delta_t : float, optional Temperature split of heated up water in Kelvin (default: 35) c_p_water : float, optional Specific heat capacity of water in J/kgK (default: 4182) rho_water : float, optional Density of water in kg/m3 (default: 995) Returns ------- dhw_annual_kwh : float Annual hot water energy demand in kWh/a """ en_per_day = vol / 1000 * rho_water * c_p_water * delta_t \ / (3600 * 1000) # in kWh dhw_annual_kwh = en_per_day * 365 return dhw_annual_kwh
75bd85e68949303d66ee658e8bd4698b7f86ec2f
60,791
def _cf_log(log_effect, *args, **kwargs): """ Log cloud feeds message with a "cloud_feeds" tag parameter. """ kwargs['cloud_feed'] = True return log_effect(*args, **kwargs)
5e8513b409c44c3ee190b3392a99f39a9cc53784
60,792
def norm_color(s): """ >>> norm_color('red') 'Red' >>> norm_color('Dark red') 'Dark Red' >>> norm_color('dkred') 'Dark Red' >>> norm_color('trred') 'Trans-Red' >>> norm_color('trdkblue') 'Trans-Dark Blue' >>> norm_color('rb') 'Reddish Brown' >>> norm_color(' trdkblue') 'Trans-Dark Blue' >>> norm_color('bley') 'Light Bluish Gray' >>> norm_color('light grey') 'Light Gray' >>> norm_color('Trans-Black') 'Trans-Black' """ s = str(s).lower().strip() shortcuts = [ ("bley", "light bluish gray"), ("dbley", "dark bluish gray"), ("bg", "light bluish gray"), ("dbg", "dark bluish gray"), ("dkbley", "dark bluish gray"), ("rb", "reddish brown"), ] for original, new in shortcuts: if s == original: return new.title() ret = "" if s[0:2] == "tr" and s[0:5] != "trans": ret += "trans-" s = s[2:] if s[0:2] == "dk": ret += "dark " s = s[2:] s = s.replace("grey", "gray") ret += s ret = ret.title() return ret
937894af7f84b117ef075dd9f56092de82cc8289
60,800
import torch def get_device(arguments): """ Sets the device that will be used to training and testing. :param arguments: A ArgumentParser Namespace containing "gpu". :return: A PyTorch device. """ # Checks if the GPU is available to be used and sets the . if arguments.gpu and torch.cuda.is_available(): return torch.device(f"cuda:{torch.cuda.device_count() - 1}") # Sets the device to CPU. else: return torch.device("cpu")
aa500a146aaa262186b27a8f9e712749437f090c
60,804
import re def get_chiral_indices_from_str(Ch): """Return the chiral indicies `n` and `m`. Parameters ---------- Ch : str string of the form 'NNMM' or "(n, m)". Extra spaces are acceptable. Returns ------- sequence 2-tuple of chiral indices `n` and `m` """ try: return int(Ch[:2]), int(Ch[2:]) except ValueError: try: return tuple([int(c) for c in re.split('[\(\),\s*]+', Ch)[1:-1]]) except Exception as e: print(e) return None
e36f2cc3adc73d98340ff2565968321e9ac7009b
60,805
def vec_dot(a, b, length=None): """Dot product of vectors *a* and *b*.""" if length is None: length = len(a) return sum(a[i] * b[i] for i in range(length))
42eb7ba84ad709fd492d1bb706863ca712e293b0
60,807
def get_smell_value(row, smells_frame, smell, key='test_name', verbose=False): """ Returns the value for the given smell for a particular test :param row: the data frame row for the test :param smells_frame: the frame with all the smells :param smell: the kind of smell :param key: the key to look for in the frame """ cut = row[key] aux = smells_frame[smells_frame['test-suite'] == cut][smell] if len(aux) != 1 and verbose: print("\t* {} entries for {}".format(str(len(aux)), cut)) return aux.iloc[0]
504458e28ac96abed94dcc5c3bc0cc9cf577dca7
60,809
def pointsAroundP(P, width, height): """ Return a list of points surround P provided that P is within the bounds of the area """ Px,Py = P if not(Px >= 0 and Px < width and Py >= 0 and Py < height): return [] result = [ (Px-1, Py), (Px+1, Py), (Px, Py-1), (Px, Py+1) ] result = [p for p in result if p[0] >= 0 and p[0] < width and p[1] >= 0 and p[1] < height] return result
b9b2e5a43a6435a908a0c8f6dfd174b141b63c62
60,810
def format_helptext(value): """Handle formatting for HELPTEXT field. Apply formatting only for token with value otherwise supply with newline""" if not value: return "\n" return "\t {}\n".format(value)
426fa6ee036c5a8376645d6455c1681b1200e174
60,812
def escape(term): """ escapes a term for use in ADQL """ return str(term).replace("'", "''")
a1abeacacbfc8b72a15898379e52ebf8cba8ccb9
60,814
from typing import Union def _generate_shortcut_linux(name : str, working_dir:str, path:str, executable:Union[str,bool], icon:str) -> str: """The steps to generate an icon for windows Parameters ---------- name : str; The name of the shortcut working_dir : str The path to the directory to execute the executable from, or create folder shortcut to path : str The path where you want to put the shortcut executable : str or bool, The path to the executable you want to create a shortcut for, set to False if you want folder shortcut icon : str The path to a custom icon to use for the shortcut Notes ----- - The function creates a .desktop file in the specified path, and returns it's content References ---------- - Desktop entry specification: https://developer.gnome.org/desktop-entry-spec/ """ if not executable: shortcut_type = "Directory" executable_string = f"" else: # If executable is specified shortcut_type = "Application" executable_string = f"\nExec='cd {working_dir} && {executable}'" # Generate the .desktop file Content data = f"""[Desktop Entry] Encoding=UTF-8 Version=1.0 Type={shortcut_type} Terminal=false{executable_string} Path='{path}' Name={name} Icon='{icon}' """ return data
d96f765452f67ba40300408c9b7378c9adc3355a
60,815
from typing import Dict from typing import List def isValidWord(word: str, hand: Dict[str, int], wordList: List[str]) -> bool: """Verify if word answer is in wordList and in hand Does not mutate hand or wordList. Args: word: guest user hand: current letter in a hand wordList: valid list of all words Returns: bool: True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. """ cp_hand = hand.copy() if word not in wordList: return False for char in word: if cp_hand.get(char, 0) < 1: return False else: cp_hand[char] = cp_hand.get(char,0) - 1 return True # one line: # return word in wordList and all(word.count(c) <= hand.get(c, 0) # for c in word) # Kiwitrader
1e45f8e4ba9e0e0352e3be4a8d87e1a96a440ef4
60,818
def string_char(char): """Turn the character into one that can be part of a filename""" return '_' if char in [' ', '~', '(', ')', '/', '\\'] else char
e318811d68858ff090447fa0e0e0aab9133461c8
60,823
def create_bigpath(nets): """ Return a list with lists of wires from every net. """ bigpath = [] for net in nets: bigpath.append(net.wires) return bigpath
5070dcedc021314238b3e5c85be0d6efcc379652
60,827
def rgbint2rgbfloat(i): """ Convert a rgb integer value (0-255) to a rgb float value (0.0-1.0). Args: i (int): Integer value from 0 to 255 Returns: float: Float value from 0.0 to 1.0 """ return i / 255
5e6e597d412cd2262defbb204bb097693270fff9
60,828
def flatten_dictionary(dictionary, separator=':', flattened_dict=None, parent_string=''): """ Flattens nested dictionary into a single dictionary: {'hello': {'world': 1, 'moon': 2}} becomes: {'hello:world': 1, 'hello:moon': 2} Uses recursion to flatten as many layers as exist in your dictionary. :param dictionary: nested dictionary you wish to flatten. :param flattened_dict: (used for recursion) current flattened dictionary to add to :param parent_string: (used for recursion) current key string to use as prefix for :return: flattened dictionary :type dictionary: dict :type flattened_dict: dict :type parent_string: str :rtype: dict """ if flattened_dict is None: # dicts are mutable, so we shouldn't use a dict as the default argument!!! flattened_dict = {} # instead, redeclare an empty dictionary here. for k, v in dictionary.items(): if parent_string: full_key = "{0}{1}{2}".format(parent_string, separator, k) else: full_key = k if isinstance(v, dict): # use recursion to flatten and add nested dictionaries to the product. _ = flatten_dictionary(v, flattened_dict=flattened_dict, parent_string=full_key) else: flattened_dict[full_key] = v return flattened_dict
6e5df742d9a9a0693cdf71469e5eee2b9f1fdd8d
60,830
def rgb_to_hex(color_RGB): """Takes a sequence of 3 elements (each one a integer from 0 to 255), representing a RGB color. Returns the HTML representation of the color (hexadecimal): #RRGGBB """ color_hex = hex((color_RGB[0] << 16) | (color_RGB[1] << 8) | (color_RGB[2])) # Convert the color values to hexadecimal color_hex = color_hex.replace("0x", "", 1) # Remove the "0x" from the beginning color_hex = color_hex.rjust(6, "0") # Ensure that the string is 6 characters long (fill with leading "0", if needed) color_hex = "#" + color_hex # Add a "#" to the beginning return color_hex
d97249b2abfcd930c1491f8ff5caa34e5965dcc0
60,835
def _mark_transition_type(lookup_dict, lulc_from, lulc_to): """Mark transition type, given lulc_from and lulc_to. Args: lookup_dict (dict): dictionary of lookup values lulc_from (int): lulc code of previous cell lulc_to (int): lulc code of next cell Returns: carbon (str): direction of carbon flow """ from_is_habitat = \ lookup_dict[lulc_from]['is_coastal_blue_carbon_habitat'] to_is_habitat = \ lookup_dict[lulc_to]['is_coastal_blue_carbon_habitat'] if from_is_habitat and to_is_habitat: return 'accum' # veg --> veg elif not from_is_habitat and to_is_habitat: return 'accum' # non-veg --> veg elif from_is_habitat and not to_is_habitat: return 'disturb' # veg --> non-veg else: return 'NCC'
10493de924b4184dd384e739963e2854fed54e0e
60,836
import re def GuessDataType(value, column_id=None): """Guess the DSPL data type of a string value. Defaults to 'string' if value is not an obvious integer, float, or date. Also, does not try to detect boolean values, which are unlikely to be used in DSPL tables. Args: value: A string to be evaluated. column_id: (Optional) Name of the column containing data; used to resolve ambiguities, e.g. between years and integers. Returns: One of {'date', 'integer', 'float', 'string'} """ stripped_value = value.strip().replace('"', '') if re.search('^-?[0-9]+$', stripped_value): if column_id == 'year': return 'date' else: return 'integer' elif re.search('^-?[0-9]+\.[0-9]+$', stripped_value): return 'float' elif re.search('^[0-9]+(/|-)[0-9]+((/|-)[0-9]+){0,1}$', stripped_value): return 'date' else: return 'string'
cbfc17280664f9b6499b4d883a3ed084b4f934f5
60,837
from typing import Dict from typing import List def _custom_text_tokenizer(text: str, lang: str, dictionary_terms: Dict[str, str]) -> List[str]: """Helper function to split text by a comma.""" del lang del dictionary_terms return text.split(',')
8489d1d02e06670938ae73ac650ee0c08c0892ec
60,838
def volpiano_characters(*groups): """Returns accepted Volpiano characters The characters are organized in several groups: bars, clefs, liquescents, naturals, notes, flats, spaces and others. You can pass these group names as optional arguments to return only those subsets: >>> volpiano_characters() '3456712()ABCDEFGHJKLMNOPQRSIWXYZ89abcdefghjklmnopqrsiwxyz.,-[]{¶' >>> volpiano_characters('naturals', 'flats') 'IWXYZiwxyz' Parameters ---------- *groups : [str] The groups to include: 'bars', 'clefs', 'liquescents', 'naturals', 'notes', 'flats', 'spaces' or 'others' Returns ------- str A string with accepted Volpiano characters """ symbols = { 'bars': '34567', 'clefs': '12', 'liquescents': '()ABCDEFGHJKLMNOPQRS', 'naturals': 'IWXYZ', 'notes': '89abcdefghjklmnopqrs', 'flats': 'iwxyz', 'spaces': '.,-', 'others': "[]{¶", } if not groups: groups = symbols.keys() return "".join((symbols[key] for key in groups))
af361f302fc531828655e1274e7c0868969c2fdc
60,839
def page_loaded_condition(driver): """Expected condition for page load.""" return driver.execute_script("return document.readyState") == 'complete'
915bb10e443fcf12cde1e3a4945d9cf2a7c2ed2d
60,840
def is_reference(d): """ Returns a boolean indicating whether the passed argument is reference. A reference is a fict in the form {'#': soul} """ return isinstance(d, dict) and "#" in d
0528cf3d39e26a76fb3108657bee13f8993057b9
60,844
def CodedBlockPattern(mb_type): """ >>> CodedBlockPattern(0) (None, None) >>> CodedBlockPattern(12) (2, 0) >>> CodedBlockPattern(13) (0, 15) """ if mb_type > 25: raise Exception('unknown mb_type %d' % (mb_type)) if mb_type == 0 or mb_type == 25: return None, None chroma = (mb_type - 1) // 4 % 3 luma = 0 if mb_type <= 12 else 15 return chroma, luma
7d0e6fae32e26c4950e220c02cd7b0c6c650f46d
60,846
def get_md_links(link_list): """Return an unordered list of links in markdown syntax.""" html_links = "\n" for link in link_list: html_links += "* [{title}]({url})\n".format(**link) return html_links
dbb146c5f744f3d5cd764d7867e2666dea954a00
60,847
def _to_11_bit(data): """ Convert a bytearray to an list of 11-bit numbers. Args: data (bytes): bytearray to convert to 11-bit numbers Returns: int[]: list of 11-bit numbers """ buffer = 0 num_of_bits = 0 output = [] for i in range(len(data)): buffer |= data[i] << num_of_bits num_of_bits += 8 if num_of_bits >= 11: output.append(buffer & 2047) buffer = buffer >> 11 num_of_bits -= 11 if num_of_bits != 0: output.append(buffer & 2047) return output
0369c4b8b442475a8aa94bad439edaf67db1ad4e
60,852
def e_sudeste(arg): """ e_sudeste: direcao --> logico e_sudeste(arg) tem o valor verdadeiro se arg for o elemento 'SE' e falso caso contrario. """ return arg == 'SE'
482abc2671902eb92c6bd9fcd62f78a9783b1eb2
60,853
def get_root(w): """ Simple method to access root for a widget """ next_level = w while next_level.master: next_level = next_level.master return next_level
4bbdf5c38da114adea9213e2903eae44c1ce6d2c
60,854
import re def _readd_double_slash_removed_by_path(path_as_posix: str) -> str: """Path(...) on an url path like zip://file.txt::http://host.com/data.zip converts the :// to :/ This function readds the :// It handles cases like: - https://host.com/data.zip - C://data.zip - zip://file.txt::https://host.com/data.zip - zip://file.txt::/Users/username/data.zip - zip://file.txt::C://data.zip Args: path_as_posix (str): output of Path(...).as_posix() Returns: str: the url path with :// instead of :/ """ return re.sub("([A-z]:/)([A-z:])", r"\g<1>/\g<2>", path_as_posix)
c50a0974ebdd3e442c819296ac888b019969e4db
60,855
def first(S): """ Simply return the first item from a collection (using next(iter(S))) """ return next(iter(S))
7ccd05d1adae32cf3c1b92740098751707991541
60,858
def get_target_indice_from_leaves(targets, sent): """ Find the indice of the target words in the terminal sequence of a parsed sentence. """ target_indice = [] idx = 0 current_target = targets[idx] for k, w in enumerate(sent): if w == current_target: target_indice.append(k) idx += 1 if idx == len(targets): break current_target = targets[idx] try: len(target_indice) == len(targets) except ValueError: print(targets) print(' '.join(sent)) return target_indice
b02a0173c33faae687a91b09e99d7ef5b54168d1
60,864
def config_get(config, section, option, default=None, raw=0, vars=None): """Get a value from the configuration, with a default.""" if config.has_option(section, option): return config.get(section, option, raw=raw, vars=None) else: return default
8efb96fddeb4e3734d4a367ee07035e3cbb20050
60,865
def get_var_name(string: str) -> str: """Gets the name from an argument variable. Args: string: Input variable declaration Returns: The name of the arguments variable as a string, e.g. "int x" -> "x". """ var = string.strip() # Not an actual variable if var in ("void", "..."): return "" # Unnamed variable, use an arbitrary name if var[-1] == "*": return var.split("_")[1] return var.split(" ")[-1].strip()
836bd3bc74da2f0add83429f4585da3281040965
60,867
def trim_txt(txt, limit=10000): """Trim a str if it is over n characters. Args: txt (:obj:`str`): String to trim. limit (:obj:`int`, optional): Number of characters to trim txt to. Defaults to: 10000. Returns: :obj:`str` """ trim_line = "\n... trimmed over {limit} characters".format(limit=limit) txt = txt[:limit] + trim_line if len(txt) > limit else txt return txt
197dd9da07d8a5a42a33246431f50b6bae25b6bf
60,873
def list_to_string(list_of_elements): """ Converts the given list of elements into a canonical string representation for the whole list. """ return '-'.join(map(lambda x: str(x), sorted(list_of_elements)))
8502409ba67e96bae7d6de8565391a090395edec
60,878
def rounder(numbers, d=4): """Round a single number, or sequence of numbers, to d decimal places.""" if isinstance(numbers, (int, float)): return round(numbers, d) else: constructor = type(numbers) # Can be list, set, tuple, etc. return constructor(rounder(n, d) for n in numbers)
d452714168867e2dd8568039bbdb3f54314299af
60,880
import torch def data_parallel_wrapper(model, cur_device, cfg): """Wraps a given model into pytorch data parallel. Args: model (torch.nn.Module): Image classifier. cur_device (int): gpu_id cfg : Reference to config. Returns: torch.nn.Dataparallel: model wrapped in dp. """ model.cuda(cur_device) # model = torch.nn.DataParallel(model, device_ids = [cur_device]) # assert cfg.NUM_GPUS == torch.cuda.device_count(), f"Expected torch device count (i.e {torch.cuda.device_count()}) same as number of gpus (i.e {cfg.NUM_GPUS}) in config file" model = torch.nn.DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())] ) return model
238a0d47936cb84f640df34ce420ab5cfa054be6
60,882
def get_next_player(players, currentplayer): """Returns the next player in an ordered list. Cycles around to the beginning of the list if reaching the end. Args: players -- List currentplayer -- Element in the list """ i = players.index(currentplayer) + 1 return players[i % len(players)]
a2bc14e0c19a5bf7f7931d557b785b6a62c8caf4
60,883
import re import random def get_patches(path, n=0): """Get selected number of patch IDs from given directory path. If number is not provided, i.e. is zero, all patch IDs are returned. :param path: Directory path where patches are :type path: Path :param n: Number of patch IDs to retrieve, defaults to 0 :type n: int, optional :return: List of patch IDs :rtype: list[int] """ patches = [patch.name for patch in path.glob('eopatch_*')] ids = [] for patch in patches: match = re.match(r'^eopatch_(\d+)$', patch) if match: ids.append(int(match.group(1))) ids.sort() return random.sample(ids, n) if n else ids
02268f0b469155db0e57d4206a68a2d00e578e4e
60,885
import networkx as nx def get_most_central_node(G): """ Calculate the closeness centrality for all nodes of graph. Return maximum node :param G: graph :return: node with maximal closeness centrality """ closeness = nx.closeness_centrality(G) return max(closeness, key=closeness.get)
277ba9e7ef855a5d342e82e7723c8c58e240037c
60,886
import math def calcular_distancia_tierra(t1: float, g1: float, t2: float, g2: float) -> float: """ Distancia entre dos puntos en la Tierra Parámetros: t1 (float): Latitud del primer punto en la Tierra g1 (float): Longitud del primero punto en la Tierra t2 (float): Latitud del segundo punto en la Tierra g2 (float): Longitud del segundo punto en la Tierra Retorno: float: Distancia entre dos puntos en la Tierra a dos cifras decimales. """ t1 = math.radians(t1) t2 = math.radians(t2) g1 = math.radians(g1) g2 = math.radians(g2) distancia = 6371.01 * math.acos(math.sin(t1) * math.sin(t2) + math.cos(t1) * math.cos(t2) * math.cos(g1 - g2)) return round(distancia, 2)
16f2448ecb4dc5dce9afa4ccac0ac8a99091e2b9
60,887
from typing import Any import functools def qualname(obj: Any) -> str: """Get the fully qualified name of an object. Based on twisted.python.reflect.fullyQualifiedName. Should work with: - functools.partial objects - functions - classes - methods - modules """ if isinstance(obj, functools.partial): obj = obj.func if hasattr(obj, '__module__'): prefix = '{}.'.format(obj.__module__) else: prefix = '' if hasattr(obj, '__qualname__'): return '{}{}'.format(prefix, obj.__qualname__) elif hasattr(obj, '__name__'): return '{}{}'.format(prefix, obj.__name__) else: return repr(obj)
1c2d4fee79f102904d6383c6b4e67d7476a89e1d
60,890
def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character. unquote('abc%20def') -> 'abc def'. """ if encoding is None: encoding = 'utf-8' if errors is None: errors = 'replace' # pct_sequence: contiguous sequence of percent-encoded bytes, decoded # (list of single-byte bytes objects) pct_sequence = [] res = string.split('%') for i in range(1, len(res)): item = res[i] try: if not item: raise ValueError pct_sequence.append(bytes.fromhex(item[:2])) rest = item[2:] except ValueError: rest = '%' + item if not rest: # This segment was just a single percent-encoded character. # May be part of a sequence of code units, so delay decoding. # (Stored in pct_sequence). res[i] = '' else: # Encountered non-percent-encoded characters. Flush the current # pct_sequence. res[i] = b''.join(pct_sequence).decode(encoding, errors) + rest pct_sequence = [] if pct_sequence: # Flush the final pct_sequence # res[-1] will always be empty if pct_sequence != [] assert not res[-1], "string=%r, res=%r" % (string, res) res[-1] = b''.join(pct_sequence).decode(encoding, errors) return ''.join(res)
a6b71447fb6e41a2fd8fc37020d7caac1d4a7bc6
60,892
from typing import Tuple def count_in_freq(freq_tuple: Tuple[str, str]) -> int: """Return the count from the statistic half of the tuple returned from most_common or least_common Parameters ---------- freq_tuple : Tuple[str, str] tuple containing stats given as (count/total, percent) from most_common or least_common Returns ------- the count from the statistic as an int """ return int(freq_tuple[0].split('/')[0])
127677e3bae94f7b60a8d4d340fdacdec6bbde8a
60,893
def create_list(text): """Create and return a list of the words present in story.""" text_list = text.split() return text_list
c501ce4b60cbca9c49b9cf5fd0f2a0e700b873e8
60,895
def infer_ensembl_vdj_chain(gene_name): """ Infer e.g., TRA or IGH from the ensembl gene name """ return gene_name[0:3]
2f0f759bd072d1c1fb9748a439b23715d106f456
60,898
def ensure_list(specifier): """ if specifier isn't a list or tuple, makes specifier into a list containing just specifier """ if not isinstance(specifier, list) and not isinstance(specifier, tuple): return [specifier,] return specifier
152c21d31839566c10479a8322dd9cc6ea3487ca
60,900
def calcMemUsage(counters): """ Calculate system memory usage :param counters: dict, output of readMemInfo() :return: system memory usage """ used = counters['total'] - counters['free'] - \ counters['buffers'] - counters['cached'] total = counters['total'] # return used*100 / total return used / total
f38487df7118c113152c8796db183c3beabc197c
60,902
def find_ngrams(single_words, n): """ Args: single_words: list of words in the text, in the order they appear in the text all words are made of lowercase characters n: length of 'n-gram' window Returns: list of n-grams from input text list, or an empty list if n is not a valid value """ ngram_list = [] if n <= 0 or n > len(single_words): return [] else: for i in range(len(single_words) - n +1): p = single_words[i:n+i]# variable p getting a list of ngrams from single words t = " ".join(p) # varibale t creating a string from the p ngram_list.append(t) return ngram_list
ed0fd4d89f95424b0fbf4180d8a2aa0aedfefb2c
60,903
def _length(stream): """Returns the size of the given file stream.""" original_offset = stream.tell() stream.seek(0, 2) # go to the end of the stream size = stream.tell() stream.seek(original_offset) return size
8520dee110a8fbab37f9c296c6d73bda1c167f2b
60,915
import json def read_json(fpath): """ read json file """ return json.load(open(fpath))
6b78c352d4139bb7924214b61f6e69096a7a9b33
60,918
def ldrag(self, nk1="", nk2="", nk3="", nk4="", nk5="", nk6="", nl1="", nl2="", nl3="", nl4="", nl5="", nl6="", **kwargs): """Generates lines by sweeping a keypoint pattern along path. APDL Command: LDRAG Parameters ---------- nk1, nk2, nk3, . . . , nk6 List of keypoints in the pattern to be dragged (6 maximum if using keyboard entry). If NK1 = P, graphical picking is enabled and all remaining command fields are ignored (valid only in the GUI). If NK1 = ALL, all selected keypoints (except those that define the drag path) will be swept along the path. A component name may also be substituted for NK1. nl1, nl2, nl3, . . . , nl6 List of lines defining the path along which the pattern is to be dragged (6 maximum if using keyboard entry). Must be a continuous set of lines. Notes ----- Generates lines (and their corresponding keypoints) by sweeping a given keypoint pattern along a characteristic drag path. If the drag path consists of multiple lines, the drag direction is determined by the sequence in which the path lines are input (NL1, NL2, etc.). If the drag path is a single line (NL1), the drag direction is from the keypoint on the drag line that is closest to the first keypoint of the given pattern to the other end of the drag line. The magnitude of the vector between the keypoints of the given pattern and the first path keypoint remains constant for all generated keypoint patterns and the path keypoints. The direction of the vector relative to the path slope also remains constant so that patterns may be swept around curves. Keypoint and line numbers are automatically assigned (beginning with the lowest available values [NUMSTR]). For best results, the entities to be dragged should be orthogonal to the start of the drag path. Drag operations that produce an error message may create some of the desired entities prior to terminating. """ command = f"LDRAG,{nk1},{nk2},{nk3},{nk4},{nk5},{nk6},{nl1},{nl2},{nl3},{nl4},{nl5},{nl6}" return self.run(command, **kwargs)
5efc57953a6d90902fbf0275e789508849f6858e
60,921
def filter_metric_by_category(metrics, category): """Returns the metric list filtered by metrics that have the specified category. @param metrics: The list of the metrics. @param category: The category name, or None if should match for all metrics that have None as category. @type metrics: list of MetricDescription @type category: str or None @return: The filtered list. @rtype: list of MetricDescription """ result = [] for metric in metrics: if metric.category is None: if category is None: result.append(metric) elif metric.category == category: result.append(metric) return result
5ff456442240d8edb066de9add4e226f11703c7c
60,926
def str_from_int(func): """Function to be used as a decorator for a member method which returns some type convertible to `int` and accepts no arguments. The return value will be converted first to an `int` then to a `str` and is expanded with leading zeros on the left to be at least 2 digits. """ def wrapped(self): return str(int(func(self))).zfill(2) return wrapped
8d22ed6f794fd1e17cab729be2819fbf6f572331
60,928
from contextlib import suppress def suppress2d(D_dict, threshold): """ Two dimensional of suppress(D, threshold) that suppresses values with absolutes values less than threshold in a dictionary of dictionaries such as is returned by forward2d(listlist) :param D_dict: dictionary of dictionaries :param threshold: value to suppress below :return: dictionary of dictionaries with same keys as D_dict >>> suppress2d(forward2d([[1, 2, 3, 4]]), 1) == { \ (2, 0): {(0, 0): 0}, \ (1, 0): {(0, 0): -2.0}, \ (0, 0): {(0, 0): 5.0}, \ (2, 1): {(0, 0): 0} \ } True """ return {key:suppress(D_dict[key], threshold) for key in D_dict.keys()}
38ae48be224c007f87800cc12a9fb7687ec08f37
60,929
def shift_time_events(events, ids, tshift, sfreq): """Shift an event Parameters ---------- events : array, shape=(n_events, 3) The events ids : array int The ids of events to shift. tshift : float Time-shift event. Use positive value tshift for forward shifting the event and negative value for backward shift. sfreq : float The sampling frequency of the data. Returns ------- new_events : array The new events. """ events = events.copy() for ii in ids: events[events[:, 2] == ii, 0] += int(tshift * sfreq) return events
7348e9daaffafdeff76639d0b609ad20e9e4258e
60,937
def int_to_dtype(x, n, signed): """ Convert the Python integer x into an n bit signed or unsigned number. """ mask = (1 << n) - 1 x &= mask if signed: highest_bit = 1 << (n-1) if x & highest_bit: x = -((~x & mask) + 1) return x
4767828f6a26b50ced70d887532fb0900542095b
60,944
def fatorial(num=1, show=0): """ -> Função fatorial param num: Numero determinado para calcular seu fatorial param show: Opção para mostrar ou não o calculo realizado """ resultado = 1 for c in range(num, 0, -1): resultado *= c if show: print(f'{c}', end=' ') if c > 1: print(f'x', end=' ') else: print(f'=', end=' ') return resultado
2633420c5b0cb1f506231dc6b33fd0bc37e648ec
60,948
from pathlib import Path from typing import List def find_conf_files(input_dir: Path) -> List[Path]: """Obtains paths for the 'conf*.csv' files containing the Hamiltonians.""" conf_files = sorted([f for f in input_dir.iterdir() if f.name[:4] == "conf"]) if conf_files == []: raise FileNotFoundError(f"No 'conf*.csv' files found in directory '{input_dir}'") return conf_files
1aded3be2fc2d093b374785284287f7ba0654814
60,952
def get_feature_directory_name(settings_dict): """Get the directory name from the supplied parameters and features.""" dir_string = "%s_%d_%d_%d_%d" % ( settings_dict["feature"], settings_dict["fft_sample_rate"], settings_dict["stft_window_length"], settings_dict["stft_hop_length"], settings_dict["frequency_bins"], ) if settings_dict["feature"] == "cqt": dir_string += "_%d" % settings_dict["cqt_min_frequency"] if settings_dict["feature"] == "mfcc": dir_string += "_%d" % settings_dict["mfc_coefficients"] return dir_string
5b0a72a4e1c38637119e54022e1b23a7a5482988
60,954
def previous_month(date): """ Return the previous month for a given date """ year = date[0] month = date[1] new_year = year new_month = month - 1 if new_month == 0: new_year -= 1 new_month = 12 return (new_year, new_month)
3220ada2fcd967d977bc0b2eb087375a3722164b
60,955
def nasnet_dual_path_scheme_ordinal(block, x, _, training): """ NASNet specific scheme of dual path response for an ordinal block with dual inputs/outputs in a DualPathSequential block. Parameters: ---------- block : nn.HybridBlock A block. x : Tensor Current processed tensor. training : bool or None Whether to work in training mode or in inference mode. Returns: ------- x_next : Tensor Next processed tensor. x : Tensor Current processed tensor. """ return block(x, training=training), x
49bca5c63a990de4e5d86b676addf63fb773bd66
60,959
import requests def load_template_from_url(url): """Load a Jinja2 template from a URL""" # fetch the template from the URL as a string response = requests.get(url) if response.status_code != 200: raise Exception( "Could not fetch the configuration template from the URL {}".format( url ) ) return response.text
4f5de53f620ace86d1448c5edf6060fb3cfa2949
60,963
import re import string def clean_text(text: str) -> str: """ Transform all text to lowercase, remove white spaces and special symbols. Args: text (str): Text to process. Returns: str: Processed text. """ # Transform all text to lowercase text = text.lower() # Remove white spaces and special symbols text = re.sub(r"https*\S+", " ", text) text = re.sub(r"@\S+", " ", text) text = re.sub(r"#\S+", " ", text) text = re.sub(r"\'\w+", "", text) text = re.sub("[%s]" % re.escape(string.punctuation), " ", text) text = re.sub(r"\w*\d+\w*", "", text) text = re.sub(r"\s{2,}", " ", text) text = text.strip() return text
fdd61e7a0edb56ca5714359b0fa38a915efdb696
60,965
import torch def meshgrid(shape): """ Wrapper for PyTorch's meshgrid function """ H, W = shape y, x = torch.meshgrid(torch.arange(H), torch.arange(W)) return x, y
bb92d510589197c801329496c608a9b4e07471ac
60,966
import json def lambda_handler(event, context): """Sample Lambda function placed into a Step Function State Machine. Parameters ---------- event: dict, required context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ Custom Output Format: dict exit_code: int : This is like an exit code of the UNIX command. message: str : A message what you want tell us. """ print(json.dumps(event)) return { "exit_code": 0, "message": "This function has finished successfully.", "result_detail": { "return1": "returned_value1", "return2": "returned_value2" } }
01f182cbff8581f0d4716b8a2e2b39ba3f89c226
60,970