content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_s3_filename(s3_path): """Fetches the filename of a key from S3 Args: s3_path (str): 'production/output/file.txt' Returns (str): 'file.txt' """ if s3_path.split('/')[-1] == '': raise ValueError('Supplied S3 path: {} is a directory not a file path'.format(s3_path)) return s3_path.split('/')[-1]
2aac60ef8ba854eb2196a37d2da0bedc30611c6b
257,565
def getTableRADecKeys(tab): """Returns the column names in the table in which RA, dec coords are stored, after trying a few possible name variations. Args: tab (:obj:`astropy.table.Table`): The table to search. Returns: Name of the RA column, name of the dec. column """ RAKeysToTry=['ra', 'RA', 'RADeg'] decKeysToTry=['dec', 'DEC', 'decDeg', 'Dec'] RAKey, decKey=None, None for key in RAKeysToTry: if key in tab.keys(): RAKey=key break for key in decKeysToTry: if key in tab.keys(): decKey=key break if RAKey is None or decKey is None: raise Exception("Couldn't identify RA, dec columns in the supplied table.") return RAKey, decKey
93807fe56826ac680605b0494af60ddc6a5014a8
28,920
def decimal_to_binary(n, l=None): """ Convert n from decimal to binary Args: n -- int -- the decimal value l -- int -- the number of bits for the binary representation return the binary value of n """ binary = bin(n)[2:] if l != None: binary = binary.zfill(l) return binary
9ad0ea3b0f253f3e5ab72a232324a02a024c6f9a
168,036
def cli(ctx, job_id): """Get dataset outputs produced by a job. Output: Outputs of the given job """ return ctx.gi.jobs.get_outputs(job_id)
07ae08ce1b7518429445c8df55caa90dcccd688d
70,651
def seq(start, stop, step=1): """Generate a list of values between start and stop every step :param start: The starting value :param stop: The ending values :param step: The step size :return: List of steps """ n = int(round((stop - start) / float(step))) if n > 1: return [start + step * i for i in range(n + 1)] else: return []
9471500a1dc13cde41beaad31092f7b00c771cca
63,125
def find_snapshots_to_delete(from_front, to_front): """ Find all snapshots in from_front that has been deleted, but has not yet been deleted in the clone to_front. """ snapshots_to_delete = [] self_max_rev = to_front.get_highest_used_revision() already_deleted_snapshots = set(to_front.get_deleted_snapshots()) for rev in from_front.get_deleted_snapshots(): if rev > self_max_rev: continue if rev in already_deleted_snapshots: continue deleted_name, deleted_fingerprint = from_front.get_deleted_snapshot_info(rev) session_info = to_front.get_session_info(rev) assert session_info['name'] == deleted_name assert to_front.get_session_fingerprint(rev) == deleted_fingerprint snapshots_to_delete.append(rev) return snapshots_to_delete
e1298e5c9a1c2cb33ae46740b12e4b33980b5d37
59,258
def qsize(queue): """Get the (approximate) queue size where available. Parameters ---------- queue : :class:`queue.Queue` Input queue. Returns ------- int Queue size, -1 if `qsize` method isn't implemented (OS X). """ try: return queue.qsize() except NotImplementedError: # OS X doesn't support qsize return -1
be170990e4f65d00252b0d9016bfd13774bb3ef1
102,729
from typing import List def _read_resultset_columns(cursor) -> List[str]: """ Read names of all columns returned by a cursor :param cursor: Cursor to read column names from """ if cursor.description is None: return [] else: return [x[0] for x in cursor.description]
cacefb20b12f327647d1f77bb12216c80388fcd6
26,755
def floor_div(arr, val): """ Floor division of array by value. """ return [i // val for i in arr]
270d2eb53a288773a36d9cb90b44ecf8f421a34f
625,938
def hasDistInfo(call): """Verify that a call has the fields required to compute the distance""" requiredFields = ["mylat", "mylong", "contactlat", "contactlong"] return all(map(lambda f: call[f], requiredFields))
1e89b5f31f1625cf470ceb9431a3cf7964e3e13b
372,125
import hashlib def digest_file(filepath): """ Get the MD5sum for a single file on disk. Files are read in a memory-efficient fashion. Args: filepath (string): a string path to the file or folder to be tested or a list of files to be analyzed. Returns: An md5sum of the input file """ block_size = 2**20 file_handler = open(filepath, 'rb') file_md5 = hashlib.md5() for chunk in iter(lambda: file_handler.read(block_size), ''): file_md5.update(chunk) file_handler.close() return file_md5.hexdigest()
d3ee1756b0d8fe193a8de434a7d594403c346409
205,716
def get_test_module_names(module_list, module_prefix='test_'): """ Return the list of module names that qualify as test modules. """ module_names = [m for m in module_list if m.startswith(module_prefix)] return module_names
5b99d8df9708aaa83127ba1600e728585fdc9275
456,088
import ipaddress def parse_ip_and_port(input): """ Parse IP and Port number combo to a dictionary:: 1.1.1.1:2000 to: .. code-block:: python {'ip': IPv4Address('1.1.1.1'), 'port': 2000} :param string input: IP and port :return: dictionary with keys ``ip`` and ``port`` """ ip_port_dict = {} address, port = input.split(':') ip_port_dict['ip'] = ipaddress.ip_address(address) ip_port_dict['port'] = port return ip_port_dict
b4cf51d96a2790f6dec9cc2e7d8ec5c34b6c3600
316,504
def _floordiv(i, j): """Do a floor division, i/j.""" return i // j
0e874bca33cda089e2ad5eb6ac4b2418e96f0f10
522,189
def rect_overlap_area(r1, r2): """ Returns the number of pixels by which rectangles r1 and r2 overlap. """ x1, y1, w1, h1 = r1 x2, y2, w2, h2 = r2 maxleft = max(x1, x2) minright = min(x1 + w1, x2 + w2) maxtop = max(y1, y2) minbottom = min(y1 + h1, y2 + h2) if minright < maxleft: return 0 if minbottom < maxtop: return 0 return (minright - maxleft) * (minbottom - maxtop)
ad96f7f816e8ac18f3fd9f37ff37f847555ea19f
180,639
def key_of_min_value(d): """Returns the key in a dict d that corresponds to the minimum value of d. """ return min(d, key=lambda key_name: d[key_name])
6c9ad0370a5b8efc7bb0b409bab9157b1690a4b5
531,783
def setintersect_ordered(list1, list2): """ returns list1 elements that are in list2. preserves order of list1 setintersect_ordered Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list1 = [1, 2, 3, 5, 8, 13, 21] >>> list2 = [6, 4, 2, 21, 8] >>> new_list = setintersect_ordered(list1, list2) >>> result = new_list >>> print(result) [2, 8, 21] """ return [item for item in list1 if item in set(list2)]
86c684ec7d17ea581c13c25fbb47381d08b1a558
346,718
def sqrt_decimal_expansion(n: int, precision: int) -> str: """Finds the square root of a number to arbitrary decimal precision. Args: n: A positive integer value. precision: The desired number of digits following the decimal point. Returns: A string representation of ``sqrt(n)`` in base 10 that includes the first ``precision`` digits after the decimal point. """ # break n into two-digit chunks n_digits = [] while n > 0: n, mod = divmod(n, 100) n_digits.append(mod) n_digits.reverse() expansion = [] remainder = 0 root_part = 0 def f(x: int) -> int: return x * (20 * root_part + x) # compute digits before decimal point for carry in n_digits: a = 1 b = f(a) c = remainder * 100 + carry while b <= c: a += 1 b = f(a) a -= 1 b = f(a) remainder = c - b root_part = root_part * 10 + a expansion.append(str(a)) expansion.append('.') # compute digits after decimal point for _ in range(precision): a = 1 b = f(a) c = remainder * 100 while b <= c: a += 1 b = f(a) a -= 1 b = f(a) remainder = c - b root_part = root_part * 10 + a expansion.append(str(a)) return ''.join(expansion)
5165f98a51a0522aa960a532b10fa07191cf9e12
693,676
def extract_brackets(line): """Splits a scroll 'call line' into identifier + suffix.""" ident, _, enil = line[1:].partition("(") thing, _, _, = enil.rpartition(")") return ident, thing
47b35a331ecf01c2772d6289f1ac8171f655573c
655,442
def format_lines(matched_lines, files, flags): """ This formats the result of the find if the pattern is in a certain line in a file. If -n is in the flags the line number will be included in the search result `-n` Print the line numbers of each matching line. :param matched_lines: a list with 1 tuple containing file_name, line_number and line :param files: files to search for the matching pattern, will be a list :param flags: The flags to use for the search :return: a formatted search result :rtype: str """ search_result = [] for file_name, line_number, line in matched_lines: line_result = "" if len(files) > 1: line_result += file_name + ":" if "-n" in flags: line_result += str(line_number) + ":" line_result += line search_result.append(line_result) return "".join(search_result)
fb24cb76bcae5063c3dd3e41e4d0d3830d18c56c
246,913
import random def genPwd(alpha, length): """ Generate a random string (a password). ``alpha'' The characters that may be present in the password. Each character in alpha will be equally likely in the generated password. ``length'' The length of the password string. """ # be sure that each character is exactly once present alpha = list(set(alpha)) # return the created password return "".join([random.choice(alpha) for _ in range(length)])
ab441f82725a871e31d04957f5eff90cb6c95efa
295,495
import re def _pythonify_type(text): """ Convert valid Copperhead type expression to valid Python expression. The Copperhead type language is very nearly syntactically valid Python. To make parsing types relatively painless, we shamelessly convert type expressions into similar Python expressions, which we then feed into the Python parser. Producing a syntactically valid Python expression involves the following conversions: - substitute 'lambda' for 'ForAll' - substitute '>>' for the '->' function operator """ text = re.sub(r'ForAll(?=\s)', 'lambda', text) text = re.sub(r'->', '>>', text) return text.strip()
67375cd7ca8691b7ffc66c7affac4c79d1260c6d
610,284
import random def rand(x,y): """ Randomizer for augmentation pipepline Args: x (int, float): lower_bound y (int, float): upper_bound Returns: random number between bounds """ # use uniform if parameters passed are below 1 if all([v < 1 for v in [x,y]]): return random.uniform(x, y) else: return random.randint(x,y)
f12fd340e98455b704143f9c637ae947f5210df8
538,942
def pt_agent_country(country): """Clean the country""" c = country.strip() if c.lower() == 'unknown': return '' return c
e87389b3a6713933b1ee4a578c7d6ab048d1ac0f
65,501
def uppercase(s: str) -> str: """ Convert a string to uppercase. Args: s (str): The string to be converted. Returns: str: The converted uppercase string. Example: >>> uppercase('completely different') == 'COMPLETELY DIFFERENT' True """ return s.upper()
f1ecb6e412ea3ce6e46531174881ad230bed3802
635,148
def load_stopwords(path): """Loads stopwords from `path`, assume each word in new line.""" stopwords = set() with open(path) as f: for line in f: stopwords.add(line.strip()) return stopwords
a1bb465f15a6678ab35895a119352d3334a879d6
572,693
import typing def get_bool( raw: typing.Any, /, ) -> bool: """ Parameters ---------- raw: any The input to get the boolean from. Returns ------- bool Raises ------ ValueError If it's unclear what the boolean is. """ if raw in ["True", "true", "t", "yes", "y", "1", 1, True]: return True if raw in ["False", "false", "f", "no", "n", "0", 0, False]: return False raise ValueError(f"Cannot assign {raw!r} to True or False!")
dd6d54610f01d2ed88899a52c477d82692b3d1fd
349,669
def dot_product(a,b): """ Computes the dot-product of two vectors. Parameters ---------- a : (x,y) tuple b : (x,y) tuple Returns ------- float """ return a[0]*b[0] + a[1]*b[1]
5c1b5e8f12c5365262c06519f1ef2dae3486774a
132,122
import hashlib def get_SHA1_from_data(data): """Compute image SHA1. :param data: image buffer :type data: buffer :return: image SHA1 :rtype: str """ sha1hash = None try: sha1 = hashlib.sha1() sha1.update(data) sha1hash = sha1.hexdigest().upper() except: print("Could not read data to compute SHA1.") return sha1hash
135839fe683897f08817712c98ef493f11c85b4e
314,046
def get_ij_from_index(r, m, n): """ The inverse of get_y_indicator_variable_index(): given the indiator variable index, return the (i ,j) pair for y_{ij} to which it corresponds. So when we get a solution from MiniSat+, the variable index given to this function gets converted to (i,j) our y_{ij}, meaning that if that indiator variable is 1, SSE i in tableau a is matched with SSE j in tableau b. Parameters: index r of indicator variable x_{r} m - order of tableau a (0 <= i,k < m) n - order of tableau b (0 <= j,l < n) Return value: i, j - indices for y indicator variable corresponding to MiniSat+ variable y_r """ i = r / n j = r % n return (i,j)
1202fc62f7a9d18a7e0fec1bc987041d75ef964d
193,656
def splitbycharset(txt, charset): """Splits a string at the first occurrence of a character in a set. Args: txt: Text to split. chars: Chars to look for (specified as string). Returns: (char, before, after) where char is the character from the character set which has been found as first; before and after are the substrings before and after it. If none of the characters had been found in the text, char and after are set to the empty string and before to the entrire string. """ for firstpos, char in enumerate(txt): if char in charset: break else: return '', txt, '' return txt[firstpos], txt[:firstpos], txt[firstpos+1:]
c23577eb96c9621909acaa816e8791e95dbf493d
699,340
def BranchFilter(branch, patch): """Used with FilterFn to isolate patches based on a specific upstream.""" return patch.tracking_branch == branch
65a1a5e09e52d25dc5e949e805e27e5d78a36c7f
311,524
def notas(* num, s=False): """ -> Função para coletar notas dos alunos e retornar informações gerais e a situação da turma. :param num: Notas da turma :param s: Situação (Boa, Razoável ou Ruim) :return: dicionário com informações sobre a turma """ soma = sum(num) qtd = len(num) maior = max(num) menor = min(num) media = soma / qtd if media >= 6: sit = 'Boa' elif media >= 5: sit = 'Razoável' else: sit = 'Ruim' total = {'Quantidade de notas': qtd, 'Maior nota': maior, 'Menor nota': menor, 'Média': media} if s: total['Situação'] = sit return total
200b7377b7fcbe9aa0ce13e4784018e719374de2
561,603
def is_above_or_to_left(ref_control, other_ctrl): """Return true if the other_ctrl is above or to the left of ref_control""" text_r = other_ctrl.rectangle() ctrl_r = ref_control.rectangle() # skip controls where text win is to the right of ctrl if text_r.left >= ctrl_r.right: return False # skip controls where text win is below ctrl if text_r.top >= ctrl_r.bottom: return False # text control top left corner is below control # top left corner - so not to the above or left :) if text_r.top >= ctrl_r.top and text_r.left >= ctrl_r.left: return False return True
dcc02e8e9424825704682f6b12683bb9de2fe132
661,288
def __sizeby(df, col, nbr=5, ascend = False): """ Count for specific col in a dataframe Parameters ---------- df : pd.DataFrame Dataframe containing the col to count from. col : str Column name to count from. nbr : int, optional Number of value to retrieves. The default is 5. ascend : boolean, optional Sort order by ascending. The default is False. Returns ------- sub_df : pd.DataFrame """ sub_df = df.groupby(col).size().sort_values(ascending=ascend).head(nbr).reset_index() sub_df.rename(columns={0:"count"}, inplace=True) return sub_df
af1bdb3904f70a5969d2b58c93dfa58db7346132
438,194
import re def get_tag_value(string, pre, post, tagtype=float, greedy=True): """ Extracts the value of a tag from a string. Parameters ----------------- pre : str regular expression to match before the the tag value post : str | list | tuple regular expression to match after the the tag value if list than the regular expressions will be combined into the regular expression (?=post[0]|post[1]|..) tagtype : str | float | int the type to which the tag value should be converted to greedy : bool Whether the regular expression is greedy or not. Returns --------------- Tag value if found, None otherwise Example ------------ get_tag_value('PID_23.5.txt', pre=r'PID_' , post='(?=_|\.txt)') should return 23.5 get_tag_value('PID_23.5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23.5 get_tag_value('PID_23_5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23 get_tag_value('PID_23.txt', pre=r'PID_', post='.txt') should return 23 get_tag_value('PID.txt', pre=r'PID_', post='.txt') should return None """ greedy = '?' if greedy else '' # For greedy search if isinstance(post, (list, tuple)): post = '(?=' + '|'.join(post) + ')' tag_list = re.findall(r'{pre}(.+{greedy}){post}'.format(pre=pre, post=post, greedy=greedy), string) if len(tag_list) > 1: raise ValueError('More than one matching pattern found... check filename') elif len(tag_list) == 0: return None else: return tagtype(tag_list[0])
a48fb09863f6e6fdc79053adb57ae7d28524f566
218,128
def calc_statistics(df): """ Build cleaned up dataframe with just stats columns. """ stats = df.loc[:, ['date', 'totale_casi', 'totale_positivi', 'nuovi_positivi', 'variazione_totale_positivi', 'deceduti', 'nuovi_decessi', 'terapia_intensiva', 'ingressi_terapia_intensiva','totale_ospedalizzati', 'dimessi_guariti', 'tamponi', 'casi_testati']] stats.insert(0, '% mortalita', df.mortalita) stats.insert(0, '% intensivi', df.intensivi) stats.insert(0, '% ricoverati', df.ricoverati) stats.insert(0, '% guariti', df.guariti) return stats
33790523ee006a92e40fe6bcc7f73f11688f0805
134,665
def s3_read_write_policy_in_json(s3_bucket_name): """ Define an IAM policy statement for reading and writing to S3 bucket. :return: an IAM policy statement in json. """ return { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:Put*", "s3:Get*" ], "Resource": [ "arn:aws:s3:::{}/*".format(s3_bucket_name) ] } ] }
b872fd3c833e0384ed891ab3709826a9e9a823bf
693,764
from typing import Tuple from typing import Optional import struct def _unwrap_apdu( packet: bytes, ) -> Tuple[Optional[int], Optional[bytes], Optional[int], Optional[int], Optional[bytes]]: """ Given a packet from the device, extract and return relevant info """ if not packet: return None, None, None, None, None (channel, tag, packet_id, reply_size) = struct.unpack(">HBHH", packet[:7]) if packet_id == 0: return channel, tag, packet_id, reply_size, packet[7:] return channel, tag, packet_id, None, packet[5:]
f99e44aa683442eadb7161502e160e86703fc05c
516,811
def map_01_to_16bit(value): """Map value from 0-1 range to 0-65535 range.""" # result = None # result = int(map_bound(value, 0.0, 1.0, 0, 65535)) # return result # return int(map_bound(value, 0.0, 1.0, 0, 65535)) # result = None # if value <= 0: # # result = 0 # return 0 # else: # if value >= 1: # # result = 65535 # return 65535 # else: # # simplified # # result = 65535 * value / 1 # return int(65535 * value) # return result return int(65535 * value)
81a5064504e83e2ab952dba5504faf2b1a63e0fe
547,938
def getTZLookup(tzfname='cities15000.txt'): """Returns a mapping from gps locations to time-zone names. The `tzfname` file is read to map gps locations to timezone names. This is from: http://download.geonames.org/export/dump/cities15000.zip Returns a list of `((lat, lon), timezone)` pairs. """ ret = [l.rstrip('\n').split('\t') for l in open(tzfname) if l.strip()] ret = [((float(l[4]), float(l[5])), l[17]) for l in ret] return ret
3dcb3b297be72eb55c2d75ffc0bf269e27775232
22,553
def get_categories(cat_file): """Get categories of plasmids from input file""" catDict = {} with open(cat_file, 'r') as infile: for line in infile: line = line.strip().split() catDict[line[0]] = line[1] return catDict
2b03c548977bb6d89450da4d0bb2a02e1cdbeb03
69,349
def intersection(l1:list, l2:list) -> list: """Calculates the intersection of l1 and l2; l1 ∩ l2 Parameters ---------- l1 : list The first list/set l2 : list The second list/set Returns ------- list The list of the intersection between L1 and L2 """ result = [] for value in l1: if value in l2: result.append(value) return result
581e6a20f990e6552334cc4ece31bb88be1cae4c
256,749
def _xrt_component_package(name, package): """ Get component package filename from base XRT package filename. Args: name (str): Package component name like 'xrt' or 'aws'. package (str): Package filename. Returns: Component package filename. """ return package[::-1].replace("trx-", ("-" + name)[::-1], 1)[::-1]
d46e919811a2e4fdcc0fc7eb75cdc062b32453c9
309,204
def CONVERT_LAMBDA(x): """ Function to convert amount in dollars to a float """ return float(x.replace("$", "").replace(",", ""))
59912840738c946a0c1eaff793fd988cd44977f8
139,445
def iso2sec(iso: str) -> int: """ :param iso: e.g. 1:01:02 :return: sec in int """ arr = iso.split(':') len_arr = len(arr) if len_arr <= 3: arr = ['0'] * (3 - len_arr) + arr else: raise Exception('len_arr > 3, arr: {}'.format(arr)) return int(arr[0]) * 60 * 60 + int(arr[1]) * 60 + int(arr[2])
6e3285955fd7e91071f2d4e7c8b17b5a167a1fef
512,552
def extract_xmax(mfile): """ Extract the maximum X-coordinates of the band structure and return that value. """ xmax = 0.0 for line in mfile: words = line.split() if len(words) == 0: return xmax else: xmax = float(words[0]) return xmax
ada90d8d1dd40538d177b07a8da177923f8ff49d
411,630
def write_evt_file(ext_files_dir, name, event): """ Append event into the evt file of the extension. :param ext_files_dir: The 'files' directory of the extension. :param name: Name of the evt file :param event: The event to append. :return: """ events_dir = ext_files_dir / 'events' events_dir.mkdir(parents=True, exist_ok=True) with open(events_dir / name, mode='w+', encoding='UTF8') as f: return f.writelines([event])
b9bc3ba32964d6ea570c880bddebb615a331dac9
403,535
def to_bit_list(val, width=16): """Convert a number to a list of bits, LSB first""" return [(1 if val & (1<<n) else 0) for n in range(width)]
66365917d9c60b10da277b8d777a3060dd70c511
91,433
def get_all_preconditions(action_set): """ Returns a set of all preconditions for the actions in the given set """ all_precons = set() for a in action_set: all_precons.update(a.precondition) return all_precons
1697c2d013b07bbfc24ca6273d16523eb1d83acf
703,431
import json def get_all_topic_id_and_meta(client): """ Execute query to return meta dict for all topics. This information should take from 'meta' measurement in the InfluxDB database. :param client: InfluxDB client connected in historian_setup method. :return: a dictionary that maps topic_id to its actual topic name and a dictionary that maps each topic to its metadata """ topic_id_map = {} meta_dicts = {} query = 'SELECT topic, meta_dict, topic_id FROM meta' rs = client.query(query) rs = list(rs.get_points()) for point in rs: topic_id_map[point['topic_id']] = point['topic'] meta = point['meta_dict'].replace("u'", "\"").replace("'", "\"") meta_dicts[point['topic_id']] = json.loads(meta) return topic_id_map, meta_dicts
0a7ed8d50438f9623eac3ee6d37c5145a11ddd6e
548,563
def separate_files_and_options(args): """ Take a list of arguments and separate out files and options. An option is any string starting with a '-'. File arguments are relative to the current working directory and they can be incomplete. Returns: a tuple (file_list, option_list) """ file_args = [] opt_args = [] for arg in args: if arg and arg[0] != "-": file_args.append(arg) else: opt_args.append(arg) return file_args, opt_args
eae2de9cb93308b78ddf279304a73c6c5e1070e2
691,482
def size(matrix): """ :param matrix: the matrix to compute the size :type matrix: matrix :return: the size of matrix (number of rows, number of cols) :rtype: typle of 2 int """ return len(matrix[0]), len(matrix)
7144202b0d341e2f242806f471f50fbee6b7420a
505,961
import re def parseRange(text): """ convert a range string like 2-3, 10-20, 4-, -9, or 2 to a list containing the endpoints. A missing endpoint is set to None. """ def toNumeric(elt): if elt == "": return None else: return int(elt) if re.search(r'-', text): rng = text.split(r':') rng = [toNumeric(elt) for elt in rng] else: v = int(text) rng = [v, v] return rng
bec19909188ffdb1de1de233a5f33675fa1ea48b
67,221
def filtered_alarm(alarm): """ Restructure a CloudWatch alarm into a simpler form. """ filtered = { "AlarmArn": alarm["AlarmArn"], "AlarmName": alarm["AlarmName"], "MetricName": alarm["MetricName"], "Namespace": alarm["Namespace"], "StateValue": alarm["StateValue"], "StateUpdated": int(alarm["StateUpdatedTimestamp"].timestamp()) } return filtered
1430fdd6f03d56cb564e5c7b6167679ec554f148
397,300
def hasShapeType(items, sort): """ Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`. :param shape: :class:`list` :param sort: type of shape """ return any([getattr(item, sort) for item in items])
9a1c8dbe0a850cc45d4be0ac9d1327b778dc987a
682,740
def compare_list(list1: list, list2: list) -> bool: """Compare two list and ignore \n at the end of two list.""" while list1[-1] == "\n" or list1[-1] == "": list1.pop() while list2[-1] == "\n" or list2[-1] == "": list2.pop() return list1 == list2
f7e925116dd952fb64e89c4da5b2256682cfb3a3
666,307
def get_population(array_islands): """ Extract the population size for every island within the island group. Return those as an array. """ pops = [] for index, isle in enumerate(array_islands): pops.append(isle.m) return pops
727f6705f12b03407dcf980c14941883f1327228
460,712
import click def locale_option(help_text=None, multiple=True): """Option for providing locale(s).""" if help_text is None: help_text = 'Locale to target.' def _decorator(func): return click.option( '--locale', type=str, multiple=multiple, help=help_text)(func) return _decorator
b0ef695a38f5f4c14b665a9e9dd5cf18d60b983f
493,079
from typing import Union def constrain(value: Union[int, float], max_val: Union[float, int], min_val: Union[float, int]=0): """ Constrain given value in given boundaries. :param value: value to be constrained :param max_val: value cannot be more than this :param min_val: returned value won't be lower than this :return: value constrained within given range """ if max_val < min_val: max_val, min_val = min_val, max_val return max(min_val, min(value, max_val))
210a7059d58ab0a0d62ad95b41200e4c8d44d6c2
435,651
def nvmf_create_target(client, name, max_subsystems=0): """Create a new NVMe-oF Target. Args: name: Must be unique within the application max_subsystems: Maximum number of NVMe-oF subsystems (e.g. 1024). default: 0 (Uses SPDK_NVMF_DEFAULT_MAX_SUBSYSTEMS). Returns: The name of the new target. """ params = {} params['name'] = name params['max_subsystems'] = max_subsystems return client.call("nvmf_create_target", params)
7b10540651b169406f942889caabef95506c4232
661,262
def ham_dist(s1, s2): """ The Hamming distance is defined between two strings of equal length. It measures the number of positions with mismatching characters. """ assert len(s1) == len(s2) return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
24294f08c88559a37c51f8151525fce92883f6b8
491,168
def generateTypeConverter(name, cache, typeConverter): """ Type converter Args: name (str): cache: typeConverter: Returns: lambda: Function to convert the type """ return lambda value: typeConverter(name, value, cache)
808c362902ae9a0173b5b7a3bbc12be0306266e9
171,865
import requests import csv def fetch_trac(base_url): """ Return a fetcher for a Trac instance >>> url, n = fetch_trac("https://debathena.mit.edu/trac")("123") >>> url u'https://debathena.mit.edu/trac/ticket/123' >>> n u'debathena-ssl-certificates should include a CRL' >>> url, n = fetch_trac("https://scripts.mit.edu/trac")("123") >>> url u'https://scripts.mit.edu/trac/ticket/123' >>> n u'scripts-remove works poorly with non-Athena accounts' """ def trac_fetcher(ticket): url = '%s/ticket/%s' % (base_url, ticket) response = requests.get(url + '?format=csv') if response.status_code == 200: reader = csv.DictReader(response.text.split('\n')) row = next(reader) return url, row.get('summary', None) else: return url, None return trac_fetcher
de17fac1de86bd338f3e9ed6f297d0ce9dd80ec9
259,552
def deal_cards(shuffled_deck): """Returns a hand of 13 cards each to four players from a shuffled deck""" hands = [[], [], [], []] print("Dealing the cards!") hands[0] = shuffled_deck[:13] hands[1] = shuffled_deck[13:26] hands[2] = shuffled_deck[26:39] hands[3] = shuffled_deck[39:] return hands
a41ce5a27e93d364e2f9d0117363804f77afbf5d
448,466
def conjoin(functions, *args, **kwargs): """Returns True if all functions return True when applied to args.""" for f in functions: if not f(*args, **kwargs): return False return True
b84746e9f14373153c277727612241a2b11d20de
599,244
def is_canonical_chromosome(chr): """Check if chr is 1-22, X or Y (M not included) Args: chr (str): chromosome name Returns: is_canonical (bool): True if chr is 1-22, X or Y """ is_canonical = False if chr.startswith("chr"): chr = chr.replace("chr", "") if chr == "X" or chr == "Y": is_canonical = True else: try: if 1 <= int(chr) <= 22: is_canonical = True except: pass return is_canonical
fd2467c26fa9b2a0f7abee840b5e12d7fee49ea6
162,138
from datetime import datetime def time_ago(date): """ Returns a string like '3 minutes ago' or '8 hours ago' Got this from joltz in #python on freenode. Thanks! >>> time_ago(datetime.now() - timedelta(seconds=90)) 'one minute ago' >>> time_ago(datetime.now() - timedelta(seconds=900)) '15 minutes ago' >>> time_ago(datetime.now() - timedelta(seconds=60*12)) '12 minutes ago' >>> time_ago(datetime.now() - timedelta(seconds=60*60*4)) 'about 4 hours ago' """ current_date = datetime.now() hours_ago = (current_date - date).seconds / 60 / 60 minutes_ago = (current_date - date).seconds / 60 days_ago = (current_date - date).days if days_ago > 0: # More than 24 hours ago return date.strftime('on %h %d, %Y at %I:%M%p') if hours_ago >= 1 and hours_ago <= 23: # An hour or more ago if hours_ago > 1: return "about %s hours ago" % str(hours_ago) else: return "about an hour ago" if minutes_ago >= 0 and minutes_ago <= 59: # Less than an hour ago if minutes_ago > 1: return "%s minutes ago" % str(minutes_ago) elif minutes_ago == 1: return "one minute ago" else: return "just now"
37c30e78540aee715eacfc88586cdeb151920e3a
426,991
from typing import Dict from typing import List def make_data_lists(img_pth_to_cap: Dict[str, str], image_paths: List[str]): """Make lists of data paths and respective captions Args: img_pth_to_cap: Dictionary of image paths to captions image_paths: List of image paths Returns: img_list: List of image paths cap: List of captions """ cap, img_list = [], [] for im_pth in image_paths: caption_list = img_pth_to_cap[im_pth] cap.extend(caption_list) img_list.extend([im_pth] * len(caption_list)) return img_list, cap
dafee60e5a6ebcab9046cfd7b90f01a9eda08d02
50,303
import calendar def _datetime_to_millis(dtm): """Convert datetime to milliseconds since epoch UTC.""" if dtm.utcoffset() is not None: dtm = dtm - dtm.utcoffset() return int(calendar.timegm(dtm.timetuple()) * 1000 + dtm.microsecond // 1000)
e013e835b062173d434b19e4734d028c41e407e2
532,279
def ConvertToNumber(value): """Converts value, a string, into either an integer or a floating point decimal number. """ try: # int() automatically promotes to long if necessary return int(value) except: return float(value)
a6c2e68d1cbed30d1daaff18ec7a395cd3d1fb62
539,437
def scienti_filter(table_name, data_row): """ Funtion that allows to filter unwanted data from the json. for this case: * fields with "FILTRO" * values with the string "nan" * passwords anything can be set here to remove unwanted data. Parameters: table_name:str name of the table we are currently filtering data_row:pandas.Series one arrow of the current table Returns: dictionary with the clean data. NOTE: this is called by the funciton ukupacha.Utils.parse_table """ data_row.dropna(inplace=True) data = {} for key, value in data_row.iteritems(): if "FILTRO" in key: continue # if value == "nan": # continue if key == "TXT_CONTRASENA": continue data[key] = value return data
03029587e43f4e8aad809b607c45f53149d94fa2
652,704
from datetime import datetime def _readable_date(string): """ A function that accepts a string formatted date and return a more readable data string format. :param string: string formatted date :return: Human readable string formatted date """ return datetime.strptime(string, '%Y%m%d').date().strftime('%B %d, %Y')
e53584b0b28ae7c8122d060047cd35f4d625da7a
465,059
def format_code(code): """ Generates the string for a code block of the example page, formatted for a 'sphinx-gallery' example script. Parameters ---------- code : string The python source code to be formatted. Returns ------- string : The formatted string for the example script. """ block_str = '' for line in code: block_str += line + '\n' return block_str + '\n'
668c77a6923236f53c6be5465a22c77a2b1cd5dc
169,674
import re def remove_all(value): """ Remove all whitespaces from a string. :param value: The value :type value: str :return: The value with all whitespaces removed :rtype: str """ return re.sub(r"\s+", "", value)
84e1c698cfbfae972b06d3af870ed5f664fc8be0
576,185
def float_or_string(arg): """Force float or string """ try: res = float(arg) except ValueError: res = arg return res
3dd47e9688ae8e4693e76482e041644bb2d8ab4d
125,697
def test_model_accuracy(model, probe_method, test_set, test_answer): """ Tests the model on the given set and returns the accuracy :param model: a trained model :param probe_method: the models query method, takes an instance as a parameter and returns the prediction :param test_set: an iterable object to probe with :param test_answer: an iterable object to correlate with the models predictions :return: the number of correct predicitons / total number of probes """ correct_count = 0 for index, element in enumerate(test_set): if model.probe_method(element) == test_answer[index]: correct_count += 1 return correct_count / len(test_set)
51deef7df7d3fe8926fd7b71706b2af68536e37b
525,189
def find_zetas_from_sigmas(sigmas, m): """Find first m complete symmetrical polynomials zetas using 'sigmas'. For this we use: zeta_k = \\sum_{i=1}^k (-1)^(i+1) sigmas[i] zetas_{k-i}.""" zetas = [0.] * m zetas[0] = 1. for k in range(1, m): zetas[k] = sum([sigmas[i] * zetas[k - i] * (-1) ** (i + 1) for i in range(1, min(len(sigmas), k + 1))]) return zetas
71cbe2580be3299b4bea889e50e5d3e0076cb0bf
505,864
def cmp_individual_scaled(a, b): """ Compares two individual fitness scores, used for sorting population Example: >>> GPopulation.cmp_individual_scaled(a, b) :param a: the A individual instance :param b: the B individual instance :rtype: 0 if the two individuals fitness score are the same, -1 if the B individual fitness score is greater than A and 1 if the A individual fitness score is greater than B. .. note:: this function is used to sorte the population individuals """ if a.fitness < b.fitness: return -1 if a.fitness > b.fitness: return 1 return 0
07fcbaf73621948ec8fe2c48e2e6a4f573203475
650,725
def bitstring_to_number(bitstring): """ Convert a bitstring to a number. E.g. ``10110101`` gives 181. Args: bitstring (str): String of ``1``\ s and ``0``\ s. Returns: int: The equivalent integer. """ return int(bitstring, 2)
86db64054deaed761638b97640301e11de8577cc
397,268
def txout_compress(n): """ Compresses the Satoshi amount of a UTXO to be stored in the LevelDB. Code is a port from the Bitcoin Core C++ source: https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L133#L160 :param n: Satoshi amount to be compressed. :type n: int :return: The compressed amount of Satoshis. :rtype: int """ if n == 0: return 0 e = 0 while ((n % 10) == 0) and e < 9: n /= 10 e += 1 if e < 9: d = (n % 10) assert (1 <= d <= 9) n /= 10 return 1 + (n * 9 + d - 1) * 10 + e else: return 1 + (n - 1) * 10 + 9
94a10e34cdb3d5abf5da1b97240539b5e3308f93
238,919
def calculate_rewards_common(covariates, coeffs_common): """Calculate common rewards. Covariates 9 and 10 are indicators for high school and college graduates. Parameters ---------- covariates : np.ndarray Array with shape (num_states, 16) containing covariates. coeffs_common : np.ndarray Array with shape (2,) containing coefficients for high school and college graduates. Returns ------- np.ndarray Array with shape (num_states, 1) containing common rewards. Reshaping is necessary to broadcast the array over rewards with shape (num_states, 4). Example ------- >>> state_space = StateSpace(2, 1, [12, 16], 20) >>> coeffs_common = np.array([0.05, 0.6]) >>> calculate_rewards_common(state_space.covariates, coeffs_common).reshape(-1) array([0.05, 0.05, 0.65, 0.65, 0.05, 0.05, 0.05, 0.05, 0.65, 0.65, 0.65, 0.65]) """ return covariates[:, 9:11].dot(coeffs_common).reshape(-1, 1)
00b268aeddda5fdec4c8faf7b22d897e13cdd8c3
91,610
def get_package(config): """ Returns the package associated with this device Args: config (dictionary): configuration dictionary Return: (string) package Raises: Nothing """ #split the device string with "-" and get the second value package = config["device"].split("-")[1] package = package.strip() return package
5a13e28eafceaaab018373141108d2f8e75f2a37
668,876
def dispense_cash(amount): """ Determine the minimum number of ATM bills to meet the requested amount to dispense Parameters ---------- amount : int The amount of money requested from the ATM Returns ------- int The number of bills needed, -1 if it can't be done """ """ If the amount isn't divisible by 10, then no need to bother cause it won't work Assuming it is divisible by 10, then let's fulfill the request starting with the largest bills and moving to smaller bills """ # Get the number of $500 bills that could be used # Total to dispense - (however much we gave in $500) figure out the 100s # Of what's left, how many $50 bills can we give # Again taking what's left, get the max number of 20s # Finally, if there is anything left it must be a 10 total_bills = 0 if amount % 10 != 0: return -1 # Can't be done, because it has to be a multiple of 10 # How many $500 bills can we dispense b_500 = amount // 500 # The // operator does integer only division - such that 4 // 3 = 1 left_over = amount % 500 # The 'mod' operator says give me the remainder of the division # How many $100 bills can we dispense b_100 = left_over // 100 left_over = left_over % 100 # How many $50 bills can we dispense b_50 = left_over // 50 left_over = left_over % 50 # How many $20 bills can we dispense b_20 = left_over // 20 left_over = left_over % 20 # How many $10 bills can we dispense b_10 = left_over // 10 total_bills = b_500 + b_100 + b_50 + b_20 + b_10 return total_bills
a85f56f900b52f4ddd0bdd93ebd97c1d80889c36
85,197
import requests def connection_ok(base_url): """Check whetcher connection is ok Post a request to server, if connection ok, server will return http response 'ok' Args: none Returns: if connection ok, return True if connection not ok, return False Raises: none """ cmd = 'connection_test' + "/" url = base_url + cmd print('url: %s'% url) # if server find there is 'connection_test' in request url, server will response 'Ok' try: r=requests.get(url) if r.text == 'OK': return True except: return False
b4d6bdfe2ec8d511238a65ef359abfbed0b5f86a
630,101
def subsetByDate(data, start, end): """Function that takes in a DataFrame and start and end dates, returning the subset of the frame with these dates""" return data[(data.index > start) & (data.index <= end)]
dcb001350b7e225845aa808068632c7b074f8ad0
494,389
def is_quoted(str): """ whether or not str is quoted """ return ((len(str) > 2) and ((str[0] == "'" and str[-1] == "'") or (str[0] == '"' and str[-1] == '"')))
b079bd4a7f3ac8814250faf522d9e38718fce986
30,353
def format_path(plot_root: str, variant: str) -> str: """ Format path. Convert representation of variant to a path. :param plot_root: root path can be url :param variant: variant :return: path of variant resource """ return f"{plot_root}{variant}.png"
bb3d53b1dee77304fd6952672f25882327b988de
146,995
def is_in_stock(res_obj): """Checks if a product is in stock Args: res_obj: requests_html response object of a canada computers product page Returns: bool: Is the product in stock """ selector = '#pi-form > div.col-12.py-2 > div.pi-prod-availability > span:nth-child(2)' stock = res_obj.html.find(selector, first=True).text if stock == 'Not Available Online': return False return True
59a560b9d40bd40045fbce4d5f90fa9d0ceb2b1b
144,582
def pad_up(size, factor): """Pad size up to a multiple of a factor""" x = size + factor - 1 return x - (x % factor)
724673db1d2ba9fecb81e2ea58c224b48541eae8
397,469
def int_array_to_hex(iv_array): """ Converts an integer array to a hex string. """ iv_hex = '' for b in iv_array: iv_hex += '{:02x}'.format(b) return iv_hex
f3332b7672a266ad9cae9fc52bc8e1152bcee58b
709,254
def pad_bytes32(instr): """ Pad a string \x00 bytes to return correct bytes32 representation. """ bstr = instr.encode() return bstr + (32 - len(bstr)) * b'\x00'
76c057b64435f2bc9d0c3c92f1b9315fb6252fd9
693,015
def _apply_nested(structure, fn): """Recursively apply a function to the elements of a list/tuple/dict.""" if isinstance(structure, list): return list(_apply_nested(elem, fn) for elem in structure) elif isinstance(structure, tuple): return tuple(_apply_nested(elem, fn) for elem in structure) elif isinstance(structure, dict): return dict([(k, _apply_nested(v, fn)) for k, v in structure.items()]) else: return fn(structure)
5c60338c070a8401b72f2d7a6e74205a63e3af83
552,297
def get_cookie_value( cookiejar, name ): """ Retrieves the value of a cookie from a CookieJar given its name. """ value = None for cookie in cookiejar: if cookie.name == name: value = cookie.value break return value
95e60548eb149bdd399ca5f3fc84ebc5fbf1eb87
544,447
def int_to_binary_string(n): """ Return the binary representation of the number n :param n: a number :return: a binary representation of n as a string """ return '{0:b}'.format(n)
7052b9c1d17c4eb0b67b27b96bb656e996922d02
239,489
def prefix_sums(A): """ This function calculate of sums of eements in given slice (contiguous segments of array). Its main idea uses prefix sums which are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array. Args: A: an array represents number of mushrooms growing on the consecutive spots along a road. Returns: an array contains the consecutive sums of the first n elements of an array A To use: >> A=[2,3,7,5,1,3,9] >> print(prefix_sums(A)) [0, 2, 5, 12, 17, 18, 21, 30] Time Complexity: O(n) """ n = len(A) P = [0] * (n + 1) for k in range(1, n + 1): P[k] = P[k - 1] + A[k - 1] return P
d61e49eb4a973f7718ccef864d8e09adf0e09ce2
707,913
def factorial(n): """ Returns the factorial of a number. """ fact = 1.0 if n > 1: fact = n * factorial(n - 1) return fact
7c20382a053cc3609fa041d1920d23b884b8aa0b
32,018
def range_check(s: str, mn: int, mx: int) -> bool: """Check a numeric str in in a range.""" return mn <= int(s) <= mx
4b7eda8f0c5ec21dfc70db2176f16231779bbb47
227,084
import time def lomuto_partition_scheme(L, draw_data, time_delay, low, high): """ Used as a component in quicksort algorithm.\n Prepares partition such that all values up to index i are smaller than the pivot and all values from i + 1 are greater than the pivot """ i = low - 1 pivot = L[high] old_highlight_idx = [] ## Display data ## for j in range(low, high): if L[j] <= pivot: i += 1 L[i], L[j] = L[j], L[i] ################ Display data ################ new_highlight_idx = [i, j] draw_data(old_highlight_idx, new_highlight_idx) old_highlight_idx = new_highlight_idx time.sleep(time_delay) draw_data(old_highlight_idx, []) ############################################## L[i+1], L[high] = L[high], L[i+1] return i + 1
dceaccda0764666c7e4c5cdc5c9185e5fb1fb139
408,999
import re def remove_extra_description_terms(description): """ Sometimes the description contains some things we don't want to include like trailing '.', extra spaces, the string (non-protein coding) and a typo in the name of tmRNA's. This corrects those issues. """ description = re.sub( r'\(\s*non\s*-\s*protein\s+coding\s*\)', '', description ) description = re.sub( r'transfer-messenger mRNA', 'transfer-messenger RNA', description, re.IGNORECASE ) description = re.sub(r'\s\s+', ' ', description) description = re.sub(r'\.?\s*$', '', description) return description
73e4ae305fc728a1ce815f040d2f4aa403df30f6
630,801