content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _page_to_title(page): """Extract the title from a page. Args: page: a unicode string Returns: a unicode string """ # print("page=%s" % page) start_tag = u"<title>" end_tag = u"</title>" start_pos = page.find(start_tag) end_pos = page.find(end_tag) assert start_pos != -1 assert end_pos != -1 start_pos += len(start_tag) return page[start_pos:end_pos]
ce480f619f9e10c52dc5d4c03f156038919bf168
143,498
def _GetNestedKeyFromManifest(manifest, *keys): """Get the value of a key path from a dict. Args: manifest: the dict representation of a manifest *keys: an ordered list of items in the nested key Returns: The value of the nested key in the manifest. None, if the nested key does not exist. """ for key in keys: if not isinstance(manifest, dict): return None try: manifest = manifest[key] except KeyError: return None return manifest
25f4e342503d7d5667cc74e31a67941804021239
127,468
def shift_sensitive_region(record: dict, original_name: str, new_name: str): """ Function to demote sensitive country names to `area_covered` from `country_territory_area`. Parameters ---------- record : dict Input record. original_name : str Original country name from provider dataset. new_name : str New WHO-recognised country name. Returns ------- type Record with sensitive countries changed. """ if record['country_territory_area'] == original_name: record['area_covered'] = record['country_territory_area'] record['country_territory_area'] = new_name return(record)
b83c15dc4ebb0102fbf69085ee5aa90667fb2087
537,065
def read_file(filename): """Read a file or return the empty string if there is some error.""" try: return open(filename, 'r').read() except IOError: return ''
7da98fed1b29ee40ce66392f0137f134f1571a81
405,727
def int_to_bytes(x, length): """Converts bigendian integer to byte array with fixed length.""" res = bytearray(length) for i in range(length): res[length - i - 1] = int(x) % 256 x = int(x) // 256 return res
f8cfceca1c51483115c7d2d877b9d4a6c7c5fef9
49,117
def format_time_delta(s): """ Formats seconds to a better representation of delta time """ hours, remainder = divmod(s, 3600) minutes, seconds = divmod(remainder, 60) ht = '{}h'.format(hours) if hours else '' mt = '{}m'.format(minutes) if minutes else '' st = '{}s'.format(seconds) if seconds else '' return '{} {} {}'.format(ht, mt, st)
230dd247599911a93036fe5f5d46485721c47c03
475,312
import shutil def which_all(path_programs): """confirm all programs in iterable path_programs are in the path. Returns list of missing program error messages.""" missing_programs = [] for program in path_programs: if not shutil.which(program): missing_programs.append("%s was not found in PATH." % program) return missing_programs
edf2238e60dc3fde08b21b6de90b46ffd556a28b
365,018
def parse_from_exif_str(temp_str): """String to float parser.""" # we assume degrees celsius for temperature, metres for length if isinstance(temp_str, str): return float(temp_str.split()[0]) return float(temp_str)
47d7159ce140e004157e0ad5a5287529b9c2d545
532,451
def redirect(path): """ Redirect requests. :param str path: Rejection status code :return dict: Redirection response """ res = { 'statusCode': 301, 'headers': { 'Location': path, }, } return res
926cadb6bbf07c88e9efb3305c327007488803a1
482,004
def sort_by_index_key(x): """ Used as key in sorted() to order items of a dictionary by the @index entries in its child-dicts if present. """ if isinstance(x[1], dict) and '@index' in x[1]: return x[1]['@index'] else: return -1
66e828b61119723b5cf6e556de8b572a800de38a
621,282
def tokenize(text: str) -> set[str]: """Lowercase text and split into a set of tokens. Parameters ---------- text : str Text to tokenize. Returns ------- set[str] Set of lowercase tokens. """ return set(text.lower().split())
0c05348dbe80b0d0b678669d9174d01569b0f8c0
451,184
def pyg_edge_index_to_tuples(edge_index): """ Convert edge_index to a list of (source, target) tuples. Args: edge_index (torch.long): Edge COO with shape [2, num_edges]. Return: edge_tuples (list of tuple): Edge tuples. """ edge_tuples = [ (edge_index[0, i].item(), edge_index[1, i].item()) \ for i in range(edge_index.shape[1]) ] return edge_tuples
b550d6c6db7f8f147e0a2e2cea90540ca05740c7
493,934
def mapf(f): """ Turns a function `f` into a function over lists, applying `f` to each element of the list. Arguments --------- f : function The function. Returns ------- g : function Function that applies `f` over each element of a list. Examples -------- Define a function `f`: >>> f = lambda x: x + 1 We apply it over a list in the following way: >>> mapf(f)([1, 2, 3]) [2, 3, 4] """ return lambda x: map(f, x)
e3403ee1f3f92df8816e2562e50c5a1b11b1f1ae
260,760
import pickle import base64 def text_pickle(obj) -> str: """Pickles object into character string""" pickle_string = pickle.dumps(obj) pickle_string_encoded: bytes = base64.b64encode(pickle_string) s = pickle_string_encoded.decode('ascii') return s
824bd09e2ba0a442719852a831978d1bf98768bd
439,330
from typing import List import itertools def parse(data: List[str], delimiter: str = "") -> List[str]: """ Parses the raw data into grouped lists :param data: The raw loaded dataset :param delimiter: Delimiting char :return: Grouped entries """ groupby = itertools.groupby(data, lambda z: z == delimiter) grouped_data = [list(y) for x, y in groupby if not x] return [" ".join(group) for group in grouped_data]
7bd271bbf7f700853448bdf8fb6f97a031290215
518,065
def _process_preamble(latex_string): """Detect Latex Preamble Arguments: latex_string {string} -- Latex Source Returns: tupple -- preamble, content """ if r"\begin{document}" in latex_string: preamble, content = latex_string.split(r"\begin{document}") if r"\end{document}" in content: content = content.split(r"\end{document}")[0] else: preamble = "\\documentclass{article}\n" content = latex_string return preamble, content
c076336deb8a8d3332993de6af97e1f18eebeb0e
415,313
def RiemannSphere(z): """Map the complex plane to Riemann's sphere via stereographic projection. """ t = 1 + z.real*z.real + z.imag*z.imag return 2*z.real/t, 2*z.imag/t, 2/t-1
1182997a96200410fefa53a1ce214a5987812df2
487,153
def distance(strand_a, strand_b): """ Compare two strings and count the differences. :param strand_a string - String representing a strand of DNA. :param strand_b string - String representing a different strand of DNA. :return int - number of differences between 2 strands. """ if len(strand_a) != len(strand_b): raise ValueError("The Hamming distance is only defined for sequences of equal length, " " so an attempt to calculate it between sequences of different lengths should not work.") dna_compared = zip(strand_a, strand_b) num_differences = 0 for sequence in dna_compared: if sequence[0] != sequence[1]: num_differences += 1 return num_differences
012e0b1640e738b17dc6a4fb4a01c1f53e0e7639
701,896
def check_stats_record_format(record): """check that the aggregation buckets have the expected format""" assert {'key', 'doc_count', 'size'} == set(record.keys()) assert set(record['size'].keys()) == {'value'} assert isinstance(record['key'], str) assert isinstance(record['doc_count'], int) assert isinstance(record['size']['value'], float) return True
8ed3a90f8af6f2380a6e3d8ccf986b738ff8befe
609,904
import math import logging from typing import Collection def many_collections(mixer, user, app, request): """Create a number of collections numbering around the page size for the fixture user.""" n_collections = int(math.ceil(request.param * app.config['PAGE_SIZE'])) assert n_collections >= 0 logging.info('Creating %s collection(s) for user', n_collections) cs = mixer.cycle(n_collections).blend(Collection, name=mixer.FAKE) for c in cs: c.add_all_permissions(user) return cs
8dee1b5638d0c48f9cf507674b4f1abc52001d0d
550,971
def _digit_to_hex(string_of_digit): """Convert string of digits to string of hex.""" return "".join( [ hex(int(i))[2:] for i in [ string_of_digit[i : i + 2] for i in range(0, len(string_of_digit), 2) ] ] )
7d62a53fc1009da2e33ac3198036e304a3e699bd
578,493
def get_hostname(results): """Get Hostname Args: results (Element): XML results from firewall Returns: hostname (str): A string containing the hostname """ hostname = results.find('./result/system/hostname').text return hostname
8cb576f1a13d1f5afe465333ce6b7a3c6fdd3b09
67,414
from pathlib import Path def is_source_file(file_path: str, extensions: list) -> bool: """ Check if given path represents source file (based by extensions provided by user). :param file_path: file path to check. :param extensions: list of possible extensions for source files. :return: true, if given path is source file, otherwise returns false. """ path = Path(file_path) return path.is_file() and path.suffix[1:] in extensions and len(path.suffixes) == 1
9e31b17bcb302514c5c3ff33591dcf88ede03641
266,446
def parse_scen_file(scen_file, n_agents): """Return the agent start locations and the goal locations. Args: scen_file (str): path to the scenario file. n_agents (int): number of agents to read from the scenario (might contain a lot of agents - the more the harder) Returns: tuple. two lists - one of start locations and one of goal locations (each locations is a tuple of x,y). """ starts = [] goals = [] with open(scen_file, 'r') as f: lines = iter(f) next(lines) for i, line in enumerate(lines): _, _, _, _, x_start, y_start, x_goal, y_goal, _ = line.split('\t') starts.append((int(x_start), int(y_start))) goals.append((int(x_goal), int(y_goal))) if i == n_agents - 1: break return tuple(starts), tuple(goals)
4cca6edf40f3463c120b0d1db878c865a505c63e
124,762
from typing import List def _product_no_duplicate(*args) -> List[List]: """ product_no_duplicate('ABCDx', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy xy ** Note that xx is not included ** Similar to itertools.product except for results with duplicates are excluded """ pools = [tuple(pool) for pool in args] result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool if y not in x] return result
4c8c5b1bdc2df409b5218b510996212773df4a34
264,590
from typing import Union def int_or_id(x: str) -> Union[int, str]: """ Convert a string to int if possible Args: x: input string Returns: Union[int, str]: int represented by x, or x itself if parsing fails """ try: return int(x) except ValueError: return x
69d23608b1ea8c220f206496fc6ca88ec8dd88a7
259,047
def euler(faces, edges, verticies): """ Calculate the value of Euler's formula of a shape. :type faces: integer :param faces: The faces of the shape :type edges: integer :param edges: The edges of the shape :type verticies: integer :param verticies: The verticies of the shape :return: The result of the euler operation :rtype: number """ # Return the calculated value return verticies + edges - faces
b3ac078360418f7c413e3351f10bad8635d6d2bf
353,639
def make_rule_key(prefix, rule, group_id, cidr_ip): """Creates a unique key for an individual group rule""" if isinstance(rule, dict): proto, from_port, to_port = [rule.get(x, None) for x in ('proto', 'from_port', 'to_port')] else: # isinstance boto.ec2.securitygroup.IPPermissions proto, from_port, to_port = [getattr(rule, x, None) for x in ('ip_protocol', 'from_port', 'to_port')] key = "%s-%s-%s-%s-%s-%s" % (prefix, proto, from_port, to_port, group_id, cidr_ip) return key.lower().replace('-none', '-None')
8d7d440b802ac4f34e5531c0680d3183795a4f73
594,482
def get_time_slot(hour, minute): """ Computes time_slot id for given hour and minute. Time slot is corresponding to 15 minutes time slots in reservation table on Sutka pool web page (https://www.sutka.eu/en/obsazenost-bazenu). time_slot = 0 is time from 6:00 to 6:15, time_slot = 59 is time from 20:45 to 21:00. :param hour: hour of the day in 24 hour format :param minute: minute of the hour :return: time slot for line usage """ slot_id = (hour - 6)*4 + int(minute/15) return slot_id
dbfc510755a0b0a9612c0aa7d94922199c3f7f7d
29,576
import glob def get_file_names(path, file_type): """ Get a list of files with given file_type in path's directory and its subdirectories If the directory is large, this might take forever, so use with care """ path_pattern = path + "**/*." + file_type files = glob.glob(path_pattern, recursive=True) return files
82adc3eea2cd67d88bd973f7f3c9bf879931728f
524,913
def get_max_seq_length(samples): """helper function to get the maximum seq length for padding preparation""" seq_lengths = [] for seq in samples: seq_lengths.append(len(seq[0])) return max(seq_lengths)
2afa71bfda9d8bace59ecab0e337bbce14eed0d6
154,565
def validate_page_title_minimum_length(page, parent): """ Ensure the page title is at least 10 characters long """ return page.title and len(page.title) >= 10
f3276093dd3edcd8296be557e0fa2d8ad33e4baf
576,799
def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) return print(word)
4270656cb9afa5987ed1bed30a6964725ac40131
291,157
def closest_edges(edge_list, threshold): """Threshold the edge_list considering only the similarity. Parameters ---------- edge_list : list List of the graph edges. It's a list of dicts. i.e [{'nodes': (i1, j2), 'similarity': matrix[i1][j2]}, ...] Returns ------- list List of the graph edges. It's a list of dicts. i.e [{'nodes': (i1, j2), 'similarity': matrix[i1][j2]}, ...] """ # the threshold determines whether two nodes are connected return [edge for edge in edge_list if edge['similarity'] > threshold]
c048734dfef46c796f6721d142efc3b413c79bbe
161,595
def get_resource_id(event): """ Returns the CFN Resource ID with format <cluster_name>_aws-auth. :param event: the CFN event :return: the CFN resource id """ cluster_name = event["ResourceProperties"]['ClusterName'] resource_id = cluster_name + "_aws-auth" return resource_id
e0d5c2e0bd14e5aa78c925814e039437ecfea788
106,240
def sum_of_divisors_v1(n): """Naive version: Find the sum of all divisors of a given integer.""" sum_div = 0 for i in range(1, n+1): # check if n is divisible by current number from 1 to n inclusive if n % i == 0: sum_div += i return sum_div
6bcebc110d07c5696e4cae86c96f601c9fa49436
130,694
def _build_arguments(keyword_args): """ Builds a dictionary of function arguments appropriate to the index to be computed. :param dict keyword_args: :return: dictionary of arguments keyed with names expected by the corresponding index computation function """ function_arguments = { "data_start_year": keyword_args["data_start_year"], "scale": keyword_args["scale"], "distribution": keyword_args["distribution"], "calibration_year_initial": keyword_args["calibration_start_year"], "calibration_year_final": keyword_args["calibration_end_year"], "periodicity": keyword_args["periodicity"], } return function_arguments
7d0d21a953b36d19d537512a4f2e92e4ec73ad1e
255,503
def sum_multiples(limit): """Sums all multiples of 3 and 5 under `limit` Args: limit (int): The limit that the sums will be calculated up to Returns: int : The sum of all multiples of 3 and 5 up to `limit` """ return sum(x for x in range(limit) if x % 3 == 0 or x % 5 == 0)
5dfe9b98e660bf97841e3b2b5c7e8e24972f2f20
658,724
def is_valid_int(val): """ Checks if given value is int """ if val and not isinstance(val, int): return False return True
0ec27bac3593da04de584dca749ed449410ea535
595,220
from typing import List def get_cum_elevation_gain(elevations: List[float]) -> float: """ Function that given the ordered sequence of elevation measurements during an activity, returns the total elevation gain. Args: elevations: List of elevation measurements. Returns: Cumulative elevation gain. """ gain = 0 # 0 gain if elevations empty if not elevations: return 0 last_elevation = elevations[0] del elevations[0] for elevation in elevations: # signed increase within the last change delta = elevation - last_elevation # only add uphill change gain += max(delta, 0) # update last_elevation to current elevation last_elevation = elevation return gain
2ba80253aebf83f817bf2c3721207c0fd93a1972
313,767
def map_inputs(building_name, inputs, mapping): """ Maps inputs from OPC server to EnergyPlus Inputs: building_name- The name of the building inputs- [(name, value, status, timestamp)] from opc Outputs: [value]- List of values, in the order specified by E+ """ input_tags = mapping[building_name]["Inputs"] ret = [] for tag in input_tags: matching_input = [t for t in inputs if t[0] == tag] ret.append(matching_input[0][1]) return ret
39adcd1ce46383af1f565ed5f9d3c6f1bf43e09c
479,190
import codecs import json def testing_read_json(fp): """Reads a UTF-8 JSON from filepath.""" with codecs.open(fp, 'r', encoding='utf-8') as f: return json.load(f)
fd453d2affdbd83f98864baa2e75459197e72d9e
357,379
def make_iterable(obj): """Check if obj is iterable, if not return an iterable with obj inside it. Otherwise just return obj. obj - any type Return an iterable """ try: iter(obj) except: return [obj] else: return obj
b95dfa37536844f3c751467126adebf39d986dc2
362,144
def is_english_word_alpha(word: str) -> bool: """Returns True when `word` is an English word. False otherwise. Args: word: Any given word Examples: >>> is_english_word_alpha("English") True >>> is_english_word_alpha("영원한") False >>> is_english_word_alpha("domestic") True >>> is_english_word_alpha("漢字") False >>> is_english_word_alpha("ひらがな") False """ return word.upper() != word.lower()
d6c4a3322e828ebbc6a30b6585ff6913616ec2ba
627,181
def get_header_with_access_token(access_token): """ Returns the header with the user access token. :param access_token: access token :type access_token: str :return: request header :rtype: dict """ return {"Authorization": f"Bearer {access_token}"}
edee80729a51c5427cd3a02e022b343f452f1895
271,785
import typing def parse_apis(apis_string: str) -> typing.List[str]: """ Parse the `Relevant API` section and get a list of APIs. :param apis_string: A string containing all APIs. :return: A sorted list of stripped API names. """ apis = list(filter(bool, apis_string.splitlines())) if not apis: raise Exception('README Relevant API parse failure!') return sorted([api.lstrip('*- ').rstrip() for api in apis])
4c9da876a08b010c5d44a051085eea20dcda8cdb
178,342
def get_rm(g): """Return membrane resistivity in Ohm*m^2 g -- membrane conductivity in S/m^2 """ return 1/g
803d4f05e702776053640280e25ca6656790cdc9
688,237
def import_profile(database, species, loci_list): """Import all possible allele profiles with corresponding st's for the species into a dict. The profiles are stored in a dict of dicts, to easily look up what st types are accosiated with a specific allele number of each loci. """ # Open allele profile file from database profile_file = open("{0}/{1}/{1}.tsv".format(database, species), "r") profile_header = profile_file.readline().strip().split("\t")[1:len(loci_list)+1] # Create dict for looking up st-types with locus/allele combinations st_profiles = {} # For each locus initate make an inner dict to store allele and st's for locus in loci_list: st_profiles[locus] = {} # Fill inner dict with allele no as key and st-types seen with the allele as value for line in profile_file: profile = line.strip().split("\t") st_name = profile[0] allele_list = profile[1:len(loci_list)+1] # Go through all allele profiles. Save locus-allele combination with the st-type for i in range(len(allele_list)): allele = allele_list[i] locus = profile_header[i] if allele in st_profiles[locus]: st_profiles[locus][allele] += [st_name] else: st_profiles[locus][allele] = [st_name] profile_file.close() return st_profiles
552ba8d3190fd06c9e35c08f19784bf9b1e485df
619,443
def tag(test): """ Decorator for tests, so that you can specify you only want to run a tagged subset of tests, with the -1 or --tagged option. """ test._tagged = True return test
01fb2e552c69c8fba79aa9637af216fda5e227e8
546,603
def startup_cost_simple_rule(mod, g, tmp): """ Startup costs are applied in each timepoint based on the amount of capacity (in MW) that is started up in that timepoint and the startup cost parameter. """ return mod.GenCommitCap_Startup_MW[g, tmp] \ * mod.startup_cost_per_mw[g]
249b06c5a5a212e90ba37ba14d70d22366d133e4
266,169
def form_for_field(config, field): """ Gets the form name which contains the field that is passed in """ for form in config['forms']: if field in form['csv_fields'].values(): return form['form_name']
d960154bbf473a2e8a730fd74fd70c3896620df0
41,994
from pathlib import Path def convert_to_store_path(nifti_file: str) -> Path: """Provide the Zarr store Path for a Nifti path.""" store_path = Path(nifti_file + '.zarr') return store_path
893f1e1ed4c504cd2c7a62b707f20ac72dd622a0
237,777
def metrics_from_mdl(mdl): """ Return a set() representing the metrics in the given MDL JSON object. Each entry is a tuple of either: ('entity', entity_name, metric_name) or ('role', role_name, metric_name) """ metrics = set() for entity_def in mdl['metricEntityTypeDefinitions']: for metric_def in entity_def['metricDefinitions']: metrics.add(('entity', entity_def['name'], metric_def['name'])) for role_def in mdl['roles']: for metric_def in role_def['metricDefinitions']: metrics.add(('role', role_def['name'], metric_def['name'])) return metrics
515c80755053fbbdd553e2350da0703b02072f8b
370,291
import random import string def generate_random_value(value_type: str, seed=None): """Given a name of a type, return random data in that type The value_type is the name of the type as a string. The type will will be checked and the appropriate value will be generated. The seed is optional but will be used to set the random seed for tests. """ if seed is not None: random.seed(seed) if value_type == "str": value = "" # Get the maximum length that the ascii_letters has for use to index it later max_length = len(string.ascii_letters) - 1 # Repeat for a random amount of characters in a reasonable range for character in range(random.randint(10, 30)): # Also adds the seed if its defined, the random seed resets after use # this sets up the seed for each iteration if seed is not None: random.seed(seed) # Get a random character from string.ascii_letters (a string of all ascii letters) and # add the char to the value, the final string value += string.ascii_letters[random.randint(0, max_length)] return value elif value_type == "int": return random.randint(0, 100) elif value_type == "float": return round(random.uniform(0, 100), 4) elif value_type == "bool": # Cast randint to bool return bool(random.randint(0, 1))
86b02434c74cd6fa31be20de8f3b2b8bad6162da
360,910
def is_palindrome(string): """ Checks if string is a palindrome """ return(string == string[::-1])
f0690233e9cf8fe7853bc0e9f13cd5b50e8796cd
536,704
def _node_value(G, node_attr): """Returns a function that returns a value from G.nodes[u]. We return a function expecting a node as its sole argument. Then, in the simplest scenario, the returned function will return G.nodes[u][node_attr]. However, we also handle the case when `node_attr` is None or when it is a function itself. Parameters ---------- G : graph A NetworkX graph node_attr : {None, str, callable} Specification of how the value of the node attribute should be obtained from the node attribute dictionary. Returns ------- value : function A function expecting a node as its sole argument. The function will returns a value from G.nodes[u] that depends on `edge_attr`. """ if node_attr is None: def value(u): return u elif not hasattr(node_attr, '__call__'): # assume it is a key for the node attribute dictionary def value(u): return G.nodes[u][node_attr] else: # Advanced: Allow users to specify something else. # # For example, # node_attr = lambda u: G.nodes[u].get('size', .5) * 3 # value = node_attr return value
6a8b061000c01686e6ead30df70bbec0f0e0957c
573,378
def data_denormalization(mean, std, data): """ Data denormalization using train set mean and std """ data[:, :, 1:] *= std data[:, :, 1:] += mean return data
6243227405163bdd2a0b7fe369ff37bdb5a916d2
219,650
from typing import List def clean_tail_empty_strings(data: List[str]) -> List[str]: """Removes empty strings from the provided data""" while data[-1] in ["", "\r"]: data.pop() return data
2f4d3caed86f93c226be4ba491c65eb60fa8efb6
374,527
def kth_element(list_a: list, k: int): """Problem 3: Find the K'th Element of a List Parameters ---------- list_a : list The input list k : int The element to fetch Returns ------- element The k'th element of the input list Raises ------ TypeError If the given argument is not of `list` type ValueError If the input list contains less than two elements, or the given k is less than 1 """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') if len(list_a) < k: raise ValueError(f'The input list contains less than [{k}] elements.') if k < 1: raise ValueError('The value of k cannot be less than 1.') return list_a[k - 1]
78e057ab595dfdb86622b0c7c6e3d3003788acd8
693,341
def euler_step(u, f, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equation. dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f(u)
63422a58cb7e73202d578bc1d53cfd178364e10b
476,076
import mpmath def sf(x, loc=0, scale=1): """ Survival function of the logistic distribution. """ with mpmath.extradps(5): x = mpmath.mpf(x) loc = mpmath.mpf(loc) scale = mpmath.mpf(scale) z = (x - loc) / scale p = (1 - mpmath.tanh(z/2)) / 2 return p
e3fbdfc751c9251ed950f468d5e019ef9bf668f9
357,426
def local_link_information_from_port(port_dict): """Get the Local Link Information from a port. :param port_dict: a Neutron port object; :return: the local link information; """ binding_profile_dict = port_dict.get('binding:profile') return binding_profile_dict.get( 'local_link_information') if binding_profile_dict else None
506cb51ac740f9598d0d412a07a577dc09e3a20f
376,179
def FlowBalance_rule(model, node): """Ensures that flows into and out of a node are equal """ return model.Supply[node] \ + sum(model.Flow[i, node] for i in model.NodesIn[node]) \ - model.Demand[node] \ - sum(model.Flow[node, j] for j in model.NodesOut[node]) \ == 0
628e8e2bb6967c9114dfcb8ea449d760180ab206
170
import requests def get_latest_version(package_name: str) -> str: """Get the latest release version of a package on PyPi by using the PyPi API. Parameters ---------- package_name: str Name of the package Returns ------- str Latest version of the package""" response = requests.get(url=f"https://pypi.org/pypi/{package_name}/json") if response.ok: content = response.json() return content.get("info").get("version") else: raise requests.ConnectionError()
9bd32008fcd33a9c2097c6d82de5b27fcae133a2
173,288
def detect_outlier(magnitude, outlier_threshold): """ Convenience function to check if any of the magnitudes surpass the threshold to mark this date as being an outlier This is used to mask out values from current or future processing Args: magnitude: float, magnitude of change at a given moment in time outlier_threshold: threshold value Returns: bool: True if these spectral values should be omitted """ return magnitude > outlier_threshold
8dc65a455791961212332522e7768fd555241536
497,549
from typing import List from typing import Any def read_nodes(path: str) -> List[Any]: """Read node names from lines. :param path: path to file :return: list of nodes """ with open(path) as f: content = f.readlines() return [ line.strip() for line in content ]
6560a7373954f338ad42a52a482866c1b69cee8b
92,202
def delegate(connection, identity_token, whitelist=None): """Returns authentication token and cookies from given X-MSTR- IdentityToken. Args: connection: MicroStrategy REST API connection object identity_token: Identity token whitelist: list of errors for which we skip printing error messages Returns: Complete HTTP response object. """ return connection.post( skip_expiration_check=True, url=f'{connection.base_url}/api/auth/delegate', json={ 'loginMode': "-1", 'identityToken': identity_token }, )
e0d3e8f7f08945e7da6f162564452f5c1d974027
655,490
def form(title, fields, methods, data, icon=None, id=None, **context): """ Used by user to edit some data. If user presses the button <method>, the appropriate method <method> will be called at AdminController. Values from the methods will be passed to the <method>'s arguments. Typical approach: [ a.form("Edit user", fields={ "username": a.field("Username", "text", "primary", "non-empty"), "age": a.field("Age", "text", "primary", "number") }, methods={ "update": a.method("Update", "primary") }, data=data) ] After user action, the method update(username, action) will be called. To fill-up this form, method get() should return {"username": "John", "age": 21} :param title: Title of the form. :param fields: Dict of fields, each key represents field ID :param methods: Dict of method buttons, each key represents form method :param data: (dict) Data passed to this field will be used by fields to fill-up the form. :param icon: (optional) Form icon :param id: (optional) An ID for API usage :param context: (optional) Context may be used by fields. """ f = {} for field_id, _field in fields.items(): f[field_id] = {"value": data.get(field_id, None)} f[field_id].update(_field) result = { "class": "form", "title": title, "fields": f, "icon": icon, "methods": {method_id: _method for method_id, _method in methods.items()}, "context": context } if id: result["id"] = id return result
df83ba66f21e2f004102060cce55e05deb19e3e9
501,280
import requests def send_msg_dding(msg, token, url=''): """ Send the nail message text to the nail group. :param msg: Message text. :param token: Rebot token. :param url: Nail request url. :return: Response content """ text = { "msgtype": "text", "text": { "content": msg }, # "at": { # "isAtAll": True # } } url_str = "{}{}".format(url, token) res = requests.request("POST", url_str, json=text) return res.json()
ea84b2c1028f8ca7038431263182d0168e004454
581,897
import six def _is_sequence(seq): """Returns true if its input is a `tuple`, `list`, or `range`. Args: seq: an input sequence. Returns: True if the sequence is a `tuple`, `list`, or `range`. """ return isinstance(seq, (tuple, list, six.moves.range))
e94094c314cff5bf9bd7525453d7906ca55d7261
698,043
import base64 def _get_base64(data: str) -> str: """Base 64 encodes data.""" ebytes = base64.b64encode(data.encode("utf-8")) estring = str(ebytes, "utf-8") return estring
a7bd3080dba077077d96602eb35142db32b003de
6,954
from typing import List from bs4 import BeautifulSoup def extract_pdf_uris_from_atom_feed(feed:bytes) -> List: """Extract PDF URIs from an Atom feed Parameters: feed (str) : the feed from which extract PDF URIs, presented as a string Returns: List : List of PDF URIs as strings """ soup = BeautifulSoup(feed, features="html.parser") pdf_uris = [] for link in soup.find_all('link'): if link.get('title') == "pdf": pdf_uris.append(link.get('href')) return pdf_uris
bb7e5c18087d2fad7e6fce05187e1dc389805624
314,139
import math def MaxLevelRowCol(tile_size, max_wid, max_ht): """ w == h == 256 -> (0, 0, 0) w == h == 512 -> (1, 1, 1) w == h == 1024 -> (2, 2, 2) Args: max_wid, max_ht: maxWidth,maxHeight tile_size: w/h of a tile in pixels (must be ^2 and square) Returns: (max_level, max_row, max_col): maximum for each """ width_in_tiles = int(math.ceil(float(max_wid)/float(tile_size))) height_in_tiles = int(math.ceil(float(max_ht)/float(tile_size))) lh = math.ceil(math.log(width_in_tiles, 2)) lw = math.ceil(math.log(height_in_tiles, 2)) level = int(max(lh, lw)) return (level, height_in_tiles-1, width_in_tiles-1)
fdace592f0f3b149d099b8ad48f829bb054c1511
568,252
import re def clean_token_string(string: str) -> str: """ Receives the token name/symbol and returns it after some cleanups. It sets to uppercase, removes double spaces and spaces at the beginning and end. """ return re.sub(r'\s\s+', ' ', string).strip().upper()
5200677ddbfe06b3c5e05428c1cf2215189de818
496,563
def get_index(nodes, name): """ Gets the index of the character based on name :param nodes: List of all character nodes :param name: Character name to get the index of :return: (int) index of the character name in nodes """ index = 0 for node in nodes: if node['name'] == name: return index index += 1 return index
c336317f6ae7055fb4989a29ba930ee8f0d331f2
225,208
from datetime import datetime def utc_timestamp(hours_since_first_epoch): """Construct a timestamp of the format "%Y-%m-%d %H:%M:%S" for the given epoch. Arguments: hours_since_first_epoch (int): Epoch for reftime Returns: ts (str) Timestamp of the format "%Y-%m-%d %H:%M:%S" """ epoch = hours_since_first_epoch * 60 * 60 ts = datetime.fromtimestamp(epoch).strftime("%Y-%m-%d %H:%M:%S") return ts
e82f7b7ee6f2b0d694cac6e77842e112f25c9f79
96,269
def get_db_uri( db_type: str, user: str, password: str, host: str, port: int, db_name: str ) -> str: """ builds a database uri from the given parameters Args: db_type (str): the type of database being accessed user (str): the name of the user who has access to the database on the host machine password (str): the password for the user host (str): the IP address of the host machine port (int): the port to access the DB on db_name (str): the name of the database to access Returns: str: the full db uri """ return f"{db_type}://{user}:{password}@{host}:{port}/{db_name}"
04bc6b78434bff0141e339d637b217b80029a33b
447,188
from typing import Optional import inspect def find_method_signature(klass, method: str) -> Optional[inspect.Signature]: """Look through a class' ancestors and fill out the methods signature. A class method has a signature. But it might now always be complete. When a parameter is not annotated, we might want to look through the ancestors and determine the annotation. This is very useful when you have a base class that has annotations, and child classes that are not. Examples -------- >>> class Parent: ... ... def foo(self, x: int) -> int: ... ... >>> find_method_signature(Parent, 'foo') <Signature (self, x: int) -> int> >>> class Child(Parent): ... ... def foo(self, x, y: float) -> str: ... ... >>> find_method_signature(Child, 'foo') <Signature (self, x: int, y: float) -> str> """ m = getattr(klass, method) sig = inspect.signature(m) params = [] for param in sig.parameters.values(): if param.name == "self" or param.annotation is not param.empty: params.append(param) continue for ancestor in inspect.getmro(klass): try: ancestor_meth = inspect.signature(getattr(ancestor, m.__name__)) except AttributeError: break try: ancestor_param = ancestor_meth.parameters[param.name] except KeyError: break if ancestor_param.annotation is not param.empty: param = param.replace(annotation=ancestor_param.annotation) break params.append(param) return_annotation = sig.return_annotation if return_annotation is inspect._empty: for ancestor in inspect.getmro(klass): try: ancestor_meth = inspect.signature(getattr(ancestor, m.__name__)) except AttributeError: break if ancestor_meth.return_annotation is not inspect._empty: return_annotation = ancestor_meth.return_annotation break return sig.replace(parameters=params, return_annotation=return_annotation)
17d3e7d554720766ca62cb4ad7a66c42f947fc1c
2,170
import math def michalewicz(ind, m=10.): """Michalewicz function defined as: $$ f(x) = - \sum_{i=1}^{n} \sin(x_i) \sin( \frac{i x_i^2}{\pi} )^(2*m)$$ with a search domain of $0 < x_i < \pi, 1 \leq i \leq n$. """ return - sum(( math.sin(ind[i]) * (math.sin(((i+1.)*(ind[i] **2.))/math.pi))**(2.*m) for i in range(len(ind)) )),
74128ad086d81a0cf634a891de93827e1aad1960
622,758
def value_or_from_dict(obj, key, default=None): """ Many Polygraphy APIs can accept a `Union[obj, Dict[str, obj]]` to allow for specifying either a global value, or a per-key (e.g. input, output, etc.) value. When a dictionary is provided, the `""` key indiciates a default value to use for keys not otherwise found. For example, Polygraphy allows for providing per-output tolerances. Thus, all of the following are valid arguments: :: # Value directly atol = 1.0 # Per-output values atol = {"out1": 1.0, "out2": 2.0} # Per-output values with default atol = {"out1": 1.0, "": 2.0} Args: obj (Union[obj, Dict[str, obj]]): The value, or per-key values. key (str): The key to use when per-key values are provided. default (obj): The default value to use if it is not found in the dictionary. Returns: obj: The value. """ if not isinstance(obj, dict): return obj if key in obj: return obj[key] elif "" in obj: return obj[""] return default
281067e9fb4f42203d1f9e77b88f945897b5eff5
621,394
def test_generate_one_task(test_init_connector): """Test the creation of one task Args: test_init_connector (object): an HTC grid connector Returns: dict: return a task to be reused by other test """ tasks = [ { "worker_arguments": "1000 1 1" } ] generated_task = test_init_connector.generate_user_task_json(tasks) generated_task.should.have.key("session_id") generated_task.should.have.key("scheduler_data") generated_task["scheduler_data"].should.have.key("task_timeout_sec") generated_task["scheduler_data"].should.have.key("retry_count") generated_task["scheduler_data"].should.have.key("tstamp_api_grid_connector_ms").which.should.be.equal(0) generated_task["scheduler_data"].should.have.key("tstamp_agent_read_from_sqs_ms").which.should.be.equal(0) generated_task.should.have.key("stats") generated_task.should.have.key("tasks_list") generated_task["tasks_list"].should.have.key("tasks").which.should.have.length_of(1) return generated_task
75abbd6d25fe90f640633d4776735c0e3c40e277
161,851
from typing import Iterable import math def lcm(numbers: Iterable[int]) -> int: """Find least common multiple of a list of integers. Parameters ---------- numbers : Iterable[int] Integers whose least common multiple is to be found Returns ------- int Least common multiple """ a, *b = numbers if len(b) > 1: return lcm(numbers=(a, lcm(numbers=b))) else: [b] = b return a * b // math.gcd(a, b)
520cb44110c900b9322c76286a488ec24890f037
231,541
def fill_color(color: str): """ Returns an SVG fill color attribute using the given color. :param color: `string` fill color :return: fill="<color>" """ return f'fill="{color}"'
8a035e9763535188b85a81741b4c1d301b7c22e3
281,171
def _parse_version(version): """Parses a VHDL version string or int, 2- or 4-digit style, to a full 4-digit version identifier integer.""" if version is None: return None version = int(version) if version < 70: version += 2000 elif version < 100: version += 1900 return version
bfa8759a71ea2d6f886c3e77bd3d268e266bc6d7
257,459
def _test_if_road(way): """Tests if a raw way is a road to consider""" tags = way.tags return 'highway' in tags and tags['highway'] not in [ 'footway', 'service', 'unclassified', 'steps', 'cycleway', 'path', 'track', 'pedestrian', 'proposed', ]
5d6d1af8a94f3fd759594ae02f5d5cbcd2e04e42
426,690
import functools def polygon_wrapper(func): """ Wrapper function to perform the setup and teardown of polygon attributes before and after creating the polygon. Keyword arguments: func (function) -- the function to draw the polygon. """ @functools.wraps(func) def draw_polygon(self, *args, **kwargs): """ Setup the Context, draw the polygon with attributes applied, and teardown the environment. """ # Save the Context so we can restore it when this is done self.context.save() # Initialize the polygon's attributes self._init_attributes(**kwargs) # Call the function result = func(self, *args, **kwargs) # Fill the polygon, if it's being filled if self.fill: self.context.fill_preserve() # Set the outline fill_color and outline the polygon self.calling_surface._set_color(self.line_color) self.context.stroke() # Restore the Context now that the polygon is drawn self.context.restore() return result return draw_polygon
76056e41c36a2c15dcb8a2e05cc4ec4c1beb68dc
704,605
def ask_to_proceed(reason=""): """ This function prompts for user permission, for whether to upload/download songs. :param reason: it can be "uploading" or "downloading". :returns: True, if user grants the permission to upload/download. :returns: False, if user denies the permission to upload/download. """ choice = "" while choice not in ('y', 'Y', 'n', 'N'): choice = input( "\n\033[1;32mWould you like to proceed with %s (y/n)?:\033[0m " % reason ) if choice in ('y', 'Y'): return True elif choice in ('n', 'N'): return False else: print("\nIncorrect input!")
797519cb34a6e27b0426414b4ab565f0e6adfabe
408,866
def validate_probability(p: float, p_str: str) -> float: """Validates that a probability is between 0 and 1 inclusively. Args: p: The value to validate. p_str: What to call the probability in error messages. Returns: The probability p if the probability if valid. Raises: ValueError if the probability is invalid. """ if p < 0: raise ValueError(f'{p_str} was less than 0.') elif p > 1: raise ValueError(f'{p_str} was greater than 1.') return p
ec805e54db85b0d288973e0e95d7dead870eba65
658,424
def get_path_kind(path): """Return a string describing which kind of path we have. Args: path (Path): A Path object. Returns: str """ if not path.exists(): return 'nonexistent' elif path.is_dir(): return 'dir' elif path.is_file(): return 'file' elif path.is_symlink(): return 'symlink' else: return 'other'
3103defdf50d1b9c14e7a22bdd5c3bfc55042984
569,522
def sip_module_name(qtcore) -> str: """ Returns the name of the sip module to import. (As of 5.11, the distributed wheels no longer provided for the sip module outside of the PyQt5 namespace). """ version_string = qtcore.PYQT_VERSION_STR try: pyqt_version_ints = tuple(int(c) for c in version_string.split(".")) if pyqt_version_ints >= (5, 11): return "PyQt5.sip" except Exception: pass return "sip"
2d36491a778520e4ed8698dd7f2898df36a8b40f
139,811
import pytz def make_aware_assuming_utc(dt): """ Return a timezone-aware datetime (in UTC) given a naive datetime. """ return pytz.utc.localize(dt)
ff40db0a56cb3841db163680d75bf067d58ff1ac
444,633
def fetch_object(service, obj_type, obj_name, create=False, create_args={}, **fetch_args): """Helper function to fetch objects from the Watson services. Params ====== - service: a Watson service instance - obj_type: object type, one of: "environment", "configuration", "collection", "workspace" - obj_name: name used to look up / create object - create: whether to create object if not found (default: False) - create_args: arguments to pass in when creating, other than name - fetch_args: other arguments used to fetch object, e.g. environment_id Returns ======= obj, obj_id: fetched object and its unique ID (for convenience) """ # Methods for each object type list_methods = { "environment": "get_environments", "configuration": "list_configurations", "collection": "list_collections", "workspace": "list_workspaces" } get_methods = { "environment": "get_environment", "configuration": "get_configuration", "collection": "get_collection", "workspace": "get_workspace" } create_methods = { "environment": "create_environment", "configuration": "create_configuration", "collection": "create_collection", "workspace": "create_workspace" } # Look up by name obj = None obj_id = None obj_list = service.__getattribute__(list_methods[obj_type])(**fetch_args) for o in obj_list[obj_type + "s"]: if o["name"] == obj_name: obj = o obj_id = obj[obj_type + "_id"] print("Found {}: {} ({})".format(obj_type, obj_name, obj_id)) break if obj_id: # fetch object fetch_args[obj_type + "_id"] = obj_id obj = service.__getattribute__(get_methods[obj_type])(**fetch_args) elif create: # create new, if desired if obj_type == "configuration": # handle configuration weirdness create_args["config_data"]["name"] = obj_name else: create_args["name"] = obj_name obj = service.__getattribute__(create_methods[obj_type])(**create_args) obj_id = obj[obj_type + "_id"] print("Created {}: {} ({})".format(obj_type, obj_name, obj_id)) return obj, obj_id
46885b465c1dfe415ba48433856fd5144546030c
667,059
def _validate_subdomain(subdomain): """ Validates the given subdomain. Parameters ---------- subdomain : `None` or `str` Subdomain value. Returns ------- subdomain : `None` or `str` The validated subdomain. Raises ------ TypeError If `subdomain` was not given neither as `None` or `str` instance. """ if subdomain is not None: if type(subdomain) is str: pass elif isinstance(subdomain, str): subdomain = str(subdomain) else: raise TypeError( f'`subdomain` can be as `None` or as `str` instance, got {subdomain.__class__.__name__}.' ) if not subdomain: subdomain = None return subdomain
559a7bbbcc2cb49b45714254593c3d756e9e1297
413,920
def add_one(number): """ Example of a simple function. Parameters ---------- number: int, float, str Returns ------- out: int, float, str The input value plus one. Raises TypeError if the input is not the expected type """ if isinstance(number, (float, int)): return number + 1 elif isinstance(number, (str)): return number + '1' else: raise TypeError('Expecting an int, float or string.')
d24a5d9e1a02098d1a6638bdc8b5493bc4d732e2
21,016
def getMissenseData(data): """ Keeps only those rows that correspond to missense mutations and are not known SNPs. Arguments: data = dataframe Returns: tp_data = dataframe """ # Keep rows that have mutation type as "Substitution - Missense" and if it # is not known SNP tp_data = data[(data["Mutation Description"] == 'Substitution - Missense')] return tp_data
0096d8dc73be67eb680dd0d64f4e883ee49b9cdd
84,343
def tangent_weight_is_default(tangent_weight): """Returns whether the given tangent weight is equal to the default value of 1/3, taking floating-point precision into account. """ return 0.3333 < tangent_weight < 0.3334
720a10e3567aa15641eddc7c8107686a60af980c
228,617
def invert_y_and_z_axis(input_matrix_or_vector): """ VisualSFM and Blender use coordinate systems, which differ in the y and z coordinate This Function inverts the y and the z coordinates in the corresponding matrix / vector entries Iinvert y and z axis <==> rotation by 180 degree around the x axis """ output_matrix_or_vector = input_matrix_or_vector.copy() output_matrix_or_vector[1] = -output_matrix_or_vector[1] output_matrix_or_vector[2] = -output_matrix_or_vector[2] return output_matrix_or_vector
5ab29aa0a74943be2c57414bbb85dbe1d1370a51
604,812
def precision_to_string(precision): """Translates a precision number (represented as Python string) into a descriptive string""" if precision == "16": return "Half" elif precision == "32": return "Single" elif precision == "64": return "Double" elif precision == "3232": return "ComplexSingle" elif precision == "6464": return "ComplexDouble" else: raise("Unknown precision: " + precision)
7f7d9b099091944d4fae1c007d83c375770a6b20
41,094
def is_permutation(str1, str2): """Check if str is permutation of another str Runtime: O(N) """ if not isinstance(str1, str) or not isinstance(str2, str): return False if len(str1) != len(str2): return False if len(str1) < 1: return False count1 = {} count2 = {} for c in str1: if c in count1: count1[c] += 1 else: count1[c] = 1 for c in str2: if c in count2: count2[c] += 1 else: count2[c] = 1 if count1 != count2: return False return True
6be7bb6001263727d6ec1784be1311202373ae6e
143,135
def function_sum(*functions): """Generates a function that returns the sum of function outputs. Args: *functions: List of functions. Returns: Callable. """ def output_function(*args, **kwargs): return sum(func(*args, **kwargs) for func in functions) return output_function
df0e9e4d6a230377fe471a17d35bc9b868cfb7a2
551,715