content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def highlight(text, org): """ Highlights the company mention in the text presented during annotation :param text: the text to be presented :param org: the mention to be highlighted :return: HTML object of text with highlighted company """ # Find locations of the company occ...
cc496e54d2b089d6844e73c50974a0c0ed9b0d5d
617,394
import pickle def cnn_load(modelpath): """ Load the saved model Input ===== modelpath: str Path to load the saved model Output ====== model: dict The dictonary that saved the network and functions. """ # Init fp = open(modelpath, 'rb') # load mode...
123bf4eb2ebc76073821e36f18473c31ce668fda
617,396
def one_of_k_encoding(x, allowable_set): """Converts input to 1-hot encoding given a set of allowable values.""" if x not in allowable_set: raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set)) return list(map(lambda s: x == s, allowable_set))
ab1954cd569ef6fd4e3c0b50ea7f3103f92ed40d
617,397
def GetParameter(content, parameterName): """ Get one parameter from the header file Arguments: content -- content of the file parameterName -- name of the parameter. Parameters available: -- bands, lines, samples, framerate Returns: param -- curren...
89be8c1238ea0e7c42768a80da15e36af92f3451
617,398
def __process_case_list(list_input, list_output): """ Process a case list and raise an exception in case of duplicate entries. """ duplicate = "" for item in list_input: if item is None or item == "": continue elif item.lower() in list_output: dup...
57f9969f9d06a4da56e988081316a98d37b2d4e8
617,400
def trim_comments(val): """ Remove in-line comments that begin with "#", and whitespace. """ return val.split("#")[0].strip()
4eec1d671896ca3e717ad99dfca4e4d0b88f1001
617,402
def generateOperation(length: int, amount: float) -> str: """ Generate an operation (operation = creation of a virtual credit card) :param length: The duration of the virtual credit card in months :type length: int :param amount: The amount in Euros contained in the virtual credit card :type am...
d66db09c6c788c3a98d09443b2ef8cb1f3258dcb
617,403
def _has_rows(rows: list) -> bool: """ Determine if the table has rows. Keyword arguments: rows -- the rows to check Returns: True if the table has rows, False otherwise """ return len(rows) > 0
ae8901084583a788a56ce47cbabf33956b939cda
617,404
def _can_walk(base, subdirectories): """ Determine if the first element of the 'subdirectories' list can be appended to the 'base' path and still specify a directory. """ # Always consider the last part of the subdirectories the filename if len(subdirectories) < 2: return False # All...
29f0dba62e5e686e31958a1ee7a8f8d356161016
617,407
def get_stable(res_file): """Returns whether the matching was found to be stable. Args: res_file: The file with IP results. Returns: Whether the matching was found to be stable. """ f = open(res_file, "r") for line in f: if 'stability_correct' in line: return l...
7ac1ee1393305059b9fbc20037657f97341bd2cc
617,410
import pkg_resources def package_installed(pkg): """Check if package is installed""" req = pkg_resources.Requirement.parse(pkg) try: pkg_resources.get_provider(req) except pkg_resources.DistributionNotFound: return False else: return True
b9b0fdad9596fbf3a8dd351c8f873e2e34dc4440
617,412
def levenshtein_distance(first,second): """ Return the levenshtein distance between two strings. http://rosettacode.org/wiki/Levenshtein_distance#Python """ if len(first) > len(second): first, second = second, first distances = range(len(first)+1) for index2, char2 in enumerate(second): new_distances = [i...
35d81800e120863a2cdda87f2255bf982339f10e
617,413
import logging def format_mesh_terms(df): """ Removes unrequired columns and pivots the mesh terms data into a dictionary. Args: df (dataframe): mesh terms as returned from retrieve_mesh_terms Returns: (dict): document_id: list of mesh terms """ logging.info("Formatting mesh ...
fdc6962bbf8dc875ad00a88643ccbdf43fad16f9
617,417
import json def read_json_from_file(filename: str, encoding: str = 'utf-8') -> dict: """Load json configuration file. :param filename: Path to file. :param encoding: Encoding in which the file is read. :return: Loaded configuration as a dict. """ if not filename: ...
3f57c107b40853819f27ccc6bb15178522fd504a
617,421
def get_object(arr, str_card): """ Get Card Object using its User Input string representation Args: arr: array of Card objects str_card: Card descriptor as described by user input, that is a 2 character string of Rank and Suit of the Card. For example, KH for King of Hearts. Returns: object pointer corresp...
94666c1b6415a1b167f7d0b50591efe193cf5ca8
617,426
def names_from_dct(spc_dct_i, tors_model): """ Build the tors name list from a dictionary """ # Read names from dct amech_ts_tors_names = () if 'amech_ts_tors_names' in spc_dct_i: amech_ts_tors_names = spc_dct_i['amech_ts_tors_names'] if tors_model in ('1dhr', '1dhrf', '1dhrfa'): ...
2ec39418a3e1dcb135bb79e8a7c9c171f102d480
617,430
def list_messages(base, queue_name): """Utility function that lists messages in Zaqar queue.""" res = base.messaging_client.list_messages(queue_name) if res['status'] != 200: msg = 'Failed in listing messsages for Zaqar queue %s' % queue_name raise Exception(msg) return res['body']['me...
186948909b6d4ea129b0fef69d8cc533bbee610a
617,432
import inspect def accepts_args(func): """returns Bool if the func have *args else False""" return 'args' in list(inspect.signature(func).parameters)
0ba0e82e345bb2cb226c22e93b33e8c2432db8ef
617,441
import ast def loadSong(fileName): """ Loads a song from a file as input. fileName: Name of the file to be read from """ with open (fileName, 'r') as f: testSong = ast.literal_eval(f.read()) return testSong
6e058f20668e5d68251e3778c9cc4f94045de71a
617,443
import re def is_rdemo(file_name): """ Return True if file_name matches a regexp for an R demo. False otherwise. :param file_name: file to test """ packaged_demos = ["h2o.anomaly.R", "h2o.deeplearning.R", "h2o.gbm.R", "h2o.glm.R", "h2o.glrm.R", "h2o.kmeans.R", "h2o.naiveBaye...
8d94bbaaddb242d1054a28f120374c1d8c4306fe
617,446
import torch def inner_product_similarity(a: torch.Tensor, b: torch.Tensor, dim: int = 1) -> torch.Tensor: """ Calculate inner product of two vectors Args: a (T, shape = (B, N_{a}, E)), data_type=torch.float: the first batch of vector to be multiplied b (T, shape = (B, N_{b}, E)), dat...
45ce149b1300524f2efb74279ae1f39c932c118d
617,447
def _split_namespace(tag): """Split a tag into namespace and local tag strings (PRIVATE).""" try: return tag[1:].split('}', 1) except ValueError: return ('', tag)
bff437f3866f9b5417fab13ee3aa382ad230ee43
617,448
def get_Q(W): """Return the apsect ratio Q=N/M of a rectangular matrix W""" if W.shape[1] > W.shape[0]: M, N = W.shape else: N, M = W.shape Q = N / M return Q
ec570d7203fc6e5bee1ea6ffb33a472f367bce7d
617,456
import collections def GetRevealedCards(development_cards_dict, game_rules): """Returns a dict from Deck to list of revealed development cards. The last N cards from each list are considered revealed cards. All other cards are considered still part of the unrevealed decks. Params: development_cards_dict...
30f0096c0576cfd4065e443411dea1a858ab0ddd
617,458
def get_highest_scoring_ids(ids_set, id2sc_dic, scfp_list=False): """ Given a set of IDs, and a ID to score mapping, return highest scoring ID(s) in list. scfp_list: If score is stored in first position of list, with ID mapping to list in id2sc_dic. >>> ...
089788c14e1d23cca02624b57157c98daa427761
617,462
def walk_line(strings, max_x, max_y, coordinates, direction, path_char): """ Given some starting points and a direction, find any connected corners in said direction. :param strings string - the text that may contain rectangles. :param max_x int - the boundary/width of the text. :param max_y int - ...
322f666591895434d23f1dd8cd454c545cd37a4f
617,467
def QuadraticOut(start=0.0, finish=1.0): """ Quadratically increasing, starts faster : f(x) = 2x - x^2 """ def quadratic_out_easing(sprite, delta): return start + (finish - start) * (2.0 * delta - delta * delta) return quadratic_out_easing
f604a3abbee379377550347c974cbdbb3d4592dc
617,468
def format_hail_linreg(linreg_expr): """ Format hail linear regression struct from arrays into slope and intercept :param StructExpression linreg_expr: :return: Formatted StructExpression :rtype: StructExpression """ return linreg_expr.annotate( beta=linreg_expr.beta[1], sta...
a1aac49ccb5ab70a64e6a47f0b8920ee23817faf
617,469
from typing import Set from typing import Dict import copy def true_positives( T: Set[int], X: Set[int], margin: int = 5, choose_earliest: bool = True ) -> Dict[int, int]: """Compute true positives without double counting. If there is multiple detected positives in the margin of a true positive and choose...
ddb9aa52c8ea3b618d5eee52066c9d1358fed8e7
617,471
def list_sra_accessions(reads): """ Return a list SRA accessions. """ accessions = [] if reads is not None: accessions = reads.keys() return accessions
1028f471610cb32518ed4b3356d9516deb9e5645
617,472
def get_board_score(board): """ Calculates the score of the winning board as per the rules of the problem :param board: List[List[str]] :return: int """ score = 0 for row in board: for num in row: if num is not None: score += int(num) return score
5a0abd5a8fdda15b8d03719ef6f8e63c9f0fed6e
617,475
def integer_bisect(bound, f): """ Finds a pair of integers (a,b) such that f(a) <= 0 < f(b) and |a - b| == 1. On entry, assumes that f(bound[0]) <= 0 < f(bound[1]) """ if bound[1] - bound[0] == 1: return bound else: midpoint = round(bound[0] + bound[1] / 2.0) if f(midpoin...
bfdc9cbdead3b239e0ef7f52b05e173dbf7e7658
617,476
def members(SWcoord, NEcoord, particles): """ Helper function: Return the sub-list of particles that exist in the box defined by SWcoord and NE coord. Parameters ---------- SWcoord: Coordinate Coordinate of the SW corner of the box NEcoord : Coordinate Coordinate of the ...
00752db8e98e870acf1344fb72b38a291392696a
617,477
import yaml def get_config(name: str = "config.yaml") -> dict: """ Parses an arbitrary config file. Assumes the default will be 'config.yaml'. Args: name (str): The name of the YAML file. Default is "config.yaml". Returns: opt (dict): A dictionary containing the parsed YAML file...
76cd9332ca3f201be70987858b55885af42fbe79
617,480
def getclosest_ij(lats,lons,latpt,lonpt): """Function to find the index of the closest point to a certain lon/lat value.""" dist_sq = (lats-latpt)**2 + (lons-lonpt)**2 # find squared distance of every point on grid minindex_flattened = dist_sq.argmin() #return np.unravel_index(mini...
860d10637dee2d694518da934c209eed08214c6d
617,484
def get_mouse_pos(mouse_pos, rows, width): """ Return the cell that has been clicked on with the mouse. params: mouse_pos (int, int): position of the cursor rows (int): number of rows in the grid width (int): width of the scren return: row, col (int, int): coordinates of ...
61c5aaedcec191744be44b69eef25442bfc2344a
617,486
import textwrap def indent(block, indent=2): """Indent a multi-line text block by a number of spaces""" return textwrap.indent(block.strip(), ' ' * indent)
9664c9dc0eee5e683d85cf178decedcce56287ee
617,491
def breadth(decomp): """ Return the sum of the exponents in the decomposition of the argument. Accepts an int or a Decomposition. Called uppercase-Omega in number theory. """ return sum([decomp[p] for p in decomp])
55db485cbdf411691688a0e8336d96d6d5d19948
617,494
def _get_target_hname(elt): """ elt is sthg like: resource "xxx" { target="#yyy" some_elt {...} } return the concatenated "#yyy/xxx" or uses the tag of 'some_elt' """ cmd_name = elt.get("name") or elt.text target = elt.get("target") if cmd_name is not None and tar...
05049268ada816a8a188ce0ff60bc34a710f0ef2
617,495
def cross(v1, v2): """Cross product of two vectors""" n = len(v1) prod = n*[0] if n == 3 and len(v2) == 3: prod[0] = v1[1]*v2[2] - v1[2]*v2[1] prod[1] = v1[2]*v2[0] - v1[0]*v2[2] prod[2] = v1[0]*v2[1] - v1[1]*v2[0] return prod
6d273b0c920586b3b023f16a4d8290349895e0b9
617,498
from typing import Sequence import itertools def _partition_spins(spins: Sequence[int]) -> Sequence[int]: """Returns the indices for splitting an array into spin channels.""" return list(itertools.accumulate(spins))[:-1]
da75365060db8057720a59646ac0f3bf25009c95
617,499
def load_ply_header(ply_path): """ load header info from ply file (triangle mesh or polygon mesh) Args: ply_path (str): path to ply file Returns: info (dict): a dictionary containing the parsed header e.g. info == {'storing_type': 'binary_little_endian', ...
abf1d7307d09644fdb059b9344453f283f355c02
617,500
def getGuess(alreadyGuessed): """ Returns the letter the player entered. Ensures the player enters a single letter and nothing else. """ while True: print('Please guess a letter.') guess = input() guess = guess.lower() if len(guess) != 1: print('Only a sin...
203702b70a9f40f515961ed52408a04aeda369e7
617,501
import calendar def get_nth_weekday(year, month, weekday, n): """ 指定年月の第n曜日の日付を取得する :param int year: year :param int month: month [1-12] :param int weekday: weekday [0-6] 0:Mon ... 6:Sun :param int n: nth :rtype: datetime.date :return: date """ if not (1 <= month <= 12 > 12 or 0 ...
61901a937ad1d069e6ef15cb0c34b90c781133a3
617,502
def process_smooth_dates_fit_inputs(x, y, dt_idx, reg_dates): """Sanitises the inputs to the SmoothDates fitting method""" if hasattr(x, 'index') and hasattr(y, 'index'): assert x.index.equals(y.index), 'If `x` and `y` have indexes then they must be the same' if dt_idx is None: dt_id...
c2c3194afdc6b8b729a331139988c972ed54ad9e
617,503
from typing import OrderedDict def attributes_to_odict_gff(attributes): """ Parse the GFF attribute column and return a dict """ if attributes == ".": return OrderedDict() ret_gff = OrderedDict() for attribute in attributes.strip().split(";"): if len(attribute): e...
90020c48c6cc5287e34bdfa4fa477351ed057f31
617,505
import ast def is_list_stored_as_string(x): """ Determine whether a value is a list stored as a strong. """ if '[' in str(x) and ']' in str(x): try: lst_x = ast.literal_eval(str(x)) is_list = isinstance(lst_x, list) assert is_list, "Expected list for the fol...
a3a07ed578ee4051a9479176899d9eab54f73348
617,506
from typing import List from typing import Dict def _check_if_key_is_reported(key: str, results: List[Dict]) -> bool: """Check if a particular key is reported by some workers. Args: key (str): A key string. results (List[Dict]): The results list returned from workers. Returns: A ...
fb1e50e8df6c766a190f7aecac2f04990ab76506
617,510
from typing import Type from typing import Any def fullclassname(cls: Type[Any]) -> str: """ Returns the fully qualified class name of the input class. """ module = cls.__module__ name = cls.__qualname__ if module is not None and module != "__builtin__": name = module + "." + name ...
2729bc50fdb7322925a7891de7b2b8cd4c473d9a
617,511
def get_sku_info(sku, config): """Returns a sku info dictionary for sku. Args: sku: String specifying machine's SKU. config: Configuration containing sku_meta. Returns: A dictionary containing sku info for the given machine sku, including - cpu - cpu usable ratio ...
1f1189d77e3de7df42e3c25f780690032d881e17
617,512
from unittest.mock import patch def _patch_async_setup_entry(return_value=True): """Patch the async entry setup of sonarr.""" return patch( "homeassistant.components.sonarr.async_setup_entry", return_value=return_value, )
8146b1883f2063f73c1fc51fd4409827dd0bdfd8
617,514
import re def strip_whitespace(string): """ Strip newline, tab and multple whitespace from a string """ return re.sub(' +', ' ', string.replace('\n', ' ').replace('\t', ' ').strip())
d8eecd66e92aa102b3143dc47f2034ec77051a16
617,516
def get(identifier): """Returns an activation function from a string. Returns its input if it is callable (already an activation for example). Args: identifier (str or Callable or None): the activation identifier. Returns: :class:`nn.Module` or None """ if identifier is None: ...
086c8b34892bfbc285bd7b9f63a2ab72b3dd922e
617,518
def CollectVotes(composite,data,badOnly): """ collects the votes from _composite_ for the examples in _data_ **Arguments** - composite: a composite model - data: a list of examples to run through _composite_ - badOnly: if set only bad (misclassified) examples will be kept **Returns** ...
e9d80f94a771199741b2a353fd4ee2212e634c01
617,522
import binascii def convertfrom_hex_notation(bytes_string: bytes): """Takes a given bytes object containing hex notation (e.g. b'\\x00\\x01\\x02\\x03') and returns a bytes object with the hexadecimal notation '\\x' glyphs removed from the output (or, transforming the output to the "Hexadecimal representation of b...
7d4086c7c4b3a894ede043e3dc58346924fd13e9
617,530
def _value_error_on_false(ok, *args): """Returns None / args[0] / args if ok.""" if not isinstance(ok, bool): raise TypeError("first argument should be a bool") if not ok: raise ValueError("call failed") if args: return args if len(args) > 1 else args[0] return None
261b026bfb564ebb62b5f85aa2e19d8958dbeb71
617,534
def find_last(s, sub): """s and sub are non-empty strings Returns the index of the last occurrence of sub in s. Returns None if sub does not occur in s""" if s.find(sub) == -1: # this is the return value for s.find if it's not there return None else: ans = s.find(sub) # found...
1b5aa7d772bc561a8eaebb0723deb8dc71361cbf
617,540
def get_action_value(mdp, state_values, state, action, gamma): """ Computes Q(s,a) as in formula above """ v = 0 for next_state in mdp.get_next_states(state, action): v += (mdp.get_transition_prob(state, action, next_state) * (mdp.get_reward(state, action, next_state) + gamma * state_...
b0ca6c9b58fd51d87a469751ba9d8cc86a22ca54
617,542
def is_src_url(param): """ Check if a parameter is a URL and return True if so NOTE: be careful about changing this as it will influence how devtool/recipetool command line handling works """ if not param: return False elif '://' in param: return True elif param.startswith('g...
a4c2c02b0bafc35f9032828b47a8a6b3eae2e6c9
617,543
import json def json_parser(result, auth_token, cls=None): """JSON Parser Method This method transforms JSON data into usable Python objects, if required and generally checks for errors. Moreover, in the case that the desired Python object requires an authentication token, this function provides that...
2f019de7735ca7a59b6d9a711ed0c5e80fd7ab47
617,544
def contains_only_zeros(image_data): """ Determines if data patch should be omitted from AL training. Patches in the border region of the image can contain only padding (only values of 0). This messes with the AL query strategy because the model is very uncertain, but the patches don't contribute to...
aad9129b891e8c492530a5944e03c46cd2228841
617,545
def is_targeting_windows(pkg_vars): """Returns true if 'platform' in pkg_vars indicates Windows.""" return pkg_vars['platform'].startswith('windows-')
83ee031170327348c57b50c86739c876e9f9f8f4
617,551
def make(error, message=None, response=None): """ Make error or success API response. :param error: True if the response format has to be as an error, False otherwise. :param message: Error message. :param response: Success dictionary response. :return: API response. """ response_dict = ...
6151c11c5a7d9c77dcb0a5792cc4c2be71aa012d
617,557
def _recursive_dict_without_none(a_dict, exclude=None): """ Remove all entries with `None` value from a dict, recursively. Also drops all entries with keys in `exclude` in the top level. """ if exclude is None: exclude = [] result = {} for (k, v) in a_dict.items(): if v is ...
4cb4bb045d840eeaad786804f8826d212f64d7c9
617,558
def version_contains_field(version, field): """ Checks if the given dictionary contains the given field. Args: version: A dictionary containing version details. field: A string representing a key path. Returns: A boolean indicating whether or not the version contains the field. """ version_fragme...
ce75f718b9afc21d1c1437a573f2f86a3d4e9771
617,560
import torch def sample_noises(size): """ Sample noise vectors (z). """ return torch.randn(size)
edce1ff6d618c4e569d725fff4dce81eb9c643d5
617,561
from typing import Generator import pkg_resources def get_plugins() -> Generator[pkg_resources.EntryPoint, None, None]: """Iterate over available plugins.""" return pkg_resources.iter_entry_points(group="stan.plugins")
c3dc6c21daf6bda2e49f99803ff747523a13922d
617,563
def add(a,b): """sum a and b""" return a+b
3f9723b613e803385f5f825b8f305066a572d6d9
617,566
def ticket_to_order_ratio(total_tickets, total_orders): """Returns the ratio of tickets to orders. Args: total_tickets (int): Total chats, emails, or tickets in the period. total_orders (int): Total orders in the period. Returns: Ratio of tickets to orders """ return (tota...
c56d1cb933e17373becc266b17cb77698744e6d0
617,569
from typing import Iterable from typing import List def add_prefix_to_list(data: Iterable[str], prefix: str) -> List[str]: """Adds a prefix to every item in an iterable (e.g. a list). Returns a list""" return [f"{prefix}{item}" for item in data]
8977e8b4744f41a5809c575f65d57457b026dce5
617,570
def str2bool(text): """Simple function to convert a range of values to True/False.""" return text.lower() in ["true", "yes", "1"]
f1bd6bb6e2fa58eb51b24b4a31e8339c59b2edb2
617,571
from datetime import datetime def utc_timestamp() -> int: """Return current utc timestamp rounded to nearest int""" return int(datetime.utcnow().timestamp())
6ca26274f5f653c8748c9c07fd21d072c023f92a
617,572
def sp(v, g): """Scalar product of the two vectors v and g Parameters ---------- v : np.array g : np.array Returns ------- float """ return (v * g).sum()
0d771201119b8bc57b3399c5f274bef65903f18e
617,575
import string import random def unique_id(prefix, size=16, chars=string.ascii_lowercase + string.digits): """Generates a unique ID of the form "prefix-..." (default: "prefix-[a-z0-9]{size}") Args: prefix: The prefix that is prepended to the ID. size: The length of the ID (excluding prefix) ...
6dceed24b01381525a2f7c47ca8228efc52f3550
617,576
def create_book(conn, book): """ Create a new book into the books table :param conn: :param book: :return: book id """ sql = ''' INSERT INTO Kirjat(id, name, tekija, status, lainaaja, varaaja) VALUES(?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, book) return...
3d5482a8d25bc81b5a031903e5acfa9e117a5cd7
617,577
import math def sanitizeAngle(theta): """ Returns an angle between 0 and 2pi. Parameters ---------- theta : float an angle Returns ------- theta : float an angle between 0 and 2*pi """ if theta < 0: theta = theta + (1 + -1 * int(theta / (math.pi * 2.0...
d4c59a8171b54eb7258cee7ddbabbce641d87d04
617,588
import re def to_number(text): """ Returns the converted decimal value or a value of None for input strings. """ # Return the value of None for any text that is null or set to 'Not Applicable' if text == '' or 'Not Applicable' in text or 'not applicable' in text or text is None: return None ...
48419f48ad044416c0ea50b19f570380a0cc3422
617,589
def cc_score_fct(i): """CC (Chamberlin-Courant) score function.""" if i == 1: return 1 else: return 0
9035a88d9acd588b7589d75f611bb2987fb89ab1
617,594
import re def split_program_by_processing_element_label(program_string): """ Split a program string into a list of individual processing element programs based on the location of <*> labels. :param program_string: multiline string containing an assembly program with <*> labels :return: the correspond...
409ec401352bb7284f17fb49a9076b5cdd0359b6
617,595
def _get_point_est(md_tuple): """Get point estimate in mean_difference/normalized_mean_difference.""" return md_tuple[0]
5d31b634b9f3d00c870ccfa23a6def45afd2d8f1
617,596
import math def day_fraction_to_time(fraction): """Convert day fraction to to time as (hour, min, sec, usec) tuple.""" subsec, sec = math.modf(round(fraction * 86400.0, 6)) # round to usec sec, usec = int(sec), int(subsec * 1e6) min_, sec = ( sec / 60, sec % 60, ) hour, min_ =...
929adb1068f505691bd3d7b9f082bdfbe5602cc5
617,597
def _is_healthy_pure(get_health_func, instance): """Checks to see if a component instance is running healthy Pure function edition Args ---- get_health_func: func(string) -> complex object Look at unittests in test_discovery to see examples instance: (string) fully qualified name of co...
c7a48104dae541fcd9a10af6b1f94236e029dc6d
617,600
def exp(n, m): """ Calculates m ^ n. """ if n == 1: # m ^ 1 = m return m else: # m ^ n = m * m ^ (n-1) return m * exp(m, n - 1)
f8a05922b0ef8fd7d772956f6f55cc2d30f36275
617,601
def _bulk_identity_factory(key_columns): """Return a function that accepts a dict mapping and returns its identity corresponding its key values mapped by `key_columns`. """ return lambda mapping: tuple(mapping.get(col.key) for col in key_columns)
29d60f29f95eb5e7f2ef3ecf28e2657ac0974924
617,609
def or_dict(list_): """Construct a dictionary with key 'or'""" return {"or": list_}
faa71105ae414a24b754e40f56f45b84daa69e3d
617,611
def map_labels(label): """ Purpose: a function used for the pandas library's ".apply()" method to convert all the specific labels in the dataframe into general labels Params: label(string) -> the label from every single row of the dataframe column Returns: a general label (string) """ ...
2bebe3f1b70c34077bd5447b6bbe84fb945a3863
617,620
def get_diffusion_information(image) : """ Return the diffusion information from the ``image`` metadata. The diffusion information is a dictionary and may contain the following keys : * ``"diffusion_bvalue"`` * ``"diffusion_gradient_orientation"`` """ result = {} i...
490228bc757caec6713dbacd0664c2e0106d5221
617,622
def add_prefix(key, prefix): """Add prefix to key.""" if prefix: key = "{}_{}".format(prefix, key) return key
03c14fae7de19a3781f6d18805c2206449c16a21
617,623
def subs_filename(subs_id, lang='en'): """ Generate proper filename for storage. """ if lang == 'en': return f'subs_{subs_id}.srt.sjson' else: return f'{lang}_subs_{subs_id}.srt.sjson'
6c972e348c89e1a9fbdbeb5fe2376e8bbff158ca
617,624
def index_to_word(searched_index, tokenizer): """ Takes an input integer index and returns the word it is mapped to. Args: searched_index: the integer index of the searched word tokenizer: the tokenizer which contains the word-index mappings Returns: word: the actual string word that the index is mapped to "...
b7a5c89f449eb9234e797edb9d776ad6c09e2e45
617,625
def _entity_type(value): """ Type function used for parsing --members/--entities arguments from colon-separated values into a list of (type, name) 2-tuples. """ entity_type, entity_name = value.split(':') return entity_type, entity_name
6d9cdfe77a135daa26968532fa95792837aba3e7
617,626
def euclidean(p1: tuple[int, int], p2: tuple[int, int]) -> int: """Calculate the distance between two points. Args: p1: First point. p2: Second point. Returns: The distance between the two points. """ diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] return (diff_x ** 2...
cd78ac92ff6792401a724247739ef6d0db825bb9
617,627
def is_ssl(socket): """True if socket is an active SSLSocket.""" return bool(getattr(socket, '_sslobj', False))
f330e717c340be7dad436c7561f6d7c2b875ebad
617,630
import mpmath def _butter_analog_poles(n): """ Poles of an analog Butterworth lowpass filter. This is the same calculation as scipy.signal.buttap(n) or scipy.signal.butter(n, 1, analog=True, output='zpk'), but mpmath is used, and only the poles are returned. """ poles = [] for k in ra...
6e044f83ec0e8732bfee4ae58744e0c7528232e4
617,633
def predict(X_test, model): """Predicts labels of X_test with a specific model Parameters: X_test - dataframe represents the test genomes features vectors model - the relevant model Returns: predictions - final predictions (0 - NHP, 1- HP) predictions_probs - probability estimates """...
269a025c7abeed49f64316b2460b26f876376065
617,634
def _is_secret_env(name): """Returns True if name might be a secret. Uses a simple heuristic to test for a secret name. """ name_lower = name.lower() secret_parts = ("password", "token", "secret") return any(part in name_lower for part in secret_parts)
0f1c9b9369bd02a86bf8493fc1b1aedc42271514
617,641
def did_gateway_mfr_test_result_include_miner_key_pass( gateway_mfr_test_result ): """ Returns true if gateway_mfr_test_result["tests"] has an entry where "test": "miner_key(0)" and "result": "pass" Input: { "result": "pass", "tests": [ { "output": "ok", ...
39d383d60eb2fbb9cf9ac7ee1ce38791ee39cbe3
617,642
def pkg_name(file: str) -> str: """Returns name of the package to which the `file` belongs. """ return __import__(file).__package__
4352807fcbe56f3dabfdb98cd9e63a3dd3ba50d0
617,643
def is_extension(filename: str, extension: str) -> bool: """ Return ``True`` if filename has the same extension as the target extension. Parameters ---------- filename: :class:`str` The filename that you want to compare with. extension: :class:`str` The target extension that...
f1779209d1e75d5efdff2801eb93116edb663e9c
617,644
def romaine_v1(string): """ (str) -> int Converts roman numerals to arabic numerals using string methods. Restrictions: string must consist of M, D, C, X, V, and/or I. Otherwise it will return 0 (which is to be expected anyway). """ string = string.strip() string = string.lower() no...
e79f16e5b5b9e3fa048650680d4b731a90e2ae7b
617,645