content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def blend_union(da, db, r): """ Blend union of the distances da, db with blend radius r. """ e = max(r - abs(da - db), 0) return min(da, db) - e * e * 0.25 / r
7128b3a78295da0a744046a0b76e466afbcf322d
625,894
def get_subplot_rows_columns_figsize(number_subplots): """Get the size of a sub plot in (rows, columns), based on the number of subplots that are going to be plotted. Parameters ----------- number_subplots : int The number of subplots that are to be plotted in the figure. """ if number_...
cb82db8dc7b22414c10d3c8957f6ab2ad44a1974
625,896
def combsort(array, scaling_factor): """ combsort(array, scaling_factor) -> list array -> [list]: A list of elements to be sorted using combsort scaling_factor -> [float]: A scalar that reduces the size of the gap every sweep (>1) """ steps = 0 gap = len(array) while ...
c576d7b2b776c82aa7246173714e22a951c05d20
625,901
def is_palindrome(n): """ Returns true/false if a number (or string) is a palindrome """ string = str(n) reversed_string = str(n)[::-1] length = len(string) for position in range(length): if string[position] != reversed_string[position]: return False return Tr...
06840ed167a0e52fcec818b8f5328f4e6ba8fed6
625,902
import re def modify_vars(vars_orig, var_modifiers): """Return a copy of `vars_orig` modified according to `var_modifiers`. Parameters ---------- vars_orig : list of str A list of variable names. var_modifiers : list of str or None, optional A list of variable modifiers. Each vari...
58f27e60b650a219abad70501e4573ab818b8450
625,903
def ck_cmd( msg, cmd ): """Checks if the first n characters of msg contain cmd. Should not contain the bot prefix when passed in. msg: String to search in.. cmd: String to search for.""" return cmd in msg[0:len(cmd)]
0aee1511d073dfab28c090b43443ef693f27fdee
625,904
def line_format(label): """ Convert time label to the format of pandas line plot """ month = label.month_name()[:3] if month == 'Jan': month += f'\n{label.year}' return month
9e3b953831bbfcf6c46a2026c96f4666ee8dacc7
625,905
import json def format_response(output_format, response): """Format the API response to the desired output format""" if not response.content: formatted = '' elif output_format == 'json': formatted = json.dumps(response.json()) elif output_format == 'pprint': formatted = json.du...
8522ea96c27e6ac5eba1416308e5b377c4ecef66
625,910
def websocketize(value): """Convert a HTTP(S) URL into a WS(S) URL.""" if not (value.startswith('http://') or value.startswith('https://')): raise ValueError('cannot websocketize non-HTTP URL') return 'ws' + value[len('http'):]
c7dd61d6e1bfbc685b4e55ad2f8e11027ece2e4c
625,914
def gradient_descent_momentum(grads, velocity, var_list, lr, mom): """Gradient descent with momentum update. Args: grads: List of gradients of the trainable variables. velocity: List of velocity of the trainable variables. var_list: List of variables to be optimized. lr: Learnin...
6ec886fc3faddeb42d2641ac480b467144899aab
625,917
from typing import List def find_duplicate_movies(filename: str) -> List[str]: """ Finds the duplicate movie titles from the given file. :param filename: str :return: list[str] """ with open(filename) as f: movies = f.readlines() seen = set() duplicates = [] for movie in m...
932beedcc84b283c18eaccc813285d9239a340be
625,918
import torch def energy(x: torch.Tensor, sps: float = 1.0): """Calculate the average energy (per symbol if provided) for each example. This function assumes that the signal is structured as: .. math:: Batch x Channel x IQ x Time. Args: x (torch.Tensor): Input Tensor (BxCxIQxT) ...
632009a1f35f470cb94dea4f88acd0036620d641
625,920
def get_primary_uri_field(fields): """Find the first field name containing URI""" for f in fields: if "URI" in f.field_name: return f return None
696ea1b15dad3c377585674100a12c128518c4c0
625,921
def make_iterable(obj): """Get a iterable obj.""" if isinstance(obj, (tuple, list)): return obj return obj,
a430443fd78d4d481892b2df47461e548f3463d4
625,922
def w020_from_defocus(radius, zi, deltaZ, wavelen=1.0): """Return the maximum wavefront error corresponding to defocus amount `deltaZ` Parameters ---------- radius : float The radius of the aperture in units of length (usually mm) zi : float Image distance (or the distance of th...
78cb6b684d5cb725f690bb0eb2f5b57f7ab6cb6e
625,925
def corrected_proj_param(big_H, lil_h, R): """ Eq. 4.11 Calculates the corrected projection parameter for a cloud target Parameters ------------ big_H : int Satellite's height above the Earth's surface, in km lil_h : int Cloud's altitude above the Earth's surface, in km ...
ff447c88449a5c1a92eb9bccc9231ff1f76233c6
625,930
def get_captcha_image_element(form): """ Return the <img> element in an lxml form that contains the CAPTCHA. NOTE: This assumes the first image in the form is the CAPTCHA image. If a form has multiple images, maybe use the etree .sourceline attribute to figure out which image is closer to the CAPTC...
95e1edfa21458f1ed6a79d200fabe6cc75b0cc55
625,933
def floor_div(arr, val): """ Floor division of array by value. """ return [i // val for i in arr]
270d2eb53a288773a36d9cb90b44ecf8f421a34f
625,938
def keep_never_expires(flags): """Filter flags to contain only flags that never expire. >>> keep_never_expires([{'expiry_milestone': -1}, {'expiry_milestone': 2}]) [{'expiry_milestone': -1}] """ return [f for f in flags if f['expiry_milestone'] == -1]
1da445b0b5f085b338e3b62c7c260a46ffcba1e9
625,941
def rk4_step(u, f, dt, *args): """Returns the solution at the next time-step using the RK4 method. Assumes that f is time independent Parameters ---------- u : array of floats solution at the current time-step. f : function function to compute the right hand-side of the sys...
dfc8b64cebf2369ffd0020521782be9028900bfa
625,945
def is_pr_comment(event): """Determine if a comment applies to a pull request.""" try: right_type = event.type == 'IssueCommentEvent' right_payload = 'pull_request' in event.payload['issue'].to_json() return right_type and right_payload except (KeyError, IndexError, AttributeError, T...
6644526d27f4d15c501da8617ad90f82993156fc
625,949
import hashlib def hash_password(password, salt): """ Securely hash a password using a provided salt :param password: :param salt: :return: Hex encoded SHA512 hash of provided password """ password = str(password).encode("utf-8") salt = str(salt).encode("utf-8") return hashlib.sha5...
376c28e92d4336ce7c8930289e281d3bb1f10623
625,951
def frange(start, end, n): """frange(start, end, n): Python's range(), for floats and complexes.""" # If the arguments are already float or complex, this won't hurt. # If they're int, they will become float. start *= 1.0 end *= 1.0 step = (end - start) / n list = [] current = start for k in range(0, n): ...
1d1257ab24688a957b7071731299695fbc9ea0df
625,954
def matchStrengthNoNoise(x, y, n): """Compute the match strength for the individual *x* on the string *y* excluding noise *n*. """ return sum(xi == yi for xi, yi, ni in zip(x, y, n) if ni != "#")
561c8e810249de043cde8b56e638df9db0ff40b8
625,956
def gap_detector(data, mask, start_pixel, width_gap): """ Reproduce a detector gap in reciprocal space data and mask. :param data: the 3D reciprocal space data :param mask: the corresponding 3D mask :param start_pixel: pixel number where the gap starts :param width_gap: width of the gap in pixe...
0e480886ea812071726372a9d4a3052cb577c05d
625,958
def is_reserved_node(node): """ Return true if the node is reserved. """ reserved_title = node.title and '[Reserved]' in node.title reserved_text = node.text and '[Reserved]' in node.text return reserved_title or reserved_text
57c31957b165d60b3e47b33897b9f4005dcac2b1
625,960
def third_measurer_I_P(uniqueTuplesDf): """ third_measurer_I_P: computes the measure I_P that counts the number of problematic tuples (tuples participating in a violation of the constraints). Parameters ---------- uniqueTuplesDf : dataframe the result of the query that finds all tu...
0e5f1d4802fdd7b680a77fc227c48d45ca31e2e2
625,961
def key_to_option(key): """Convert a dictionary key to a valid command line option. This simply replaces underscores with dashes. """ return key.replace('_', '-')
93a01aa1177ad87eb55fe1623181c0874659568c
625,964
from typing import Union from typing import Any import json import logging def load_json(s: Union[str, bytes]) -> Any: """ Like json.loads() but prints the input if parsing fails """ try: return json.loads(s) except json.decoder.JSONDecodeError: sep = "----------------" log...
2cf71a8c65c5548fc650948e9605d96463209353
625,966
def nlopt_status(constant): """ Convert the enumerated constant returned by the optimization process into a human-readable string. Input ----- constant : ``int`` The constant returned by the optimization algorithm as result. Returns ------- status : ``str`` A human-read...
27eee0b0ce8955ba463845c20d07b8289764945a
625,967
def render_no_change(text): """Render inline markdown text with no changes """ return [text]
18dd284ad5986de270a6dfc552f1fc105c36e3a2
625,968
def join(separator: str, separated: list) -> str: """ >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' >>> join("#", "a") 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' >>> join("#", ["a", "b", "c", 1]) Traceback (most ...
4762f6ca96ff69211035dbaa31969406b80f262e
625,972
def update(event, context): """Noop.""" return event["PhysicalResourceId"], {}
2d897160c7342ebfdf56fe0a3fd1cbc1b3f33790
625,973
def _get_opt_attr(obj, attr_path): """Returns the value at attr_path on the given object if it is set.""" attr_path = attr_path.split(".") for a in attr_path: if not obj or not hasattr(obj, a): return None obj = getattr(obj, a) return obj
db7662f11074e501a2342a038326d633010d1cb6
625,974
import random def randomized_primality_test(n, k): """ Checks if n is a prime number using probabilitic methods. In particular, this function uses Fermat's primality test. See http://en.wikipedia.org/wiki/Fermat_primality_test for a description of the method. Args: n: int, number to test...
d7625531dc93e72f9a2c63f843ad9bd08673d50b
625,976
import math def sqrt(x): """Returns square root of x value""" return math.sqrt(x)
4252f3d464250cd8f63412473f5707ccdfcec95b
625,978
import pickle def load_synthetic(name, datadir): """ Loads data from pickle file with the given name (produced by save_synthetic function) :param name: name of the pickle file in datadir containing the expression data :return: np.array of expression with Shape=(nb_samples, nb_genes) and list of gene s...
cabe16e50f4cc72e42ef3f7ac8ee23f98872ff10
625,980
def net_addr(addr): """Get network address prefix and length from a given address.""" if addr is None: return (None, None) nw_addr, nw_len = addr.split('/') nw_len = int(nw_len) return nw_addr, nw_len
11d4b798338d88a1348ef8efd82fbc3b49b9eb7f
625,985
def kw_bigram_score(concept, segment): """ Rank the segment using the key word search algorithm :param segment (list): a list of the tokens in the segment :param concept (str): the concept :return: a numeric score of the number of occurences of the concept word normalized by document length """ ...
353692bd932eccc46bd6fd6e316f6919ab810d1f
625,988
def even_or_odd(number): """Return 'Even' or 'Odd' if number is even or odd.""" if number % 2 == 0: return "Even" return "Odd"
bbc2acf702598943f3df7c49ccd6484d00578908
625,989
def _winpath_to_uri(path): """Converts a window absolute path to a file: URL.""" return "///" + path.replace("\\", "/")
8a35cbc43ee05ea9566910b49ef6c682aad06bb1
625,990
def get_gq(df): """ Calculate GQ """ pl_arr = df[['PL_ref', 'PL_het', 'PL_hom']].values pl_arr.sort(axis=1) gq = [(row[1] - row[0]) for row in pl_arr] return gq
45a2c1666c86a31ffdc7107e890ca1192c76ecbd
625,991
def binary_search(sorted_arr, wanted_num): """ Szuka elementu w posortwanej tablicy, jeżeli znajdzie to zwraca indeks szukanego elementu. W przypadku nie znalezienia elemetu zwraca -1.""" left = 0 right = len(sorted_arr) - 1 mid = 0 while left <= right: mid = (right + left) // 2 if ...
fc3abd941bc134effc3ce8bbe741ee3a92ea6386
625,992
def check_for_period(message): """Check that there is no period in the end of the subject line.""" splitted = message.splitlines() check = not splitted[0].endswith(".") return check
2a59f787f92c51a288873d6d1e6bb24b40db3848
625,993
def str2bool(val): """ Convert the strings "True" and "False" to the booleans True and False. """ if val == "True": return True elif val == "False": return False else: raise Exception("unknown string for bool '%s'" % val)
1121ea8080b1cebab098c612f5b48c032080d412
625,997
def GetTokensInSubRange(tokens, start, end): """Get a subset of tokens within the range [start, end).""" tokens_in_range = [] for tok in tokens: tok_range = (tok.lineno, tok.column) if tok_range >= start and tok_range < end: tokens_in_range.append(tok) return tokens_in_range
3f745d476530c17e9c407a0e4a563897cd0d78ad
626,001
def metadata_filter_as_dict(metadata_config): """Return the metadata filter represented as either None (no filter), or a dictionary with at most two keys: 'additional' and 'excluded', which contain either a list of metadata names, or the string 'all'""" if metadata_config is None: return {} ...
b851fdfc759f89571d1b39cf34d82122ad3a3e40
626,004
def unpad(text): """ Unpads the text from the given block size. :param text | <str> :return <str> """ return text[0:-ord(text[-1])]
5b992062cb85374a62b839ba53f5c110ff4aeab0
626,006
def get_reverted_disk_rses_id_name_map(disk_rses_id_name_map): """Revert k:v to v:k""" return {v: k for k, v in disk_rses_id_name_map.items()}
51ea8b84a5d23f365b3e6a182b62ca586dae7009
626,008
def print_name(name, word_count_threshold=7, break_point_ratio=0.6): """Splits name of item in legend into 2 lines if word count exceeds threshold""" words = name.split(" ") word_count = len(words) if word_count > word_count_threshold: position = round(word_count*break_point_ratio) ...
4312c9c5b4c34329ff2ac4d49d27dfae70fee1b1
626,010
import ipaddress def netmask_to_prefixlen(netmask: str) -> int: """ Takes an IP netmask and returns the corresponding prefix length :param str netmask: IP netmask (e.g. 255.255.0.0) :return: prefix length """ return ipaddress.ip_network('0.0.0.0/{}'.format(netmask)).prefixlen
890e5f5f480ad22605853a4d8fa40ce76368312d
626,012
def GetBuilderSuccessMap(builder_run, overall_success): """Get the pass/fail status of all builders. A builder is marked as passed if all of its steps ran all of the way to completion. We determine this by looking at whether all of the steps for all of the constituent boards ran to completion. In cases wher...
66779a5530810dce8562e39f39858eab0d5fedf6
626,015
def find_versions(dependencies, heuristics): """ Try to find version information by calling a series of functions in turn. *dependencies*: a list of Dependency objects. *heuristics*: a list of functions that accept a component as the single argument and return a version number o...
71784a084230d6d24e38cbca0537515d377997e1
626,018
def preprocess_input(cin: str): """ Maps user input into matrix indexes Parameters ---------- cin : str For example F5 Returns ------- If the case was F5, it will return 4, 5 """ letter = cin[0] number = int(cin[1]) d = {'A': 0, 'B': 1, 'C': 2, 'D': 3,...
54a85b79b8b1bb49d740d78a0a3894c203c82b6a
626,019
from typing import Iterable from typing import Any from typing import Iterator import itertools def flatten(iterables: Iterable[Iterable[Any]]) -> Iterator[Any]: """Flatten an iterable of iterables into one consecutive iterator. Only flattens one level (i.e., items which are themselves iterable will be u...
0e7c562314b726ab0f5379ce64584c5bca00db1c
626,020
def _list2str(array): """ Join a list with spaces between elements. """ return ' '.join(str(a) for a in array)
722ece18cb869a6801761c7550e5ecc5c6d4b19a
626,024
def check_if_tuple_exists(cursor, table_name, kennziffer, year): """ Checks if the tuple is already in te DB. :param cursor: for the db to check :param table_name: name of the table to check in :param kennziffer: this value is checked :param year: this value is checked :return: True if the t...
ae6bf3c4dab0e98ef01c0e1fcee7de351f66b0cd
626,026
import math def get_square_subplot_grid(n): """Get a (h, w) square arrangement for any number of subplots.""" side = math.ceil(n ** .5) return side, side
70d4c80758326bb15d5c4141713afdf3feb1c576
626,027
import hashlib def hash_file(path): """Hashes a file specified by the path given and returns the hex digest.""" # If the hashing function changes, this may invalidate lots of cached data. # Don't change it lightly. h = hashlib.sha1() with open(path, 'rb') as fh: while True: d...
6191518a89e5263c4e944f8c6c17fb1193dac1cd
626,028
def whitelist(d, fields): """Whitelists a dictionary by keeping ONLY the selected `fields`. Non-destructive (creates and returns a new dict).""" ret = type(d)() for f in fields: if f in d: ret[f] = d[f] return ret
833d403dd228da5ee00a3741ab77ecb4ad52ef88
626,029
def getCentroids(proptable): """ Returns labeled object centroids and labels in a dictionary. Parameters ---------- proptable : pd.DataFrame labeled object properties with centroid & label columns Returns ------- props_dict : dict Dictionary with 'centroids' and 'l...
46d6ab7a1350abc24d2745e578441b712e71101b
626,032
import re def remove_tags(html): """ Function will clean html by removing html tags leaving behind plaintext. Args: html (string): The html to be cleaned Returns: (string): The plaintext """ # return BeautifulSoup(html, "lxml").text html = re.sub("<[^<]+?>", "", html) h...
307b9db48b54abdcd0380a427b18c77d275b206d
626,033
def all(f, iterable) -> bool: """ If all the conditions are True then return True, otherwise return False at the first failiure""" for e in iterable: if not f(e): return False return True
cb6b7d2d6b4a670012635c50c4c79b8ddacf124d
626,039
def get_cve_id_from_vuln(vuln): """ Returns CVE ID from vulnerability document When there is no CVE, returns "No-CVE" string """ return vuln.get('cve_id', "No-CVE")
a0f2162a02e18e0e322f706662de86bc654b3927
626,040
def _flatten_nested_list(x): """ Flatten nested list Argument -------- x : list nested list with different leveling of different objects Returns ------- flatten version of list """ out = [] for xi in x: if type(xi) is list: out += _flatten_nested...
88bf948dbd97af26e73e6c2830a1b99ec335acc0
626,042
def is_spoiler(message_text: str, link: str) -> bool: """ Finds the given link in the message and tells if it's inside spoiler tag or not. """ link_pos = message_text.find(link) spoiler_tags_count = message_text[:link_pos].count('||') return spoiler_tags_count % 2 == 1
73a7502d5ade68fba9f330e3bfeffc694567e3cd
626,044
def u_func(h, c, par): """ Cobb-Douglas utility function for consumption and housing quality Args: h (float): housing quality and equal to housing price c (float): other consumption par: simplenamespace containing relevant parameters phi (float): C-D weights ...
4396740a793e0d37328bfc89ae9ea9f029b0e2d3
626,050
def get_package_name() -> str: """ Get name of the package. """ return __name__.split('.', 1)[0]
7890a0cb7eb2a5f89317304ef318fde0a8e26942
626,053
import calendar def nthday(nth, day, mdate): """Calculate the Nth day of the month""" # Generate calendar cal = calendar.monthcalendar(mdate.year, mdate.month) # Get all the specified days days = [week[day - 1] for week in cal] # Remove any zeros (zeros indicate that week doesn't include that ...
7a5afdab06e754f79a6e1c794863f9aea412dde4
626,054
from typing import Tuple def precisionRecallF1(correct: int, extracted: int, groundTruth: int) -> Tuple[float, float, float]: """ Calculates metrices. :param correct: Number of correct keywords. :type correct: int :param extracted: Number of extracted keywords. :type extracted: int :param...
e35b2bbeef22e3eeace40484544fc08dc528f13d
626,059
def count_object(network, class_ids, scores, bounding_boxes, object_label, threshold=0.75): """ Counts objects of a given type that are predicted by the network. :param network: object detection network :type network: mx.gluon.nn.Block :param class_ids: predicted object class indexes (e.g. 123) ...
31dd31319a6d579d98929ec9a57892a560b058f3
626,060
def strike(text: str) -> str: """Make text to strike.""" return f'~{text}~'
89f83b130e3650ef5f96355329f103ba4f609a46
626,061
import colorsys def hls_to_rgb(hue, saturation, lightness): """Convert HSL back to RGB.""" t = colorsys.hls_to_rgb(hue, saturation, lightness) return tuple(int(round(x * 255)) for x in t)
5fe8cb1def731ab5fa00fbb4db7c1e853685febf
626,062
def runCode(instructions, executed, current, acc, change): """Executes the given list of instructions. Each instruction has an integer value to be used for its function, this can be positive or negative. Supported instructions: * acc: adds its integer value to the accumulator value * j...
da7e756b9688bd3f17511e9b877d3ba6f1dd118b
626,063
def _rgba_to_rgb(im): """ Drops the alpha channel in an RGB image. """ return im.convert("RGB")
b49916b826629e0be231dc5993c7563e4d94424d
626,065
from typing import Callable from typing import Optional from typing import Tuple from typing import Any from typing import Union import time def combined_timeout( func: Callable, timeout: Optional[float] = None ) -> Tuple[Any, Union[float, None]]: """Call func(timeout) and return reduced timeout for subsequen...
5edf16e2288ac4536eb111e78b90639fc4b0f5bc
626,069
def plotwidth(figure, nrows, ncols): """Calculate the plot width of the figure, assuming square subplots. Does this by calculating the height per plot and multiplying by number of columns. """ height = figure.get_figheight() / nrows return height * ncols
ab6bf687357717157c319cffe2918a7ac2775302
626,071
def first_translatable(store): """returns first translatable unit, skipping header if present""" if store.units[0].isheader() and len(store.units) > 1: return store.units[1] else: return store.units[0]
483380882efe037e89098275cabf870f9302f61e
626,074
import torch def batch_center_mask(img_size, num_pixels, batch_size): """Masks all the output except the num_pixels by num_pixels central square of the image. Parameters ---------- img_size : see single_random_mask num_pixels : int Should be even. If not even, num_pixels will be repl...
978708db1c209ae0e3493d2e2d256e1f7f0a0b76
626,077
def check_date(date: str, text: str) -> bool: """ Compares the date in the card with the specified date. """ return date == text[:len(date)]
54ed8f29a87c5b000b790b14231a9a6107addc4e
626,078
def left_pad(string, length, character=" "): """Left pad a `string` to `length` characters with `character`.""" if not isinstance(string, str): string = str(string) if not isinstance(character, str): character = str(character) return string.rjust(length, character)
8b55c3527d7653b89cc1c55642c95d19e640f166
626,080
def _count_enabled_bits(hexstr: str) -> int: """Parse a raw value like f202 to number of bits enabled.""" if hexstr == '': return 0 value_int = int(hexstr, 16) enabled_bits_count = bin(value_int).count('1') return enabled_bits_count
79513d1562c398eb66a0112728bba6e656009f5a
626,085
def compress_dna(text: str) -> int: """Compress a DNA string into a bit string Arguments: text {str} -- DNA string to compress Returns: int -- integer bit-string representing DNA Example: >>> compress_dna("ACGT") 283 """ bit_string = 1 for nt in text...
218cd554bd143a93905f406369dca14a8be61aa4
626,086
def get_quad_tag_parts(reftag:str): """ Return a 4-tuple given a tag """ # Split tag into parts tag_parts = reftag.split("/") if len(tag_parts) < 3 or len(tag_parts) > 4: return None, None, None, None tag_prefix = tag_parts[0] tag_context_name = tag_parts[1] tag_value_name...
40d20c75625da3440484c707b6507964eca441df
626,087
def convert_bool(s): """Convert pseudo-boolean string values into Python boolean. If given argument is any of '1', 'enable', 'on', 't', 'true', 'y', or 'yes' it is considered True, else False. """ return s in ('1', 'enable', 'on', 't', 'true', 'y', 'yes')
4c3b15ac960a71861f33c99f2af5c415824f1108
626,088
def gain_cal(Tlna, Tf, R1, R2, R3, R4, R5, Tp, Fghz, TP4corr): """ Computes minical parameters from minical data This uses the Stelreid/Klein calibration algorithm Stelzried and Klein, Proc. IEEE, 82, 776 (1994) to compute B, BC and CC, as well as Tnd. The true gain is B ( BC*R + B*CC*R^2 ) @type Tlna...
cc5bc5ff40887f77c3eb3ffb27af7a6544bf89f8
626,089
from typing import Tuple from typing import Callable from typing import Optional import inspect def import_function(path: str) -> Tuple[Callable, Optional[type]]: """Import and evaluate a function. If the function is defined in a class, evaluate the class additionally. Args: path (str): The path ...
a5acb81a98e723951c330a51553bdbf105affaf5
626,092
def split_datetime(dataframe): """ Split the date-time feature of a dataset into date and hour Parameters ---------- dataframe : dataframe, shape(n_samples, 64), the full dataset Returns ------- dataframe : the dataframe with the date-time feature split into...
e6d17cf2882e20b1d2632539f947348f1b386d56
626,093
import requests def get_versions_from_devpi(url): """ Get list of versions for package from devpi server. :param url: package url :type: str :rtype: list """ response = requests.get(url, headers={'Accept': 'application/json'}) if not response.ok: return [] payload = respo...
e3ead228648ad8ad5ed9ef54e86aa2674f88d8a3
626,099
def binary_search(listData, value): """inputs: sorted array, value outputs: value if it is in the array, -1 otherwise efficiency: O(log(n)) method: Find mid value of array; return value if equal to given value. Perform same procedure on portion of list before or after mid value, depending on...
2578255135dc7c682d9e2c147110d4cf957fda72
626,102
def create_test_docs(count): """Produce some test documents.""" def doc(i): return '{"name": "name", "_key": "%s", "is_public": true}' % i return '\n'.join(doc(i) for i in range(0, count))
4393776f1f3998fb768026ee1fe75043b25628cf
626,109
def class_name_to_function_name(name): """Convert a python class name in CamelCase to a lower case function_name with underscores.""" function_name = "" for char_idx, char in enumerate(name): if char == char.upper() and char_idx > 0 and name[char_idx - 1] == name[char_idx - 1].lower(): f...
64bc6303053821c4778a6d0f9205dc735e1fc334
626,115
def _trace_mm(x, y): """ Computes ``trace(x.T @ y)``. """ assert len(x.shape) >= 2 assert len(y.shape) >= 2 return (x * y).sum((-1, -2))
ef6abd1bab214c1adc7be7683e822c7fd1fb1c8c
626,121
from bs4 import BeautifulSoup def parse_xml_response(response): """Parses XML response to Python dict Parameters ---------- response : str XML string response from Regon API operation Returns ------- dict XML data converted to dict. Raises ------ TypeError ...
fe46fc432559e542196d9898e7ba37d36694cebf
626,122
def find_divisors_v1(n): """Finds all divisors for a given number 'n' different than that number.""" if n == 1: return [1] return [x for x in range(1, n) if n%x == 0]
8ac88a66b90e9c85a6d8c341f25c03ae8fefed29
626,125
import random def uniform_sequence(n): """ Return sample sequence of length n from a uniform distribution. """ return [ random.uniform(0,n) for i in range(n)]
829d9fdad25cfa4f58cd15b695de7b9cfaf52cf3
626,133
from io import StringIO import tokenize def is_full_statement(*lines: str) -> bool: """ Check if a set of lines makes up a full python statement :param lines: list of line of python code :return: True if line in `lines` made up a full python statement """ try: stream = StringIO() ...
834a167fd74459dfede56e4cfbdaec1b51f2344b
626,135
def _pd_df_cols_match_metadata_cols_ordered(df, table_metadata): """ Are the columns in the metadata exactly the same as those in the dataframe i.e. same columns in the same order """ pd_columns = list(df.columns) md_columns = [c["name"] for c in table_metadata["columns"]] return pd_column...
073fd669de75cac73093c8c8112963bfb999477a
626,137
def map_orb(orb, nbasis): """Map spin orbital to spatial index.""" if orb // nbasis == 0: s = 0 ix = orb else: s = 1 ix = orb - nbasis return ix, s
091d44e45825b3d4fd9213e138d87a0d5e194fc9
626,138
def factorial(n): """ Return the Factorial of a number using recursion Parameters: n -- Number to get factorial of """ if not n: return 1 return n*factorial(n-1)
266fb83622a7ac050c7d2406aca222854de8004f
626,139