content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def script_guard(line): """Detect the idiomatic trick C{if __name__ == "__main__":}""" return (len(line) == 5 and line[1][1] == '__name__' # this is the most selective and line[0][1] == 'if' and line[2][1] == '==' and line[4][1] == ':' and line[3][1][1:-1] == '__main__')
dd34af72e172470d8d88aa001854b69289c1dc89
593,570
import math def round_up_to_multiple(n, unit): """Round ``n`` up to a multiple of ``unit`` Round ``n`` (a positive or negative number) away from zero, so that ``result % unit == 0``. In other words, the return value will be an exact multiple of ``unit``. >>> round_up_to_multiple(14, 4) 16 ...
fe48366d1e07be91230f1118c1d0b6b8b0a33025
593,572
def get_available_metrics() -> list: """Get list of available metrics.""" metrics = [ "NSE", "MSE", "RMSE", "KGE", "Alpha-NSE", "Pearson r", "Beta-NSE", "FHV", "FMS", "FLV", "Peak-Timing", ] return metrics
f872fa5411b2038ee2ccdd153508fd7d0acabdc5
593,576
def missing_explanation(json): """Returns false if all recommendations have an explanation. Returns errormessage and status code if not.""" for recommendations in json.values(): for rec in recommendations: if 'explanation' not in rec: return 'Recommendations must include ...
54d390b5f8e202afae2a90743d66e27dfc083bc1
593,577
import math def count_lattice_paths(n): """ Counts the total number of possible routes in an `n`x`n` grid from the top left to the bottom right moving only down and right. """ return int(math.factorial(2 * n) / math.factorial(n)**2)
6cf2272865e5f74b7ba511c76e56910b55a768c1
593,582
def _find(shapely_point, regions_dataframe): """ Find the regions that contains a Point. Args: shapely_point: A shapely.geometry.Point instance that holds the position in longitude and latitude regions_dataframe: pandas.DataFrame containing a NUTS or LAU table. Returns: ...
65400cefc3a291a1e09a845f2017c1d47a3b1efd
593,583
def lookup_label(label, symtable): """Label lookup with user-friendly exception.""" if label not in symtable: raise Exception("Undefined label '%s'" % label) return symtable[label]
97c97e4115d1032e154f611ec453e4014c47f62a
593,584
def split_class_and_test_names(nodeid): """Returns the class and method name from the current test""" names = nodeid.split('::') names[0] = names[0].replace('/', '.') names = [x.replace('.py', '') for x in names if x != '()'] classnames = names[:-1] classname = '.'.join(classnames) name = na...
048e5d79a1f51b7cca13b590945d549ce87bdc13
593,585
def get_hashtag(tweet): """ Get hashtag of a tweet. :tweet: string. :return: hashtag or empty string. """ hashtag = "" idx_of_tag = tweet.rfind('#') if idx_of_tag is not -1: idx_of_tag_end = tweet.find(' ', idx_of_tag) if idx_of_tag_end is -1: # hashtag is the last word...
41ef05695ef6965ed396ff7ab2e32751a28e6291
593,586
def distance_squared(x1, y1, x2, y2): """ Helper function to return the square of the distance between points (x1,y1) and (x2,y2). :Parameters: x1: float X coordinate of first point y1: float Y coordinate of first point x2: float X coordinate of second point ...
66fead189b9b1984adf5d4dc24dc57c27cf6a2d9
593,587
def sra_blast_hits_count(cxn, iteration): """Count the blast hits for the iteration.""" sql = """ SELECT COUNT(*) AS count FROM aux.sra_blast_hits WHERE iteration = ? """ result = cxn.execute(sql, (iteration, )) return result.fetchone()[0]
5f9bed038fe9477afa8c5482668314eb45eb9926
593,591
import re def extract_type(name: str) -> str: """If the argument is the name of a method (of form C.m), return the type portion in quotes (e.g. "y"). Otherwise, return the string unmodified. """ name = re.sub('^"[a-zA-Z0-9_]+" of ', '', name) return name
71b59186be3037002cb0bcb670d2b7234ace2dfc
593,592
def get_scale_for_nth_feature_map(k, m=4, scale_min=0.1484375, scale_max=0.75): """Calculating scale value for nth feature map using the given method in the paper. inputs: k = nth feature map for scale calculation m = length of all using feature maps for detections, 6 for ssd300, 4 for blazeface...
1bca0c6c7309d3cb87e9a4ac17712d416cedfdcc
593,593
import psutil import socket def get_ip_interface(ifname): """ Get the local IPv4 address of a network interface. KeyError is raised if the interface doesn't exist. ValueError is raised if the interface does no have an IPv4 address associated with it. """ net_if_addrs = psutil.net_if_addr...
ba55914586e05a7707825d10907dec8430f071fb
593,595
import math def py37_isqrt(n): """Return largest integer r such that r^2 <= n""" if n < 10000000000000000000000: # trial and error return math.floor(math.sqrt(n)) else: # https://stackoverflow.com/a/53983683 if n > 0: x = 1 << (n.bit_length() + 1 >> 1) whil...
7f5a93f8b8db5ecfc49c239343fb679063ea0534
593,596
from typing import Generator import re def _iter_string(version_string: str) -> Generator[int, None, None]: """ Iterate over the version elements from a string. :param version_string: The version as a string. :return: Iterable elements of the version. """ return (int(x) for x in re.split("[.,]", version_stri...
c1db42a2992fdb08a695bf43076014043eaf2ef6
593,600
def rchop(in_string, ending): """ Strip a matching end pattern from a string. """ if in_string.endswith(ending): return in_string[:-len(ending)] return in_string
ac68dc6500dc9231c2b881251e0abe1ae34644d2
593,604
def verify_interface_enabled(netbox_interfaces, pyats_interfaces): """Verifies whether the current interface state matches what's in NetBox Args: netbox_interface: Interfaces for a given device in NetBox pyats_interfaces: Current interfaces on a device Returns: results: Dictionary ...
e20cf20e0f1fdcc518a1b78b8ff9148a3adc0f2d
593,605
from bs4 import BeautifulSoup def find_company_indeed(card: BeautifulSoup) -> str: """ Processes an individual job card to find the name of the company that posted the job. Args: card (BeautifulSoup object): A BS4 object consisting of the section of the HTML doc result for a ...
6dd5b3977e31668cdc973bcf46788f3c0bdadb0c
593,608
import random def simulate_sensors(prev, stdev, min, max): """Gaussian distribution for simulated sensor readings.""" delta = random.gauss(0, stdev) new = prev + delta if new < min or new > max: new = prev - delta return new
4692d2d11f879256e6b76b70582f1ca7f56e236f
593,609
def _create_task_dict(options): """Creates a dict representation of the requested task.""" params = {} params['lunch_target'] = options.lunch_target params['mmma_targets'] = options.mmma_targets params['issue'] = options.issue params['patchset'] = options.patchset params['hash'] = options.hash return pa...
c44247deb5f04571246d108bf3deaa5bd985c177
593,612
def bin2dec(string): """Convert a binary string to decimal number""" return int(string,2)
079a2d0da977a28984b30a189f4852dabc88e7cc
593,614
def get_pairs_list_from_names_values(names, values): """Return a list of pairs from list of keys and list of lists of params e.g. names = ['a', 'b', 'c'] values = [1, 2, 3, 4, 5, 6, 7, 8, 9] return: [('a', 1), ('b', 2), ('c', 3), ('a', 4), ('b', 5), ('c', 6), ('a', 7), ('b', 8...
73675a924d9eefb62eb5eb8fbf067ca60e814427
593,615
def stdDistortion(a,b): """Returns `std(b/a)`""" return (b/a).std() # include the sign
5a4115db4ca44439e45bf900f63071c419f66050
593,616
def clean_uid(uid): """ Return a uid with all unacceptable characters replaced with underscores """ if not hasattr(uid, 'replace'): return clean_uid(str(uid.astype('S'))) try: return uid.decode('utf-8').replace(u"/", u"_").replace(u":", u"_") except AttributeError: return...
479384a6afc948e8fe5ea833478a2889f7aa2fc1
593,619
import requests def check_url_status_code(url: str, cookies: dict = {}, headers: dict = {}, desired_status_code: int = 200) -> bool: """ Check the status code for a given url when requested :rtype: bool :param cookies: dict, headers to pass to the requests.head call :param headers: dict, cookies t...
e9d275029668fa27965a5382e4626210d04bcba9
593,622
def _calc_gfloat_params_backward(op, *grads): """Gradients for the CalcGfloatParams op.""" return None
01ad275e92ba829aa05eef38e831f81cc1d59999
593,624
def sanitize_tf_resource_name(name): """Sanitize concatenated name for terraform resource names""" return name.replace(".", "-").replace("_", "")
c719ff039ea069c6dd49928039798fb7537eaf96
593,625
def get_coin_from_file_name(fname): """ Identifies the coin under analysis from the data dump file name. :param fname: file name :return: str, coin name """ if "litecoin" in fname: return "litecoin" if "cash" in fname: return "bitcoincash" if "bitcoin" in fname: ...
c2dac7023a5690aee2896c42632a5f707d8b8eab
593,626
def deltaf(series, baseline): """calculate deltaf over f for a signal (1D array)""" deltaf = series - baseline return deltaf / baseline
06899e35b6229aca983bdc01207bddba53b56c6f
593,627
def get_input (question, valid): """Asks a user for input till valid response""" s = "{} [{}]: ".format(question, valid) val = input(s) while val not in valid or len(val) == 0 or val == valid: print("Not a valid answer [{}]".format(valid)) val = input(s) return val
e3ae87d877ea94bc7ac47df09a819b33d506d3d1
593,630
import re def __get_driver_series_tag_text(tag): """ Returns the driver series number from the given HTML tag Keyword Args: tag -- Device driver section header tag """ driver_regex = re.compile('[0-9]+\.?[0-9]*\.?[0-9]*') match = driver_regex.search(tag.text) if match: match_t...
2d93b36746b6fe755b08783cc779f48e76938ba2
593,632
def retr_kpath(xtalstr,ini0): """ Retrieve the kpath """ ini0["kpath"] = xtalstr.kpath ini0["kpath_label"] = xtalstr.kpath_label return ini0
5e6f54b831166ff21bc6e625769f7b3e1f57539f
593,633
def equil_replicate_set(job): """Check if number of equil replicates done has been set.""" return isinstance(job.doc.get("equil_replicates_done"), int)
35a9dd6100c6c27b869ea7f3633b92ce775001f8
593,635
import re def clump_fractions(s): """ Replaces the whitespace between the integer and fractional part of a quantity with a dollar sign, so it's interpreted as a single token. The rest of the string is left alone. clump_fractions("aaa 1 2/3 bbb") # => "aaa 1$2/3 bbb" """ return...
acd37ade270556b9894c1b56947f6b4eef0c093a
593,637
def mse_loss(linear_o, y): """Returns a vector of mean squared errors of each object. Given a vector of linear ouputs a vector of ground truth target values y returns squared residuals. Linear outputs can be e.g. <w, x_i> + b. """ return 0.5 * (linear_o.flatten() - y.flatten())**2 / linear_o.si...
d31d8eb59bb24574ac9cc8c3e1d32d071c2e73bf
593,642
def impedance(vp,rho): """ This function calculates an impedance value """ ai = vp*rho return ai
7e843e6b4ed1a78b1e19c289cd71827449ccd613
593,647
def example4(S): """Return the sum of the prefix sums of sequence S.""" n = len(S) prefix = 0 total = 0 for j in range(n): prefix += S[j] total += prefix return total
b0a70831adcff8a72cb92751f5974f4722d98457
593,649
def parse_field_table_column(coldef): """Parse the input field table column definition. Return dictionary with identifier, type and options (if any). """ parts = [p.strip() for p in coldef.split(';')] if len(parts) == 1: return {'identifier': coldef, 'type': 'string'} else: resul...
c073eec1b66ff177febe2b802e03207511175516
593,650
def parse_accept(accept): """Parses the Accept header sent with a request. Args: accept (str): the value of an Accept header. Returns: (list): A list containing the MIME types that the client is able to understand. """ return accept.replace(" ", "").split(",")
c7c9b6e1806b98fda3d91e71b1d6b364bf02050a
593,652
def take_0_k_th_from_2D_list(obj_list, k=0, verbose=False): """returns the element obj_list[0][k] if obj_list is a nested list of depth 2, or obj_list otherwise.""" if isinstance(obj_list, list): if verbose: print("obj_list is:", obj_list) if isinstance(obj_list[0], list): ...
0d45ebb00c9620c4b423a30aec04fe815d0c94ea
593,653
import re def read_version (CMakeLists): """ Read version from variables set in CMake file Parameters ---------- CMakeLists : CMake file path Returns ------- version : tuple Version as (major, minor, revision) """ major = re.compile(r'set\s+\(RFBP_MAJOR\s+(\d+)\)') minor = re.compile(r'set...
26853170e328274e6e57c8b80852376b1acf6184
593,657
def datetime_to_iso(date): """ convert a datetime object to an ISO_8601 formatted string. Format of string is taken from JS date to string """ return date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
29768984b64f1c66c5d9ee809058d352927c5658
593,660
import uuid def base_regional_data_file_data(fake_file_name, regional_user): """Return data file creation data without a file.""" return { "original_filename": fake_file_name, "slug": str(uuid.uuid4()), "extension": "txt", "section": "Active Case Data", "user": str(regi...
5586b8e8781174b66a99f53a05433d192815bff2
593,663
def remove_quotes(string): """ remove all (double) quotes""" return string.replace("'", "").replace('"', '')
3f0b5a6afe50f261bd2563c6ae4165bfd2481c0e
593,664
def eng_notation(x): """Converts number to string in engineering notation. Returns a formatted string for numeric value |x| rounded to an int in quasi-engineering notation, i.e: - if |x| is less than 1,000,000 use the standard integer format; - else use the <a>E<b> form where x = a * 10^b and b is a mult...
10ff06ff83a330023f15dcf35aa286d10c63f8a7
593,666
import torch def intersection(anchors, targets): """ Compute the sizes of the intersections of `anchors` by `targets`. Assume both anchors and targets are in tl br format """ ancs, tgts = anchors, targets a, t = ancs.size(0), tgts.size(0) ancs, tgts = ancs.unsqueeze(1).expand( a, t...
884b82fd6397fd651d8a9f368622dfa81eb32767
593,668
def binwidth(bins): """ Return binwidth from a linear array """ return (bins[1:] - bins[0:-1])
a71240fd471c5054de61145f5257c613a787bebc
593,671
def bdev_nvme_get_controller_health_info(client, name): """Display health log of the required NVMe bdev controller. Args: name: name of the required NVMe bdev controller Returns: Health log for the requested NVMe bdev controller. """ params = {} params['name'] = name return...
23d272d4321732609e235e4b7bfc0594eb3a1573
593,672
import torch from typing import Dict def forward_pass(model: torch.nn.Module, sample: Dict[str, torch.Tensor], device: torch.device) -> Dict[str, torch.Tensor]: """ Forward pass of the network for a given sample """ img = sample['img'].to(device) bboxes = sample['bbox...
429c34efe10bbe7ebcbf157db26795c3861419cb
593,674
def deg_p_polynomials(n,deg): """ Given n and deg, return all coefficient lists of monomials in n variables of degree deg. Example: deg_p_polynomials(2,3) returns [[3,0],[2,1],[1,2],[0,3]] """ if deg == 0: return [[0 for _ in range(n)]] if n == 1: return [[deg]] polys = [] for ...
1784d1f36ff9388f332208a561a87e808ab951ed
593,675
def find_migration_file_version(config, migrations, version, prior=False): """ Returns int (or None on failure) Finds the target migration version by its version string (not sortable version) in the list of migrations """ # find target ix = None for ix, m in enumerate(migrations): ...
c376af2a1a2c01ae66d26b9aebfb4552029642a6
593,676
import math def circular_easeinout(pos): """ Easing function for animations: Circular Ease In & Out """ if pos < 0.5: return 0.5 * (1 - math.sqrt(1 - 4 * (pos * pos))) return 0.5 * (math.sqrt(-((2 * pos) - 3) * ((2 * pos) - 1)) + 1)
2f9e936b42a68198ae0c5dc8723e25482712897c
593,677
import re def get_reviewer_image_section(svg_image_contents, section="both-alleles", insert_title=None): """Extract the upper panel (short allele), lower panel (long allele), or both panels of the REViewer image. The panels start with this line tag: <line x1="510" y1="386" x2="11710" y2="386" stroke="blac...
3aefb289f7a534c888715c4f4e2c6f1e35e89b9f
593,680
def classify(model, dataframe): """Classifies a dataframe using a trained random forest model Args: model: trained RandomForestClassifier dataframe: A features dataframe Returns: dataframe of raw predictions """ return model.transform(dataframe)\ .select(['...
c0331c2767772c386fd7a8eac7f2d30d974841dc
593,683
def get_test_dimensions() -> list: """Functions in qt_utils that allow arbitrary numbers of dimensions will be tested for all dimensions in this list.""" return [3, 5, 10, 50]
21b036a2c694e72e28cd7832dd7c502e40d7bf3a
593,684
def product(iterable): """ Returns the product of the elements of an iterable """ res = 1 for i in iterable: res *= i return res
0b1a3c152f60e1176e014791d107a8df16f3828e
593,689
def get_package_versions(package_list): """ Get packages information by inspecting __version__ attribute. Parameters: ---------- package_list : list of str List of package names. Returns ------- dict of module Version_info pairs. """ module_versions = {} for...
3da437d49d65cfbdc5c7b0462b408efa40c20bfb
593,702
def rsplit(text, token=' ', maxsplit=-1): """ Returns a list of the words in the provided string, separated by the delimiter string (starting from right). :param text: the string should be rsplit :param token: token dividing the string into split groups; default is space. :param maxsplit: Number of ...
ef88bad6fb2f2bcf39c8b1367ec7b9722cf95c79
593,705
import typing import json def _read_brand(filename: str, comment: str) -> typing.Dict: """Read a brand from a file. :param filename: the filename of the file with the brand :param comment: the comment characters that prefix each line of the brand :return: the data that is encoded in the brand """...
09a5224a517f10cf3186689a8fbdfe12a207acdc
593,707
def bool_replace(text): """In text replace str values 'true' and 'false' by boolean values Args: text (str): Incoming text. Returns: str: Formatted text. """ if text == "false": return False elif text == "true": return True else: return text
ba6385178282ee07f27cb56fab8fa5f2fb339e4a
593,709
def path_tuple(parser_path, control_path): """Returns a tuple structure of strings and Transition objects representing the vertices traversed by a path. Note that the mapping is not injective, because a pair of vertices may be joined by multiple edges.""" return tuple( [n.src for n in parser_pa...
62105541148ad56ad12f04c46f6416879abf6703
593,713
def correctness_measure(y_true, y_predict): """Estimate correctness measure (it is equivalent to the Spearman Footrule) correctness_acc = 1 - \frac{\sum_{i=1}^k |r_i - \hat{r}_i|}{0.5*k^2} Parameters ---------- y_true : string, e.g. "L1>L2>L3" y_predict : list, e.g. ["L1", "L3", "L2"] Re...
a82460436daaec9ad156133775500fdbde01739e
593,715
def sumsequences(N,K): """ All sequences of length N with numbers adding up to K; The number of such is sequences is given by the multiset number: N+K-1 over K. """ seqs = [ [] ] for i in range(N-1): new_seqs = [] for s in seqs: for j in range(K - sum(s) + 1): ...
4d957edaa5ef35b6d4ae5b5041efcd8f501bfad2
593,719
def in_range(in_num, minimum, maximum): """ Sees if the entered value is within the given range :param in_num: The number to check :type in_num: float :param minimum: The minimum value of the range (inclusive) :type minimum: float :param maximum: The maximum value of...
deed8bb8199afa2834c99930fded83b1c46dbf14
593,720
def _pg_db_config_to_cmdline_params(pg_db_config): """Format postgres config dict to CodeChecker cmdline parameters.""" params = [] for key, value in pg_db_config.items(): params.append('--' + key) params.append(str(value)) return params
5eb9ec580f30c1cd6ffa085670867f7c6a0b4707
593,723
import string import random def random_name(size=64, chars=string.ascii_uppercase+string.digits): """ Random string """ return ''.join(random.choice(chars) for _ in range(size))
dfb48505b2bb49000e7114b900e7ca2ca87a1f48
593,728
def bubble_sort(input_data): """Implementation of the bubble sort algorithm, employs an enhancement where the inner loops keep track of the last sorted element as described in the video below. (https://www.youtube.com/watch?v=6Gv8vg0kcHc) The input_data is sorted in-place, this is dangerous to do ...
75a298e645b1567c75befa25cdf703ac48cfe554
593,731
def plot(self, **kwds): """ It calls the pandas DataFrame.plot() method. Parameters ---------- **kwds: arguments pandas plot() arguments. Returns ------- axes : matplotlib.axes.Axes or numpy.ndarray of them """ axes = self.data.plot(**kwds) return axes
043f02c3bbb0c4604f8b2f764b7faca010d4f0dc
593,732
def mass_surface_balsa_monokote_cf( chord, span, mean_t_over_c=0.08 ): """ Estimates the mass of a lifting surface constructed with balsa-monokote-carbon-fiber construction techniques. Warning: Not well validated; spar sizing is a guessed scaling and not based on structural analysis....
fa0d9a3cda6fa01e973fa01e0a02f7e4a69b991b
593,735
def calc_RC_via_bulk_time(capacitance, L, sigma): """ Characteristic time for induced double layer to form considering a capacitance. units: s Notes: Squires, 2010 - "characteristic time for induced double layer to form" Inputs: capacitance: F/m^2 C^2*s^2/kg/m^2/m^2 (...
7627b0400d129744bf763f14896ee67f8c47d1c6
593,736
def snake_case_to_camel_case(s): """Convert snake case names to camel case, for polyswarmd compatibility. Unfortunate special case for ERC20Relay contract. :param s: String to convert :return: Converted string """ acronyms = {'ERC'} ret = ''.join(c.title() for c in s.split('_')) for a ...
2cba361f55ca233cd16df3bc37352cadb2410851
593,739
def menu(conn): """ Acts as a menu """ print("What would you like to do? \n 1.Create Activity \n 2.Update Activity \n 3.Delete Activity") choice = int(input("Please enter a valid integer... \n")) if choice == 1: return 1 elif choice == 2: return 2 elif choice == 3: ...
069932a9806c1f430a7afcc985d96f013e8a3c98
593,741
def _GetFilterFromArg(filter_arg, messages): """Gets a Filter message object from a filter phrase.""" if not filter_arg: return None flag_event_types_to_enum = { 'upgradeevent': messages.Filter.EventTypeValueListEntryValuesEnum.UPGRADE_EVENT, 'upgradeavailableevent': messages.F...
fe7a55a94329803fbcbf72265a769f23d410dfe2
593,742
def sum_of_digits(number): """ What comes in: An integer. What goes out: Returns the sum of the digits in the given integer. Side effects: None. Example: If the integer is 83135, this function returns (8 + 3 + 1 + 3 + 5), which is 20. """ # -----------------------------------...
d5173761e77bbdbfc66ac7d3e8f98a4d276e60be
593,745
def mimo_batchify(x, num_heads): """ For some tensor x of size (num-heads * batch, ...) reshape it into a form factor that is matched with mimo systems. """ # Ensure the batch is divisible by number of heads assert x.size(0) % num_heads == 0 # Get the shape for arbitrary sized tensors ...
73e9dbb40c37ef4358fb29bd682654961d71a9ed
593,748
def get_max_id(corpus): """ Return the highest feature id that appears in the corpus. For empty corpora (no features at all), return -1. """ maxid = -1 for document in corpus: maxid = max(maxid, max([-1] + [fieldid for fieldid, _ in document])) # [-1] to avoid exceptions from max(empty...
931302e9990bf2f661114526f18e59c363a06b2c
593,749
def generate_source_static(n_bins): """Create the source structure for the given number of bins. Args: n_bins: `list` of number of bins Returns: source """ binning = [n_bins, -0.5, n_bins + 0.5] data = [120.0] * n_bins bkg = [100.0] * n_bins bkgerr = [10.0] * n_bins ...
40a72c2e5f34fabe93c71299dd7a3463f9639a91
593,757
def subclasses(base_cls): """ Discovers the inheritance tree of a given class. The class must have an abstract() method. A class of the hierarchy will only be the part of the returned classes, if it's abstract() method returns False. :param base_cls: type, root of the inheritance hierarchy. :return:...
a957c28c69875b2fa31ea35f216a4af3f3165194
593,762
import re def get_images(strs): """ Parses a list of strings, expected to be tags or templates to get matching image patterns and returns a count of the matches. """ matches = re.findall( r"Зображення[1-9]{1,2}|Изображение:|" + r"Зображення:|Файл:|File:|Image:|photo[1-9][a-z]", ...
195343d06cf08fdbeef5d6da5a2091451ecd6747
593,769
def get_categorical_info(analyzer, dataset_sub_names): """Returns the categorical information for the given feature names. :param analyzer: The error analyzer containing the categorical features and categories for the full dataset. :type analyzer: BaseAnalyzer :param dataset_sub_names: The subs...
bbaaa5deb7f1b0784e76e224f007e1848585b267
593,771
def get_hits(results): """Return a list of documents from an Elasticsearch search result. Parameters ---------- results : dict An Elasticsearch search result. Returns ------- |list| of |dict| The list of documents in the search result. """ return results['hits']['h...
aeac9f4d37b0e20130d5926e0d76b35fee16bc1f
593,777
def bool_helper(bool_string): """ Needed a helper that could take a string version of a bool and convert it to the actual bool value """ if bool_string.lower() == 'true': return True else: return False
01824d3c7e64b053dfc4bf6f206565f699d5ba3c
593,780
def metadataset2dataset_key(metadataset_name): """Return the dataset name corresponding to a metadataset name Metadatasets are not ever stored in the HDF5 and instead are only used to store data needed to correctly calculate dataset values. This function maps a metadataset name to its corresponding da...
144bdf1f93ae568a39824dfdbd6b00114021bd4a
593,781
import yaml from typing import OrderedDict def ordered_dump(data, stream=None, **kwargs): """ Dumps a .yml file, retaining the ordering of the dict structure. Args: data (dict): Data dictionary to be saved to .yml file stream (file stream, optional): Reference to pre-existing .yml fil...
a2b1a021befb328d2cf63d9a484f669bbff7c59d
593,782
import json def nbcheck(nbdirs, return_ooo_cells=False): """ Given a list of directories pointing to Jupyter notebooks, checks that code cells are run in order. Note: Usage of f-strings in this code requires Python 3.6, introduced in [PEP 498](https://www.python.org/dev/peps/pep-0498/) Usage...
afbda869dc1e167fde13635afac7ec7cf80e25f1
593,784
import hashlib def fingerprint(s): """ md5加密字符串 :param s: 需要加密的字符串,一般为文章url :return: 加密值 """ m1 = hashlib.md5() m1.update(s.strip().encode("utf-8")) ret = m1.hexdigest() return ret
6fefea7971ce356877e3b094e5c02354227233cb
593,788
def list_div_by_7_but_not_5(start=2000, stop=3200): """ Question1: all numbers divisible by 7 but not by 5 from selected range """ return ','.join([ str(value) for value in range(start,stop+1) \ if value%7 == 0 and value%5 != 0 ])
7a3228f7783869007ada5d11d4f1a53ebefc9e7c
593,790
def hill_eq_brentq(xvalues_for_curve, hill_constants, y_value_curve_center): """ Residual function for the four parameter sigmoidal Hill equation. For further detail on the Hill equation, see the relevant docstring for hill_eq. y = hill_eq(x) - y_value_curve_center Parameters ---------- xvalu...
db57acc732346051db43318c29ebe0b5facc4582
593,791
def bprop_scalar_uadd(x, out, dout): """Backpropagator for `scalar_uadd`.""" return (dout,)
c6258cf655b4a22737b6addd861d4320aaf4901f
593,795
import re def is_valid_hostname(hostname): """ Takes a hostname and tries to determine if it is valid or not Args: hostname: String of the hostname to check Returns: Boolean if it is valid or not """ # Borrowed from https://stackoverflow.com/questions/2532053/validate-a-hostn...
fd56f664cbd41483b006f832c83f4e0d15e35098
593,796
def clean_url(url): """Convert user input URL to clean URL.""" if url.endswith("/api/"): url = url[:-5] elif url.endswith("/api"): url = url[:-4] elif url.endswith("/"): url = url[:-1] return url
33464902c28beb4ce5ce135485a7f8f324425f5e
593,797
import re def inputValid(userInput): """Verifies user input as valid. Accepts strings. Returns True for valid input, False for invalid.""" regex = "\d+[d,D]+\d+[+,-]\d+" if re.search(regex, userInput): return True else: return False
8278fc30a25c26e2e7816a4a729210d0005c4953
593,798
from typing import Callable def unwrap_callback(callback: Callable) -> Callable: """If the callback was wrapped with :func:`.wrap_callback`, this will unwrap it. Otherwise, the callback will just be returned unchanged. """ return getattr(callback, 'wrapped', callback)
617bfceb5d8eb83b6c06fbace313ce39888621aa
593,799
def findInList(mylist,element): """ check if an element is in the list """ pos=-1 try: pos=mylist.index(element) except ValueError: pos=-1 return pos!=-1
29312aaef7e7f5e81ed9026b51a31646cced75e8
593,802
import math def next_pow_of_2(n): """ Returns the smallest integer greater than or equal to n which is a power of 2 """ return 2**int(math.ceil(math.log2(n)))
bc1bef29330a5dc34914573f74ddbddea5af778b
593,805
def prefix_base_url(base_url, endpoint): """ Returns ``base_url`` + ``endpoint`` with the right forward slashes. >>> prefix_base_url('https://play.dhis2.org/dev/', ... '/api/trackedEntityInstances') 'https://play.dhis2.org/dev/api/trackedEntityInstances' >>> prefix_base_url('ht...
1c2cafb8f07a67d930b23229ef4894839f54908a
593,819
def linear_regression_model(x_points: list[float], y_points: list[float]) -> \ tuple[float, float]: """Returns a tuple of two integers containing the formula for the linear regression line for the given points using the least squares regression line formula. The first point is m, the slope of the li...
606650894b71b0a5ef40a95fa3ba657ae8ad0436
593,821
def check_module_lines(lines, module): """ Check if a normalized module name appears in the given lines :param lines: The lines to check :param module: A module name - e.g. "xt_set" or "ip6_tables" :return: True if the module appears. False otherwise """ full_module = "/%s.ko" % module r...
383d278a7f7bc122b358e8824c605ec068286da8
593,825
def hash_dict(d): """ Sorts the dict's keys, then returns the dict in a standardized string form """ keys = sorted(list(d.keys())) if len(keys)==0: return "{}" s = "{" for k in keys[:-1]: s += "%s: %s, "%(repr(k), repr(d[k])) k = keys[-1] s += "%s: %s}"%(repr(k), repr(d[k])) ...
322288d946d177ef14a02a7d279ef2224be70fb5
593,828