content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def calculate_percent(numerator, denominator): """Return percentage value, round to 2 digits precision. Parameters: numerator (int): parts of the whole denominator (str): the whole Returns: float: percentage value rounded (00.00) """ percent = (numerator / denominator) * 10...
d60c540369ebd733af26888497b65dce0027cdf5
666,261
def _get_statusline(params): """Generate a mock statusline like rspec would output.""" total = sum(params.values()) statusline = 'Finished in 0.001s seconds\n' passed = params.get('passed', 0) failed = params.get('failed', 0) error = params.get('error', 0) total = passed + failed + error ...
bda52894cf2495c3fe48dfe14f1127e2e6409728
666,265
from typing import OrderedDict def list_tag_attributes(attributes): """rewrite JATS list-type attribute as an HTML class attribute""" if "list-type" in attributes: list_type_class_map = OrderedDict( [ ('list-type="alpha-lower"', 'class="list list--alpha-lower"'), ...
9f7f8ee7aaba3eb6131acbebd230cbe998cf996a
666,266
import torch def l2_normalize(tensor): """Return tensor / l2_norm(tensor).""" l2_norm = torch.norm(tensor, p=2) tensor /= l2_norm return tensor
99cfe124180955480d72a041119e5a9bf94d2efd
666,267
def combo(iter_1, iter_2): """ Assume both iterables has same length combo([1, 2, 3], 'abc') Output: [(1, 'a'), (2, 'b'), (3, 'c')] """ combo_list = [] for x in range(len(iter_1)): tupl = iter_1[x], iter_2[x] combo_list.append(tupl) return combo_list
3cff4dc991efd0ee19de0ae3533cf22aaf24ba56
666,268
def _safe_indexing(X, indices): """Return items or rows from X using indices. copy of sklearn utils safe_indexing with handling of slice as well Allows simple indexing of lists or arrays. Parameters ---------- X : array-like, sparse-matrix, list, pandas.DataFrame, pandas.Series. ...
0419f9a91227d1e8c281f3e55c30a82953ca7d41
666,274
import sqlite3 def execute_sql(dbfile,query,params=None): """Execute SQL against a SQLite file Args: dbfile: SQLite database file query: SQL query params: sequence of parameters Returns: list of matching rows """ conn=sqlite3.connect(dbfile) conn.row_f...
36c2c8475b7b79397891752f33310a98cb8f3819
666,278
from typing import List def add_bcc(cmd: List[int]): """Compute BCC (= Block Checking Charactor) and append to command sequence. Returns: list of binary data with BCC code. """ check: int = 0x00 for b in cmd: check = check ^ b cmd.append(check) return cmd
6fac48e348cdb2c6fd63f1545a09fa5ea6ddba61
666,279
import time def gmtime2ams(unixtime): """Converts float unix time to GMT time in format '2011-12-11 09:00:21.555'""" msec = int((unixtime%1)*1000) tm = time.gmtime(int(unixtime)) s = time.strftime("%Y-%m-%d %H:%M:%S", tm) return s + (".%03d"%msec)
d18744b30d188e2190dc817e0e0941f07a49fd23
666,280
def BuildSt(st): """Organizes information in a single standard_timings.StandardTiming object. Args: st: A standard_timings.StandardTiming object. Returns: A dictionary of standard timings information. """ return { 'X resolution': st.x_resolution, 'Ratio': st.xy_pixel_ratio, 'Freque...
80b35d58b032721294d77711bcb9c4631d707cab
666,282
def file_len(fname): """Returns Number of lines of a file""" with open(fname) as f: i = -1 for i, l in enumerate(f): pass return i + 1
16d6146af3e90c24d93b224835e37604e9405dc0
666,287
def predict_times_model(times, model): """Predict times alignment from a model object. Parameters ---------- times : 1d array Timestamps to align. model : LinearRegression A model object, with a fit model predicting timestamp alignment. Returns ------- 1d array ...
e9ed5758bcb73e776be92b44cd4c2491ae30e5cf
666,290
import torch def get_recall(SR, GT, threshold=0.5): """ Args: SR: tensor Segmentation Results GT: tensor Ground Truth threshold: the threshold of segmentation Returns: RC: Recall rate """ # Sensitivity == Recall SR = SR > threshold GT = GT == torch.max(G...
54f75d00f339987c62124cd0c8d0d0e91bae23dd
666,291
import re def parse_element_string(elements_str, stoich=False): """ Parse element query string with macros. Has to parse braces too, and throw an error if brackets are unmatched. e.g. Parameters: '[VII][Fe,Ru,Os][I]' Returns: ['[VII]', '[Fe,Ru,Os]', '[I]'] e.g.2 Parameters: '...
d26950193148dd43712c5c8d0c33b4f4196e7849
666,292
import torch def get_flat_params_from(model): """ Get the flattened parameters of the model. Args: model: the model from which the parameters are derived Return: flat_param: the flattened parameters """ params = [] for param in model.parameters(): params.append(pa...
4acc67cadabed4863367e7c6ef59cf04fe132315
666,294
from typing import List from typing import Tuple from typing import Optional def html_wrap_span( string: str, pairs: List[Tuple[int, int]], css_class: Optional[str] = "accentuate" ) -> str: """Wrap targeted area of Assertion with html highlighting to visualize where the error or warning is targeted ...
075e5a95b9ba6bc5fd818169824149b46796790c
666,296
def construct_info_message(module, branch, area, version, build_object): """ Gathers info to display during release Args: module(str): Module to be released branch(str): Branch to be released area(str): Area of module version(str): Release version build_object(:class...
0e3074e26414cc4da74bd6e4ccc9f5f719e69957
666,297
def rotate_points(points, R): """ Rotate points by the rotation matrix R """ rotated_points = R @ points return rotated_points
5bbae2fcacabb4f40b897c15be4c1ba7feb24746
666,298
def erase_special(x): """ Removes special characters and spaces from the input string """ return ''.join([i for i in x if i.isalnum()])
839d6b2db14af782b50ee16ee24b27d6208e893d
666,300
import tempfile import zipfile def extract_files(file_path, output_dir=None): """ Extracts files from a compressed zip archive. :param str file_path: the path to the input zip archive containing the compressed files. :param str or None output_dir: the path to the directory in which to extract the file...
522bf86dc880d08349dbd9b599ba048a392d7f0e
666,301
def compare_list(list1: list, list2: list) -> bool: """Compare two list and ignore \n at the end of two list.""" while list1[-1] == "\n" or list1[-1] == "": list1.pop() while list2[-1] == "\n" or list2[-1] == "": list2.pop() return list1 == list2
f7e925116dd952fb64e89c4da5b2256682cfb3a3
666,307
def datetime_format(date, caller=None): """Convert given datetime.datetime object to a string of appropriate form. Choose the format according to the "caller" arg., which is a string indicating the name of the function calling this function. """ if caller == "corona": return date.s...
daadbaa4d5146f6a86c5ce24150e0dabebc3bb09
666,309
def calc_relative_ratio(rel_pow_low_band, rel_pow_high_band): """Calculate ratio of relative power between two bands. Parameters ---------- rel_pow_low_band : float Relative power of lower band. rel_pow_high_band : float Relative power of higher band. Outputs ------- ra...
fa3762a57e6e427630621c22c9108f8ed2df46af
666,310
import importlib def get_trainer(cfg, net_G, net_D=None, opt_G=None, opt_D=None, sch_G=None, sch_D=None, train_data_loader=None, val_data_loader=None): """Return the trainer object. Args: cfg (Config): Loaded config object. net_G...
6b9856727a165fd962ad8da107bb73b769c72757
666,311
def complete_out_of_view(to_check_box, im_w, im_h): """ check if the bounding box is completely out of view from the image :param to_check_box: bounding box, numpy array, [x, y, x, y] :param im_w: image width, int :param im_h:image height, int :return: out of view flag, bool """ complete...
671d9a774bcab4b45df7ac3f6f1266f95d7674c1
666,320
import re def rename_state(rename, src): """ Given a list of (old_str, new_str), replace old_strin src with new_str. :param rename: a list of (old_str, new_str) :param src: code :return: renamed src """ for (old, new) in rename: match = True index = 0 while match: ...
57a958964f6a2d70dfca32fca90e1aacc620b729
666,322
def validate_cipher_suite_id(cipher_suite_id): """Validates that a CipherSuite conforms to the proper format. Args: cipher_suite_id (int): CipherSuite id. Returns: (int): The original CipherSuite id. """ if not isinstance(cipher_suite_id, int): raise TypeError("CipherSuite...
7bf45a6270cad22481765e009a19618d6691ce8b
666,327
import json def trigger_mutation_test(limit): """ Test data for IFTTT trigger bunq_mutation """ result = [{ "created_at": "2018-01-05T11:25:15+00:00", "date": "2018-01-05", "type": "MANUAL", "amount": "1.01", "balance": "15.15", "account": "NL42BUNQ0123456789", ...
dc749cb7aaa3f65e29181ada2a07a727915fd90b
666,328
def all_are_none(*args) -> bool: """ Return True if all args are None. """ return all([arg is None for arg in args])
f23b00b5f0d7ae50e08cc25b48f524cb13fa2753
666,330
def default_join(row, join, *elements): """ Joins a set of objects as strings :param row: The row being transformed (not used) :param join: The string used to join the elements :param elements: The elements to join :return: The joined string """ return str(join).join(map(str, elements)...
2663c2d0869330eb370ac2befdd4fca9f46ea8f0
666,331
def freeze(model): """ Freezes all the parameters in the model Returns ------- Model the model itself """ for param in model.parameters(): param.requires_grad = False model.training = False return model
70afe94a83eaf1203e099d47ecc53209d70ba658
666,334
def tirar_bijecao(line): """ Retira o número de correspondência das regras. :param line: lista com a regra :return: lista com a regra sem número de correspondência. """ regra_sem_bij = [] for e in line: regra_sem_bij.append(e[:-1]) return regra_sem_bij
e02917190c9960ae571c2ddaf97dfd92ead18581
666,335
def identity(x): """Return the argument as is.""" return x
b46c085f18d367db1d307bad26d28e8d55096756
666,336
def dec_str_to_int(ch): """function to process a decimal string into an integer.""" return int(ch)
5c1eb00f8b4704c18ede4d75666d097816568420
666,339
def partition_all(n): """Partition a collection into sub-collections (lists) of size n.""" def generator(coll): temp = [] for i, item in enumerate(coll, 1): temp.append(item) if not i % n: yield temp temp = [] if temp: y...
54bea1f22b2b0a494461a3737111b5e8e25ca8b0
666,341
def CONCAT_ARRAYS(*arrays): """ Concatenates arrays to return the concatenated array. See https://docs.mongodb.com/manual/reference/operator/aggregation/concatArrays/ for more details :param arrays: A set of arrays(expressions). :return: Aggregation operator """ return {'$concatArrays': ...
0b77fb6b9c687ef9217c1f6e6504ed3a70d25db9
666,347
import re def crush_invalid_field_name(name): """Given a proposed field name, replace banned characters with underscores, and convert any run of underscores with a single.""" if name[0].isdigit(): name = "_%s" % name name = re.sub(r'[^a-z0-9_]', "_", name.lower()) return re.sub(r'__*', "_", na...
dbc672b4a725169ca1c335f3ae2f335279460f9c
666,354
def basis_function(degree, knot_vector, span, t): """Computes the non-vanishing basis functions for a single parameter t. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. Uses recurrence to compute the basis functions, also known as Cox - de Boor recursion formula. """ le...
b23549dfa81a87acf2478120eaf9c9e1e84005d5
666,355
def gen_user_list_id(user_list_obj): """ Generates the Elasticsearch document id for a UserList Args: user_list_obj (UserList): The UserList object Returns: str: The Elasticsearch document id for this object """ return "user_list_{}".format(user_list_obj.id)
80aa70a0ad6c3a13822968b1f111cbc669fa7d62
666,357
def get_gamma_distribution_params(mean, std): """Turn mean and std of Gamma distribution into parameters k and theta.""" # mean = k * theta # var = std**2 = k * theta**2 theta = std**2 / mean k = mean / theta return k, theta
49b5ccdf7b83c949b81ad05e6d351cfb0b1f4d26
666,361
def admins_from_iam_policy(iam_policy): """Get a list of admins from the IAM policy.""" # Per # https://cloud.google.com/appengine/docs/standard/python/users/adminusers, An # administrator is a user who has the Viewer, Editor, or Owner primitive role, # or the App Engine App Admin predefined role roles = [ ...
a2bf60ead9ba27de7013b87a70baeb2fb5d17dab
666,362
import torch def to_tensor(data): """ Convert numpy array to PyTorch tensor. """ return torch.view_as_real(torch.from_numpy(data))
dec478a853e2e71d8578c59648db484b208685a8
666,363
def pretty_str(label, arr): """ Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a...
4e48a9e68a1fa764c4af5827dd2b015868829986
666,367
def merge_duplicate_concepts(concepts): """ NHP has many duplicate ingredients in the raw data. During data preprocessing each unique ingredient string is assigned a unique ID, so duplicate ingredient entries will have the same ID. This function merges those entries into a single concept. :para...
9138e97c82ed15c44fd59f2e46d1465fa2f41cfa
666,368
def dict_factory(cursor, row) -> dict: """Transform tuple rows into a dictionary with column names and values Args: cursor: database cursor row: row Returns: dict: a dictionary containing the column names as keys and the respective values """ output = {} for idx, col in...
fbc8d1e1157f0d6d3f70236ad36b6002ba34b45e
666,372
import torch def onehot(y, num_classes): """ Generate one-hot vector :param y: ground truth labels :type y: torch.Tensor :param num_classes: number os classes :type num_classes: int :return: one-hot vector generated from labels :rtype: torch.Tensor """ assert len(y.shape) in [...
b112afc1d3ae7b2182a2304fddac1d473b896576
666,375
import math def __MtoE(M,e): """Calculates the eccentric anomaly from the mean anomaly. Args: M(float): the mean anomaly (in radians) e(float): the eccentricity Returns: float: The eccentric anomaly (in radians) """ E = M dy = 1 while(abs(dy) > 0.0...
06697e5582e72c570a48b66978f215c215df9fc8
666,380
def identity_grid(grid): """Do nothing to the grid""" # return np.array([[7,5,5,5],[5,0,0,0],[5,0,1,0],[5,0,0,0]]) return grid
04115496775baa3a002331c16aaf89ef851e501b
666,385
from typing import List def intcode_computer(program: List[int], sum_code: int = 1, multiply_code: int = 2, finish_code: int = 99 ) -> List[int]: """ An Intcode program is a list of integers separated by commas (like 1,0,0,3,9...
0110d2803923e92ac024b108b9bd05704d215d8d
666,397
def routepack(value): """Pack a route into a string""" return str(value).replace("/","!")
f243f61924f316554c8f07949f8d759e2bd42940
666,401
def order_pythonic(sentence: str) -> str: """Returns ordered sentence (pythonic). Examples: >>> assert order_pythonic("") == "" >>> assert order_pythonic("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est" """ return " ".join( sorted(sentence.split(), key=lambda x: "".join(filter(str....
b6d47419afe86137471412937f31d17bbc5934d0
666,403
from typing import Union from typing import List from typing import Set from typing import Counter def list_equal( left: Union[List[Union[str, int]], Set[Union[str, int]]], right: Union[List[Union[str, int]], Set[Union[str, int]]], use_sort=True, ) -> bool: """ 判断列表是否相等,支持具有重复值列表的比较 参考:https:/...
081072a0bba9b33904e330cd4268e5b1fbd14fbe
666,407
def check_callbacks(bot, url): """Check if ``url`` is excluded or matches any URL callback patterns. :param bot: Sopel instance :param str url: URL to check :return: True if ``url`` is excluded or matches any URL callback pattern This function looks at the ``bot.memory`` for ``url_exclude`` patter...
060e031caab1efcc43e4a0e606001075bc23395f
666,408
def make_biplot_scores_output(taxa): """Create convenient output format of taxon biplot coordinates taxa is a dict containing 'lineages' and a coord matrix 'coord' output is a list of lines, each containing coords for one taxon """ output = [] ndims = len(taxa['coord'][1]) header = '...
4c461fb160544333109a126806cea48047103db1
666,409
import re def derive_ip_address(cidr_block, delegate, final8): """ Given a CIDR block string, a delegate number, and an integer representing the final 8 bits of the IP address, construct and return the IP address derived from this values. For example, if cidr_block is 10.0.0.0/16,...
402008bfcac8b4682b1edf01798d931a2a3930ec
666,411
def get_struct_member_vardecl(struct_type, member_name, declvisitor=None): """Return the type for the member @member_name, of the struct type defined by @struct_type.""" for vardecllist in struct_type.children: assert vardecllist.type == "VarDeclList" for vardecl in vardecllist.children: ...
b880c40dcc4f9a983e948b4cb98dc28963030c2c
666,414
def nc_define_var(ncid, metadata): """ Define a new variable in an open netCDF file and add some default attributes. Parameters ---------- ncid: netCDF4.Dataset Handle to an open netCDF file. metadata: dict Bundle containing the information needed to define the variable. ...
be2f30a469f0e36ae24bb1fa4722f41b0833e690
666,417
def eval_vehicle_offset(pixel_offset, mx=3.7/780): """ Calculates offset of the vehicle from middle of the lane based on the value of the pixel offset of center of the detected lane from middle of the camera image. The vehicle offset is calculated in meters using the scale factor mx (in meter...
a06566505f3cd207674b6bb3e652defe1660eef2
666,425
def dict_from_hash(hashstring): """ From a hashstring (like one created from hash_from_dict), creates and returns a dictionary mapping variables to their assignments. Ex: hashstring="A=0,B=1" => {"A": 0, "B": 1} """ if hashstring is None: return None if len(hashstring) == 0: return {} re...
966b33f0fd919506b99cd4e154033c952a002a99
666,428
def is_compose_project(group_id, artifact_id): """Returns true if project can be inferred to be a compose / Kotlin project """ return "compose" in group_id or "compose" in artifact_id
7b659c459c2f39485ee59fc43b70ee81c5e5bb95
666,431
def steering2(course, power): """ Computes how fast each motor in a pair should turn to achieve the specified steering. Input: course [-100, 100]: * -100 means turn left as fast as possible, * 0 means drive in a straight line, and * 100 means turn right as fast as po...
3e6c8919042fa167d1c98fcb26f05d2aa4955a41
666,437
def minmax(dates): """Returns an iso8601 daterange string that represents the min and max datemap.values(). Args: datestrings: [d1, d2, d3,] Returns: ['min_date/max_date',] Example: >>> minmax(['2008-01-01', '2010-01-01', '2009-01-01']) "2008-01-01/2010-01-01" ...
012a081fadb633384c7369e9d637bb9761667489
666,438
def horiz_div(col_widths, horiz, vert, padding): """ Create the column dividers for a table with given column widths. col_widths: list of column widths horiz: the character to use for a horizontal divider vert: the character to use for a vertical divider padding: amount of padding to add to eac...
b83399e401d655fcaa6ad3ff66fb936c8737a8da
666,442
from bs4 import BeautifulSoup def cleanHTML(raw_html): """ Remove HTML tags """ return BeautifulSoup(raw_html,"lxml").text
b52f8acdc77d57dea6f5874c6ea94f61eed11756
666,443
def appendDtectArgs( cmd, args=None ): """Append OpendTect arguments Parameters: * cmd (list): List to which the returned elements will be added * arg (dict, optional): Dictionary with the members 'dtectdata' and 'survey' as single element lists, and/or 'dtectexec' (see odpy.getODSoftwareDir) ...
e3af9ee1bb9cf73b7e836ada985d342e53012f2e
666,446
def __evaluate_tree(predictor, input): """Function for evaluating a given decision tree on a given input.""" return predictor.evaluate(input)
d41816254a035e25edd7e20baf1f058010502559
666,449
import struct def readLong(f): """Read unsigned 4 byte value from a file f.""" (retVal,) = struct.unpack("L", f.read(4)) return retVal
4f2554908eacd160cc3aabd3a4cdb8e03a5d17e0
666,454
def tank_geometry(geometry, om_key): """ Returns the IceTop tank geometry object corresponding to a given DOM. """ if om_key.om == 61 or om_key.om == 62: return geometry.stationgeo[om_key.string][0] elif om_key.om == 63 or om_key.om == 64: return geometry.stationgeo[om_key.string][1]...
2dc58089b9b3305b5e43fcb6a4896e4ee66b46b6
666,458
def ogrtype_from_dtype(d_type): """ Return the ogr data type from the numpy dtype """ # ogr field type if 'float' in d_type.name: ogr_data_type = 2 elif 'int' in d_type.name: ogr_data_type = 0 elif 'string' in d_type.name: ogr_data_type = 4 elif 'bool' in d_type.n...
19ab7b80d014edb6c211b800fee480eaba6349cc
666,463
def mniposition_to(mnipoint, affine): """ project the position in MNI coordinate system to the position of a point in matrix coordinate system Parameters ---------- point : list or array The position in MNI coordinate system. affine : array or list The position information of t...
631a5fa1362099599511c85c0d3f07a76c3e8723
666,469
from typing import List from typing import Tuple def partition_leading_lines( lines: List[str], ) -> Tuple[List[str], List[str]]: """ Returns a tuple of the initial blank lines, and the comment lines. """ for j in range(len(lines)): if lines[j].startswith("#"): break else: ...
3be97e68e26a333f886f6643f645b8075f2140fc
666,470
def convert_16_to_8(value): """Scale a 16 bit level into 8 bits.""" return value >> 8
423d05e414bf6959b2b9a3903f2c074bc9fc09f3
666,471
from datetime import datetime def is_time_in_given_format(time_string, time_format): """Tests whether a time string is formatted according to the given time format.""" try: datetime.strptime(time_string, time_format) return True except ValueError: return False
0fbde6aaf302a26411091d46cfbfb5cee37992c2
666,472
def prompt(text): """ Add >>> and ... prefixes back into code prompt("x + 1") # doctest: +SKIP '>>> x + 1' prompt("for i in seq:\n print(i)") '>>> for i in seq:\n... print(i)' """ return '>>> ' + text.rstrip().replace('\n', '\n... ')
76389b51e5c6095282e779cc19c73239840279f9
666,482
def increment(string): """ for "A", return "B" for "AC", return "AD" After AZ comes `A[`. That's OK for my purposes. """ rest = string[:-1] last = chr(ord(string[-1]) + 1) #print rest+last return rest + last
5b7ce40a24cda7d80f7d4f289677f2a67d636d7d
666,484
def set_carry(self) -> int: """ Set the carry bit. Parameters ---------- self: Processor, mandatory The instance of the processor containing the registers, accumulator etc Returns ------- self.CARRY The carry bit Raises ------ N/A Notes ----- N...
0f1d90b0665b4b2d25ebc11bb4302899d60bbf54
666,485
def read_quota_file(file_quota): """Read the quota information from a file generated with the command 'mmrepquota -j <fileset>.""" fin = open(file_quota,'r') text = fin.readlines() fin.close() # Remove some control characters from the input. text = [line.strip() for line in text] retur...
2512814fbebcee79747ff906672b91b6fbc0ac84
666,486
def cellsDirs(pos, size): """ Returns all possible directions in a position within a 2D array of given size. """ x, y = pos width, height = size dirs = [] if x > 0: dirs.append([-1,0]) if x < width-1: dirs.append([1,0]) if y > 0: dirs.append([0,-1]) if y < height-1: dirs.append(...
2a7615e15f3e268ceb0f4fdb09cca140471bebfa
666,487
def _parse_color_string(colors, n=None, r=False, start=0, stop=1): """ Parses strings that are formatted like the following: 'RdBu_r_start=0.8_stop=0.9_n=10' 'viridis_start0.2_r_stop.5_n20' 'Greens_start0_n15' """ if isinstance(colors, str): color_settings = colors.split('_') ...
c7ca24e7a8d345f94cdbabd623c60756aeeefe34
666,492
def split(str, sep=None, maxsplit=-1): """Return a list of the words in the string, using sep as the delimiter string.""" return str.split(sep, maxsplit)
013c637e8f6aa00b7389371f366f0fe2a06172b7
666,500
def inner_product(L1,L2): """ Inner product between two vectors, where vectors are represented as alphabetically sorted (word,freq) pairs. Example: inner_product([["and",3],["of",2],["the",5]], [["and",4],["in",1],["of",1],["this",2]]) = 14.0 """ sum = 0.0 i = 0 ...
4d93b0a6b36d2a2749486046e1693c4fb6e721ad
666,501
import asyncio def async_test(loop=None, timeout=None): """ Decorator enabling co-routines to be run in python unittests. :param loop: Event loop in which to run the co-routine. By default its ``asyncio.get_event_loop()``. :param timeout: Test timeout in seconds. """ loop = loop or asyncio.ge...
b4d52e6bd46a081141f8e757b07fa76f2c10e1c2
666,506
def lopen_loc(x): """Extracts the line and column number for a node that may have an opening parenthesis, brace, or bracket. """ lineno = x._lopen_lineno if hasattr(x, "_lopen_lineno") else x.lineno col = x._lopen_col if hasattr(x, "_lopen_col") else x.col_offset return lineno, col
75545bb527dac4ab0ceffffbbd2c3f028ac4f898
666,509
def factorial(number): """ Factorial Using Recursion Example : 5! Factorial is denoted by ! Factorial(5) : 5 X 4 X 3 X 2 X 1 = 120 """ if number == 0: return 1 else: print(f"{number}*", end=" ") return number * factorial(number-1)
1ef2c2c1a4f3213208b89e956f1f15976abf8044
666,517
from typing import Optional def percent(flt: Optional[float]) -> str: """ Convert a float into a percentage string. """ if flt is None: return '[in flux]' return '{0:.0f}%'.format(flt * 100)
937a1608be53460369210cdce9150547bcb1fe56
666,522
def nd_cross_variogram(x1, y2, x2, y1): """ Inner most calculation step of cross-variogram This function is used in the inner most loop of `neighbour_diff_squared`. Parameters ---------- x, y : np.array Returns ------- np.array """ res = (x1 - x2)*(y1 - y2) return r...
63197005b9340b4cc4cd5c187d8e8fe4745339e5
666,526
def is_set(b: int, val: int, v6: bool) -> bool: """Return whether b-th bit is set in integer 'val'. Special case: when b < 0, it acts as if it were 0. """ if b < 0: b = 0 if v6: return val & (1 << (127 - b)) != 0 else: return val & (1 << (31 - b)) != 0
62326cf74a9e21e9ef2a321f35b1f00e76a2cb90
666,529
def get_chromosome_names_in_GTF(options): """ Function to get the list of chromosome names present in the provided GTF file. """ chr_list = [] with open(options.annotation, "r") as GTF_file: for line in GTF_file: if not line.startswith("#"): chr = line.split("\t")[0] ...
958708fc2564b4d33591701a9f3cf3bd12981b09
666,535
from typing import List def tablinks(tabs: List[str]) -> str: """Adds list of tabs/sections for the reports that are able to be clicked. For every 6 tabs we push them onto a new line. Parameters ---------- tabs : List[str] List of tabs/sections for the reports. Returns ------- st...
ed3d82028b400a9aaf80c96cde42b1bd4a220696
666,536
def mash_infusion( target_temp, initial_temp, grain_weight, water_volume, infusion_temp=212 ): """ Get Volume of water to infuse into mash to reach scheduled temperature All temperatures in F. http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions ...
258fbe486201629f13868d080ae3a712a6bac743
666,539
def parse_args(argv): """Parse Alfred Arguments Args: argv: A list of arguments, in which there are only two items, i.e., [mode, {query}]. The 1st item determines the search mode, there are two options: 1) search by `topic` 2) search ...
a5a401abda9c00ecd4d21f6b361edfaf0b527bda
666,541
def bool_like(value, name, optional=False, strict=False): """ Convert to bool or raise if not bool_like. Parameters ---------- value : object Value to verify name : str Variable name for exceptions optional : bool Flag indicating whether None is allowed stric...
5383d41471a5a780b07455dfd8d98c47df680ee8
666,542
def import_custom_event(my_module): """Import CustomEvent from my_module.""" return my_module.CustomEvent
c64c06b8c76754c80b9928a3c6f03baae974d6da
666,543
from typing import MutableMapping from typing import Optional from typing import List def extract_dependencies(content: MutableMapping) -> Optional[List[str]]: """ Extract the dependencies from the Cargo.toml file. :param content: The Cargo.toml parsed dictionnary :returns: Packages listed in the dep...
7daed68e970210509979acdc600f0f11a68b266c
666,544
def identity(obj): """Returns obj.""" return obj
0ea589df24d3b480b604b9c67e56011d9b0102a6
666,545
from typing import Mapping def subdict(d: Mapping, keys=None): """Gets a sub-dict from a Mapping ``d``, extracting only those keys that are both in ``keys`` and ``d``. Note that the dict will be ordered as ``keys`` are, so can be used for reordering a Mapping. >>> subdict({'a': 1, 'b': 2, 'c': 3,...
ffd0578fa0ad642f6573ae392cb17e8c9220569f
666,546
import re def validate_name(name, minlength=1, maxlength=30, fieldname='name'): """Validates a name with length and regular expression criteria. Parameters ---------- name : str or QString Name to be validated. minlength : int The minimum length of the name. maxlength : in...
731a0d844ef88250c2aa47323215d96f6e3a9d9e
666,548
def strip_mate_id(read_name): """ Strip canonical mate IDs for paired end reads, e.g. #1, #2 or: /1, /2 """ if read_name.endswith("/1") or read_name.endswith("/2") or \ read_name.endswith("#1") or read_name.endswith("#2"): read_name = read_name[0:-3] return read_nam...
13d2467b837462c2a05ad0813cddc0279304d3d9
666,552
def build_content_type(format, encoding='utf-8'): """ Appends character encoding to the provided format if not already present. """ if 'charset' in format: return format return "%s; charset=%s" % (format, encoding)
771eecd94e37cab1f3ffbf9a671bd77fe3639be1
666,553
def Inside_triangle(p, a, b, c): """ inside_triangle(p, a, b, c) p: point (x,y) a, b, c: vertices of the triangle (x,y) >>> inside_triangle(p, a, b, c) """ detT = (a[0]-c[0])*(b[1]-c[1]) - (a[1]-c[1])*(b[0]-c[0]) lambda1 = ((b[1]-c[1])*(p[0]-c[0]) - (b[0]-c[0])*(p[1]-c[1])) / detT lambd...
78aa765746d12cdc7c1b4a4c75d2a311584a5da4
666,554