content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
from typing import TextIO def _readline_sk( fp: TextIO, ) -> list: """ Skips lines starting with '#' or '!'. Splits and returns all other lines. Parameters ---------- fp: TextIOWrapper of .snt or .ptn file. Returns ------- arr: The current line in 'fp' split by whitespace. """ arr = fp.readline().split() while arr[0][0] in ['!','#']: arr = fp.readline().split() return arr
8f8a893802759e20668df75b926e02160f69a6e9
409,327
from typing import Tuple def auto_figure_size(figure_shape: Tuple, scaling_factor: int = 4) -> Tuple: """Scales figure shape to generate figure dimensions. Args: figure_shape (Tuple): Figure shape in determines of rows and columns. scaling_factor (int, optional): Defaults to 4. Returns: Tuple: figure dimensions in inches for matplotlib. """ return figure_shape[1] * scaling_factor, figure_shape[0] * scaling_factor
9c584becb9b4cb7a396b7b18647e5fd1a4bc3cc9
592,625
def exclude_blank(seq): """Remove empty and None items from an iterable""" return [x for x in seq if x]
b03c539353889f9ac2d4b3b803e8ac3229f23cb1
463,892
def get_mask(img, axis=None): """Detect regions of interest in a thresholded image Receive a thresholded single-channel image as a 2D uint8 numpy array. Assuming white background, get a mask vector indicating rows or columns (depending on the argument to `axis`) that contain any number of non-white pixels. Return the mask vector as a 1D boolean numpy array. Note: The speed of the implementation allowed for quickly processing sheets of characters into >120,000 separate characters labeled for training/validating dataset. """ if axis not in (0, 1): raise ValueError('missing or invalid argument to `axis`') return (img != 255).any(axis=axis)
14ada59a1429874527b22f4942b6fd8dcec56e05
363,692
def check_interval(child_span, parent_span): """ Given a child span and a parent span, check if the child is inside the parent """ child_start, child_end = child_span parent_start, parent_end = parent_span if ( (child_start >= parent_start) &(child_end <= parent_end) ): return True else: return False
6c6a8e636ad181af821d185ba35f18db41d0ce77
13,473
def input_default(prompt, default): """Displays the prompt, returns input (default if user enters nothing).""" response = input("{} [{}]: ".format(prompt, default)) return response if response else default
7c8f30c22469bc5082f26e2934296baac5a90a2e
597,385
def _CompareAnomalyBisectability(a1, a2): """Compares two Anomalies to decide which Anomaly's TestMetadata is better to use. Note: Potentially, this could be made more sophisticated by using more signals: - Bisect bot queue length - Platform - Test run time - Stddev of test Args: a1: The first Anomaly entity. a2: The second Anomaly entity. Returns: Negative integer if a1 is better than a2, positive integer if a2 is better than a1, or zero if they're equally good. """ if a1.percent_changed > a2.percent_changed: return -1 elif a1.percent_changed < a2.percent_changed: return 1 return 0
ab5ea6d8a88c4df7c56dfea6785137650ba79876
619,696
from dateutil import tz def video_in_period(latest_date, oldest_date, video_date): """Return a Boolean indicating if a said video was uploaded in a specified period. :param latest_date: Upper bound of time interval. :param oldest_date: Lower bound of time interval. :param video_date: video's upload date, in ISO 8601 format, corresponding to UTC+00 (GMT) timezone. :return: True / False depending if the video's upload date is defined period or not. """ tz_local = tz.tzlocal() latest_date_utc = latest_date.astimezone(tz_local) oldest_date_utc = oldest_date.astimezone(tz_local) if oldest_date_utc <= video_date <= latest_date_utc: return True return False
cecde782a412323782b128806a92a4c99159201d
165,948
def all_factors(num): """ Return the set of factors of n (including 1 and n). You may assume n is a positive integer. Do this in one line for extra credit. Example: >>> all_factors(24) {1, 2, 3, 4, 6, 8, 12, 24} >>> all_factors(5) {1, 5} """ factors = set() for i in range(1, int(num / 2) + 1): if num % i == 0: factors.add(i) factors.add(num) return factors
014225dd3117106b53ad678b3258944197cd31a3
445,325
def checksum(im_path, hfunc="sha1", chunk_size=4096): """Compute checksum of file at given path inputs: im_path: String: Path to file to read hfunc: String: hashlib function to use for hash. Options are: sha1, sha224, sha256, sha384, sha512, blake2b blake2s, md5 chunk_size: int: size of binary chunks to use in reading file returns: checksum_value: String: String of hexadecimal value of checksum """ hash_func = eval(f"hashlib.{hfunc}()") with open(im_path, "rb") as fid: for chunk in iter(lambda: fid.read(chunk_size), b""): hash_func.update(chunk) return hash_func.hexdigest()
eaf0ea72f98d79814e2e9419cb2857613f56e38d
382,855
from typing import Union import unicodedata def _unicode_character_name(char: str) -> Union[str, None]: """Get the full unicode char name""" try: return unicodedata.name(char) except ValueError: return None
905803c632908bfa68fb52a27ce76e536182835d
472,632
def _pad_jagged_sequence(seq): """ Pads a 2D jagged sequence with the default value of the element type to make it rectangular. The type of each sequence (tuple, list, etc) is maintained. """ columns = max(map(len, seq)) # gets length of the longest row return type(seq)( ( sub_seq + type(sub_seq)(type(sub_seq[0])() for _ in range(columns - len(sub_seq))) for sub_seq in seq ) )
65285795ccf56edaea61180d42bca861df2d0794
620,038
def required_keys(expr): """ >>> required_keys("VAR1=='VAL1' and VAR2=='VAL2' and VAR3=='VAL3'") ['VAR1', 'VAR2', 'VAR3'] """ return sorted({term.split("=")[0].strip() for term in expr.split("and")})
d6818957dea84c97dd1032e3b2b41be762fbf358
444,794
def zero_float(string): """ Try to make a string into a floating point number and make it zero if it cannot be cast. This function is useful because python will throw an error if you try to cast a string to a float and it cannot be.""" try: return float(string) except: return 0
a902b8ea9fa994ccb674d65dba1e04ceb88fceb7
127,061
def rcBase(base): """Return the reverse complement of the base.""" base = base.upper() if base == 'A': return 'T' if base == 'C': return 'G' if base == 'G': return 'C' if base == 'T': return 'A' return 'N'
368f337adc24a16b324e9323b5a249cfa0971733
569,192
from typing import Iterable from typing import List from typing import Optional def sorted_dedup(iterable: Iterable) -> List[Optional[int]]: """Sorted deduplication without removing the possibly duplicated `None` values.""" dedup: List[Optional[int]] = [] visited = set() for item in iterable: if item is None: dedup.append(item) elif item not in visited: dedup.append(item) visited.add(item) return dedup
b7b5424157bccb764c3db03fadf4ca88e6c50b02
677,551
def fun_command(func): """ A decorator to indicate a "fun command", one that the bot skips when it is 'exhausted' """ func.fun_cmd = True return func
33a5f5de6b00302b724f7c749ed64fbadf2db2e4
403,896
def print_with_count(resource_list): """Print resource list with the len of the list.""" if isinstance(resource_list, str): return resource_list resource_list = [str(elem) for elem in resource_list] return f"(x{len(resource_list)}) {str(resource_list)}"
ced8277905ff3dfa166935bf5b711018d34de188
471,275
import calendar def to_timestamp(date): """Convert a datetime object into a calendar timestamp object Parameters ---------- date : datetime.datetime Datetime object e.g. datetime.datetime(2020, 10, 31, 0, 0) Returns ------- cal : calendar.timegm Calendar timestamp corresponding to the input datetime """ return calendar.timegm(date.timetuple())
514ea392268dc94aa0a14b1dd5ce04425d1ed3bb
35,782
def clean_data(df): """ Function to remove the duplicates and fill NA values if any. :param df: The data frame to clean :return: Cleaned data frame """ df.drop_duplicates(inplace=True) df.fillna(value=0, inplace=True) return df
f166658b0bafb6a692f2faded1924f30c8ae7ef3
180,787
def isEmulator(title): """Returns True if 'emulator' is written in stream title, False otherwise.""" return 'emulator' in title
2bb0baf5434694abb0ae3c4d154c61317b5ffab6
142,208
def is_article(_item): """Item is an article :param _item: Zotero library item :type _item: dict :returns: True if conf, encyArt or journalArt """ return _item["data"]["itemType"] in [ "conferencePaper", "encyclopediaArticle", "journalArticle", ]
6b68199ed28a3dce114e0ddf97bc18f7cf9bc400
338,002
import pytz def get_tz(tz): """ Pass a string and return a pytz timezone object. This function can also infer the timezone from the city, if it is a substring of the timezone. e.g. 'Dubai' will return 'Asia/Dubai.' """ try: t_z = pytz.timezone(tz) except pytz.UnknownTimeZoneError: print("Searching for TZ...") zones = pytz.common_timezones for z in list(zones): if (tz in z) and (tz not in list(zones)): tz = z print(f"Timezone: {z}") t_z = pytz.timezone(tz) return t_z
476f135ad76bbdcacd38acb1eb67e52bd2a59273
114,310
def normalized(expression): """Converts the expression to the syntax necessary for Pandas' DataFrame.eval method. Args: expression: The expression to normalize Returns: A normalized version of the expression usable in Pandas' DataFrame.eval method. """ return expression.replace('!', '~').replace('&&', '&').replace('||', '|')
527d2f82b47a12704c7cffcf5c1fd933854e8ab5
494,180
def initialize_distribution(states, actions): """ initialize a distribution memory :param states: a list of states :param actions: a list of actions :return: a dictionary to record values """ dist = {} for i in states: dist[i] = {} for j in actions: dist[i][j] = [0.0] return dist
d99ff9485d209590b0fa5f8fa772ebe2c1c2303d
600,666
def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: value = value[key] return value except (KeyError, IndexError): return ''
e228678722226289e9cc2e1e1be8aa751159746e
623,415
def as_words(string): """Split the string into words >>> as_words('\tfred was here ') == ['fred', 'was', 'here'] True """ return string.strip().split()
543472e536da2024d118a22575348bbb263abcaf
75,907
def multi_table(number: int): """ This function returns multiplication table for 'number'. """ return '\n'.join(f'{i} * {number} = {i * number}' for i in range(1, 11))
deacd7db6ff67824ac8bd0b8d5cbd821a0e76dc1
433,240
import math def distL2(x1,y1,x2,y2): """Compute the L2-norm (Euclidean) distance between two points. The distance is rounded to the closest integer, for compatibility with the TSPLIB convention. The two points are located on coordinates (x1,y1) and (x2,y2), sent as parameters""" xdiff = x2 - x1 ydiff = y2 - y1 return int(math.sqrt(xdiff*xdiff + ydiff*ydiff) + .5)
da2bfb2521a71e31fc73ec3de8121e5210adf268
293,046
def build_bitfield(left, right, num): """ Builds a bit-field in the specified range [left:right] with the value 'num', inside a 32-bit integer, and returns it. For example: field(4, 2, 3) => 12 Assumptions: * 31 >= left >= right >= 0 * The number is assumed to be small enough to fit the field. If it isn't, its lowest left-right+1 bits are taken. Note that if you take the low bits as the field (N-1:0) and the number is signed, the result will be correct as long as the signed number fits in N bits. """ mask = 2 ** (left - right + 1) - 1 return (int(num) & mask) << right
dc642dd8b8cc09b515e3c55823b6274f8ace8ba5
307,531
import hashlib def hash_file(pathname): """Returns a byte string that is the SHA-256 hash of the file at the given pathname.""" h = hashlib.sha256() with open(pathname, 'rb') as ifile: h.update(ifile.read()) return h.digest()
bdd82aa57abacee91a4631d401af35f0274eb804
13,859
import re def getCallConnectionInfo(call, dest, pdmssp=False): """ Method expects call dict input from output from getCallStatusV2() method. Extract call info - RemotePartyNumber, CallState, CallHandle and LineID, from call if dest matches. INPUTS: call as dict(body), dest as string OUTPUT: Returns response body as dict when dest match successful, None when match unsuccessful. """ body_dict = {} if not pdmssp: for i in range(len(call["data"])): # Removes 'sip:' from RemotePartyNumber if present. body_dict["RemotePartyNumber"] = re.sub( "^sip:", "", call["data"][i]["RemotePartyNumber"] ) if body_dict["RemotePartyNumber"] == dest: body_dict["CallState"] = call["data"][i]["CallState"] body_dict["CallHandle"] = call["data"][i]["CallHandle"] body_dict["LineID"] = call["data"][i]["LineID"] elif pdmssp: for i in range(len(call["data"]["body"]["data"])): # Removes 'sip:' from RemotePartyNumber if present. body_dict["RemotePartyNumber"] = re.sub( "^sip:", "", call["data"]["body"]["data"][i]["RemotePartyNumber"] ) if body_dict["RemotePartyNumber"] == dest: body_dict["CallState"] = call["data"]["body"]["data"][i]["CallState"] body_dict["CallHandle"] = call["data"]["body"]["data"][i]["CallHandle"] body_dict["LineID"] = call["data"]["body"]["data"][i]["LineID"] return body_dict
9e61f245d1d237c52379dd77fd1b4a8833a12e82
314,696
def map_samples_to_indices(c): """Return a dict mapping samples names (key) to sample indices in the numpy genotype arrays (value). """ c.execute("select sample_id, name from samples") return {row['name']: row['sample_id'] - 1 for row in c}
0d2d22daad51b6dd54a2b12621324e51e1f5d61d
120,808
def get_parking_id(id_string): """Get parking ID as an integer if any, otherwise None""" if id_string: return int(id_string) else: return None
90d87048e24f77d2fed1a9867011334ed0376b69
282,387
def get_class_annotations(cls): """Get variable annotations in a class, inheriting from superclasses.""" result = {} for base in reversed(cls.__mro__): result.update(getattr(base, "__annotations__", {})) return result
0cec1a752ebe453db797b0a55b107ba851d28bbb
239,209
def apply_replacements(s, ren_dict): """Replace occurrences of keys with values in a string""" for k, v in ren_dict.items(): s = s.replace(k,v) return s
f10123733119532fc6313ba7e921efe26a3df1ae
176,236
from typing import Dict from typing import Any def validate_key(config_dict: Dict[str, Any], key: str, value_type: type, default: Any): """ Returns config_dict[key] if the value exists and if of type value_type, otherwise returns a default value. """ return ( config_dict[key] if key in config_dict and isinstance(config_dict[key], value_type) else default )
4115d285f16d3b19ac79945bd3dafc4fb5f3440c
93,313
def GetLinkedInUrl() -> str: """Returns URL to LinkedIn.""" return 'https://www.linkedin.com'
fc3fbcc694baae7d29cb1260ede1b3d8f722cd2f
527,893
def get_interface_routes(context, iface): """ Determine the list of routes that are applicable to a given interface (if any). """ return context['routes'][iface['ifname']]
74785c7ebf761c58e378e6a17d18536460c70865
486,623
def cent(q: int, halfmod: int, logmod: int, val: int) -> int: """ Constant-time remainder. :param q: Input modulus :type q: int :param val: Input value :type val: int :param halfmod: q//2 :type halfmod: int :param logmod: ceil(log2(q)) :type logmod: int :return: Value in the set [-(q//2), ..., q//2] equivalent to x mod q. :rtype: int """ y: int = val % q intermediate_value: int = y - halfmod - 1 return y - (1 + (intermediate_value >> logmod)) * q
33338c3cba62ba55ce42eaaa1bef3a86c7859d9d
434,913
def normalize_pc_counter(dict_in): """ Normalize a dictionary by the sum of the total values. Meant to be used with the net ql values from :obj:`decitala.hm.hm_utils`. >>> d = {0: 0, 1: 0.375, 2: 0, 3: 0.25, 4: 0.375, ... 5: 0.375, 6: 0.375, 7: 0, 8: 0.75, 9: 0.25, 10: 0, 11: 0 ... } >>> for pc, norm_val in normalize_pc_counter(d).items(): ... print(pc, norm_val) 0 0.0 1 0.13636363636363635 2 0.0 3 0.09090909090909091 4 0.13636363636363635 5 0.13636363636363635 6 0.13636363636363635 7 0.0 8 0.2727272727272727 9 0.09090909090909091 10 0.0 11 0.0 """ net = sum(dict_in.values()) normalized_dict = {x: (y / net) for x, y in dict_in.items()} assert round(sum(normalized_dict.values())) == 1 return normalized_dict
e406f4b96093f4ae9293b08614ef23dbecf582e0
552,329
def _phi(speciation_initiation_rate, speciation_completion_rate, incipient_species_extinction_rate): """ Returns value of $\varphi$, as given in eq. 6 in Etienne et al. (2014). Parameters ---------- speciation_initiation_rate : float The birth rate, b (the incipient species birth rate and the "good" species birth rate are assumed to be equal): the rate at which new (incipient) species are produced from either incipient or "good" species lineages. speciation_completion_rate : float The rate at which incipient species get converted to good species, $\lambda_1$. incipient_species_extinction_rate : float The incipient species exctinction rate, $\mu_1$: the rate at which incipient species go extinct. Returns ------- t : float The duration of speciation. """ phi = speciation_completion_rate - speciation_initiation_rate + incipient_species_extinction_rate return phi
dcd56555661f565d5a6648734125fb3f2e997aad
636,122
def MoveStr2List(mv: str) -> list: """ param: mv: str [x_src, y_src, x_dst, y_dst] return: mv_list: List-> [int: x_src, y_src, x_dst, y_dst] """ mv_list = [] if mv != " ": mv_list = list(map(int, mv[1:-1].split(","))) return mv_list
dedb0d2b044c5e1dd990d76fbf4986661408ebf2
626,913
def is_operator(node): """This function checks whether a validation node is an operator or not. Args: node(str): The node key you want to check. Returns: : bool. """ return node.startswith('$')
fe8136058b924f9831af1dba3d67c2bf5ed30687
624,682
def create_stack( cfn_client, template_path, stack_name, params={}, capabilities=[], timeout=300, interval=30, ): """ Creates a cloudformation stack from a cloudformation template """ with open(template_path) as file: body = file.read() stack_params = [ {"ParameterKey": key, "ParameterValue": value, "UsePreviousValue": False} for key, value in params.items() ] resp = cfn_client.create_stack( StackName=stack_name, TemplateBody=body, Parameters=stack_params, Capabilities=capabilities, ) stack_id = resp["StackId"] print(f"Creating stack {stack_name}, waiting for stack create complete") waiter = cfn_client.get_waiter("stack_create_complete") waiter.wait( StackName=stack_name, WaiterConfig={"Delay": interval, "MaxAttempts": timeout // interval + 1}, ) return stack_name, stack_id
80608a4a04e70701bbc5c1628a4300b69aec7486
632,909
import re def get_molecular_barcode(record, molecular_barcode_pattern): """Return the molecular barcode in the record name. Parameters ---------- record : screed record screed record containing the molecular barcode molecular_barcode_pattern: regex pattern molecular barcode pattern to detect in the record name Returns ------- barcode : str Return molecular barcode from the name,if it doesn't exit, returns None """ found_molecular_barcode = re.findall(molecular_barcode_pattern, record['name']) if found_molecular_barcode: return found_molecular_barcode[0][1]
1507cf7ad3c39c02b6dfdfdd12c6800155346253
22,648
def find_in_list(content, token_line, last_number): """ Finds an item in a list and returns its index. """ token_line = token_line.strip() found = None try: found = content.index(token_line, last_number+1) except ValueError: pass return found
b53c8dd84b97404f96d3422389ad678950375cff
413,710
def _parse_single_header(b3_header): """ Parse out and return the data necessary for generating ZipkinAttrs. Returns a dict with the following keys: 'trace_id': str or None 'span_id': str or None 'parent_span_id': str or None 'sampled_str': '0', '1', 'd', or None (defer) """ parsed = dict.fromkeys(("trace_id", "span_id", "parent_span_id", "sampled_str")) # b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId} # (last 2 fields optional) # OR # b3={SamplingState} bits = b3_header.split("-") # Handle the lone-sampling-decision case: if len(bits) == 1: if bits[0] in ("0", "1", "d"): parsed["sampled_str"] = bits[0] return parsed raise ValueError("Invalid sample-only value: %r" % bits[0]) if len(bits) > 4: # Too many segments raise ValueError("Too many segments in b3 header: %r" % b3_header) parsed["trace_id"] = bits[0] if not parsed["trace_id"]: raise ValueError("Bad or missing TraceId") parsed["span_id"] = bits[1] if not parsed["span_id"]: raise ValueError("Bad or missing SpanId") if len(bits) > 3: parsed["parent_span_id"] = bits[3] if not parsed["parent_span_id"]: raise ValueError("Got empty ParentSpanId") if len(bits) > 2: # Empty-string means "missing" which means "Defer" if bits[2]: parsed["sampled_str"] = bits[2] if parsed["sampled_str"] not in ("0", "1", "d"): raise ValueError("Bad SampledState: %r" % parsed["sampled_str"]) return parsed
10b716172bf3927b12fb0afbc13bfe15ac957108
415,498
def sum_3_multiples(y): """Calculate the sum of the multiples of 3.""" sum3=0 for i in range(1, y+1): num_to_add=3*i sum3=sum3+num_to_add return sum3
9f04eb2c85d2528a4addf3332181eabf8ec66800
109,103
def get_target_ids(targetcount, targetspec): """Get target ids from target spec: * a - individual item * a:b - range a to b (non-inclusive), step 1 * a:b:c - range a to b (includes a, not b), step c (where c is positive or negative) """ targetranges = [] for el in targetspec.split(","): a, b, c = 0, 1, 1 abc = el.split(":") if len(abc) > 3: raise Exception("bad targetspec") if abc[0]: a = int(abc[0]) if len(abc) == 1: b = a+1 else: b = int(abc[1] or targetcount) if len(abc) == 3: c = int(abc[2]) targetranges.append(range(a, b, c)) return targetranges
31f9eb4f48b2bbeab7cf83df77f31d0d4d83d3a0
337,600
import calendar def get_day(date_obj): """Get the name of the day based on the date object.""" return calendar.day_name[date_obj.weekday()]
f872fbc1fb3166272effc2e97e7b24c8434ef4cf
63,382
def get_longitude(dataset): """Get longitude dimension from XArray dataset object.""" for dim_name in ['lon', 'long', 'longitude']: if dim_name in dataset.coords: return dataset[dim_name] raise RuntimeError('Could not find longitude dimension in dataset.')
d9152f36a2dcdea82c242fdea421779344e83286
514,032
import MySQLdb def guess_type(m): """ Returns fieldtype depending on the MySQLdb Description """ if m in MySQLdb.NUMBER: return 'Currency' elif m in MySQLdb.DATE: return 'Date' else: return 'Data'
771b1c2d61214d0f376c837f93b0c452be577806
114,418
def join_byte(x, y, z): """Join parts of a byte: 2 bits x + 3 bits y + 3 bits z""" return (int(x) << 3 | int(y)) << 3 | int(z)
bdcdc330802a6bf3ef5d0981bc517bed6f1b6179
158,963
def dummy_annotation_csv_file(tmpdir_factory): """Create csv file for testing.""" content = ("onset,duration,description\n" "2002-12-03 19:01:11.720100,1.0,AA\n" "2002-12-03 19:01:20.720100,2.425,BB") fname = tmpdir_factory.mktemp('data').join('annotations.csv') fname.write(content) return fname
7798494d4708d29f345c07ee902634f9b8a6d49e
526,236
import torch def _pad_norm(x, implicit=False): """Add a channel that ensures that prob sum to one if the input has an implicit background class. Else, ensures that prob sum to one.""" if implicit: x = torch.cat((1 - x.sum(dim=1, keepdim=True), x), dim=1) return x
4439886e811d2a1e6d5241edc6cc39f0f645019b
637,330
from typing import List from pathlib import Path import torch def average_checkpoints(filenames: List[Path]) -> dict: """Average a list of checkpoints. Args: filenames: Filenames of the checkpoints to be averaged. We assume all checkpoints are saved by :func:`save_checkpoint`. Returns: Return a dict (i.e., state_dict) which is the average of all model state dicts contained in the checkpoints. """ n = len(filenames) avg = torch.load(filenames[0], map_location="cpu")["model"] for i in range(1, n): state_dict = torch.load(filenames[i], map_location="cpu")["model"] for k in avg: avg[k] += state_dict[k] for k in avg: if avg[k].is_floating_point(): avg[k] /= n else: avg[k] //= n return avg
d6a534dfa62d7d0d1dfab1d58f5261080e889bb9
662,005
def _unescape(value): """ Unescape escapes in a python string. Examples: \xFF \uFFFF \U0010FFFF \\ \n \t \r """ return value.encode('ascii').decode('unicode_escape')
b6cc88129bc9243d4093c79951bc84172ff5c4e7
494,258
import copy def _make_dust_fA_valid_points_generator(it, min_Rv, max_Rv): """ compute the allowed points based on the R(V) versus f_A plane duplicates effort for all A(V) values, but it is quick compared to other steps .. note:: on 2.74: SMC extinction implies f_A = 0. and Rv = 2.74 Parameters ---------- it: an iterable an initial sequence of points that will be trimmed to only valid ones min_Rv: float lower Rv limit max_Rv: float upper Rv limit Returns ------- npts: int the actual number of valid points pts: generator a generator that only produce valid points """ itn = copy.copy(it) npts = 0 def is_valid(ak, rk, fk): return ( fk / max_Rv + (1.0 - fk) / 2.74 <= 1.0 / rk <= fk * 1.0 / min_Rv + (1.0 - fk) / 2.74 ) # explore the full list once # not very time consuming for ak, rk, fk in itn: if is_valid(ak, rk, fk): npts += 1 # make the iterator pts = ( (float(ak), float(rk), float(fk)) for ak, rk, fk in it if is_valid(ak, rk, fk) ) return npts, pts
e31962b44c9148191ad73fa481c53d6896273311
252,366
from typing import Any def terminal(v: Any) -> bool: """Detect terminal key ending in type other than non-empty dict or list.""" if isinstance(v, (dict, list)): if v: return False return True
522656cea231c0dbd5b8acfe4f9c642c32c669bb
154,024
def interpret_flags(bitmask, values): """ Args: bitmask: flags to check values: array of tuples containing (value, description) pairs Returns: string containing descriptions of flags """ return ', '.join(desc for num, desc in values if num & bitmask) if bitmask else None
54835ff7d5823e0ab69772a7116b52cc1f45cd4f
379,825
def split_by_unicode_char(input_strs): """ Split utf-8 strings to unicode characters """ out = [] for s in input_strs: out.append([c for c in s]) return out
290bb5ec82c78e9ec23ee1269fe9227c5198405e
11,347
def show_fact_sheet_a(responses, derived): """ If the claimant is claiming special extraordinary expenses, Fact Sheet A is indicated. """ return responses.get('special_extraordinary_expenses', '') == 'YES'
551ddb54706d1f107f040ab9a8d14e4c77dd3fe6
169,582
import requests import json def pingCOWIN(date,district_id): """ Function to ping the COWIN API to get the latest district wise details Parameters ---------- date : String district_id : String Returns ------- json """ url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id={district_id}&date={date}".format(district_id = district_id, date = date) headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' } response = requests.get(url,headers=headers) return json.loads(response.text)
65b6d994a01de601c5974ebd78fe05d8281ae7f6
327,255
def _geom_sum(r, n): """Computes sum of geometric series. Use n=float('inf') for infinite series. """ return (1 - r**(n + 1)) / (1 - r)
166210ad0c2de6d3be072874dcc7e1634e52361a
182,462
def timezone_format(value): """ Check the value of the timezeone offset and, if postive, add a plus sign""" try: if int(value) > 0: value = '+' + str(value) except: value = '' return value
e6abafec8c66b3891bba33a5f1110a4a406e9777
645,975
import time def log_tail(contents=''): """return a string, which can be write to the tail of a log files""" s = '================================================================\n' s += '[time] ' + time.asctime(time.localtime()) + '\n' s += '[program finish succeed!]\n' s += contents s += '===============================================================\n' return s
f03c68285ea8cf335a7eb8475085501eeb1c1eee
669,398
def tel_type(items): """Return 1 if phone is ground or 2 if cellphone.""" ground_prefixes = ['12', '13', '14', '15', '16', '17', '18', '22', '23', '24', '25', '29', '32', '33', '34', '41', '42', '43', '44', '46', '48', '52', '54', '55', '56', '58', '59', '61', '62', '63', '65', '67', '68', '71', '74', '75', '76', '77', '81', '82'] map_pattern = dict(zip(ground_prefixes, [1 for _ in range(len(ground_prefixes))])) items = (items.str.slice(0, 2) .map(map_pattern) .fillna(2) .apply(int)) return items
96dbb22f0d6845a3843d80155c4bd86ad0d70a03
326,577
def make_comment(dictobj, fieldname): """Render a dict's field to text. Return '<fieldname>: <dictobj["fieldname"]>' or '' """ return "{0}: {1}\n\n".format(fieldname, dictobj[fieldname]) if \ fieldname in dictobj and dictobj[fieldname] != "" else ""
d0580ec938ccf868a78d19a0bd9bd075f816abb7
426,018
def pretty_size(size, unit=1024): """ This function returns a pretty representation of a size value :param int|long|float size: the number to to prettify :param int unit: 1000 or 1024 (the default) :rtype: str """ suffixes = ["B"] + [i + {1000: "B", 1024: "iB"}[unit] for i in "KMGTPEZY"] if unit == 1000: suffixes[1] = 'kB' # special case kB instead of KB # cast to float to avoid losing decimals size = float(size) for suffix in suffixes: if abs(size) < unit or suffix == suffixes[-1]: if suffix == suffixes[0]: return "%d %s" % (size, suffix) else: return "%.1f %s" % (size, suffix) else: size /= unit
abeafa97d45212c0170b981e9448e63acc1a54d2
17,914
def get_parent(vmfs): """ From a set of VMFs, determines which one has the lowest map version number, and is therefore the parent. """ # This avoids the need to subscript and slice. vmfs = iter(vmfs) parent = next(vmfs) lowestRevision = parent.revision for vmf in vmfs: revision = vmf.revision if revision < lowestRevision: parent = vmf lowestRevision = revision return parent
bae83d2e02edc835c533873994285870246c7623
38,298
import re def get_isotopes(ratio_text): """ Regex for isotope ratios. Parameters ----------- ratio_text : :class:`str` Text to extract isotope ratio components from. Returns ----------- :class:`list` Isotope ration numerator and denominator. """ forward_isotope = r"([a-zA-Z][a-zA-Z]?[0-9][0-9]?[0-9]?)" backward_isotope = r"([0-9][0-9]?[0-9]?[a-zA-Z][a-zA-Z]?)" fw = re.findall(forward_isotope, ratio_text) bw = re.findall(backward_isotope, ratio_text) lfw, lbw = len(fw), len(bw) if (lfw > 1 and lbw > 1) or ((lfw < 2) and (lbw < 2)): return [] elif lfw == 2: return fw elif lbw == 2: return bw
21268b3c115c487d5888f583ae5101baaf6cb18c
263,505
import math, random def split_list(data, splits={'train': 8, 'test': 2}, shuffle=True, seed=0): """ Split the list according to a given ratio Args: data (list): a list of data to split splits (dict): a dictionary specifying the ratio of splits shuffle (bool): shuffle the list before seed (int): random seed used for shuffling Returns: a dictionary of the splitted list """ data = data.copy() # work on a copy of the oridinal list n_tot = len(data) split_tot = float(sum([v for v in splits.values()])) n_split = {k:math.ceil(n_tot*v/split_tot) for k,v in splits.items()} if shuffle: random.seed(seed) random.shuffle(data) splitted = {} cnt = 0 for k, v in n_split.items(): splitted[k] = data[cnt:cnt+v] cnt += v return splitted
d9b25512e666a03ec2b589850c47a45231b279a0
7,053
def count_total_deaths(D): """Returns total number of deaths.""" return D[-1]
c5884d13913a99c2114e06a06414c3495e4d3285
238,532
def get_full_hitmask(rect): """ Returns a completely full hitmask that fits the image, without referencing the images colour_key or alpha. """ mask = [] for x in range(rect.width): mask.append([]) for y in range(rect.height): mask[x].append(True) return mask
3bd028a1bb15e4633ece70038b621e228e4bbfde
566,396
def get_pep_dep(libname: str, version: str) -> str: """Return a valid PEP 508 dependency string. ref: https://www.python.org/dev/peps/pep-0508/ """ return f"{libname}{version}"
2cfb972c038b56a4d9055fe3e32c4c50f7e2e02e
249,835
def db_model_exists(conn, experiment, fold): """ Check if model already exists in database. Args: conn: Sqlite3 connection object. experiment: Experiment name. fold: Fold number. Returns: True if model exists, False otherwise. """ cur = conn.cursor() for _ in cur.execute("SELECT * FROM experiments WHERE experiment=? and fold=?", (experiment, fold)): return True return False
bea8b102b96d62ef9020bf2fecd35345cdb6bfc3
509,971
def get_average_age(ages): """ Get the average age from a dictionary of age counts. Args: ages (dict): dictionary of age counts Return: float: The average age given the age count. """ average_age = 0 total_population = sum(ages.values()) for a in ages: average_age += ages[a] * a average_age = average_age/total_population return average_age
ca09dd7ec9db75cc3a09e01733c97c4aa4fa80a5
166,032
def add_edges(graph, edges): """Add edge(s) to graph Args: graph (Graph): Graph to add edge(s) to edges (list): List of edges Returns: Graph: Return the modified graph """ for e in edges: if isinstance(e[0], tuple): graph.edge(*e[0], **e[1]) else: graph.edge(*e) return graph
ad1f1320712175b125d37ca50f50f716a5e6c9f4
427,815
from typing import Union def clean_base64(value: Union[str, bytes]) -> bytes: """ Force bytes and remove line breaks and spaces. Does not validate base64 format. :raises ValueError: :raises TypeError: """ if isinstance(value, bytes): value_base64_bytes = value elif isinstance(value, str): try: value_base64_bytes = value.strip().encode(encoding='ascii', errors='strict') except UnicodeEncodeError as exc: raise ValueError("Only ASCII characters are accepted.", str(exc)) from exc else: raise TypeError("Value must be str or bytes.") # remove line breaks and spaces # warning: we may only remove characters that are not part of the standard base-64 alphabet # (or any of its popular alternatives). value_base64_bytes_cleaned = value_base64_bytes \ .replace(b'\n', b'') \ .replace(b'\r', b'') \ .replace(b'\t', b'') \ .replace(b' ', b'') return value_base64_bytes_cleaned
e22d589d11c8bf3df680f8cb3a9893c5224010d0
367,905
def hex_to_rgb(color): """ "#FFFFFF" -> [255,255,255] """ return [int(color[i:i+2], 16) for i in range(1, 6, 2)]
a16c55c0b9ea0eeea5da4f8b9f17b93969a7247f
204,941
def _validate_dict(s, accept_none=False): """ A validation method to check if the input s is a dictionary otherwise raise error if it is not convertable """ if s is None and accept_none: return None if isinstance(s, dict): return s else: raise ValueError('{} is not a dictionary!'.format(s))
8834142153fa2cb71d4a76e6a977324a698b8723
621,234
import six def set_show(plotdata): #------------------------------------------------------------------ """ Determine which figures and axes should be shown. plotaxes._show should be true only if plotaxes.show and at least one item is showing or if the axes have attribute type=='empty', in which case something may be plotting in an afteraxes command, for example. plotfigure._show should be true only if plotfigure.show and at least one axes is showing. """ for figname in plotdata._fignames: plotfigure = plotdata.plotfigure_dict[figname] plotfigure._show = False if plotfigure.show: # Loop through all axes to make sure at least some item is showing for plotaxes in six.itervalues(plotfigure.plotaxes_dict): plotaxes._show = False if plotaxes.show: # Loop through plotitems checking each item to see if it # should be shown for plotitem in six.itervalues(plotaxes.plotitem_dict): plotitem._show = plotitem.show if plotitem.show: plotaxes._show = True plotfigure._show = True # Check to see if the axes are supposed to be empty or # something may be in the afteraxes function if not plotaxes._show: if plotaxes.afteraxes is not None or plotaxes.type == 'empty': plotaxes._show = True plotfigure._show = True return plotdata
4f674bc3e05ad78831e0e6de818e66b2803fed71
609,732
def alpha_check(word, target_s): """ This function will check if every alphabets of word in target_s :param word: str, a word want to check alphabets :param target_s: str, a string of alphabet wanted. :return: bool, if every alphabets of word in target_s """ for alpha in word: if alpha not in target_s: return False return True
c921c5e3e62cd2827dbb11f9b692b7e0c4fc229c
202,787
def flat(*nums): """ Build a tuple of ints from float or integer arguments. Useful because PIL crop and resize require integer points. """ return tuple(int(round(n)) for n in nums)
f96681e8f075a4c7f51c8d735ead3fc7f61768df
261,830
def is_succeeded(status, **_): """For when= function to test if a pod has succeeded.""" return status.get('phase') == 'Succeeded'
508d6d0e8d7ef97785a8d0517f449850e810175e
615,495
def imf_flat(x): """ Compute a flat IMF (useful for simulations, not for normal BEAST runs) Parameters ---------- x : numpy vector masses Returns ------- imf : numpy vector unformalized IMF """ return 1.0
810c0aab54c98ada3e68ea11a0fcd64ba680279d
399,130
def finite_diff_kauers(sum): """ Takes as input a Sum instance and returns the difference between the sum with the upper index incremented by 1 and the original sum. For example, if S(n) is a sum, then finite_diff_kauers will return S(n + 1) - S(n). Examples ======== >>> from sympy.series.kauers import finite_diff_kauers >>> from sympy import Sum >>> from sympy.abc import x, y, m, n, k >>> finite_diff_kauers(Sum(k, (k, 1, n))) n + 1 >>> finite_diff_kauers(Sum(1/k, (k, 1, n))) 1/(n + 1) >>> finite_diff_kauers(Sum((x*y**2), (x, 1, n), (y, 1, m))) (m + 1)**2*(n + 1) >>> finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n))) (m + 1)*(n + 1) """ function = sum.function for l in sum.limits: function = function.subs(l[0], l[- 1] + 1) return function
224e91b82c01acc5fb781acb72d8af18f9b08f63
275,581
def join_columns_with_divider(table, decorator): """Join each line in table with the decorator string between each cell""" return [decorator.join(row) for row in table]
3c87f1ccbd6ee58dac7e4375f8eb50d61fa22388
599,126
def get_agents_with_name(name, stmts): """Return all agents within a list of statements with a particular name.""" return [ag for stmt in stmts for ag in stmt.agent_list() if ag is not None and ag.name == name]
f9936596754264d9047bd106ac9bfd7328c3d53c
563,034
def _split_dataset_id(dataset_id): """splits a dataset id into list of values.""" return dataset_id.split("|")[0].split(".") + [(dataset_id.split("|")[1])]
9a1c3d23af502fd21db3de9485cfcdb75d84ba6d
694,076
def add_notice_to_docstring( doc, instructions, no_doc_str, suffix_str, notice): """Adds a deprecation notice to a docstring.""" if not doc: lines = [no_doc_str] else: lines = doc.splitlines() lines[0] += ' ' + suffix_str notice = [''] + notice + [instructions] if len(lines) > 1: # Make sure that we keep our distance from the main body if lines[1].strip(): notice.append('') lines[1:1] = notice else: lines += notice return '\n'.join(lines)
3e2899bbbe4162eeae9d7384778d5592fbb10c7a
187,184
import re def extract_template(pattern): """Extracts a 'template' of a url pattern given a pattern returns a string Example: input: '^home/city (-(?P<city_name>bristol|bath|cardiff|swindon|oxford|reading))?$' output: 'home/city(-{})?' """ pattern = pattern.strip('$^') pattern = re.sub(r'\(\?P.+?\)', '{}', pattern) return pattern
4d36c5f0b6d3ac4072b376119d78b083419143c4
21,156
def _display(stats, plot=False): """ Take stats dictionary and display on same format as nanowrimo. plot - make a compact plotting format """ if plot: # this is a more compact format for the plot output = \ """ Day {current_day} / {target_time_period} Words: {total_words_written} / {target_word_count} Today: {words_written_today} words Rate for deadline: {needed_words_per_day} wpd Current Rate: {average_words_per_day} wpd Current finish: {finish_date} """ else: # same layout as nanowrimo output = \ """ Period: {starting_date} - {ending_date} Your average per day: {average_words_per_day} Words written today: {words_written_today} Target word count: {target_word_count} Target average word count per day: {target_average_word_count} Total words written: {total_words_written} Words remaining: {words_remaining} Current day: {current_day} Days remaining: {days_remaining} At this rate you will finish on: {finish_date} Words per day to finish on time: {needed_words_per_day} """ return output.format(**stats)
d10a3d096a7736a7fe5493823c152ea955e51491
143,290
def _get_observer_name(spec): """ Gives observer name from YAML short hand naming format """ return spec[:1].upper() + spec[1:] + "Observer"
1e25e44fa22d59fd0292800872ce7b236fdaabe9
535,283
import base64 def bytes2hex(data: bytes) -> str: """Convert bytes to a hex string.""" return base64.b16encode(data).decode('ascii').lower()
7439d46808075730efc5b37e89ed64dc8e9536da
380,027
def find(iterable, selector): """ Return the first item in the `iterable` that causes the `selector` to return `True`. """ for x in iterable: if selector(x): return x
d9c91ab468edd672d23af31b21008f8bfad4f86e
269,378
def strip_minijail_command(command, fuzzer_path): """Remove minijail arguments from a fuzzer command. Args: command: The command. fuzzer_path: Absolute path to the fuzzer. Returns: The stripped command. """ try: fuzzer_path_index = command.index(fuzzer_path) return command[fuzzer_path_index:] except ValueError: return command
a6ed7e60a685dddfcd14e2b65fb3996de8ef9443
151,463
def make_f_beta(beta): """Create a f beta function Parameters ---------- beta : float The beta to use where a beta of 1 is the f1-score or F-measure Returns ------- function A function to compute the f_beta score """ beta_2 = beta**2 coeff = (1 + beta_2) def f(global_, local_, node): """Compute the f-measure Parameters ---------- global_ : np.array All of the scores for a given query local_ : np.array The scores for the query at the current node node : skbio.TreeNode The current node being evaluated """ p = len(global_) / len(local_) r = len(local_) / node.ntips return coeff * (p * r) / ((beta_2 * p) + r) return f
f0e6993ac956171c58415e1605706c453d3e6d61
4,901
def indent(s, N=4): """indent a string""" return s.replace("\n", "\n" + N * " ")
78f33d0c6c01417400525196867573a3ff2ae158
495,412