content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import math def moments_get_orientation(m): """Returns the orientation in radians from moments. Theta is the angle of the principal axis nearest to the X axis and is in the range -pi/4 <= theta <= pi/4. [1] 1. Simon Xinmeng Liao. Image analysis by moments. (1993). """ theta = 0.5 * math.atan( (2 * m['mu11']) / (m['mu20'] - m['mu02']) ) return theta
0b75e86e324dccd5fe2c4332dfeb15d63a417b9b
7,525
def get_article_case(article, word): """Determines the correct article casing based on the word casing""" return article.capitalize() if word[0].istitle() else article
603810cb60c3719c102afe024cdc0ce474d37bfa
7,526
import collections def deep_convert_to_plain_dict(an_odict): """ Recursively convert `an_odict` and any of its dictionary subelements from `collections.OrderedDict`:py:class: to plain `dict`:py:class: .. note:: This is naive, in that it will not properly handle dictionaries with recursive object references. :Args: an_odict a (presumably) `collections.OrderedDict`:py:class: to convert :Returns: an "unordered" (i.e., plain) `dict`:py:class: with all ordered dictionaries converted to `dict`:py:class: """ a_dict = {} for (key, value) in an_odict.items(): if type(value) is collections.OrderedDict: a_dict[key] = deep_convert_to_plain_dict(value) else: a_dict[key] = value return a_dict
0a463981909153d4beee64fbbf5fad489adf78ac
7,527
def _members_geom_lists(relation_val, footprints): """ Add relation members' geoms to lists. Parameters ---------- relation_val : dict members and tags of the relation footprints : dict dictionary of all footprints (including open and closed ways) Returns ------- tuple of lists """ outer_polys = [] outer_lines = [] inner_polys = [] inner_lines = [] # add each members geometry to a list according to its role and geometry type for member_id, member_role in relation_val["members"].items(): if member_role == "outer": if footprints[member_id]["geometry"].geom_type == "Polygon": outer_polys.append(footprints[member_id]["geometry"]) elif footprints[member_id]["geometry"].geom_type == "LineString": outer_lines.append(footprints[member_id]["geometry"]) elif member_role == "inner": if footprints[member_id]["geometry"].geom_type == "Polygon": inner_polys.append(footprints[member_id]["geometry"]) elif footprints[member_id]["geometry"].geom_type == "LineString": inner_lines.append(footprints[member_id]["geometry"]) return outer_polys, outer_lines, inner_polys, inner_lines
a0ccf10ef75c381b5839cf8e17ba304a7488ecda
7,529
import math def fuzzifier_determ(D: int, N: int) -> float: """The function to determ the fuzzifier paramter of fuzzy c-means """ return 1 + (1418 / N + 22.05) * D**(-2) + (12.33 / N + 0.243) * D**(-0.0406 * math.log(N) - 0.1134)
3bf0f85a74400c19fae74349ea651eba8b600697
7,531
from typing import List def _is_paired(ordered_list: List[int]) -> bool: """Check whether values are paired in ordered_list.""" consecutive_comparison = [ t == s for s, t in zip(ordered_list, ordered_list[1:]) ] return (all(consecutive_comparison[0::2]) & (not any(consecutive_comparison[1::2])))
ba7052de513bcc7bf274e38005c459715e9f60b8
7,532
def steps(number): """ Count steps needed to get to 1 from provided number. :param number int - the number provided. :return int - the number of steps taken to reach 1. """ if number < 1: raise ValueError("Provided number is less than 1.") steps = 0 while number != 1: steps += 1 # Even if number % 2 == 0: number = number / 2 else: number = number * 3 + 1 return steps
8681691946b5ba2d261a1ae753d2a04c46ac1719
7,533
import numpy def _get_sr_pod_grid(success_ratio_spacing=0.01, pod_spacing=0.01): """Creates grid in SR-POD space SR = success ratio POD = probability of detection M = number of rows (unique POD values) in grid N = number of columns (unique success ratios) in grid :param success_ratio_spacing: Spacing between adjacent success ratios (x-values) in grid. :param pod_spacing: Spacing between adjacent POD values (y-values) in grid. :return: success_ratio_matrix: M-by-N numpy array of success ratios. Success ratio increases while traveling right along a row. :return: pod_matrix: M-by-N numpy array of POD values. POD increases while traveling up a column. """ num_success_ratios = int(numpy.ceil(1. / success_ratio_spacing)) num_pod_values = int(numpy.ceil(1. / pod_spacing)) unique_success_ratios = numpy.linspace( 0, 1, num=num_success_ratios + 1, dtype=float ) unique_success_ratios = ( unique_success_ratios[:-1] + success_ratio_spacing / 2 ) unique_pod_values = numpy.linspace( 0, 1, num=num_pod_values + 1, dtype=float ) unique_pod_values = unique_pod_values[:-1] + pod_spacing / 2 return numpy.meshgrid(unique_success_ratios, unique_pod_values[::-1])
6349afbecc8994c1078f2fa019a5a721862b0d15
7,534
import re def replace_space(string): """Replace all spaces in a word with `%20`.""" return re.sub(' ', '%20', string)
9b9b400f913efb7ee1e86a87335955744c9b1a3a
7,536
import re def port_to_string(port): """ Returns clear number string containing port number. :param port: port in integer (1234) or string ("1234/tcp") representation. :return: port number as number string ("1234") """ port_type = type(port) if port_type is int: return str(port) if port_type is str: return re.findall(r"\d+", port)[0]
5d526406566c7c37af223ed8e5744ba13771f55f
7,537
from typing import Optional def code_block(text: str, language: Optional[str] = None) -> str: """Creates a code block using HTML syntax. If language is given, then the code block will be created using Markdown syntax, but it cannot be used inside a table. :param text: The text inside the code block :param language: The language to use for syntax highlighting """ if language: return f'```{language}\n{text}\n```' return f'<pre><code>{text}</code></pre>'
5d8b272d2a93463171e5a51beaccd8293db280dc
7,538
def merge(line): """ Helper function that merges a single row or column in 2048 """ result = list(line) head = 0 i = 1 while (i < len(result)): if (result[i] != 0): if (result[head] == result[i]): result[head] += result[i] result[i] = 0 head += 1 elif (result[head] == 0): result[head] = result[i] result[i] = 0 else: tmp = result[i] result[i] = 0 result[head + 1] = tmp head += 1 i += 1 return result
1a843ef4dc9c1b6cf20036f24288cb6166ae207b
7,539
def get_transcripts_from_tree(chrom, start, stop, cds_tree): """Uses cds tree to btain transcript IDs from genomic coordinates chrom: (String) Specify chrom to use for transcript search. start: (Int) Specify start position to use for transcript search. stop: (Int) Specify ending position to use for transcript search cds_tree: (Dict) dictionary of IntervalTree() objects containing transcript IDs as function of exon coords indexed by chr/contig ID. Return value: (set) a set of matching unique transcript IDs. """ transcript_ids = set() # Interval coordinates are inclusive of start, exclusive of stop if chrom not in cds_tree: return [] cds = list(cds_tree[chrom].overlap(start, stop)) for cd in cds: transcript_ids.add(cd.data) return list(transcript_ids)
51aa6f1aa97d2f977840376ea2c4bf422ff8e7a6
7,540
def parse_flattened_result_only_intent(to_parse): """ Parse out the belief state from the raw text. Return an empty list if the belief state can't be parsed Input: - A single <str> of flattened result e.g. 'User: Show me something else => Belief State : DA:REQUEST ...' Output: - Parsed result in a JSON format, where the format is: [ { 'act': <str> # e.g. 'DA:REQUEST', 'slots': [ <str> slot_name, <str> slot_value ] }, ... # End of a frame ] # End of a dialog """ def parse_intent(intent_str): pos_list = [] for i in range(len(intent_str)): for j in range(i + 1, min(len(intent_str), i + 4)): sub_str = intent_str[i:j + 1] if sub_str == 'da:' or sub_str == 'err:': pos_list.append(i) break if not pos_list or len(pos_list) == 1: return [intent_str] return [intent_str[:pos] for pos in pos_list[1:]] + [intent_str[pos_list[-1]:]] belief = [] # Parse # to_parse: 'DIALOG_ACT_1 : [ SLOT_NAME = SLOT_VALUE, ... ] ...' to_parse = to_parse.strip() intents = parse_intent(to_parse) for idx, dialog_act in enumerate(intents): d = dict() d['act'] = dialog_act.replace('.', ':') d['slots'] = [] if d != {}: belief.append(d) return belief
05c7346197fa3f98f1c4194ea7d92622483d0f51
7,541
import argparse def process_command_line(): """ returns a 1-tuple of cli args """ parser = argparse.ArgumentParser(description='usage') parser.add_argument('--config', dest='config', type=str, default='config.yaml', help='config file for this experiment') parser.add_argument('--test', dest='test', action='store_true', help='run test') parser.add_argument('--train', dest='train', action='store_true', help='run training') parser.add_argument('--gpu', dest='gpu', type=str, default='0', help='gpu') args = parser.parse_args() return args
573ec38b1b57538ebb97b082f71343a49081dfc7
7,542
import re def strip_outer_dollars(value): """Strip surrounding dollars signs from TeX string, ignoring leading and trailing whitespace""" if value is None: return '{}' value = value.strip() m = re.match(r'^\$(.*)\$$', value) if m is not None: value = m.groups()[0] return value
3ad283af2835ba2bcf2c57705f2faa9495ea4e7a
7,543
import os def menu_select(title='~ Untitled Menu ~', main_entries=[], action_entries=[], prompt='Please make a selection', secret_exit=False): """Display options in a menu for user selection""" # Bail early if (len(main_entries) + len(action_entries) == 0): raise Exception("MenuError: No items given") # Build menu menu_splash = '{title}\n\n'.format(title=title) valid_answers = [] if (secret_exit): valid_answers.append('Q') # Add main entries if (len(main_entries) > 0): for i in range(len(main_entries)): entry = main_entries[i] # Add Spacer if ('CRLF' in entry): menu_splash += '\n' valid_answers.append(str(i+1)) menu_splash += '{number:>{mwidth}}: {name}\n'.format(number=i+1, mwidth=len(str(len(main_entries))), name=entry.get('Display Name', entry['Name'])) menu_splash += '\n' # Add action entries if (len(action_entries) > 0): for entry in action_entries: # Add Spacer if ('CRLF' in entry): menu_splash += '\n' valid_answers.append(entry['Letter']) menu_splash += '{letter:>{mwidth}}: {name}\n'.format(letter=entry['Letter'].upper(), mwidth=len(str(len(action_entries))), name=entry['Name']) menu_splash += '\n' answer = '' while (answer.upper() not in valid_answers): os.system('cls') print(menu_splash) answer = input('{prompt}: '.format(prompt=prompt)) return answer.upper()
2495d79218e03430642eb4d099223fa2e2f3b357
7,545
def estimate_price(mileage, theta0, theta1): """ Estimate price function: """ return theta0 + theta1 * mileage
43ba05aacc3cb94f9bf3223f6ea8f74a569c2537
7,546
def similar_date(anon, obj, field, val): """ Returns a date that is within plus/minus two years of the original date """ return anon.faker.date(field=field, val=val)
d9a723d3c22954797895b43d57f297330272c8cb
7,547
def structure_sampling_values(graph, centrality, function): """ helper function to compute the centrality values for an edge""" cent = centrality.get_values(graph) edges = graph.get_edges() left_values =cent[edges[:,0]] right_values=cent[edges[:,1]] values = function(left_values, right_values) return values
a0608646867704dea6b1e27e4cfee8b3062ab0da
7,548
def dummy_wrapper(fn): """Simple wrapper used for testing""" def _run_callable(*args, **kwargs): return fn(*args, **kwargs) return _run_callable
60d92942fd1d87b835ea05dd00baea8a71117fac
7,549
def get_backlinks(dictionary): """ Returns a reversed self-mapped dictionary @param dictionary: the forwardlinks """ o = dict() for key, values in dictionary.items(): try: for v in values: try: o[v].add(key) except KeyError: o[v] = {key} except TypeError as te: try: o[values].add(key) except KeyError: o[values] = {key} return o
43b28e4f177a7813ba8d8c0960d04e71ad28f83b
7,550
import zipfile def unzip(zip_address, file_name, encoding='UTF-8'): """解压zip数据包 :param zip_address: 压缩包的地址 :param file_name: 压缩包里面文件的名字 :param encoding: 文件的编码 :return: 压缩包里面的数据:默认编码的UTF-8 """ f = zipfile.ZipFile(zip_address) fp = f.read(file_name) lines = fp.decode(encoding) return lines
ba71fd6f923c2c410b0461796da513583c15b9aa
7,551
def has_name_keywords(ustring): """是否含有名称的标识字符""" if (u'店名' in ustring) or \ (u'店家' in ustring) or \ (u'名字' in ustring): return True return False
e009e567ecf060b0b225802de523dea60ab8a02e
7,552
def bbox_flip(bbox, width, flip_x=False): """ invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2 also note need to save before assignment :param bbox: [n][x1, y1, x2, y2] :param width: cv2 (height, width, channel) :param flip_x: will flip x1 and x2 :return: flipped box """ if flip_x: xmax = width - bbox[:, 0] xmin = width - bbox[:, 2] bbox[:, 0] = xmin bbox[:, 2] = xmax return bbox
485496752c83e0e8424b9f67a56a861373db5fc5
7,553
def greeting(): # OK """Beschreibung: Dient zum besonderen aussehen :return: gibt die eingegebenen Zeichen decodiert aus Details: print(b'\xe2\x95\x94'.decode('utf-8')) ergibt ╔ die linke obere Ecke print(b'\xe2\x95\x91'.decode('utf-8')) ergibt ║ somit lassen sich "Rahmen bauen" """ dic = { '\\' : b'\xe2\x95\x9a', '-' : b'\xe2\x95\x90', '/' : b'\xe2\x95\x9d', '|' : b'\xe2\x95\x91', '+' : b'\xe2\x95\x94', '%' : b'\xe2\x95\x97', } def decode(x): return (''.join(dic.get(i, i.encode('utf-8')).decode('utf-8') for i in x)) print(decode('+--------------------------------------%')) print(decode('| Willkommen bei uns im Zauberwald |')) print(decode('\\--------------------------------------/'))
4800675329568bda9015782bb2f30513fb842931
7,554
import logging import json def read_json_file_into_memory(json_file): """ Purpose: Read properly formatted JSON file into memory. Args: json_file (String): Filename for JSON file to load (including path) Returns: json_object (Dictonary): Dictonary representation JSON Object Examples: >>> json_file = 'some/path/to/file.json' >>> json_object = read_json_file_into_memory(json_file) >>> print(json_object) >>> { >>> 'key': 'value' >>> } """ logging.info(f"Reading JSON File Into Memory: {json_file}") try: with open(json_file, "r") as json_file_obj: return json.load(json_file_obj) except Exception as err: logging.exception(f"Cannot Read json into memory ({json_file}): {err}") raise err
70c2e6ab6180700ce77469b8afa0d0df8e0eee95
7,555
def to_base_10(num: str, from_base: int, key="0123456789abcdefghijklmnopqrstuvwxyz", digits=100, minus_sign="-") -> int: """Convert a num in from_base to base 10.""" if len(key) < from_base: raise ValueError("Must have key length > base") if num == key[0]: return 0 if num[0] == minus_sign: sign = -1 else: sign = 1 new_num = 0 num_length = len(num) for i in range(num_length): try: new_digit = key.index(num[i]) except ValueError: raise ValueError("digit, " + str(num[i]) + ", not in key") new_num += from_base ** (num_length - i - 1) * new_digit return new_num * sign
128127fe1f55250f46e057fa92f72d25966be626
7,557
import torch def dist(batch_reprs, eps = 1e-16, squared=False): """ Efficient function to compute the distance matrix for a matrix A. Args: batch_reprs: vector representations eps: float, minimal distance/clampling value to ensure no zero values. Returns: distance_matrix, clamped to ensure no zero values are passed. """ prod = torch.mm(batch_reprs, batch_reprs.t()) norm = prod.diag().unsqueeze(1).expand_as(prod) res = (norm + norm.t() - 2 * prod).clamp(min = 0) if squared: return res.clamp(min=eps) else: return res.clamp(min = eps).sqrt()
be4d50e35ed11255eef2dc1acb4645de1453964c
7,559
def unquote(s): """Strip single quotes from the string. :param s: string to remove quotes from :return: string with quotes removed """ return s.strip("'")
15d29698e6a3db53243fc4d1f277184958092bc6
7,561
import string def normalize(text): """ Remove all punctuation for now """ return ''.join('' if c in string.punctuation else c for c in text)
9332583adb0ff3bfbe37170b2acdd58f09b3fe5e
7,562
def p_AB(A, b, L): """ Numerator of function f. """ a11, a12, a13, a21, a22, a23, a31, a32, a33 = \ A[0, 0], A[0, 1], A[0, 2], \ A[1, 0], A[1, 1], A[1, 2], \ A[2, 0], A[2, 1], A[2, 2] b1, b2, b3 = b[0, 0], b[1, 0], b[2, 0] return L**4*(-a11*a22*b3**2 + a11*a23*b2*b3 + a11*a32*b2*b3 - a11*a33*b2**2 + a11*b2**2 + a11*b3**2 + a12*a21*b3**2 - a12*a23*b1*b3 - a12*a31*b2*b3 + a12*a33*b1*b2 - a12*b1*b2 - a13*a21*b2*b3 + a13*a22*b1*b3 + a13*a31*b2**2 - a13*a32*b1*b2 - a13*b1*b3 - a21*a32*b1*b3 + a21*a33*b1*b2 - a21*b1*b2 + a22*a31*b1*b3 - a22*a33*b1**2 + a22*b1**2 + a22*b3**2 - a23*a31*b1*b2 + a23*a32*b1**2 - a23*b2*b3 - a31*b1*b3 - a32*b2*b3 + a33*b1**2 + a33*b2**2 - b1**2 - b2**2 - b3**2) + L**3*(3*a11*a22*b3**2 - 3*a11*a23*b2*b3 - 3*a11*a32*b2*b3 + 3*a11*a33*b2**2 - 2*a11*b2**2 - 2*a11*b3**2 - 3*a12*a21*b3**2 + 3*a12*a23*b1*b3 + 3*a12*a31*b2*b3 - 3*a12*a33*b1*b2 + 2*a12*b1*b2 + 3*a13*a21*b2*b3 - 3*a13*a22*b1*b3 - 3*a13*a31*b2**2 + 3*a13*a32*b1*b2 + 2*a13*b1*b3 + 3*a21*a32*b1*b3 - 3*a21*a33*b1*b2 + 2*a21*b1*b2 - 3*a22*a31*b1*b3 + 3*a22*a33*b1**2 - 2*a22*b1**2 - 2*a22*b3**2 + 3*a23*a31*b1*b2 - 3*a23*a32*b1**2 + 2*a23*b2*b3 + 2*a31*b1*b3 + 2*a32*b2*b3 - 2*a33*b1**2 - 2*a33*b2**2 + b1**2 + b2**2 + b3**2) + L**2*(-3*a11*a22*b3**2 + 3*a11*a23*b2*b3 + 3*a11*a32*b2*b3 - 3*a11*a33*b2**2 + a11*b2**2 + a11*b3**2 + 3*a12*a21*b3**2 - 3*a12*a23*b1*b3 - 3*a12*a31*b2*b3 + 3*a12*a33*b1*b2 - a12*b1*b2 - 3*a13*a21*b2*b3 + 3*a13*a22*b1*b3 + 3*a13*a31*b2**2 - 3*a13*a32*b1*b2 - a13*b1*b3 - 3*a21*a32*b1*b3 + 3*a21*a33*b1*b2 - a21*b1*b2 + 3*a22*a31*b1*b3 - 3*a22*a33*b1**2 + a22*b1**2 + a22*b3**2 - 3*a23*a31*b1*b2 + 3*a23*a32*b1**2 - a23*b2*b3 - a31*b1*b3 - a32*b2*b3 + a33*b1**2 + a33*b2**2) + L*(a11*a22*b3**2 - a11*a23*b2*b3 - a11*a32*b2*b3 + a11*a33*b2**2 - a12*a21*b3**2 + a12*a23*b1*b3 + a12*a31*b2*b3 - a12*a33*b1*b2 + a13*a21*b2*b3 - a13*a22*b1*b3 - a13*a31*b2**2 + a13*a32*b1*b2 + a21*a32*b1*b3 - a21*a33*b1*b2 - a22*a31*b1*b3 + a22*a33*b1**2 + a23*a31*b1*b2 - a23*a32*b1**2)
530655f0e6e56ef6aca4ad82d5076543caec0ddb
7,563
def binary_to_decimal(binary): """ Converts a binary number into a decimal number. """ decimal = 0 index = 0 while binary > 0: last = binary % 10 binary = binary / 10 decimal += (last * (2 ** index)) index += 1 return decimal
f1efdf19c802345e6badfed430dd82e3f067a419
7,564
def namelist(names: list) -> str: """ Format a string of names like 'Bart, Lisa & Maggie' :param names: an array containing hashes of names :return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. """ if not names: return "" names_list = [name['name'] for name in names] if len(names_list) == 1: return names_list[0] elif len(names_list) == 2: return '{} & {}'.format(names_list[0], names_list[1]) else: return ', '.join(names_list[:-1]) + ' & ' + names_list[-1]
b0b931f3f9365824931173c2aec3ac213342e0c3
7,565
def loadIUPACcompatibilities(IUPAC, useGU): """ Generating a hash containing all compatibilities of all IUPAC RNA NUCLEOTIDES """ compatible = {} for nuc1 in IUPAC: # ITERATING OVER THE DIFFERENT GROUPS OF IUPAC CODE sn1 = list(IUPAC[nuc1]) for nuc2 in IUPAC: # ITERATING OVER THE DIFFERENT GROUPS OF IUPAC CODE sn2 = list(IUPAC[nuc2]) compatib = 0 for ( c1 ) in ( sn1 ): # ITERATING OVER THE SINGLE NUCLEOTIDES WITHIN THE RESPECTIVE IUPAC CODE: for ( c2 ) in ( sn2 ): # ITERATING OVER THE SINGLE NUCLEOTIDES WITHIN THE RESPECTIVE IUPAC CODE: # CHECKING THEIR COMPATIBILITY if useGU: if ( (c1 == "A" and c2 == "U") or (c1 == "U" and c2 == "A") or (c1 == "C" and c2 == "G") or (c1 == "G" and c2 == "C") or (c1 == "G" and c2 == "U") or (c1 == "U" and c2 == "G") ): compatib = 1 else: if ( (c1 == "A" and c2 == "U") or (c1 == "U" and c2 == "A") or (c1 == "C" and c2 == "G") or (c1 == "G" and c2 == "C") ): compatib = 1 compatible[ nuc1 + "_" + nuc2 ] = compatib # SAVING THE RESPECTIVE GROUP COMPATIBILITY, REVERSE SAVING IS NOT REQUIRED, SINCE ITERATING OVER ALL AGAINST ALL return compatible
931f2a765ec9499b8553d13d7de93c6b261622de
7,567
def to_fullspec(rs, es, hds): """ Rotationally symmetric dump of a list of each to fullspec """ output = [] for idx in range(0, len(rs)): row = {"r": [rs[idx]], "e": [es[idx]], "d": hds[idx] * 2} output.append(row) return output
98cac8ba938249d6af0decfeffedf594ab1d6660
7,568
def get_uniq_list(data): """ 列表去重并保持顺序(数据量大时效率不高) :param data: list :return: list """ ret = list(set(data)) ret.sort(key=data.index) return ret
d4a43acd42608210c022317999673bd281e5e247
7,569
import re def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" # text = force_text(text) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines return re_newlines.sub('\n', text)
835f038f0873546db96d8e9d2a0d622b4e974f7d
7,570
def check_families(trace_events, families, event_definitions): """ Looks for event types found in the trace that are not specified in the event definitions. :param trace_events: Events found in the trace (filtered by family). :param families: Families to look for. :param event_definitions: Event definitions. :return: Message report list """ print("\n- Checking families... %s" %families) report = [] trace_event_types = [] for line in trace_events: if line[0] not in trace_event_types: trace_event_types.append(line[0]) trace_event_types.sort() print("\t- Found event types:") print(str(trace_event_types)) event_types = event_definitions.keys() event_types.sort() print("\t- Expected event types:") print(str(event_types)) for event_type in trace_event_types: if event_type not in event_types: report.append("ERROR: Unexpected event type %d found in check_families" % event_type) for event in event_types: if event not in trace_event_types: report.append("ERROR: Missing event type %d found in check_families" % event) return report
2533835283d388ad2fe37d79f6e87f14103a5bee
7,571
import re def convertSQL_LIKE2REGEXP(sql_like_pattern): """Convert a standard SQL LIKE pattern to a REGEXP pattern. Function that transforms a SQL LIKE pattern to a supported python regexp. Returns a python regular expression (i.e. regexp). sql_like_pattern[in] pattern in the SQL LIKE form to be converted. """ # Replace '_' by equivalent regexp, except when precede by '\' # (escape character) regexp = re.sub(r'(?<!\\)_', '.', sql_like_pattern) # Replace '%' by equivalent regexp, except when precede by '\' # (escape character) regexp = re.sub(r'(?<!\\)%', '.*', regexp) # Set regexp to ignore cases; SQL patterns are case-insensitive by default. regexp = "(?i)^(" + regexp + ")$" return regexp
16589a99327885dc034fb33af1e69a42a453ccbd
7,573
import argparse def parse_arguments(solving_methods): """ Main CLI for interfacing with Monte Carlo Sudoku Solver. Arguments: solving_methods: tuple(str) Methods for solving sudoku puzzles. Returns: argparse.Namespace Argparse namespace containg CLI inputs. """ parser = argparse.ArgumentParser(description=("Write description here")) parser.add_argument("sudoku_fpath", type=str, help="Sudoku file to be solved.") parser.add_argument( "solving_method", type=str, help="Methods for solving sudoku: " + ", ".join(solving_methods), ) return parser.parse_args()
33c5419f4cd3944ee2fe39adbb2cd9776bb5a566
7,575
def make_enumeration(entries, divider=', '): """ :param entries: :param divider: :return: """ enumeration = { 'type': 'enumeration', 'entries': entries, 'divider': divider } return enumeration
0fee40bf69613944b57f2d1967ee0cdb87e7493b
7,576
def get_module_name(): """ モジュール名取得 Return: モジュール名 """ return __name__
45836eb290ff628baf9082829b9e95d9d4e45d78
7,578
def get_base_folder(image_file): """The base folder""" return '/'.join(image_file.split('/')[:-6])
14f212e80d57b71d2b379d2f5024c8f89ea438f3
7,579
import math def calc_distance(x1, y1, x2, y2): """ Calculate the distance between 2 point given the coordinates :param x1: Point 1 X coordinate :param y1: Point 1 Y coordinate :param x2: Point 2 X coordinate :param y2: Point 2 Y coordinate :return: Double. Distance between point 1 and point 2 """ dx = x2-x1 dy = y2-y1 distance = math.hypot(dx, dy) return distance
dd143ed5dd088c8a4d205c47363cd463798796d9
7,581
def uniform_pdf(x): """ Uniform Distribution(균등 분포) 확률 밀도 함수 """ return 1 if 0 <= x < 1 else 0
8aa049fc5ce2524edbfed892e4c0de1ce439ff58
7,583
def unit(value, unit, parenthesis=True): """Formats the numeric value of a unit into a string in a consistent way.""" formatted = f"{value:,g} {unit}" if parenthesis: formatted = f"({formatted})" return formatted
fe039ec681a16e4a317f1a500c29ab44615addd1
7,584
def normalize_val_list(val_list): """Returns a list of numeric values by the size of their maximum value.""" max_val = float(max(val_list)) return [ val/max_val if max_val != 0 else 0 for val in val_list ]
f594a6c281253bc181e436d1e1e3e1a83d07b56c
7,587
def sieve(iterable, indicator): """Split an iterable into two lists by a boolean indicator function. Unlike `partition()` in iters.py, this does not clone the iterable twice. Instead, it run the iterable once and return two lists. Args: iterable: iterable of finite items. This function will scan it until the end indicator: an executable function that takes an argument and returns a boolean Returns: A tuple (positive, negative), which each items are from the iterable and tested with the indicator function """ positive = [] negative = [] for item in iterable: (positive if indicator(item) else negative).append(item) return positive, negative
55f64a2aea55af05bd2139328157e3a877b8f339
7,589
import re def property_to_snake_case(property_type): """Converts a property type to a snake case name. Parameters ---------- property_type: type of PhysicalProperty of str The property type to convert. Returns ------- str The property type as a snake case string. """ if not isinstance(property_type, str): property_type = property_type.__name__ return re.sub(r"(?<!^)(?=[A-Z])", "_", property_type).lower()
fc0aa1c811a2de0bbd77f146a1816e8d7a31e08a
7,590
def read_binary(filepath): """return bytes read from filepath""" with open(filepath, "rb") as file: return file.read()
98587f79b5a2d8b8ff82909cb03957c0b3e2db7d
7,592
def sra_valid_accession(accession): """ Test whether a string is an SRA accession """ if accession.startswith('SRR') and len(accession) == 10: return True return False
3a4c5f40490f68490620ddacb430a0fcc8dfdd89
7,593
def alaska_transform(xy): """Transform Alaska's geographical placement so fits on US map""" x, y = xy return (0.3*x + 1000000, 0.3*y-1100000)
3f86caeee7b34295ce0680017dd70d6babea2a62
7,594
import requests import json def get_user_simple_list(access_token, dept_id): """ 获取部门用户信息 :return: { "errcode": 0, # 返回码 "errmsg": "ok", # 对返回码的文本描述内容 "hasMore": false, # 在分页查询时返回,代表是否还有下一页更多数据 "userlist": [ { "userid": "zhangsan", # 员工id "name": "张三" # 成员名称 } ] } """ url = 'https://oapi.dingtalk.com/user/simplelist?access_token={0}&department_id={1}'.format( access_token, dept_id ) r = requests.get(url) str_json = json.loads(r.text) return str_json
4fe63f8a8554015e02193005023181aa22ec23a5
7,595
def increase_by_1_list_comp(dummy_list): """ Increase the value by 1 using list comprehension Return ------ A new list containing the new values Parameters ---------- dummy_list: A list containing integers """ return [x+1 for x in dummy_list]
9ad24064a7cf808cba86523e5b84fe675c6c128b
7,597
import os def save_config(config, path): """ Write the configuration file to ``path``. """ os.umask(0o77) f = open(path, "w") try: return config.write(f) finally: f.close()
8174cc17b97664a6253d906618cf1a45896c08b9
7,599
import unicodedata def is_hw(unichr): """unichrが半角文字であればTrueを返す。""" return not unicodedata.east_asian_width(unichr) in ('F', 'W', 'A')
260d79199c8551b635fb343a72ffeb30e7707958
7,600
def deletedup(xs): """Delete duplicates in a playlist.""" result = [] for x in xs: if x not in result: result.append(x) return result
0f36899c9ce2710564d5d5938b54edbdd64afd81
7,602
from typing import Any def prettyStringRepr(s: Any, initialIndentationLevel=0, indentationString=" "): """ Creates a pretty string representation (using indentations) from the given object/string representation (as generated, for example, via ToStringMixin). An indentation level is added for every opening bracket. :param s: an object or object string representation :param initialIndentationLevel: the initial indentation level :param indentationString: the string which corresponds to a single indentation level :return: a reformatted version of the input string with added indentations and line break """ if type(s) != str: s = str(s) indent = initialIndentationLevel result = indentationString * indent i = 0 def nl(): nonlocal result result += "\n" + (indentationString * indent) def take(cnt=1): nonlocal result, i result += s[i:i+cnt] i += cnt def findMatching(j): start = j op = s[j] cl = {"[": "]", "(": ")", "'": "'"}[s[j]] isBracket = cl != s[j] stack = 0 while j < len(s): if s[j] == op and (isBracket or j == start): stack += 1 elif s[j] == cl: stack -= 1 if stack == 0: return j j += 1 return None brackets = "[(" quotes = "'" while i < len(s): isBracket = s[i] in brackets isQuote = s[i] in quotes if isBracket or isQuote: iMatch = findMatching(i) takeFullMatchWithoutBreak = False if iMatch is not None: k = iMatch + 1 takeFullMatchWithoutBreak = not isBracket or (k-i <= 60 and not("=" in s[i:k] and "," in s[i:k])) if takeFullMatchWithoutBreak: take(k-i) if not takeFullMatchWithoutBreak: take(1) indent += 1 nl() elif s[i] in "])": take(1) indent -= 1 elif s[i:i+2] == ", ": take(2) nl() else: take(1) return result
0c25810f5bd559a8dda09a2ec07bf6ea18956716
7,603
import os def replace_tail(path: str, search: str, replace: str) -> str: """ >>> replace_tail('/dir1/dir2/path.ext', '/dir1', '/dir2') 'dir2/dir2/path.ext' >>> replace_tail('/dir1/dir2/path.ext', '/dir1/', '/dir2/') 'dir2/dir2/path.ext' >>> replace_tail('/dir1/dir2/path.ext', '/dir3', '/dir2') '/dir1/dir2/path.ext' """ # Ensure the search path has a trailing slash search = os.path.join(search, "") # Ensure the search path has a trailing slash and no leading slash replace = os.path.join(replace, "") replace = replace[1:] if replace.startswith(os.path.sep) else replace return path.replace(search, replace, 1) if path.startswith(search) else path
cc9cc5d808a2befa1427543b3a1f3f71d48d4d87
7,604
def get_mapping(d): """ Reports fields and types of a dictionary recursively :param object: dictionary to search :type object:dict """ mapp=dict() for x in d: if type(d[x])==list: mapp[x]=str(type(d[x][0]).__name__) elif type(d[x])==dict: mapp[x]=get_mapping(d[x]) else: mapp[x]=str(type(d[x]).__name__) return mapp
87722f1429a93a934af08cb68519576cfc2cd7b0
7,606
def help(event): """Returns some documentation for a given command. Examples: !help help """ def prepare_doc(doc): return doc.split('\n')[0] plugin_manager = event.source_bot.plugin_manager prendex = 'Available commands: ' if len(event.args) < 1: return prendex + ', '.join(plugin_manager.cmd_docs.keys()) if len(event.args) > 1: return 'no...' cmd = event.args[0] doc = 'no...' if cmd in plugin_manager.cmd_docs: if plugin_manager.cmd_docs[cmd] is not None: doc = '{0}: {1}'.format(cmd, prepare_doc(plugin_manager.cmd_docs[cmd])) return doc
dbc2baed887df46e0d101d48a1a338760329679e
7,607
def remplace_mot_entre_parentheses(texte: str): """ Les mots entre parenthèse représente le petite texte dans Animal Crossing. Cela n'est pas prononcées. """ while '(' in texte and ')' in texte: debut = texte.index("(") fin = texte.index(")") texte = texte[:debut] + "*" * (fin-debut) + texte[fin+1:] return texte
30b2e86f56be6a4faee2f8c827c58d85ad62eb88
7,610
def knapsack(v, w, n, W): """ Function solves 0/1 Knapsack problem Function to calculate frequency of items to be added to knapsack to maximise value such that total weight is less than or equal to W :param v: set of values of n objects, :param w: set of weights of n objects, first element in v, w is useless relevant values start from index 1 :param n: number of items :pram W: maximum weight allowd by knapsack """ m = [[0 for j in range(W+1)] for i in range(n+1)] for j in range(W+1): m[0][j] = 0 for i in range(1, n+1): for j in range(W+1): if w[i] > j: m[i][j] = m[i-1][j] else: m[i][j] = max(m[i-1][j], m[i-1][j-w[i]]+v[i]) return m[n][W]
07537ab374f006a943a6ab19d90ee4cd580f9abf
7,611
def __normalize_request_parameters(post_body, query): """ Return a normalized string representing request parameters. This includes POST parameters as well as query string parameters. "oauth_signature" is not included. :param post_body: The body of an HTTP POST request. :type post_body: string :param query: The query string of the request. :type query: string :returns: The post body and query string merged into a single query string with the "oauth_signature" key removed. :rtype: string """ # Spaces can be encoded as + in HTTP POSTs, so normalize them. post_body = post_body.replace(b"+", b"%20") parts = post_body.split(b"&") if query: parts += query.split(b"&") # OAuth 1.0 §9.1.1. return b"&".join(entry for entry in sorted(parts) if entry.split(b"=")[0] != b"oauth_signature")
2cd7e72530a461629dd5034665c09dd240734313
7,612
import os def test_repo_dir(dir, name): """ Test an entered GitHub repository directory name. """ subdir = os.path.basename(dir) return subdir != name
b8fdbcb82e53fd1079b611617b3acf534af25fe5
7,613
import re def remove_punctuation(line): """ 去除所有半角全角符号,只留字母、数字、中文 :param line: :return: """ rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]") line = rule.sub('', line) return line
d63f355c5d48ec31db0412dd7b12474bf9d6dd6b
7,615
import time def CurrentTimeInSec(): """Returns current time in fractional seconds.""" return time.time()
3dc3bda89622ffdf0067d489c10f539cb6274e21
7,616
def euler2(f2p, b, t, h, p): """ tuple b = boundary condition (x0, y0, y'0) float h = step int t = number of steps lambda f2p = dy/dx int p = significant digits after x values """ x = b[0] y = b[1] yp = b[2] y2p = f2p(x, y, yp) ret = [(x, y)] #list of tuples to be returned with x and the associated y, y' and y" values for i in range(0, t): x = round(x + h, p) y = y + h * yp + h**2 * y2p / 2 yp = yp + h * y2p y2p = f2p(x, y, yp) ret.append((x,y)) return ret
67e390f0c21ba87d8aeec97920403c2d62678dc9
7,619
def parse_int(text: str) -> int: """ Takes in a number in string form and returns that string in integer form and handles zeroes represented as dashes """ text = text.strip() if text == '-': return 0 else: return int(text.replace(',', ''))
1f49a2d75c2fadc4796456640e9999796fddfa93
7,620
def _get_object_url_for_region(region, uri): """Internal function used to get the full URL to the passed PAR URI for the specified region. This has the format; https://objectstorage.{region}.oraclecloud.com/{uri} Args: region (str): Region for cloud service uri (str): URI for cloud service Returns: str: Full URL for use with cloud service """ server = "https://objectstorage.%s.oraclecloud.com" % region while uri.startswith("/"): uri = uri[1:] return "%s/%s" % (server, uri)
72b069e1657b94c7800ba7e5fd2269909e83c856
7,621
def sequence_delta(previous_sequence, next_sequence): """ Check the number of items between two sequence numbers. """ if previous_sequence is None: return 0 delta = next_sequence - (previous_sequence + 1) return delta & 0xFFFFFFFF
8580c26d583c0a816de2d3dfc470274f010c347f
7,623
def get_transitions(data_vals, threshold, hysteresis): """ Find the high-to-low and low-to-high state transistions """ pend_len, time_vals, sens_vals = data_vals # Get initial state if sens_vals[0] > threshold: state = 'high' else: state = 'low' # Find state changes high2low = [] low2high = [] for i in range(1,time_vals.shape[0]): if state == 'high': if sens_vals[i] < (threshold - 0.5*hysteresis): # This is a high to low transition state = 'low' # Find last point above threshold n = i-1 while sens_vals[n] < threshold: n -= 1 # Save crossing points pt_below = (time_vals[i], sens_vals[i]) pt_above = (time_vals[n], sens_vals[n]) high2low.append((pt_above, pt_below)) else: if sens_vals[i] > (threshold + 0.5*hysteresis): # This is a low to high transistion state = 'high' # Find last point below threshold n = i-1 while sens_vals[n] > threshold: n -= 1 # Save crossing points pt_above = (time_vals[i], sens_vals[i]) pt_below = (time_vals[n], sens_vals[n]) low2high.append((pt_below,pt_above)) return high2low, low2high
144a6463178820ef1cc6a6943cda5fe2e7117274
7,624
def single_number_generalized(nums, k, l): """ Given an array of integers, every element appears k times except for one. Find that single one which appears l times. We need a array x[i] with size k for saving the bits appears i times. For every input number a, generate the new counter by x[j] = (x[j-1] & a) | (x[j] & ~a). Except x[0] = (x[k] & a) | (x[0] & ~a). In the equation, the first part indicates the the carries from previous one. The second part indicates the bits not carried to next one. Then the algorithms run in O(kn) and the extra space O(k). :param nums: given array :type nums: list[int] :param k: times for every but one elements :type k: int :param l: times for single element :type l: int :return: single element :rtype: int """ if len(nums) == 0: return 0 x = [0] * k x[0] = ~0 for i in range(len(nums)): t = x[k - 1] for j in range(k - 1, 0, -1): x[j] = (x[j - 1] & nums[i]) | (x[j] & ~nums[i]) x[0] = (t & nums[i]) | (x[0] & ~nums[i]) return x[l]
90e28c2023622f23e808b89bb255d67aefe7bda8
7,626
import os def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "mnist": 900, } parts = fname.split("-") split = parts[1] shard_id = parts[2] task_id = int(shard_id) + shard_id_increment[split] return task_id
46586b0ca13793fadb199b197cb22ac8be180557
7,627
import re def find_matched_pos(str, pattern): """ Find all positions (start,end) of matched characters >>> find_matched_pos('ss12as34cdf', '\d') [(2, 3), (3, 4), (6, 7), (7, 8)] """ match_objs = re.finditer(pattern ,str) match_pos = [match_obj.span() for match_obj in match_objs] return match_pos
17e352299d7874bdfb66a4a181d04e90fba0af7e
7,628
def box_area(box): """ Calculates the area of a bounding box. Source code mainly taken from: https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ `box`: the bounding box to calculate the area for with the format ((x_min, x_max), (y_min, y_max)) return: the bounding box area """ return max(0, box[0][1] - box[0][0] + 1) * max(0, box[1][1] - box[1][0] + 1)
3a52a41e8dc92d3a3a2e85a33a4ebcbbb7131091
7,629
def dsigmoid(sigmoid_x): """ dSigmoid(x) = Sigmoid(x) * (1-Sigmoid(x)) = Sigmoid(x) - Sigmoid(x)^2 """ return sigmoid_x - sigmoid_x**2
37e163e6baab1a2b584e9eef726895c919c80406
7,630
def progress_bar(iteration, total): """ entertain the user with a simple yet exquisitely designed progress bar and % :param iteration: :param total: :return: """ try: perc = round((iteration/total)*100, 2) bar = ('░'*19).replace('░','█',int(round(perc/5,0))) + '░' return str("{:.2f}".format(perc)).zfill(6) + '% [' + bar + ']' except ZeroDivisionError: # this happens in never versions of python. return nothing return ''
a32bd5edd108142583f0ea1573848c91c6d61c33
7,631
def par_auteur(name): """ Add 'par' to the author names """ author_phrase = '' if name: author_phrase = " par {},".format(name) return author_phrase
a09bbc79cb152239bc178d74ebd11cc0f74c1d30
7,632
from typing import Dict from typing import List def remove_items(item_capacities:Dict[str,int], items_to_remove:List[str])->Dict[str,int]: """ Remove the given items from the given dict. >>> stringify(remove_items({"x":3, "y":2, "z":1, "w":0}, ["x","y"])) '{x:2, y:1, z:1}' >>> stringify(remove_items({"x":3, "y":2, "z":1, "w":0}, ["y","z"])) '{x:3, y:1}' """ for item in items_to_remove: item_capacities[item] -= 1 return {item:new_capacity for item,new_capacity in item_capacities.items() if new_capacity > 0}
c17b972050b4054121fffd478dd3252f90959b8a
7,633
import os def load_environment_auth_vars() -> tuple: """Attempts to load authentication information from environment variables if none is given, looks for a username under "FHIR_USER", password under "FHIR_PW" and the token under "FHIR_TOKEN" Returns: Tuple containing username, password and token if they were found or None if they are not present in the env vars """ username = os.getenv("FHIR_USER", None) password = os.getenv("FHIR_PW", None) token = os.getenv("FHIR_TOKEN", None) return username, password, token
b3f629524f1f74bb7b3c44ec0c2d8b2cff2ff3a5
7,634
def get_min_freeboard(fjord): """ Get a required minimum median freeboard for filtering out icebergs """ minfree = {"JI": 15, "KB":5} try: return minfree.pop(fjord) except KeyError: print("The current fjord does not have a minimum freeboard median entry - using a default value!") return 10
b80fec4224dcf8ce0d24a19ca28e88e66db52150
7,636
from typing import Optional from typing import Callable import functools import click def server_add_and_update_opts(f: Optional[Callable] = None, *, add=False): """ shared collection of options for `globus transfer endpoint server add` and `globus transfer endpoint server update`. Accepts a toggle to know if it's being used as `add` or `update`. usage: >>> @server_add_and_update_opts >>> def command_func(subject, port, scheme, hostname): >>> ... or >>> @server_add_and_update_opts(add=True) >>> def command_func(subject, port, scheme, hostname): >>> ... """ if f is None: return functools.partial(server_add_and_update_opts, add=add) def port_range_callback(ctx, param, value): if not value: return None value = value.lower().strip() if value == "unspecified": return None, None if value == "unrestricted": return 1024, 65535 try: lower, upper = map(int, value.split("-")) except ValueError: # too many/few values from split or non-integer(s) raise click.BadParameter( "must specify as 'unspecified', " "'unrestricted', or as range separated " "by a hyphen (e.g. '50000-51000')" ) if not 1024 <= lower <= 65535 or not 1024 <= upper <= 65535: raise click.BadParameter("must be within the 1024-65535 range") return (lower, upper) if lower <= upper else (upper, lower) if add: f = click.argument("HOSTNAME")(f) else: f = click.option("--hostname", help="Server Hostname.")(f) default_scheme = "gsiftp" if add else None f = click.option( "--scheme", help="Scheme for the Server.", type=click.Choice(("gsiftp", "ftp"), case_sensitive=False), default=default_scheme, show_default=add, )(f) default_port = 2811 if add else None f = click.option( "--port", help="Port for Globus control channel connections.", type=int, default=default_port, show_default=add, )(f) f = click.option( "--subject", help=( "Subject of the X509 Certificate of the server. When " "unspecified, the CN must match the server hostname." ), )(f) for adjective, our_preposition, their_preposition in [ ("incoming", "to", "from"), ("outgoing", "from", "to"), ]: f = click.option( f"--{adjective}-data-ports", callback=port_range_callback, help="Indicate to firewall administrators at other sites how to " "allow {} traffic {} this server {} their own. Specify as " "either 'unspecified', 'unrestricted', or as range of " "ports separated by a hyphen (e.g. '50000-51000') within " "the 1024-65535 range.".format( adjective, our_preposition, their_preposition ), )(f) return f
bc2427a7a0996528dc1411186c51b11c7b4db339
7,637
def build_tag_regex(plugin_dict): """Given a plugin dict (probably from tagplugins) build an 'or' regex group. Something like: (?:latex|ref) """ func_name_list = [] for func_tuple in plugin_dict: for func_name in func_tuple: func_name_list.append(func_name) regex = '|'.join(func_name_list) return '(?:' + regex + ')'
367b95067cabd4dcdfd8981f6a14b650da3601c5
7,638
def is_html_like(text): """ Checks whether text is html or not :param text: string :return: bool """ if isinstance(text, str): text = text.strip() if text.startswith("<"): return True return False return False
a499e14c243fcd9485f3925b68a0cef75fa069cb
7,639
def relu_prime(x): """ ReLU derivative. """ return (0 <= x)
8908af6f6748291477e3379443fe7714fed289ad
7,641
import importlib def import_optional_dependency(name, message): """ Import an optional dependecy. Parameters ---------- name : str The module name. message : str Additional text to include in the ImportError message. Returns ------- module : ModuleType The imported module. """ try: return importlib.import_module(name) except ImportError: raise ImportError( f"Missing optional dependency '{name}'. {message} " + f"Use pip or conda to install {name}." ) from None
22d638e86b8d979b746507790532273d161323c8
7,642
def curate_url(url): """ Put the url into a somewhat standard manner. Removes ".txt" extension that sometimes has, special characters and http:// Args: url: String with the url to curate Returns: curated_url """ curated_url = url curated_url = curated_url.replace(".txt", "") curated_url = curated_url.replace("\r", "") # remove \r and \n curated_url = curated_url.replace("\n", "") # remove \r and \n curated_url = curated_url.replace("_", ".") # remove "http://" and "/" (probably at the end of the url) curated_url = curated_url.replace("http://", "") curated_url = curated_url.replace("www.", "") curated_url = curated_url.replace("/", "") return curated_url
42ea836e84dfb2329dd35f6874b73ac18bde48d1
7,643
import requests def get_news(): """ Returns two dictionnary object containing news articles informations. The first one is a short version, with little informations and the second one contains all the informations. """ API_KEY = 'd913f4f1287a42819abc66f428e0fad4' sources = 'bloomberg'+ ',' + 'the-wall-street-journal' + ',' + 'les-echos' + ',' + 'business-insider' all_news = [] short_news = [] try: request_result = requests.request("GET", "https://newsapi.org/v2/" +"top-headlines?sources="+sources +"&sortBy=top&apiKey="+API_KEY) all_news = request_result.json()['articles'] all_news = sorted(all_news, key=lambda k: k['publishedAt'], reverse=True) for article in all_news: short_news.append({'source':article['source']['name'], 'title':article['title']}) return short_news, all_news except: print('Error while loading the sources') return None, None
4145ddfd669c54f8bfe285ccde67b7a08b724a85
7,644
def get_enzyme_train_set(traindata): """[获取酶训练的数据集] Args: traindata ([DataFrame]): [description] Returns: [DataFrame]: [trianX, trainY] """ train_X = traindata.iloc[:,7:] train_Y = traindata['isemzyme'].astype('int') return train_X, train_Y
8a3f6e29aca5737396c0e4007c5ff512592e51b9
7,646
def patch_utils_path(endpoint: str) -> str: """Returns the utils module to be patched for the given endpoint""" return f"bluebird.api.resources.{endpoint}.utils"
31ae02bd0bee7c51ea5780d297427fdac63295b3
7,647
def rgbToGray(r, g, b): """ Converts RGB to GrayScale using luminosity method :param r: red value (from 0.0 to 1.0) :param g: green value (from 0.0 to 1.0) :param b: blue value (from 0.0 to 1.0) :return GreyScale value (from 0.0 to 1.0) """ g = 0.21*r + 0.72*g + 0.07*b return g
59a874d1458ae35e196e1ca0874b16eadfd1a434
7,650
def choose_reads(hole, rng, n, predicate): """Select reads from the hole metadata.""" reads = [] required_reads = set(v for v in hole.metadata.required_reads if predicate(v)) allowed_reads = set(v for v in hole.metadata.allowed_reads if predicate(v)) while len(reads) < n and (required_reads or allowed_reads): if required_reads: read = rng.choice(list(required_reads)) reads.append(read) required_reads = required_reads - {read} allowed_reads = allowed_reads - {read} else: read = rng.choice(list(allowed_reads)) reads.append(read) required_reads = required_reads - {read} allowed_reads = allowed_reads - {read} return reads
cae99bcd36b6d7169da0682a5f54d168538766d5
7,651
def maximum(x, y): """Returns the larger one between real number x and y.""" return x if x > y else y
e98a4e720936a0bb271ee47c389811111fd65b00
7,652
def is_acceptable_multiplier(m): """A 61-bit integer is acceptable if it isn't 0 mod 2**61 - 1. """ return 1 < m < (2 ** 61 - 1)
d099dd53296138b94ca5c1d54df39b9cf7ad2b5d
7,653
def extractRSS_VSIZE(line1, line2, record_number): """ >>> extractRSS_VSIZE("%MSG-w MemoryCheck: PostModule 19-Jun-2009 13:06:08 CEST Run: 1 Event: 1", \ "MemoryCheck: event : VSIZE 923.07 0 RSS 760.25 0") (('1', '760.25'), ('1', '923.07')) """ if ("Run" in line1) and ("Event" in line1): # the first line event_number = line1.split('Event:')[1].strip() else: return False """ it's first or second MemoryCheck line """ if ("VSIZE" in line2) and ("RSS" in line2): # the second line RSS = line2.split("RSS")[1].strip().split(" ")[0].strip() #changed partition into split for backward compatability with py2.3 VSIZE = line2.split("RSS")[0].strip().split("VSIZE")[1].strip().split(" ")[0].strip() #Hack to return the record number instea of event number for now... can always switch back of add event number on top #return ((event_number, RSS), (event_number, VSIZE)) return ((record_number, RSS), (record_number, VSIZE)) else: return False
89c14bbb3a2238ec9570daf54248b4bd913eecca
7,654
import pkg_resources def show_template_list(): """Show available HTML templates.""" filenames = pkg_resources.resource_listdir(__name__, "data") filenames = [f for f in filenames if f.endswith(".html")] if not filenames: print("No templates") else: for f in filenames: print(f) return True
f86d5ec772127be6183bfe14ebda324a05e43cd3
7,655
import hashlib def ripemd160(msg): """one-line rmd160(msg) -> bytes""" return hashlib.new('ripemd160', msg).digest()
a8484404fc3418fcca20bebfd66f36c3a33c9be3
7,656
from typing import Optional import re def extraer_numero_iniciativa(numero_evento: str) -> Optional[int]: """Algunos numeros de evento traen la iniciativa a la que pertenecen, esta función intenta extraer el ID Returns ------- int or None ID de iniciative o None si no existe un numero con las caracteristicas buscadas """ tokens = re.split(r"\W+|_", numero_evento) iniciativa = None for token in tokens: if len(token) == 5 and token.isnumeric(): iniciativa = int(token) return iniciativa return iniciativa
3c1abffca75a66bfad5c9556a194b904b39422c0
7,657