content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def query(db): """Query the database for hosts that require client certificates. Parameters ---------- db : pymongo.database.Database The Mongo database connection Returns ------- pymongo.cursor.Cursor: Essentially a generator for a list of dicts, each containing the pshtt scan results for a single host that requires authentication via client certificates. The results are sorted by agency name. """ client_cert_hosts = db.https_scan.find( {"latest": True, "live": True, "https_client_auth_required": True}, {"_id": False, "latest": False}, ).sort([("agency.name", 1)]) return client_cert_hosts
b21f4e47664124dfe613b3579abfc5559c562b80
421,611
def round_masses(mass): """ Round all the masses for the output to 8 digits after comma """ if mass == '-': return '-' else: return round(mass, 8)
bb7f3fbbda7fbc2453ab8dfd3060e9c92e1e54cc
74,673
from datetime import datetime def gen_today_file_name() -> str: """ generate today json filename Returns: today_in_history-*.json """ now = datetime.now().strftime('%m-%d') file_today: str = 'today_in_history-%s.json' % now return file_today
37991e761021a1d5742b82359fbdf88d1d58f975
15,745
from datetime import datetime def check_expiration(expiry_date: bytes) -> bool: """Check if the MRZ expiry date is older than today's date.""" date = expiry_date.decode("utf-8") date_obj = datetime.strptime(date, "%y%m%d") if date_obj.date() < datetime.now().date(): return False return True
fb0b6af3fd144fa31965074277aff3c9a6b665eb
321,862
def map_val(val, in_min, in_max, out_min, out_max): """ Function based on the map function for the arduino https://www.arduino.cc/reference/en/language/functions/math/map/ """ return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
f4caed41e549387966e36904545a5bd18001740c
589,088
def get_list(node, tag): """ Get sub-nodes of this node by their tag, and make sure to return a list. The problem here is that xmltodict returns a nested dictionary structure, whose substructures have different *types* if there's repeated nodes with the same tag. So a list of one thing ends up being a totally different thing than a list of two things. So, here, we look up a sub-node by its tag, and return a list regardless of whether it matched 0, 1, or more things. """ subnode = node.get(tag, []) if isinstance(subnode, list): return subnode else: return [subnode]
1eebf70507960f4f97bb25ec5f4b728e80cd2b2a
626,529
def gymnastics(lis): """ Returns the average of the list. """ if len(lis) > 2: lis = sorted(lis) del lis[-1] del lis[0] return int(sum(lis) / len(lis))
0e535139be1ed80eee1319b68ad21753f7b4bb17
317,165
def sum_sequence(sequence): """ What comes in: A sequence of integers. What goes out: Returns the sum of the numbers in the given sequence. Side effects: None. Examples: sum_sequence([8, 13, 7, -5]) returns 23 sum_sequence([48, -10]) returns 38 sum_sequence([]) returns 0 Type hints: :type sequence: list or tuple (of integers) """ # ------------------------------------------------------------------------- # DONE: 3. Implement and test this function. # Tests have been written for you (above). # # RESTRICTION: # You may NOT use the built-in sum function # in IMPLEMENTING this function. # -- The TESTING code above does use built_ins.sum # as an ORACLE in TESTING this function, however. # ------------------------------------------------------------------------- total = 0 for k in range(len(sequence)): total = total + sequence[k] return total
78c9a1ddf131ae34f12b051918d787cf9e240c7d
513,746
def readcsv(infile, separator=',', ignoreheader=False): """Read a csv file into a list of lists""" with open(infile, 'r') as f: list_of_rows = [[x.strip() for x in r.split(separator)] for r in f.readlines()] return list_of_rows if not ignoreheader else list_of_rows[1:]
4d590e9f5881db0d2278336bbb95dfd106416690
571,039
def _calculate_total_mass_(elemental_array): """ Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_()) :param elemental_array: an array of dictionaries containing information about the elements in the system :return: the total weight of the system """ return sum(a["weight"] for a in elemental_array)
1c02c9ecbd09e7a3e74c7207dc435ee4e9ebbcf7
639,455
def polygon_clip(subject_polygon, clip_polygon): """ clip a polygon with another polygon (ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python) :param subject_polygon: a list of (x,y) 2d points, any polygon :param clip_polygon: a list of (x,y) 2d points, has to be *convex* :return: a list of (x,y) vertex point for the intersection polygon """ def inside(p): return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]) def compute_intersection(): dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]] dp = [s[0] - e[0], s[1] - e[1]] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3] output_list = subject_polygon cp1 = clip_polygon[-1] for clip_vertex in clip_polygon: cp2 = clip_vertex input_list = output_list output_list = [] s = input_list[-1] for subject_vertex in input_list: e = subject_vertex if inside(e): if not inside(s): output_list.append(compute_intersection()) output_list.append(e) elif inside(s): output_list.append(compute_intersection()) s = e cp1 = cp2 if len(output_list) == 0: return None return output_list
1145848a7cd5f59352f07dcd02dc0d6df9a91d62
295,177
def creds_changed(context: dict, identity_code: str) -> bool: """ Check whether the credentials were changed by the user. Args: context (dict): Integration context from Demisto. identity_code (str): Lansweeper application identity code. Returns: creds_changed (bool): True if credentials were changed, False otherwise. """ return context.get("identity_code", "") != identity_code
c41810e4a79141bf4213356c736f9551f5bb0254
234,685
from typing import Sequence def html_open(style: Sequence[str]) -> str: """ HTML tags to open a style. :param style: sequence of html tags without the '<' and '>' :return: opening html tags joined into a single string >>> style = ['font color="red" size="32"', 'b', 'i', 'u'] >>> html_open(style) '<font color="red" size="32"><b><i><u>' """ return "".join((f"<{x}>" for x in style))
581ef4dc25e4985d6c64bd96ec0d8089ee22d59c
410,947
def _mobius(p, q): """ Applies the mobius transformation that fixes the line from q to the origin and sends q to the origin to the point p. Parameters ---------- p : list of floats, length 2 The coordinate we are applying this transformation to. q : list of floats, length 2 The coordinate that gets sent to the origin by this map. Returns ------- list of floats, length 2 The transformed coordinate p after applying the transformation that moves q to the origin. """ # pylint:disable=invalid-name # pure math formula u, v = p a, b = q return [-1 * ((u-a)*(a*u+b*v-1)+(v-b)*(a*v-b*u))/((a*u+b*v-1)**2+(a*v-b*u)**2), -1 * ((v-b)*(a*u+b*v-1)-(u-a)*(a*v-b*u))/((a*u+b*v-1)**2+(a*v-b*u)**2)]
190296816b2bc9403fdfcb362862c6e062502914
572,597
def is_tty(stream): # taken from catkin_tools/common.py # pragma: no cover """Returns True if the given stream is a tty, else False""" return hasattr(stream, 'isatty') and stream.isatty()
dee3bb24aa2e7cd39fcbf0d63051c9c5a5980b52
588,826
def take_one(ls): """ Extract singleton from list """ assert len(ls) == 1 return ls[0]
bfb1abb4a96aa08c6abd95ae53a8e6828730e08c
560,554
def _process_wohand(data: bytes) -> dict[str, bool | int]: """Process woHand/Bot services data.""" _switch_mode = bool(data[1] & 0b10000000) _bot_data = { "switchMode": _switch_mode, "isOn": not bool(data[1] & 0b01000000) if _switch_mode else False, "battery": data[2] & 0b01111111, } return _bot_data
e15d5d29b98a07155259f898474a2c9a90db7c02
530,393
import math def split_list_equally(list_to_split: list, num_inter_lists: int): """ Split list_to_split in equally balanced lists among num_inter_lists """ if num_inter_lists < 1: raise Exception("max_items_per_line needs to be greater than 0") max_list_items = math.ceil(len(list_to_split) / num_inter_lists) return [ list_to_split[i : i + max_list_items] for i in range(0, len(list_to_split), max_list_items) ]
4107f8db4e795c5f55e479c43d21757bf7f265e1
560,044
def make_timestamp_range(start, end): """Given two possible datetimes, create the query document to find timestamps within that range using $gte for the lower bound and $lt for the upper bound. """ ts_range = {} if start: ts_range['$gte'] = start if end: ts_range['$lt'] = end return ts_range
cf450f7f9c3f8dc239ed72924ad660438b677956
560,965
def reverse_probs(probs): """ Reverses the conditional probability assuming that variables are uniformly distributed Parameters ---------- probs : probs[x][y] = Pr(Y=y | X=x) Returns ------- reverse : reverse[y][x] = Pr(X=x | Y=y) assuming X is uniform """ reverse = {} for x, probs_x in probs.items(): for y, p in probs_x.items(): reverse.setdefault(y, {})[x] = p for y, probs_y in reverse.items(): norm = sum(probs_y.values()) for x, p in probs_y.items(): probs_y[x] = p / norm return reverse
20a0b189027c76bbd4bbd1938778399a08a5d981
584,577
def unpack_twist_msg(msg, stamped=False): """ Get linear and angular velocity from a Twist(Stamped) message. """ if stamped: v = msg.twist.linear w = msg.twist.angular else: v = msg.linear w = msg.angular return (v.x, v.y, v.z), (w.x, w.y, w.z)
1182a9c5c9aff25cb2df261a32409d0b7df8d08d
679,576
import random import string def get_random_key(n=10): """ Randomly generate string key. :param int n: Length/size of key to generate :return str: Randomize text key """ if not isinstance(n, int): raise TypeError("Non-integral key size".format(n)) if n < 1: raise ValueError("Non-positive key size: {}".format(n)) return "".join(random.choice(string.ascii_letters) for _ in range(n))
92fc680c7ad2a98cac8a842a51ef94fec5adfb4e
307,300
def capacity_cost_rule(mod, prj, prd): """ The capacity cost of projects of the *fuel_spec* capacity type is a pre-specified number with the following costs: * fuel production capacity x fuel production fixed cost; * fuel release capacity x fuel release fixed cost; * fuel storage capacity x fuel storage fixed cost. """ return ( mod.fuel_production_capacity_fuelunitperhour[prj, prd] * mod.fuel_production_capacity_fixed_cost_per_fuelunitperhour_yr[prj, prd] + mod.fuel_release_capacity_fuelunitperhour[prj, prd] * mod.fuel_release_capacity_fixed_cost_per_fuelunitperhour_yr[prj, prd] + mod.fuel_storage_capacity_fuelunit[prj, prd] * mod.fuel_storage_capacity_fixed_cost_per_fuelunit_yr[prj, prd] )
c3c41b4e120c9a53812e1f5ba10bcb3f5325852b
614,855
def get_list_by_separating_strings(list_to_be_processed, char_to_be_replaced=",", str_to_replace_with_if_empty=None): """ This function converts a list of type: ['str1, str2, str3', 'str4, str5, str6, str7', None, 'str8'] to: [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6', 'str7'], [], ['str8']] """ final_list =[] if list_to_be_processed is not None and list_to_be_processed is not False and list_to_be_processed != "": for i in range(0, len(list_to_be_processed)): if list_to_be_processed[i] is None or list_to_be_processed[i] is False or list_to_be_processed[i] == "": temp_list = [] else: if list_to_be_processed[i] == "": list_to_be_processed[i] = str_to_replace_with_if_empty temp_list = list_to_be_processed[i].split(char_to_be_replaced) for j in range(0, len(temp_list)): temp_list[j] = temp_list[j].strip() final_list.append(temp_list) return final_list
7702dd577145c910f4bedc67c85cae6fa7de0854
684,900
def write_list_to_file(list, file_to_write): """ Iterates over the entries in a list and writes them to a file, one list entry corresponds to one line in the file :param list: the list to be written to a file :param file_to_write: the file to write to :return: 0 on success """ with open(file_to_write, 'w') as f: for line in list: f.write(line.rstrip('\n')+"\n") return 0
ced1adf675d4fce9ef75e3bafe05b8458bf4fc32
485,054
import torch def device(tensor=None): """ Get the available computaiton device """ return 'cuda' if torch.cuda.is_available() else 'cpu'
0cbd033270d87a132043d64844411be4a75f90ab
228,397
from math import sqrt def meanstdv(members): """ Calculate mean and standard deviation of data x[]: mean = {\sum_i x_i \over n} std = sqrt(\sum_i (x_i - mean)^2 \over n-1) """ num, mean, std = len(members), 0, 0 for item in members: mean = mean + item mean = mean / float(num) for item in members: std = std + (item - mean)**2 std = sqrt(std / float(num - 1)) return mean, std
d434c3214e2f558ff5b6ef260df0888c06ad4751
339,940
import struct def ub32(b): """Convert bytes (LSB first) to a 32-bit integer. Example: ub32(b'\x12\x34\x56\x78') == 0x78563412 """ (value, ) = struct.unpack('<I', b) return value
73b6e32711ba87d943a20cffb3b705029e8f4e05
335,027
import json def dumpJson(path: str, data: dict): """ Dump data to json path. Returns ------- `tuple(path or exception, True or False)` : First item in tuple is a path if dumping succeeds, else it's an exceptions. Same thing goes for the second tuple """ try: with open(path, "w+") as f: json.dump(data, f, indent=4) return path, True except Exception as e: return e, False
22d568e0833ee325a273967c4752e15ca469c3e8
641,128
def mb(x): """Represent as MB""" return x / 10**6
a1300c4ca37d1517e40a4e4d558281eaa7f3848c
492,233
import inspect def derive_top_level_package_name(package_level=0, stack_level=1): """Return top level package name. Args: package_level (int): How many package levels down the caller is. 0 indicates this function is being called from the top level package, 1 indicates that it's being called from a sub-package, etc. stack_level (int): How many levels down the stack the caller is from here. 1 indicates this function is being called from module scope, 2 indicates this function is being called from another function, etc. This will first get the package name of the module containing the caller. ``package_level`` segments will be then be chopped off of the package name. If this is called from a sub-package, ``package_level`` will have to be adjusted accordingly (add 1 for each sub-package). If this is called indirectly (e.g., via :func:`init_settings`) ``stack_level`` will have to be adjusted accordingly (add 1 for each nested function). """ assert package_level >= 0, 'Package level should be greater than or equal to 0' assert stack_level > 0, 'Stack level should be greater than 0' frame = inspect.stack()[stack_level][0] package = frame.f_globals['__package__'] package = package.rsplit('.', package_level)[0] return package
e9ff1119cd02f01c355aef1e68fae55db7fbbba0
639,304
def get_all_sell_orders(market_datas): """ Get all sell orders from the returned market data :param market_datas: the market data dictionary :return: list of sell orders """ sell_orders = [] for _, market_data in market_datas.items(): for order in market_data: if not order['is_buy_order']: sell_orders.append(order) return sell_orders
47fe504b72d9028d4d2e999ee4b748d9dae7f6ee
101,156
import random def calculate_retry_delay(attempt, max_delay=300): """Calculates an exponential backoff for retry attempts with a small amount of jitter.""" delay = int(random.uniform(2, 4) ** attempt) if delay > max_delay: # After reaching the max delay, stop using expontential growth # and keep the delay nearby the max. delay = int(random.uniform(max_delay - 20, max_delay + 20)) return delay
7579c9b1a3bced2f9c111354f77c27526b66e066
366,548
def low_uint_bound_of_half(number): """ returns the low unsigned integer bound of a half of a number (it is simply a right shift method) """ return number >> 1
76847fbf4a82c47406e983f7e9a1cc7e504c5a7e
542,087
def distortion_correct( x, y, x_d=3235.8, y_d=2096.1, A=0.0143, B=0.0078, r_d=1888.8): """Distortion correct pixel position according to Ken's model where x'=x_d+(x-x_d)*(1+A*(r/r_d)**2+B*(r/r_d)**4) y'=y_d+(y-y_d)*(1+A*(r/r_d)**2+B*(r/r_d)**4) """ # calculate the radius of the source r = ((x - x_d) ** 2 + (y - y_d) ** 2) ** 0.5 # calucluate the x and y corrected positions xi = x_d + (x - x_d) * (1 + A * (r / r_d) ** 2 + B * (r / r_d) ** 4) yi = y_d + (y - y_d) * (1 + A * (r / r_d) ** 2 + B * (r / r_d) ** 4) return xi, yi
ee0cdb9411dbf151fdecddd338f75721bc561b37
315,685
from typing import List def default_json_dir() -> List: """ Default json path for access control entities """ return ["/etc/oidc-proxy/acl"]
6c36e596f7ee0cadfef5e64d4998fb875133ef21
243,840
def get_env_dimensions(env): """ Returns the observation space and action space dimensions of an environment. """ return env.observation_space.shape[0], env.action_space.n
26182dbe7ee76a5da74d939f5c9f3aafeaed4abc
272,834
def version_to_string(version, parts=3): """ Convert an n-part version number encoded as a hexadecimal value to a string. version is the version number. Returns the string. """ part_list = [str((version >> 16) & 0xff)] if parts > 1: part_list.append(str((version >> 8) & 0xff)) if parts > 2: part_list.append(str(version & 0xff)) return '.'.join(part_list)
c766a2efdede43149d2592fbf3cbea1f6f279b4a
22,788
def array_unique(array): """ Removes duplicate values from an array """ return list(set(array))
028642c36d7a86cf10d20bf9b740539befaa4da8
287,586
def graphprot_predictions_read_in_ids(predictions_file): """ Given a GraphProt .predictions file, read in column 1 IDs in order appearing in file, and store in list. >>> test_file = "test_data/test.predictions" >>> graphprot_predictions_read_in_ids(test_file) ['SERBP1_K562_rep01_2175', 'SERBP1_K562_rep01_544', 'SERBP1_K562_rep01_316'] """ ids_list = [] with open(predictions_file) as f: for line in f: cols = line.strip().split("\t") seq_id = cols[0] ids_list.append(seq_id) f.close() return ids_list
70b426d3336a694920919647406fae4f06597797
364,839
from typing import Optional def convert_cm3(value: int) -> Optional[float]: """Convert a value from the ToonAPI to a CM3 value.""" if value is None: return None return round(float(value) / 1000.0, 2)
04f5c21fc51ce1418d3a25c9d6479d417f5ccb1a
476,375
def find_nth_document(homophonesGroupCollection, n): """ Return nth document from database (insertion order). """ return homophonesGroupCollection.find_one(skip=n)
2cbc42501943623f7e541f2b73292b165be37b78
478,879
def _SheriffIsFound(sheriff_key): """Checks whether the sheriff can be found for the current user.""" try: sheriff_entity = sheriff_key.get() except AssertionError: # This assertion is raised in InternalOnlyModel._post_get_hook, # and indicates an internal-only Sheriff but an external user. return False return sheriff_entity is not None
51f7a5d09d55f1f4a75aeaeedccb9dbcf3bbcdf4
591,017
def blocks_table_l() -> dict[int, int]: """The table is the number of blocks for the correction level L. Returns: dict[int, int]: Dictionary of the form {version: number of blocks} """ table = { 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2, 10: 4, 11: 4, 12: 4, 13: 4, 14: 4, 15: 6, 16: 6, 17: 6, 18: 6, 19: 7, 20: 8, 21: 8, 22: 9, 23: 9, 24: 10, 25: 12, 26: 12, 27: 12, 28: 13, 29: 14, 30: 15, 31: 16, 32: 17, 33: 18, 34: 19, 35: 19, 36: 20, 37: 21, 38: 22, 39: 24, 40: 25 } return table
deb53cc3c84de9129dc190d3458bdc7f3050b5c0
462,420
def merge_dicts(*dict_args, **extra_entries): """ Given an arbitrary number of dictionaries, merge them into a single new dictionary. Later dictionaries take precedence if a key is shared by multiple dictionaries. Extra entries can also be provided via kwargs. These entries have the highest precedence. """ res = {} for d in dict_args + (extra_entries,): res.update(d) return res
a670ee5e0333a79e630295f0965c8882910269a2
535,948
def world2Pixel(geoMatrix, x, y): """ Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate """ ulX = geoMatrix[0] ulY = geoMatrix[3] xDist = geoMatrix[1] pixel = int((x - ulX) / xDist) line = int((ulY - y) / xDist) return (pixel, line)
ec79dd58ec456c13f1349dd27900c1841c5d6dad
539,451
def is_related(x): """Compute whether a journey includes at least one related link click.""" return x > 0
d3f12f130a3e6823648dcafdec0739e2f2b5cacb
183,534
import six def get_from_dict_if_exists(key, dictionary, convert_key_to_binary=True): """ Get the entry from the dictionary if it exists Args: key: key to lookup dictionary: dictionary to look in convert_key_to_binary: convert the key from string to binary if true Returns: the value of dictionary[key] or None """ if convert_key_to_binary: key = six.b(key) if key not in dictionary: return None return dictionary[key]
024a00a8e09267ba039f6bc327794288352dd712
95,837
def cat_ranges_for_reorder(page_count, new_order): """ Returns a list of integers. Each number in the list is correctly positioned (newly ordered) page. Examples: If in document with 4 pages first and second pages were swapped, then returned list will be: [2, 1, 3, 4] If first page was swapped with last one (also 4 paegs document) result list will look like: [4, 2, 3, 1] """ results = [] # key = page_num # value = page_order page_map = {} for item in new_order: k = int(item['page_order']) v = int(item['page_num']) page_map[k] = v for number in range(1, page_count + 1): results.append( page_map[number] ) return results
219858bb483968826da1dd968a26151703188923
279,594
def get_object(model, **kwargs): """Retrieves a database object of the given class and attributes. model is the class of the object to find. kwargs are the parameters used to find the object. If no object is found, returns None. """ try: return model.objects.get(**kwargs) except model.DoesNotExist: return None
353acfa8675c77da0a4077d5bec6e863c48792e9
171,961
from pathlib import Path def assets_dir() -> Path: """Path to test assets directory.""" return Path(__file__).parent / "assets"
f71bb99d46424e47997c0233b5fd2c04fb154e24
487,428
def make_set(str_data, name=None): """ Construct a set containing the specified character strings. Parameters ---------- str_data : None, str, or list of strs Character string(s) to be included in the set. name : str, optional A name to be used in error messages. Returns ------- set A set of character strings. """ if not str_data: return set() elif isinstance(str_data, str): return {str_data} elif isinstance(str_data, set): return str_data elif isinstance(str_data, list): return set(str_data) elif name: raise TypeError("The {} argument should be str, set, or list: {}".format(name, str_data)) else: raise TypeError("The argument should be str, set, or list: {}".format(str_data))
e31a3d46586c75aeb7d0eb3ef9e059b12c9febc2
543,029
from pathlib import Path def load_groups(input_path: Path) -> list: """ Load in the customs quesetionarre response data into a buffer and group together the responses that are associated with a single group. Responses belonging to a single group are on contiguous lines, and groups are separated by a blank line. Splitting by "\n\n" will break apart the responses from separate groups, and then removing the "\n" characters from in-group responses should then just give us the specific responses void of whitespace characters. Remove empty characters per line and also empty groups. Args: input_path [pathlib.Path]: path to input data Returns: list of lists: [ [group-responses] ] """ with open(input_path, "r") as infile: groups = list( filter( None, [ list( filter( None, [line.strip() for line in group.split("\n") if line != ""], ) ) for group in infile.read().split("\n\n") ], ) ) return groups
f23eb0398757e749786a7ba1fdcb8dede18736fd
37,170
from typing import Union def kelvin_to_celsius(k_degrees: Union[int, float]) -> int: """Returns kelvins converted to celsius :param k_degrees: temperature in kelvins :type k_degrees: float :return: temperature converted to celsius without the fractional part :rtype: int """ MIN_TEMP_KELVIN = 0 K_C_RATIO = 273.15 if not isinstance(k_degrees, (int, float)): raise TypeError("Incorrect argument type of k_degrees. " f"Expected {int} or {float}, " f"got {type(k_degrees)} instead!") if k_degrees < MIN_TEMP_KELVIN: raise ValueError("Incorrect value of k_degrees. " f"k_degrees cannot be lower than {MIN_TEMP_KELVIN}!") celsius = int(k_degrees - K_C_RATIO) return celsius
346d78325228e9eea8367beefcd25bb219e16c40
66,229
def cumulative_sum(points): """ Returns the cumulative sum. """ # logger.info('calculating cumulative sum') csum = [0,] prev = 0 # logger.info('start appending points') for p in points: csum.append(p+prev) prev = p+prev # logger.info('returning sum') return csum
18407079c0bcf2f4f5e2c0b2d3659afb3b537c08
74,989
def _prune_array(array): """Return an array equivalent to the input array. If the input array is a view of a much larger array, copy its contents to a newly allocated array. Otherwise, return the input unchanged. """ if array.base is not None and array.size < array.base.size // 2: return array.copy() return array
2741bca37f97410bac757ec3d0708b71725aa59a
207,702
def region_builder(data): """ Takes an instance of a ping result and builds a dictionary ready to display. The ping result returns the raw results. This function returns a dictionary with all the sections formatted. :param data: dic Result of ping call. :return dic Result of the ping ready to display. """ if len(data) == 1: return {'index': -1, 'region': data[0].ljust(4), 'average': '', 'maximum': '', 'color': '| color=#444'} index = float(data[1]) region_initials = '{region}:'.format(region=data[0].ljust(4)) average = '{average} {unit}'.format(average=data[1], unit=data[3]) maximum = '(max {maximum} {unit})'.format(maximum=data[2], unit=data[3]) if index < 100: color = '|color=#0A640C' # Green elif index < 150: color = '|color=#FEC041' # Yellow else: color = '|color=#FC645F' # Red return {'index': index, 'region': region_initials, 'average': average, 'maximum': maximum, 'color': color}
040ca4f28c08a3a4bb437fd0dff56606e3b63fcd
425,773
from typing import List from typing import Callable from typing import Iterator from typing import Dict def transform( transformers: List[Callable[[Iterator[Dict]], Iterator[Dict]]], data: Iterator[Dict] ) -> Iterator[Dict]: """Call transformers in order.""" for transformer in transformers: data = transformer(data) return data
38f2ff1c3e3bab3d4d4bf50817a025a4463d4f0f
153,216
import inspect def clsname(obj): """Get objects class name. Args: obj (:obj:`object`): The object or class to get the name of. Returns: (:obj:`str`) """ if inspect.isclass(obj) or obj.__module__ in ["builtins", "__builtin__"]: return obj.__name__ return obj.__class__.__name__
f2787e0f94f95bcafb4668130eb8ab23d84fd7b6
616,015
def print_error(p, i): """ Returns the error message for package installation issues. :param str p: The name of the package to install. :param str i: The name of the package when imported. """ error_message = f""" {i} not present. Please do the installation using either: - pip install {p} - conda install -c conda-forge {p} """ return error_message
b447643c1585f3dd05c2e09f525ecba97a14de5e
161,982
from typing import Match def replace_one_decorated_callable_start(m: Match) -> str: """Define the replacement function used in `correct_all_decorated_callable_starts`.""" start = int(m[5]) + int(m[6]) # number of decorators + line number of the first decorator return f"{m[1]}/_type={m[2]}{m[3]}{start}:{m[4]}"
819079d96e2aa60b745f16488dae916880dc0ba6
648,236
def get_numeric_list(numeric_range): """Convert a string of numeric ranges into an expanded list of integers. Example: "0-3,7,9-13,15" -> [0, 1, 2, 3, 7, 9, 10, 11, 12, 13, 15] Args: numeric_range (str): the string of numbers and/or ranges of numbers to convert Raises: AttributeError: if the syntax of the numeric_range argument is invalid Returns: list: an expanded list of integers """ numeric_list = [] try: for item in numeric_range.split(","): if "-" in item: range_args = [int(val) for val in item.split("-")] range_args[-1] += 1 numeric_list.extend([int(val) for val in range(*range_args)]) else: numeric_list.append(int(item)) except (AttributeError, ValueError, TypeError) as error: raise AttributeError( "Invalid 'numeric_range' argument - must be a string containing " "only numbers, dashes (-), and/or commas (,): {}".format( numeric_range)) from error return numeric_list
04e690f65db4569e80d43b23f90589da7fa9f254
393,899
def generate_md_code_str(code_snippet: str, description: str = 'Snippet') -> str: """The normal ``` syntax doesn't seem to get picked up by mdv. It relies on indentation based code blocks. This one liner accommodates for this by just padding a code block with 4 additional spaces. Hacky? Sure. Effective? Yup. :param code_snippet: :param description: :return: formatted code snippet """ code_snippet = code_snippet.replace('\n', '\n ') return f'\n###{description}:\n {code_snippet}\n'
4f6f1f61f211292c9f92975fb12659f283f566ef
674,158
def remove_digits(text): """ Remove digits in given text :param text: arbitrary string :return: digit removed text """ text = str(text) __remove_digits = str.maketrans('', '', '0123456789') return text.translate(__remove_digits).strip()
162b984ba951db6a138d6644587a53daf25f43cb
304,400
from datetime import datetime def _json_decoder_hook(obj): """Decode JSON into appropriate types used in this library.""" if "starttime" in obj: obj["starttime"] = datetime.strptime(obj["starttime"], "%Y-%m-%dT%H:%M:%SZ") if "endtime" in obj: obj["endtime"] = datetime.strptime(obj["endtime"], "%Y-%m-%dT%H:%M:%SZ") return obj
00b5634770d3bf823811cea3b7b5e9c035706878
305,479
def selection_sort(alist): """ Sorts a list using the selection sort algorithm. alist - The unsorted list. Examples selection_sort([4,7,8,3,2,9,1]) # => [1,2,3,4,7,8,9] a selection sort looks for the smallest value as it makes a pass and, after completing the pass, places it in the proper location Worst Case: O(n^2) Returns the sorted list. """ # Traverse through all array elements for i in range(len(alist)): # assume that the first item of the unsorted segment is the smallest lowest_value_index = i # This loop iterates over the unsorted items for j in range(i + 1, len(alist)): if alist[j] < alist[lowest_value_index]: lowest_value_index = j # Swap values of the lowest unsorted element with the first unsorted # element alist[i], alist[lowest_value_index] = alist[lowest_value_index], alist[i] return alist
f986addfdfd402403d57524a9f8b0d46751367a9
614,631
def get_attributes(obj): """ Fetches the attributes from an object. :param obj: The object. :type obj: object :returns: A dictionary of attributes and their values from the object. :rtype: dict """ return {k: getattr(obj, k) for k in dir(obj) if not k.startswith("__")}
6e1cea3ed8ad2fa1c00f7c2eb86efb4a629e9f06
17,790
from typing import List def get_requirements() -> List[str]: """Returns all requirements for this package.""" with open('requirements.txt') as f: requirements = f.read().splitlines() return requirements
fc49b661c07c40ecf1c8d51fb90eb56ee6049a56
686,416
from typing import Optional def _filter_key(k: str) -> Optional[str]: """Returns None if key k should be omitted; otherwise returns the (possibly modified) key.""" if k.startswith("return_"): return None elif k.endswith("_max") or k.endswith("_min"): return None else: k = k.replace("monitor_return", "mr") k = k.replace("wrapped_return", "wr") return k
2d5cfc3b7fb5ef4e072273c8a46ab9a3b5f1a4ca
96,855
def within_range_list(num, range_list): """Float range test. This is the callback for the "within" operator of the UTS #35 pluralization rule language: >>> within_range_list(1, [(1, 3)]) True >>> within_range_list(1.0, [(1, 3)]) True >>> within_range_list(1.2, [(1, 4)]) True >>> within_range_list(8.8, [(1, 4), (7, 15)]) True >>> within_range_list(10, [(1, 4)]) False >>> within_range_list(10.5, [(1, 4), (20, 30)]) False """ return any(num >= min_ and num <= max_ for min_, max_ in range_list)
b1c448f86f7d584abdbc65ea19315853ad615eec
170,726
import json def jsonify(value): """ Convert a value into a JSON string that can be used for JSONB queries in Postgres. If a string happens to contain the character U+0000, which cannot be represented in a PostgreSQL value, remove the escape sequence representing that character, effectively stripping out that character from all strings. """ return json.dumps(value, ensure_ascii=False).replace("\\u0000", "")
7fff497b302822f8f79f0e68b2576c26458df99c
706,308
def get_phred_query(sample_id, gt_ll, genotype, prefix=" and ", invert=False): """Default is to test < where a low value phred-scale is high confidence for that genotype >>> get_phred_query(2, 22, "het") ' and gt_phred_ll_het[1] < 22' >>> get_phred_query(2, 22, "het", prefix="") 'gt_phred_ll_het[1] < 22' >>> get_phred_query(2, 22, "het", prefix="", invert=True) 'gt_phred_ll_het[1] > 22' """ assert genotype in ("het", "homref", "homalt") if not gt_ll: return "" # they passed in the subject: if hasattr(sample_id, "sample_id"): sample_id = sample_id.sample_id sign = ["<", ">"][int(invert)] s = "gt_phred_ll_{genotype}[{sample_id}] {sign} {gt_ll}"\ .format(sample_id=sample_id-1, genotype=genotype, gt_ll=gt_ll, sign=sign) return prefix + s
3b913725bafec554c105173fb4ff720324aa8ae7
28,475
def has_races(path): """Checks if a result file has races.""" with open(path, 'r') as f: return len(f.readlines()) > 2
f56913771e1c0df9e0dc04258bd6172b236eb72b
117,850
def gcd(p, q): """Implementation of Euclid's Algorithm to find GCD between 2 numbers""" if q == 0: return p return gcd(q, p % q)
627ad701807223208f3856473d30440d3e82a471
309,423
def generate_unique_name(pattern, nameset): """Create a unique numbered name from a pattern and a set Parameters ---------- pattern: basestring The pattern for the name (to be used with %) that includes one %d location nameset: collection Collection (set or list) of existing names. If the generated name is used, then add the name to the nameset. Returns ------- str The generated unique name """ i = 0 while True: n = pattern % i i += 1 if n not in nameset: return n
6b4860a6733b924939027a349677c88f5e69788c
117,587
def generate_anisotropy_str(anisotropy): """Generate a string from anisotropy specification parameters. Parameters ---------- anisotropy : None or tuple of values Returns ------- anisotropy_str : string """ if anisotropy is None: anisotropy_str = 'none' else: anisotropy_str = '_'.join(str(param) for param in anisotropy) return anisotropy_str
2f5a02e20daba73ad89c5465678aa07d1fc92d31
470,426
from pathlib import Path def _should_install(session): """Decide if we should install an environment or if it already exists. This speeds up the local install considerably because building the wheel for this package takes some time. We assume that if `sphinx-build` is in the bin/ path, the environment is installed. """ if session.bin_paths is None: session.log("Running with `--no-venv` so don't install anything...") return False bin_files = list(Path(session.bin).glob("*")) sphinx_is_installed = any("sphinx-build" in ii.name for ii in bin_files) force_reinstall = "reinstall" in session.posargs should_install = not sphinx_is_installed or force_reinstall if should_install: session.log("Installing fresh environment...") else: session.log("Skipping environment install...") return should_install
b21feba715cd5889fd7f4ff3d3547daa9e684b21
543,609
def get_sequence_from_seq_dict(bedline, seq_dict, bedtools_format=True): """ Extract the sequence of a specific bedline object from a seq_dict. The seq dict must contain RNA sequences, i.e. stranded and spliced. Args: bedline (bedline): bedline for which we have to get the seqeunce seq_dict (dict): dictionary of SeqIO objects bedtools_format (bool): sequence names are produced by bedtools -nameOnly Returns: Seq: sequence object """ if bedtools_format: name = bedline.name + "(" + bedline.strand + ")" else: name = bedline.name try: seq = seq_dict[name].seq except KeyError as e: raise Exception('The record for '+name+' was not found in the fasta file') from e return(seq)
dd4d3e4b8eeba6d743eac47a4059a5b6434e2b20
139,785
def get_releases(listing: list, specie: str) -> list: """ return the list of gencode releases found on the site. Highest fist. Parameters ---------- listing : list list of gencode FTP paths, some ending with "release_nn" or "release_Mnn" specie : str mouse of human. mouse release numbers are prefixed with "M" Returns ------ list releases sorted from highest to lowest """ # ignore releases without a consistent system. releases = [int(ftpdir[-2:]) for ftpdir in listing if ftpdir[-2:].isdigit()] releases = sorted([str(n) for n in releases if n > 21], reverse=True) if specie == "mouse": releases = ["M" + r for r in releases] # dear gencode: why? return releases
bd0844cce447cfdbbbe95dd68b750764b804325b
90,009
def ts_bin_states(df, column): """ Binning of states that last for several samples. Basically, it is a 'state_changed' counter. E.g.: Index: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | State: | a | a | a | a | b | b | b | a | a | State_bin: | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 2 | Parameters: ----------- df : DataFrame Pandas DataFrame. column : str Name of column with states to be binned. Returns: ----------- df : DataFrame Updated DataFrame """ df[column+'_bin'] = 0 states = list(df[column].unique()) last_st = None st_bin = -1 for index, row in df.iterrows(): curr_st = row[column] if curr_st == last_st: df.loc[index,column+'_bin'] = st_bin else: st_bin += 1 df.loc[index,column+'_bin'] = st_bin last_st = curr_st return df
84f3160981e9e60289dc54edc12ff18377d988a5
436,601
import logging def remove_rn(reference_node_name): """ Removes the RN from the end of a reference node's name :param reference_node_name: node with a reference prefix :return: Node with reference prefix removed """ flg = logging.getLogger("lettuce.xgenSetup.remove_rn") last_r = reference_node_name.rfind('R') rn_removed = reference_node_name[:last_r] flg.info("Converting {0} to {1}.".format(reference_node_name, rn_removed)) return rn_removed
51763bd9cb99d0172a10741e1604dff6c6baac4a
578,061
def area_square(r): """Return the area of a square with side length R.""" return r * r
4b5a25010e14c956eb14a6365fb047c7cb022d6a
368,419
from bisect import bisect_left def binary_search(arr: list, item) -> int: """ performs a simple binary search on a sorted list :param arr: list :param item: :return: int """ i = bisect_left(arr, item) if i != len(arr) and arr[i] == item: return i else: return -1
31c6ddc2c8a23885971fbd5541871d632d24fe90
201,876
def is_disc_aligned(disc, time_counter, align_offset): """Check if disc is aligned.""" return ((disc['cur_position'] + time_counter + align_offset) % disc['positions'] == 0)
3dded7fbd062920faa0c80edb3e384543e1e81fa
87,368
def list_to_map(j, k): """Turn a list into a map.""" return {entry[k]: entry for entry in j}
96fbed9a6ffa6683ce6c0ca1b3f211c0c927a91a
570,224
def offline_ap_processing(offline_aps: list): """ Args: offline_aps: list of offline APs from response.json()['list'] Returns: list with offline AP name """ offline_aps_device_names = list() for offline_ap in offline_aps: device_data = f"Hostname: <{offline_ap.get('deviceName')}> / " \ f"MAC: <{offline_ap.get('apMac')}> / IP: <{offline_ap.get('ip')}>" offline_aps_device_names.append(device_data) return offline_aps_device_names
ac644f6ee3b298a48992cc87530f8be8951cc48e
115,547
import curses def newwin_after(prev_win, h, w, xstart, y_skip=1): """ Create a new curses window starting: - on the y_skip rows after the prev_win, - starting at absolute column xstart :param prev_win : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) """ ybeg, xbeg = prev_win.getbegyx() ymax, xmax = prev_win.getmaxyx() win = curses.newwin(h, w, ybeg + ymax + y_skip - 1, xstart) return win
1342b2034dcba019ae365db03f9ad9660f326afc
481,633
import math def prime_factors(n): """ return a list prime factors for n """ prime_factors = [] while n % 2 == 0: prime_factors.append(2) n = n / 2 # int(math.sqrt(n))+1 is the max to test for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: prime_factors.append(i) n = n / i # Left over prime if n > 2: prime_factors.append(n) return prime_factors
f474e491345a7a8f209239f752cf792abe67f17d
203,588
def is_constant_type(expression_type): """Returns True if expression_type is inhabited by a single value.""" return (expression_type.integer.modulus == "infinity" or expression_type.boolean.HasField("value") or expression_type.enumeration.HasField("value"))
66a3237971299df3c7370f039d87a8b5f4ae2be5
5,565
def set_transformer_in_out(transformer, inputCol, outputCol): """Set input and output column(s) of a transformer instance.""" transformer = transformer.copy() try: transformer.setInputCol(inputCol) except AttributeError: try: transformer.setInputCols([inputCol]) except AttributeError: message = ( "Invalid transformer (doesn't have setInputCol or setInputCols): ", str(transformer.__class__) ) raise ValueError(message) try: transformer.setOutputCol(outputCol) except AttributeError: try: transformer.setOutputCols([outputCol]) except AttributeError: # we accept transformers that do not have an outputCol # (as ColumnDropper) pass return transformer
4bf9bd4abeaa6435df5316c9201d62dd97645cd5
34,970
def rotate_list(alist): """Pop the last element of list out then put it into the first of list. :param alist: A list that want to rotated. :return alist: A rotated list. """ assert type(alist) == list last = alist.pop() alist.insert(0, last) return alist
d3fefe92870aea63e51fff82c274990a0d9151f6
637,657
import re def mangle(string): """Mangles a string to conform with the naming scheme. Mangling is roughly: convert runs of non-alphanumeric characters to a dash. Does not convert '.' to avoid accidentally mangling extensions and does not convert '+' """ if not string: string = "" return re.sub(r"[^a-zA-Z0-9.+]+","-",string)
e181aeef23814fdabf67f41c35ae3979138f1850
527,671
def Un(X, Z): """ Computes Un, full two-sample U-statistic.""" return (X.reshape((-1, 1)) > Z.reshape((1, -1))).mean()
2fa8b5453ca4ba85c8da4d62b38b043a52513c34
477,555
from typing import Union def clamp(value: Union[int, float], min_: Union[int, float], max_: Union[int, float]) -> Union[int, float]: """ Clamps the value between minimum and maximum values. :param value: number to clamp :param min_: minimum value :param max_: maximum value :return: clamped number """ # If inside the boundaries, return the actual value if min_ <= value <= max_: return value # When going over the boundary, return min/max elif value < min_: return min_ else: return max_
dbd79a8e27d79486e0a05827462ae5fd71fc6818
82,960
def truncate_recordings(recordings, max_floor, min_length=300): """ Truncate the recordings so that they never exceed a given floor. This can be used, for example, to train an agent to solve the beginning of every level. Args: recordings: a list of Recordings. max_floor: the floor which no recording should get up to. min_length: the minimum length of a truncated recording for it to be included in the result. Returns: A list of truncated Recordings. """ res = [] for rec in recordings: if rec.floor < 0: continue trunc = rec.truncate(max_floor) if trunc is not None and trunc.num_steps >= min_length: res.append(trunc) return res
cb247ab9a741c9ed8754a9a2ff2c5119eb161c7f
209,047
from typing import Optional from typing import Tuple def get_paginated_indices(offset: Optional[int], limit: Optional[int], length: int) -> Tuple[int, int]: # pylint: disable=invalid-sequence-index """ Given an offset and a limit, return the correct starting and ending indices to paginate with that are valid within a given length of the item being paginated. :param offset: The offset from the starting item for the request :param limit: The limit or amount of items for the request :param length: The length of the list which we are getting indices to paginate """ # Either both limit and offset are set set or neither are set, so if one or more isn't set # then we return the entire list. This usually implies `v1` is being called where we don't paginate at all. if offset is None or limit is None: return 0, length # Remove any negative values. offset = max(offset, 0) limit = max(limit, 0) # If limit is set higher than the number of builds, reduce limit. limit = min(length, limit) starting_index = offset ending_index = min((starting_index + limit), length) return starting_index, ending_index
381557ca08d5ceacbebb739b81f81e4c29d1033a
481,597
def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Positive and negative values are handled. base : int, optional Convert `number` to the `base` number system. The valid range is 2-36, the default value is 2. padding : int, optional Number of zeros padded on the left. Default is 0 (no padding). Returns ------- out : str String representation of `number` in `base` system. See Also -------- binary_repr : Faster version of `base_repr` for base 2. Examples -------- >>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' >>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20' """ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if base > len(digits): raise ValueError("Bases greater than 36 not handled in base_repr.") elif base < 2: raise ValueError("Bases less than 2 not handled in base_repr.") num = abs(number) res = [] while num: res.append(digits[num % base]) num //= base if padding: res.append('0' * padding) if number < 0: res.append('-') return ''.join(reversed(res or '0'))
1ff4609f475c248bf840c5ac1b82ad42d3c575b3
634,255
def bits2positions(bits): """Converts an integer in the range 0 <= bits < 2**61 to a list of integers in the range 0 through 60 inclusive indicating the positions of the nonzero bits. Args: bits: int. An integer in the range 0 <= bits < 2 ** 61 Returns: A list of integers in the range 0 though 60 inclusive. """ return list(i for i in range(61) if (2 ** i) & bits > 0)
41d31ec9744aa6b02e55bfe5b9e4b85818bd5765
496,104
import json import requests def create_remote_version(access_token, version_info, tribe_url): """ Creates a new version for an already existing geneset in Tribe. Arguments: access_token -- The OAuth token with which the user has access to their resources. This is a string of characters. version_info -- The dictionary containing the values for the fields in the version that is going to be created in Tribe. One of these is the resource_uri of the geneset this version will belong to. Returns: Either - a) The newly created version (as a dictionary), or b) An empty list, if the request failed. """ headers = { 'Authorization': 'OAuth ' + access_token, 'Content-Type': 'application/json' } payload = json.dumps(version_info) versions_url = tribe_url + '/api/v1/version' version_response = requests.post( versions_url, data=payload, headers=headers ) # If something went wrong and the version was not created # (making the response status something other than 201), # return the response as is given by Tribe if (version_response.status_code != 201): return version_response try: version_response = version_response.json() return version_response except ValueError: return version_response
28704ff0aaca5144674dd82c98d740124f63b527
264,554
def strip(text, chars=None): """ Creates a copy of ``text`` with the leading and trailing characters removed. The ``chars`` argument is a string specifying the set of characters to be removed. If omitted or None, the ``chars`` argument defaults to removing whitespace. The ``chars`` argument is not a prefix or suffix; rather, all combinations of its values are stripped:: >>> >>> strip(' spacious ') 'spacious' >>> strip('www.example.com','cmowz.') 'example' The outermost leading and trailing ``chars`` argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:: >>> >>> comment_string = '#....... Section 3.2.1 Issue #32 .......' >>> strip(comment_string,'.#! ') 'Section 3.2.1 Issue #32' :param text: The string to copy :type text: ``str`` :param chars: The characters to remove from the ends :type chars: ``str`` :return: A copy of ``text`` with the leading and trailing characters removed. :rtype: ``str`` """ assert isinstance(text,str), '%s is not a string' % text return text.strip(chars)
1e7857c82d7eaba076e22d29efa6909ca6d8d845
366,913