content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def make_slow_waves(events, data, time, s_freq): """Create dict for each slow wave, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, trough, zero, peak, end samples data : ndarray (dtype='float') vector with the data time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the SWs, with information about start, trough_time, zero_time, peak_time, end, duration (s), trough_val, peak_val, peak-to-peak amplitude (signal units), area_under_curve (signal units * s) """ slow_waves = [] for ev in events: one_sw = {'start': time[ev[0]], 'trough_time': time[ev[1]], 'zero_time': time[ev[2]], 'peak_time': time[ev[3]], 'end': time[ev[4] - 1], 'trough_val': data[ev[1]], 'peak_val': data[ev[3]], 'dur': (ev[4] - ev[0]) / s_freq, 'ptp': abs(ev[3] - ev[1]) } slow_waves.append(one_sw) return slow_waves
eb84b4cc4d4024246905597be68d8dc170c9aeeb
403,498
def totalcost(endclasses): """ Tabulates the total expected cost of given endlcasses from a run. Parameters ---------- endclasses : dict Dictionary of end-state classifications with 'expected cost' attributes Returns ------- totalcost : Float The total expected cost of the scenarios. """ return sum([e['expected cost'] for k,e in endclasses.items()])
0ddffda6ee537d9f5159ad722ffb4925df39e035
570,142
import collections def compute_f1_single(prediction, ground_truth): """Computes F1 score for a single prediction/ground_truth pair. This function computes the token-level intersection between the predicted and ground-truth answers, consistent with the SQuAD evaluation script. This is different from another common way of computing F1 (e.g. used by BiDAF) that uses the intersection between predicted answer span and ground-truth spans. The main difference is that this method gives credit to correct partial answers that don't match any full answer span, while the other one wouldn't. Args: prediction: predicted string. ground_truth: ground truth string. Returns: Token-wise F1 score between the two input strings. """ # Handle empty answers for Squad 2.0. if not ground_truth and not prediction: return 1.0 prediction_tokens = prediction.split() ground_truth_tokens = ground_truth.split() common = collections.Counter(prediction_tokens) & collections.Counter( ground_truth_tokens) num_same = sum(common.values()) if num_same == 0: return 0.0 precision = num_same / len(prediction_tokens) recall = num_same / len(ground_truth_tokens) f1 = (2 * precision * recall) / (precision + recall) return f1
5fd82efdcd128fab3b4f40704b9f229348551828
332,611
import random def subsample(samples, labels, target_size): """subsample a dataset""" resized = random.sample(list(zip(samples, labels)), target_size) return zip(*resized)
221d7548cc00c5df61216788c9b5fe104b94e7c8
560,769
import torch def tensor_dot(x, y): """Performs a tensor dot product.""" res = torch.einsum("ij,kj->ik", (x, y)) return res
987198ddb5a851c01ec31ab6bfeaf7c3dac133af
84,640
import math def norm(p0,p1): """Calculate norm_2 distance between two points""" return math.sqrt((p1[0]-p0[0]) ** 2 + (p1[1]-p0[1]) ** 2)
e22c01b52114c1989bdeda66909e84381d9d4d93
477,630
def has_fusion(args): """Returns whether some kind of Fusion reference is given """ return args.fusion or args.fusions or \ args.fusion_tag
08377f211dbd48c404ef0488089a9b2923ee296e
102,029
def read(fname, mode = "r"): """Read content from a given file. Args: fname (str, Path): The path to the file. mode (str): File mode while opening. Defaults to "r". Returns: [type]: The content within the file. Example >>> bpy.read("path/to/file") 'Hello, World!' """ with open(fname, mode = mode or "r") as f: data = f.read() return data
fb46f57e59a3e4580e8d8801df6c4ebb93af0357
328,574
def add_end_slash(url: str): """Add final slash to url.""" if not url.endswith("/"): return url + "/" return url
82301f238ba8692ac210e3a310e461499b824e57
438,592
def is_leap(year,print_=False): """ returns true if year is leap year, otherwise returns False and prints the output per assignment of print_""" if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: if print_: print("Leap year") return True else: if print_: print("Leap yearNot a leap year") return False else: if print_: print("Leap year") return True else: if print_:print("Not a leap year") return False
f68111ae533e1cca3561f2517755e1d75728aa6a
460,699
from pathlib import Path def sim_top_build(pytestconfig): """Return path to Verilator sim model.""" path = Path(pytestconfig.getoption('verilator_model')).resolve() assert path.is_file() return path
bae5fc842ebb9c734e72fdfa1616ac0727dd5721
333,939
def _colors(strKey): """ Function gives access to the RxCS console colors dictionary. The Function returns a proper console color formating string (ANSI colors) based on the key given to the function. |br| Available keys: 'PURPLE' 'BLUE' 'GREEN' 'YELLOW' 'RED' 'BLACK' 'DARK_MAGENTA' 'AQUA' 'BLUE_BG' 'DARK_BLUE' 'DARK_GREEN' 'GREY30' 'GREY70' 'PROGRESS' -> color for progress signs ('>>>', '>>', '>') 'INFO' -> color for info messages 'BULLET_INFO' -> color for bullet info messages 'BULLET' -> color for bullets ('*') 'WARN' -> color for warning messages 'PARAM' -> color for parameters printing 'OK' -> color for good messages 'ENDC' -> console formatting string which switches of the coloring Args: strKey (string): key of the color Returns: strColor (string): console color formating string """ # Define colors dColors = {} dColors['PURPLE'] = '\033[95m' dColors['BLUE'] = '\033[94m' dColors['GREEN'] = '\033[92m' dColors['YELLOW'] = '\033[93m' dColors['RED'] = '\033[91m' dColors['BLACK'] = '\033[30m' dColors['DARK_MAGENTA'] = '\033[35m' dColors['AQUA'] = '\033[96m' dColors['BLUE_BG'] = '\033[44m' dColors['DARK_BLUE'] = '\033[34m' dColors['DARK_GREEN'] = '\033[32m' dColors['GREY30'] = '\033[30m' dColors['GREY70'] = '\033[97m' # Define colors for communication dColors['PROGRESS'] = dColors['DARK_MAGENTA'] dColors['INFO'] = dColors['DARK_GREEN'] dColors['BULLET_INFO'] = dColors['AQUA'] dColors['BULLET'] = dColors['DARK_MAGENTA'] dColors['WARN'] = dColors['RED'] dColors['PARAM'] = dColors['AQUA'] dColors['OK'] = dColors['DARK_GREEN'] dColors['ENDC'] = '\033[0m' # Return the correct color strColor = dColors[strKey] return strColor
90f09148ac709299d1666930e7c675595d04663f
681,689
def rebin(arr, new_shape): """ Rebin 2D array arr to shape new_shape by averaging. inputs: arr: numpy array to reduce at the size new_shape new_shape: tuple of the wanted size as (width, height) output: numpy array of the reduced arr from https://scipython.com/blog/binning-a-2d-array-in-numpy/ """ shape = (new_shape[0], arr.shape[0] // new_shape[0], new_shape[1], arr.shape[1] // new_shape[1]) return arr.reshape(shape).mean(-1).mean(1)
05149c7d364e3e138d0e3c623d1d28cc26cf3416
372,163
def prefix(name): """Returns a rule that matches symbols that start with `name`.""" def rule(symbol): return symbol.startswith(name) or None return rule
26c351ef9d9dacb2ae4d01350354235cded0db44
367,514
def measurement_with_tools(measurement, tmpdir): """Create a measurement with all dummy tools attached. """ measurement.add_tool('pre-hook', 'dummy') measurement.add_tool('post-hook', 'dummy') measurement.add_tool('monitor', 'dummy') measurement.root_task.default_path = str(tmpdir) return measurement
78d52cad9cf1faab36ec057f3622366a3b71e0a5
348,418
import requests def send_image(chat_id, token, image_url): """Send message to Telegram BOT Args: chat_id (int): chat_id number: -111111 token [str]: Token to HTTP API: 11111111:AAAAAAAAA image_url (str): Image url Returns: str : Response Status Code """ data = {'chat_id':chat_id, 'photo':image_url} response = requests.post('https://api.telegram.org/bot' + token + '/sendPhoto', data) return response.status_code
692ea6e30f8f135fff3ced180f568feee56b022e
205,753
import re def get_pos(pattern, string): """Get start position for each pattern match in string """ return set(m.start() for m in re.finditer(pattern, string))
afd4f49e224ff842835be4d5382aae72e2b083c9
209,423
import re def clean(text): """ Cleans text, removes excess tabs, CRs, spaces :param text: raw text string :return: clean text string """ text = re.sub('\s*\n\s*', '\n', text) text = re.sub('[ \t]{2,}', ' ', text) return text.strip()
57475bb5e2955d33cdefa7ba593413affa3293e2
586,773
import threading def run_on_another_thread(function): """ This decorator will run the decorated function in another thread, starting it immediately. :param function: :return: """ def f(*args, **kargs): threading.Thread(target=function, args=[*args, *kargs]).start() return f
f539b508d70d0cd24c9fa27d59090de8f6a9f8cd
398,550
def chr22XY(c): """Reformats chromosome to be of the form Chr1, ..., Chr22, ChrX, ChrY, etc. Args: c (str or int): A chromosome. Returns: str: The reformatted chromosome. Examples: >>> chr22XY('1') 'chr1' >>> chr22XY(1) 'chr1' >>> chr22XY('chr1') 'chr1' >>> chr22XY(23) 'chrX' >>> chr22XY(24) 'chrY' >>> chr22XY("X") 'chrX' >>> chr22XY("23") 'chrX' >>> chr22XY("M") 'chrM' """ c = str(c) if c[0:3] == 'chr': c = c[3:] if c == '23': c = 'X' if c == '24': c = 'Y' return 'chr' + c
13677f728ce8221e9a6966951353deba703f3294
702,021
def convert_string_AE2BE(string, AE_to_BE): """convert a text from American English to British English Parameters ---------- string: str text to convert Returns ------- str new text in British English """ string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() else w for w in string.split()]) return string_new
b032b007ad59ef653733e01b3c7b43de5d2a956a
663,916
def createMysqlEscapeList(num): """Create a string with a list of %s for escaping.""" esc_str = '' for i in range(num): esc_str += '%s, ' return esc_str.rstrip(', ')
00ea775c31e38365a1d8d14e37f72be0ebd9fdf8
262,777
def prepare_numbers(numbers): """Prepares the numbers for the chatbot to interpret. Parameters ---------- numbers : list Numbers that the user has input into the chatbot Returns ------- numb : list List of integers that the chatbot can use to put into the calculator. """ numb = [] for item in numbers: numb.append(int(item)) return numb
3f60538c993e2f544e25ca3b6a988856585284fb
111,636
def top_row(matrix): """ Return the first (top) row of a matrix. Returns a tuple (immutable). """ return tuple(matrix[0])
c41968ccef372ee609911640650541b99921aa43
457,095
def generate_report(data): """ Process the property data from the web page, build summary dictionary containing: * 'property_name' - Name of property * 'property_type' - Type of property e.g. 'Apartment' * 'room_type' - Type or number of bedrooms * 'room_number' - Number of bedrooms * 'bathrooms' - Number of bathrooms * 'general_amenities' - List of general amenities * 'family_amenities' - List of family amenities * 'safety_feats' - List of safety amenities :param data: dict Web page data, derived from 'bootstrapData' JSON string :return: dict Summarised property information (see above) """ listing = data['bootstrapData']['listing'] # Initialise summary data dictionary. Some values have been assigned default values of 'Not found' # in the event that the data is not present in the web page data summary_data = { 'property_name': listing['name'], 'property_type': 'Not found', 'rooms': 'Not found', 'bathrooms': 'Not found', 'general_amenities': [], 'family_amenities': [], 'safety_feats': [] } # Iterate through 'Space' section to build room details for detail in listing['space_interface']: if detail.get('label') == 'Property type:' and detail['value']: summary_data['property_type'] = detail['value'] if detail.get('label') == 'Bedrooms:' and detail['value']: summary_data['rooms'] = detail['value'] if detail.get('label') == 'Bathrooms:' and detail['value']: summary_data['bathrooms'] = detail['value'] # Iterate through amenities to build list of amenities grouped by category for amenity in listing['listing_amenities']: if amenity['is_present']: if amenity['category'] == 'family': summary_data['family_amenities'].append(amenity['name']) elif amenity['category'] == 'general' and amenity['is_safety_feature']: summary_data['safety_feats'].append(amenity['name']) else: summary_data['general_amenities'].append(amenity['name']) return summary_data
92d178f8fe2ec4e11433837440a454bf2b8d4e67
558,165
def GetParentFromFlags(args, is_list_api, is_insight_api): """Parsing args to get full url string. Args: args: argparse.Namespace, The arguments that this command was invoked with. is_list_api: Boolean value specifying whether this is a list api, if not append recommendation id or insight id to the resource name. is_insight_api: whether this is an insight api, if so, append insightTypes/[INSIGHT_TYPE] rather than recommenders/[RECOMMENDER_ID]. Returns: The full url string based on flags given by user. """ url = '' if args.project: url = 'projects/{0}'.format(args.project) elif args.billing_account: url = 'billingAccounts/{0}'.format(args.billing_account) elif args.folder: url = 'folders/{0}'.format(args.folder) elif args.organization: url = 'organizations/{0}'.format(args.organization) url = url + '/locations/{0}'.format(args.location) if is_insight_api: url = url + '/insightTypes/{0}'.format(args.insight_type) if not is_list_api: url = url + '/insights/{0}'.format(args.INSIGHT) else: url = url + '/recommenders/{0}'.format(args.recommender) if not is_list_api: url = url + '/recommendations/{0}'.format(args.RECOMMENDATION) return url
1df2b6bfc23e74277339a545cfaf131053c22dcb
287,939
from typing import List def mock_random_choice(candidates: List, weights: List[float], *, k: int) -> List: """ This is a mock function for random.choice(). It generates a deterministic sequence of the candidates, each one with frequency weights[i] (count: int(len(candidates) * k). If the sum of total count is less than number, then the deficiency is given to the candidates with the highest weight. :param candidates: candidates to choose from. :param weights: frequency of each candidate to be chosen. :param k: total number of output list. :return: a list of items in the candidates. """ # normalization sum_of_weights = sum(weights) weights = [weight / sum_of_weights for weight in weights] counts: List[int] = [int(k * weights[i]) for i in range(len(weights))] if sum(counts) < k: max_idx: int = weights.index(max(weights)) counts[max_idx] += k - sum(counts) result: List = list() for i in range(len(counts)): result += [candidates[i] for _ in range(counts[i])] return result
c60aebb59aeb299e6e36b9b7ed24a0fe6e0882b3
654,177
def patch_grype_wrapper_singleton(monkeypatch, test_grype_wrapper_singleton): """ This fixture returns a parameterized callback that patches the calls to get a new grype wrapper singleton at that path to instead return the clean, populated instance created by test_grype_wrapper_singleton. """ def _test_grype_wrapper_singleton(patch_paths: list): for patch_path in patch_paths: monkeypatch.setattr( patch_path, lambda: test_grype_wrapper_singleton, ) return _test_grype_wrapper_singleton
f95f45f80a8af1a71f1f8ee1ef55162b63ddc9af
38,656
import asyncio def singleton(func): """ A decorator that ensures only one instance of a coroutine is running at any time. """ func.lock = asyncio.Lock() async def func_wrapper(self, *args, **kwargs): if func.lock.locked(): return async with func.lock: await func(self, *args, **kwargs) return func_wrapper
ddede0b30fe5c05b5213135c24029b90f35c580d
471,701
def establish_relevant_columns(df): """ Creates a dataframe with columns that are useful for month/year pivoting. :type df: pd.DataFrame :param df: A pd.DataFrame object that has exactly two columns: 'Date' containing DateTime values, and 'Miles' containing floats. :return A pd.DataFrame instance with 'Date', 'Year', 'Month', 'DayOfWeek', and 'Miles' columns """ # First, drop NA values from the Miles column df.dropna(axis=0, how='any', subset=['Miles'], inplace=True) # Next, establish year, name-of-month, an name-of-day columns in the dataframe. df['DayOfWeek'] = df['Date'].dt.strftime('(%w): %A') df['Month'] = df['Date'].dt.strftime('(%m): %B') df['Year'] = df['Date'].dt.year return df
dfebafeb5bad6e4815ec44040f1acf6ad0340ea3
163,157
def get_sum(list): """Calc the sum of values from a list of numbers Args: list: The list from where the calc will be done Returns: Return the sum of values from a list of numbers """ sum = 0 for value in list: sum += value return sum
1d5e588993da40ff9f04e3f1cb5a5214c1b686bd
571,095
def split_labels(data, label_idx=-1): """ Split labels from numerical data :param data: array of inputs data :type data: nd.array :param label_idx: index where label is located in the array. It can be only at start of at the end of the array :type label_idx: int :return: data without labels, labels :rtype: nd.array, nd.array """ # return (Data, Labels) if label_idx == -1 or label_idx == data.shape[-1]: return data[..., :-1], data[..., -1] elif label_idx == 0: return data[..., 1:], data[..., 0] else: raise RuntimeError('Labels must be on axis 0 or 1')
d3b59dca790255ae14269836ace58df151f84684
25,890
def shift2d(x,w,a,b): """Shift a 2d quadrature rule to the box defined by the tuples a and b""" xs=[[a[0]],[a[1]]]+x*[[b[0]-a[0]],[b[1]-a[1]]] ws=w*(b[0]-a[0])*(b[1]-a[1]) return xs,ws
84c2090cc0e1689a79aa2c7fa40fb399bc03f535
699,329
import re def get_fig_name(title, tag, legends=[]): """Get the name of the figure with the title and tag.""" fig_name = "_".join(re.split("/|-|_|,", title) + legends).replace(" ", "") return f"{fig_name}_generalization_{tag}.pdf"
a1bb5c3d91eba412ffaca7354b5d663c37de0a46
653,975
def lt(y): """lt(y)(x) = x < y >>> list(filter(lt(3), [1,2,3,4,5])) [1, 2] """ return lambda x : x < y
a98e87097e0518b30c456d380509551f7516f1d6
69,892
def client(app): """Creates a flask.Flask test_client object :app: fixture that provided the flask.Flask app :returns: flask.Flask test_client object """ return app.test_client()
1041652fc1c84cfd81a92f09d09980dc2333f858
154,448
def matches(case, rule): """Match a test case against a rule return '1' if there's a match, 0 otherwise """ if len(case) != len(rule): return 0 match = 1 for i in range(len(case)): if rule[i] != "*" and case[i] != rule[i]: match = 0 break return match
354ac866c49c0bcc7d0a9be10a8585ed67e4cb1b
171,778
def set_name_from_dict(string, dictionary, key, leading, trailing): """Replaces the string with the value from a specified dictionary key, prepending and appending the leading/trailing text as applicable""" return "{}{}{}".format(leading, dictionary[key], trailing)
4641822ccca293b59a39f666fd715329d884c529
659,585
from typing import List def generate_def(functions: List[str], dll_name: str) -> str: """Generate .def file defining provided functions Args: functions: list of functions to define dll_name: name for LIBRARY Returns: string containing a .def file that defines and exports those functions """ text = [] text.append("LIBRARY " + dll_name) text.append("") text.append("EXPORTS") for i in functions: text.append(" " * 4 + i) text.append("") return "\n".join(text)
b859772b4af34b00cb1bcecee36bc7811cf8d42d
499,737
def get_next_line(fin): """return the next, non-blank line, with comments stripped""" line = fin.readline() pos = line.find("#") while (pos == 0 or line.strip() == "") and line: line = fin.readline() pos = line.find("#") return line[:pos]
23ca167db675916e0f2bf007a9204237176ca022
506,171
def pascal_case(str): """convert string to pascal case""" return ''.join(x for x in str.replace('_', ' ').title() if not x.isspace())
68d6a2ca288d2243801107c52de70fda465b8604
542,690
def get_stream_id_for_topic(topic_name, rng=2): """To distribute load, all the topics are not in the same stream. Each topic named is hashed to obtain an id which is in turn the name of the stream. This uses the djb2 algorithm, as described here https://mapr.com/docs/60/AdministratorGuide/spyglass-on-streams.html""" if rng == 1: return 0 h = 5381 for c in topic_name: h = ((h << 5) + h) + ord(c) return abs(h % rng)
f2d462a0985d9e8c24f02800ba3f72d77bbae344
512,874
import requests def is_responsive_404(url): """ Hit a non existing url, expect a 404. Used to check the service is up as a fixture. :param url: :return: """ try: response = requests.get(url) if response.status_code == 404: return True except ConnectionError: return False
46a5f869d4e86accaa07dc186e1fe758a49ab312
111,384
def regex_match_lines(regex, lines): """ Performs a regex search on each line and returns a list of matched groups and a list of lines which didn't match. :param regex regex: String to be split and stripped :param list lines: A list of strings to perform the regex on. """ matches = [] bad_lines = [] for line in lines: match = regex.search(line) if match: matches.append(match.groups()) else: bad_lines.append(line) return matches, bad_lines
8553dda253a26919ba41b774d5335ccd018aa2c2
516,149
import hashlib import six import base64 def CalculateMd5Hash(file_path): """Calculate base64 encoded md5hash for a local file. Args: file_path: the local file path Returns: md5hash of the file. """ m = hashlib.md5() with open(file_path, 'rb') as f: m.update(f.read()) return six.ensure_text(base64.b64encode(m.digest()))
2a24ce3dd4f6e5f9d9a5d9be5632e6d481fd690b
37,851
def validate(metric, net, val_data, batch_fn, data_source_needs_reset, dtype, ctx): """ Core validation/testing routine. Parameters: ---------- metric : EvalMetric Metric object instance. net : HybridBlock Model. val_data : DataLoader or ImageRecordIter Data loader or ImRec-iterator. batch_fn : func Function for splitting data after extraction from data loader. data_source_needs_reset : bool Whether to reset data (if test_data is ImageRecordIter). dtype : str Base data type for tensors. ctx : Context MXNet context. Returns ------- EvalMetric Metric object instance. """ if data_source_needs_reset: val_data.reset() metric.reset() for batch in val_data: data_list, labels_list = batch_fn(batch, ctx) outputs_list = [net(X.astype(dtype, copy=False)) for X in data_list] metric.update(labels_list, outputs_list) return metric
d816a1f2d2568cbe9ab8f6159be09c63644735b3
382,057
from typing import Dict def largest_valued_key(dic: Dict[str, set]) -> str: """Find the key with the largest value.""" biggest_size = -1 biggest_key = None for key, value in dic.items(): length = len(value) if length > biggest_size: biggest_size = length biggest_key = key assert isinstance(biggest_key, str) return biggest_key
2d4312217b93560514fb717251028baaeee7a6fe
18,335
import typing def _secret_key(secret_key: typing.Union[bytes, str]) -> bytes: """ensure bytes""" if isinstance(secret_key, str): return secret_key.encode('latin1') return secret_key
a8999c5df6a1e9a09659747172e9747ed628f691
274,587
def my_formatter_2f(x,p): """Format tick marks to have 2 significant figures.""" return "%.2f" % (x)
642a6a612ed25cadc8309dc698671baaa91780b1
246,818
def has_ways_in_center(tile, tolerance): """Return true if the tile has road pixels withing tolerance pixels of the tile center.""" center_x = len(tile) / 2 center_y = len(tile[0]) / 2 for x in range(center_x - tolerance, center_x + tolerance): for y in range(center_y - tolerance, center_y + tolerance): pixel_value = tile[x][y] if pixel_value != 0: return True return False
111520a1959696dfb254e20bc5a7698f8cd3f3f3
457,639
def vecDistanceSquared(inPtA, inPtB): """calculate the square of the distance between two points""" ddx = inPtA[0] - inPtB[0] ddy = inPtA[1] - inPtB[1] ddz = inPtA[2] - inPtB[2] return ddx*ddx + ddy*ddy + ddz*ddz
dd054e1a2e6fde7d56bd0febd18847c09e900e8c
617,796
from typing import Dict from typing import Any def prefix_dict(d: Dict[str, Any], prefix: str): """ Prefix every key in dict `d` with `prefix`. """ return {f"{prefix}_{k}": v for k, v in d.items()}
ab27c08cf25c19ca2073bb7432692a838d0ada87
128,919
def parseInput(input): """ Converts an input string of integers into an array of integers. """ return [int(num) for num in input.split(',')]
0d29a72c1c19b2703c6f736de5819cd58ab08d4d
73,725
def s2f(s): """ Convert a string to a float even if it has + and , in it. """ if s == None or s == '': return None if type(s) == type(0.0) or type(s) == type(0): # Already a number return s if s: return float(s.replace(',', '')) return None
ef8c3ed83dc1440286a346765a6f8a6cbfbadc12
346,224
import math def tile_iterator(tile_order, width, height, tile_width, tile_height): """ Returns iterator function depending of tile_order. Also iterator functions has 'len' field which consists number of tiles :param tile_order: could be 'VERTICAL', 'HORIZONTAL', 'CENTER_SPIRAL' :param width: render width :param height: render height :param tile_width: max tile width :param tile_height: max tile height :return: ((tile_x, tile_y), (tile_w, tile_h)) by every iterator call """ def get_tiles_vertical(): for x in range(0, width, tile_width): for y in range(height, 0, -tile_height): y1 = max(y - tile_height, 0) yield (x, y1), (min(tile_width, width - x), min(tile_height, y - y1)) def get_tiles_horizontal(): for y in range(height, 0, -tile_height): y1 = max(y - tile_height, 0) for x in range(0, width, tile_width): yield (x, y1), (min(tile_width, width - x), min(tile_height, y - y1)) def get_tiles_center_spiral(): x = (width - tile_width) // 2 y = (height - tile_height) // 2 def get_tile(): if x + tile_width > 0 and x < width and y + tile_height > 0 and y < height: x1 = max(x, 0) y1 = max(y, 0) x2 = min(x + tile_width, width) y2 = min(y + tile_height, height) return (x1, y1), (x2 - x1, y2 - y1) return None tile = get_tile() if tile: yield tile side = 0 have_tiles = True while have_tiles: have_tiles = False side += 1 for _ in range(side): y -= tile_height tile = get_tile() if tile: have_tiles = True yield tile for _ in range(side): x += tile_width tile = get_tile() if tile: have_tiles = True yield tile side += 1 for _ in range(side): y += tile_height tile = get_tile() if tile: have_tiles = True yield tile for _ in range(side): x -= tile_width tile = get_tile() if tile: have_tiles = True yield tile def get_tiles_number(): if tile_order != 'CENTER_SPIRAL': x_count = math.ceil(width / tile_width) y_count = math.ceil(height / tile_height) else: x = (width - tile_width) // 2 y = (height - tile_height) // 2 x_count = math.ceil(x / tile_width) + math.ceil((width - x) / tile_width) y_count = math.ceil(y / tile_height) + math.ceil((height - y) / tile_height) return x_count * y_count tile_func = { 'VERTICAL': get_tiles_vertical, 'HORIZONTAL': get_tiles_horizontal, 'CENTER_SPIRAL': get_tiles_center_spiral, }[tile_order] # adding 'len' field into function object tile_func.len = get_tiles_number() return tile_func
b96591fbe00dce046ab3f1b059023fa90bb877ec
560,231
def return_core_dense_key(core_idx, dense=False): """Return core dense keys in the right format.""" if dense is False: return (core_idx, 0) else: return (core_idx, dense)
4ed9e9fd75d9ec7549d227378f9da8089244a414
311,205
def bitmap2str(b, n, on='o', off='.'): """ Generate a length-n string representation of bitmap b """ return '' if n==0 else (on if b&1==1 else off) + bitmap2str(b>>1, n-1, on, off)
25817d00d604492cf3d03ed8b1f849f8fc859194
564,498
from pathlib import Path def is_equal_or_child_of(source1: Path, source2: Path) -> bool: """ Checking if a source equal or a child of another source. :param source1: Child source to check :type source1: Path :param source2: Parent source to check :type source2: Path :return: Is sources1 relative to source2 :rtype: bool """ source1, source2 = source1.absolute(), source2.absolute() if source2 == source1: return True return source2 in source1.parents
3278fae2fac3e1b239a75b56355526a061d9f28e
442,747
def rem_item_from_list(item, string): """ Removes all occurrences of token from string. If no occurrences of items are in string, nothing is removed.""" return string.replace(item, "")
5b0406c57aed3b786c4f20501be80e18f945928f
695,833
def is_registration_api_v1(request): """ Checks if registration api is v1 :param request: :return: Bool """ return 'v1' in request.get_full_path() and 'register' not in request.get_full_path()
fe82c373420022ad198785eb2c8575abe7d29c56
464,607
def error(p:float, p_star:float) -> tuple: """ Compute the absolute error and relative error in approximations of p by p^\\star. ---------------------------- Args: p, p_star: Float. Returns: (absolute error, relative error). Raises: None. """ absolute_error = abs(p - p_star) relative_error = absolute_error / p return (absolute_error, relative_error)
e75a96616592a8f844c967a2968a748860023732
232,313
import math def distance(x1, y1, x2, y2): """distance: euclidean distance between (x1,y1) and (x2,y2)""" return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
b7b4662a88c9afd4b63d6ab04fc51749916749f1
696,214
def get_endpoint(url): """Get the parent url of this url.""" return url.rsplit("/", 1)[0]
42022b2e897a76ca56bb70d72e45c6eaea478d95
593,424
def _get_log_formatter(verbosity_level): """ Get a log formatter string based on the supplied numeric verbosity level. :param int verbosity_level: the verbosity level :return: the log formatter string :rtype: str """ formatter = "%(levelname)s: %(message)s" if verbosity_level >= 3: formatter = "%(levelname)s: %(name)s: %(message)s" return formatter
b34d470b679e3b7d540290ef394ccada418b9ef7
595,733
def multiply(m, n): """Recursively multiply the number 'm' by 'n' times >>> multiply(5, 3) 15 """ """BEGIN PROBLEM 2.1""" return m if n == 1 else m + multiply(m, n - 1) """END PROBLEM 2.1"""
389e9692db846230e53670ceb53ffffcdad007f9
410,771
def loose_bool(s: str) -> bool: """Tries to 'loosely' convert the given string to a boolean. This is done by first attempting to parse it into a number, then to a boolean. If this fails, a set of pre-defined words is compared case-insensitively to the string to determine whether it's positive/affirmative or negative. Parameters ---------- * s: `str` - The string to convert. Returns ------- * `bool`: The resulting boolean. Raises ------ * `ValueError` when the boolean value can't be determined. """ s = s.strip() try: return bool(float(s)) except ValueError: pass s = s.lower() if s in ['y', 'yes', 't', 'true', 'do', 'ok']: return True elif s in ['n', 'no', 'f', 'false', 'dont']: return False else: raise ValueError(f"String {repr(s)} cannot be loosely casted to a boolean")
a22eaac28b0b3452ca2656d2dff7836bb0daa49a
331,070
def read_converged(content): """Check if program terminated normally""" converged = False for line in content.split("\n"): if 'EXECUTION OF GAMESS TERMINATED NORMALLY' in line: converged = True return converged
d3132bd1fd8d61556f0f48eb19ff5042ac2f6302
533,569
def isAnalysisJob(trf): """ Determine whether the job is an analysis job or not """ if (trf.startswith('https://') or trf.startswith('http://')): analysisJob = True else: analysisJob = False return analysisJob
75ccaf711dd04dc99aca266533fee7303fad3e85
698,038
def format_signing_data(api_key_id, host, url, method): """ Format the input data for signing to the exact specification. Mainly, handles case-sensitivity where it must be handled. >>> format_signing_data('0123456789abcdef', 'veracode.com', '/home', 'GET') 'id=0123456789abcdef&host=veracode.com&url=/home&method=GET' >>> format_signing_data('0123456789abcdef', 'VERACODE.com', '/home', 'get') 'id=0123456789abcdef&host=veracode.com&url=/home&method=GET' """ # Ensure some things are in the right case. # Note that path (url) is allowed to be case-sensitive (because path is sent along verbatim) # This is an HTTP fact, not a rule of our own design. stackoverflow.com/a/17113291/884640 api_key_id = api_key_id.lower() host = host.lower() method = method.upper() # BTW we do not use a stdlib urlencode thing, because it is NOT exactly URL-encoded! return 'id={api_key_id}&host={host}&url={url}&method={method}'.format(api_key_id=api_key_id, host=host, url=url, method=method)
6e1959a127ac76559d08fe896f7dcdd822e270ff
274,449
import torch def masked_logsumexp(x: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor: """Computes logsumexp over elements of a tensor specified by a mask in a numerically stable way. Parameters ---------- x The input tensor. mask A tensor with the same shape as `x` with 1s in positions that should be used for logsumexp computation and 0s everywhere else. dim The dimension of `x` over which logsumexp is computed. Default -1 uses the last dimension. Returns ------- torch.Tensor Tensor containing the logsumexp of each row of `x` over `dim`. """ max_val, _ = (x * mask).max(dim=dim) max_val = torch.clamp_min(max_val, 0) return torch.log( torch.sum(torch.exp(x - max_val.unsqueeze(dim)) * mask, dim=dim)) + max_val
838b747bbcbd155f0ba338268c732575283c324a
412,012
def total_others_income(responses, derived): """ Return the total of other incomes """ total = 0.0 for income in derived['others_income']: try: total += float(income['income_others_amount']) except ValueError: pass return total
ab9dcca24609a32c846dcabdea08fc262d725a03
503,366
def non_basemap_layers(layers): """Retrieve all map layers which are not basemaps""" return [layer for layer in layers if not layer.is_basemap]
8a8bab454d97e8fe686be874c56421d2013a039f
51,901
def findDivisors (n1, n2): """Assumes that n1 and n2 are positive ints Returns a tuple containing all common divisors of n1 & n2""" divisors = () #the empty tuple for i in range(1, min (n1, n2) + 1): if n1%i == 0 and n2%i == 0: divisors = divisors + (i,) return divisors
60c20f6866fbed2cfc79bbe0b28396751fdfe6ff
530,854
def estimate_average_price(order_qty: float, order_price: float, current_qty: float, current_entry_price: float) -> float: """Estimates the new entry price for the position. This is used after having a new order and updating the currently holding position. Arguments: order_qty {float} -- qty of the new order order_price {float} -- price of the new order current_qty {float} -- current(pre-calculation) qty current_entry_price {float} -- current(pre-calculation) entry price Returns: float -- the new/averaged entry price """ return (abs(order_qty) * order_price + abs(current_qty) * current_entry_price) / (abs(order_qty) + abs(current_qty))
2466ba8a3d4374d83e44b4ffeff262a8741d621d
466,559
def I2(Q,dfg): """ Computes the I^2 value, ie, percent of variation due to heterogeneity rather than chance By convention, Q = 0 if Q < k-1, so that the precision of a random effects summary estimate will not exceed the precision of a fixed effect summary estimate See Higgins & Thompson 2002; DOI: 10.1002/sim.1186 :param Q: Q statistics (measure of the dispersion of the effect sizes) :param dfg: degress of freedom :return: I2 statistic """ # if pd.isnull((Q < dfg)): # I2 = 0 # return I2 # else: I2=((Q-dfg)/Q)*100 return I2
4e9b08f1484f578cb6a0af9c630ba607071fd21c
523,802
def uniq(iterable, key=lambda x: x): """ Remove duplicates from an iterable. Preserves order. :type iterable: Iterable[Ord => A] :param iterable: an iterable of objects of any orderable type :type key: Callable[A] -> (Ord => B) :param key: optional argument; by default an item (A) is discarded if another item (B), such that A == B, has already been encountered and taken. If you provide a key, this condition changes to key(A) == key(B); the callable must return orderable objects. """ keys = set() res = [] for x in iterable: k = key(x) if k in keys: continue res.append(x) keys.add(k) return res # Enumerate the list to restore order lately; reduce the sorted list; restore order # def append_unique(acc, item): # return acc if key(acc[-1][1]) == key(item[1]) else acc.append(item) or acc # srt_enum = sorted(enumerate(iterable), key=lambda item: key(item[1])) # return [item[1] for item in sorted(reduce(append_unique, srt_enum, [srt_enum[0]]))]
219cba5494198fc806b503e9000a7e491fe2a7c5
625,466
import random def split_test_from_training_data(network, ratio=0.1): """ Splits a given network into two networks with disjoint edges randomly. """ test_edges = random.sample(list(network.edges()), int(len(network.edges()) * ratio)) training_network = network.copy() training_network.remove_edges_from(test_edges) test_network = network.copy() test_network.remove_edges_from(training_network.edges()) return training_network, test_network
589c2b4f8c56941bca70a7342e5a47a41e23ce86
631,072
from typing import List def append_suffix(name: str, suffix: List[str]) -> List[str]: """ Helper function to append suffixes to the given name. """ return list(map(lambda x: name + x, suffix))
6ce093b30eced8b9f5bc52503fd91cf95c6accba
190,428
def pybel_to_inchi(pybel_mol, has_h=True): """ Convert an Open Babel molecule object to InChI Args: pybel_mol (OBmol): An Open Babel molecule. has_h (bool): Whether the molecule has hydrogen atoms. ``True`` if it does. Returns: str: The respective InChI representation of the molecule. """ if has_h: inchi = pybel_mol.write('inchi', opt={'F': None}).strip() # Add fixed H layer else: inchi = pybel_mol.write('inchi').strip() return inchi
219842968790d62cb05cd91228aacc500bf726a5
327,062
import json def json_dump(obj, path): """Save a json object to a file.""" with open(path, 'w') as f: return json.dump(obj, f, indent=2)
dc1ca23ed1322d860cf2c9236e56394489acf29e
101,818
def path_as_0_moves(path): """ Takes the path which is a list of Position objects and outputs it as a string of rlud directions to match output desired by Rosetta Code task. """ strpath = "" for p in path: if p.directiontomoveto != None: strpath += p.directiontomoveto return strpath
6423f7c4c46fc79cd38cdddb3d367411ef9a05d4
663,515
import csv def read_path2port_map(filename): """ Reads csv file containing two columns: column1 is path name, column2 is port number :param filename: :return: dictionary with port as key and path as value """ res = {} with open(filename, 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: res[row[1]] = row[0] return res
39a317c21d66c544bd50576493cb1e50dbc5b6bf
72,391
def get_height(image): """get_height(image) -> integer height of the image (number of rows). Input image must be rectangular list of lists. The height is taken to be the number of rows. """ return len(image)
3aa94c4b2458d2a233f32ee10889e52566c04ecb
14,979
def month_str(month, upper=True): """Returns the string e.g. 'JAN' corresponding to month""" months=['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] mstr = months[month - 1] if upper: mstr = mstr.upper() return mstr
535422928b6fa66691d6f29431ca3dc1a064b670
514,630
from pathlib import Path import yaml def load_plot_these_methods_config(path): """ Loads PLOT_THESE_METHODS.yaml present at `path`. Args: path (str): path where config files can be found. Returns: (set): a set of method that needs to be plotted. an empty set if the file is not found. """ include_methods = Path(path).resolve() / "PLOT_THESE_METHODS.yaml" if include_methods.exists(): with open(str(include_methods), "rb") as f: plot_these_methods = yaml.safe_load(f) return set([x for x, plot in plot_these_methods.items() if plot]) return {}
17f5951d82a3ad24747cbe868743d436275b6082
160,088
def identify_url(url): """ A possible way to identify the link. Not Exhaustive! :param url: :return: 0 - Profile 1 - Profile post 2 - Group 3 - Group post """ if "groups" in url: if "permalink" in url: return 3 else: return 2 elif "posts" in url: return 1 else: return 0
eb2c63c9d421e0ce1dd3d5cb8a144403895433fe
541,087
import math def next_even_number(val): """Returns the next even number after the input. If input is even, returns the same value.""" return math.ceil(val / 2) * 2
700334e60c4abfa949524c1825b7ee97dd8f75cd
76,213
from datetime import datetime def get_tag(tag=None): """ Simple helper function to create a tag for saving a file if one does not already exist. This is useful because in some places we don't know whether we will have a tag or not, but still want to save files. Parameters ---------- tag : string or None (optional) Name of file if it already exists Returns ---------- tag : string or None (optional) Name picked for the file """ # Get the data and time in a file-saving--friendly format date_time = datetime.now().strftime("%m_%d_%Y_%H_%M_%S") # If there is no tag, use the date and time tag = date_time if tag is None else tag return tag
5cecc708086dbcb1a7361ecf55dd015f9edaeedf
624,785
import torch def project_to_2d_linear(X, camera_params): """ Project 3D points to 2D using only linear parameters (focal length and principal point). Arguments: X -- 3D points in *camera space* to transform (N, *, 3) camera_params -- intrinsic parameteres (N, 2+2+3+2=9) """ assert X.shape[-1] == 3 assert len(camera_params.shape) == 2 assert camera_params.shape[-1] == 9 assert X.shape[0] == camera_params.shape[0] while len(camera_params.shape) < len(X.shape): camera_params = camera_params.unsqueeze(1) f = camera_params[..., :2] c = camera_params[..., 2:4] XX = torch.clamp(X[..., :2] / X[..., 2:], min=-1, max=1) return f*XX + c
bdd879930f6ee03eb170b85445e0a17727d37de2
287,529
def bdf_width(width: int) -> int: """Calculates the width in bits of each row in the BDF from the actual witdth of a character in pixels.""" # NOTE: Lines in BDF BITMAPs are always stored in multiples of 8 bits # (https://stackoverflow.com/a/37944252) return -((-width) // 8) * 8
c9d478d41ab94358524e384cf0c384994052626c
637,243
def get_n_beads(n, i1 ,i2): """ given length of the ring polymer (n) and the starting-ending positions (i1, i2) returns the length of the segment of the smaller length :param n: number of elements :type n: int :param i1: starting position :type i1: int :param i2: ending position :type i2: int :return: length of the smaller segment :rtype: int """ if (n < max(i1,i2)) | (i1<0) | (i2<0): return 0 else: return min(abs(i2-i1)+1, n - abs(i2-i1)+1)
5dee01efe31f9d98972dcdc997ad60ea1ba45b39
664,458
def int_to_bytes_big_endian(x: int, n_bytes: int) -> bytearray: """Converts integer to bytes in big endian mode""" if x >= 256 ** n_bytes: raise ValueError("Conversion overflow") res = bytearray(n_bytes) shift = 0 for i in range(n_bytes - 1, -1, -1): res[i] = (x >> shift) & 0xff shift += 8 return res
95487c6be1c24f68585619643ca90a1a87c3b1fb
528,032
def strip_2tuple(dict): """ Strips the second value of the tuple out of a dictionary {key: (first, second)} => {key: first} """ new_dict = {} for key, (first, second) in dict.items(): new_dict[key] = first return new_dict
20f721da141f75bceb8bfd90d7ab02dbb82a01ce
660,188
def _parse_row(row): """Parses a row of raw data from a labelled ingredient CSV file. Args: row: A row of labelled ingredient data. This is modified in place so that any of its values that contain a number (e.g. "6.4") are converted to floats and the 'index' value is converted to an int. Returns: A dictionary representing the row's values, for example: { 'input': '1/2 cup yellow cornmeal', 'name': 'yellow cornmeal', 'qty': 0.5, 'range_end': 0.0, 'unit': 'cup', 'comment': '', } """ # Certain rows have range_end set to empty. if row['range_end'] == '': range_end = 0.0 else: range_end = float(row['range_end']) return { 'input': row['input'], 'name': row['name'], 'qty': float(row['qty']), 'range_end': range_end, 'unit': row['unit'], 'comment': row['comment'], }
e4b521a8906dbe46c80604f93a76bea39db21f8a
134,912
def evalt(t): """ Evaluate tuple if unevaluated >>> from logpy.util import evalt >>> add = lambda x, y: x + y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5 """ if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else: return t
6214f6c3e35be0556e04d5994d6f2e730756917a
642,052
def split_cdl(cdl_string): """ Accepts a comma delimited list of values as a string, and returns a list of the string elements. """ return [x.strip() for x in cdl_string.split(',')]
8f73bdfdc1a70f513ed8f381a93bdd7392e4b332
564,590
def build_url() -> str: """Build url for standings source""" return 'https://www.hockey.no/live/Standings?date=01.11.2020&tournamentid=397960&teamid=0'
039f0ead632f9e2e9af54fc028552d9f8d7343b2
610,308
def decode_text(text): """Decodes a string from HTML.""" output = text output = output.replace('\\n', '\n') output = output.replace('\\t', '\t') output = output.replace('\s', '\\') output = output.replace('&lt;', '<') output = output.replace('&gt;', '>') output = output.replace('&quot;', '"') return output
0ea8d4ead854a44cf0da6e8b3a08c6f286d3420e
307,550
def format_time(start, end): """ Format length of time between start and end. :param start: the start time :param end: the end time :return: a formatted string of hours, minutes, and seconds """ hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, 60) return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)
5e6879251c6f253c0260dd31fc455f0c87901ab9
634,061
import re def str_pattern_valid(sname, pattern_group): """ Whether the sname matches the pattern in pattern_group """ for patt_str in pattern_group: pattern = re.compile(patt_str) match = re.match(pattern, sname) if match is not None: return True return False
b9f86b58a068d88a9defeb279ab1a9a24cec9fdf
608,616