content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def box_iou(boxes1, boxes2): """Compute IOU between two sets of boxes of shape (N,4) and (M,4).""" # Compute box areas box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])) area1 = box_area(boxes1) area2 = box_area(boxes2) ...
8cec4aefcb8b9779b444f3095ea9b6b97cf456b0
686,206
def cli(ctx, common_name, directory, blatdb="", genus="", species="", public=False, metadata=""): """Add an organism Output: a dictionary with information about the new organism """ return ctx.gi.organisms.add_organism(common_name, directory, blatdb=blatdb, genus=genus, species=species, public=public,...
e82b2be65c0c54c1da744e5ae68d0b8125fab2c1
686,207
def _check_role(brain, match_kind, match, target_dict, cred_dict): """Check that there is a matching role in the cred dict.""" return match.lower() in [x.lower() for x in cred_dict['roles']]
257ece25588b7f6933c5e314be229c9ad937bb81
686,208
def _offdiag_offdiagf3(hessian_inp, K_phi, dGdXu, dGdXv, dGdYu, dGdYv, dGdZu, dGdZv, G, u, v): """off-diagonals of off-diagonal super elements (3rd term) """ hessian_inp[u*3,v*3+1] = hessian_inp[u*3,v*3+1] + (2*K_phi)/(1-G**2)*dGdXu*dGdYv hessian_inp[u*3,v*3+2] = hessian_inp[u*3,v*3+2] ...
669ea1d7dc5cc1bb4f6e8ed0b469847bd32ecf10
686,209
import requests def fetch_json(uri): """Perform an HTTP GET on the given uri, return the results as json. If there is an error fetching the data, raise an exception. Args: uri: the string URI to fetch. Returns: A JSON object with the response. """ data = requests.get(uri) ...
d42cf52a43e9a06e49b0ede3cae69e074b2cbae9
686,211
import re def read_intro(path): """ Reads the introduction out of the documentation page so that we can maintain it when we rewrite the file """ try: contents = open(path, "r").read() except FileNotFoundError: return "" match = re.search(r"\n# [^\n]*\n(.*?)\n## ", contents...
54245e640606fdc2817b8e031d15d1863a7eefc7
686,212
def my_method2(o): """ This is anoooother doctring of a method living inside package1. Why? Just because I wanted to have more than one. Parameters ---------- o : int Note that this parameter should be a string because it wanted to be different. Returns ------- Five...
15d67e2ecc7d617516e29a70555780ed628edce8
686,213
from vobject import icalendar from datetime import datetime def monkeypatch_vobject_performance(): """ This works around a performance issue in the unmaintained vobject library which calls a very expensive function for every event in a calendar. Since the slow function is mostly used to compare timezo...
7118cedf869172875b0f13f9aec668cfdca173cb
686,214
import requests def authenticate_with_refresh_token(client_id, redirect_uri, refresh_token): """Get an access token with the existing refresh token.""" try: url = 'https://api.tdameritrade.com/v1/oauth2/token' headers = { 'Content-Type': 'application/x-www-form-urlencoded' ...
dc08162e6316466b23715e59d1489e899c1c3789
686,215
def root_center(X, root_idx=0): """Subtract the value at root index to make the coordinates center around root. Useful for hip-centering the skeleton. :param X: Position of joints (NxMx2) or (NxMx3) :type X: numpy.ndarray :param root_idx: Root/Hip index, defaults to 0 :type root_idx...
0a2738cf902e0036e24eb36b646aec2207c9bbb6
686,216
def getOperands(inst): """ Get the inputs of the instruction Input: - inst: The instruction list Output: - Returns the inputs of the instruction """ if inst[0] == "00100": return inst[3], inst[4] else: return inst[2], inst[3]
90789fbc7f7effa2cae3a1db68e74bb125f2a109
686,217
def concatenate(symbs): """ ['C','H','H','H','H'] --> 'CH4' """ ns = len(symbs) formula = '' groups = [[],] cntg = 0 cnt = 0 while True: if cnt > ns - 1: break gs1 = groups[cntg] gs2 = [] sj = symbs[cnt] if sj not in gs1: ...
4de04864799fb785a5e7a874cf2bf9d81fa95db8
686,218
def checkfile(findstring, fname): """ Checks whether the string can be found in a file """ if findstring in open(fname).read(): #print(findstring, "found in", fname) return True return False
6f9afa50cf776c977010bbc14f95bd107f8a62d3
686,219
import argparse def check_range(value): """validate range""" try: minutes = int(value) except ValueError: raise argparse.ArgumentTypeError('%s is an invalid data type, Integer value expected.' % value) if minutes < 1 or minutes > 1440: raise argparse.ArgumentTypeError('%s is an...
a620b19ba76769cd91125e4019f3a0b986042572
686,220
def _digest_via_skip(graph): """ Skipping digestion """ return 0
5ab512c07887df755ac78f0a548fa7e444173962
686,221
def crop_region(image, region): """Crops a singular region in an image Args: image (image): A numpy image region (dict): A dictionary containing x1, y1, x2, y2 Returns: image: The cropped image """ return image[ region["y1"]:region["y2"], region["x1"]:region["x2"] ]
26566d9e081abcfffe41be227c6548a9a3a6cad5
686,222
from typing import Sequence import random def sample_coins(coin_biases: Sequence[float]) -> int: """Return integer where bits bias towards 1 as described in coin_biases.""" result = 0 for i, bias in enumerate(coin_biases): result |= int(random.random() < bias) << i return result
b9c2aa8e31e19a175229625da8958d3525343dbd
686,223
import os import errno def mkdir_p(path): """`mkdir -p` functionality (don't raise exception if path exists) Make containing directory and parent directories in `path`, if they don't exist. Arguments: path (str): Full or relative path to a directory to be created with mkdir -p Returns: ...
899929463ed446a1619d49bdcdd6eabe3d383839
686,224
import numpy def _sample(probability_vec): """Return random binary string, with given probabilities.""" return map(int, numpy.random.random(probability_vec.size) <= probability_vec)
f6acac073a9deb2562ff936b814751df6aad826c
686,225
import re def is_valid_email(email): """ Validates an email address. :type email: str :param email: The email address to be validated. :rtype: bool :return: True or False depending on whether field passes validation. """ if email is None: return False if not re.match(r'^...
9e5ee79ae76ec063183dd6aaeb0664ab72d38873
686,226
def get_webhook(file_name): """ Read webhook from a file. Note: the file must only contain one line, which is the whole url of webhook. """ with open(file_name) as f: return f.readlines()[0].strip()
29c12f2b4fa48c941a98b2b34739a5caaf4ad854
686,227
def _to_annotation_generator(fns): """" Generic method which takes a set of functions, and returns a generator that yields function.__name__, function result pairs. """ def fn_gen(c): for f in fns: yield f.__name__, f(c) return fn_gen
86423d60397b3f8988e9ce5bc5ae7d20de6ffac9
686,228
def find(func, iteratee): """Returns the first element that match the query""" for value in iteratee: if func(value): return value return None
0b081f2281b648479771f032cbd3aba1c8bca754
686,229
import inspect def get_wrapped_source(f): """ Gets the text of the source code for the given function :param f: Input function :return: Source """ if hasattr(f, "__wrapped__"): # has __wrapped__, going deep return get_wrapped_source(f.__wrapped__) else: # Returning ...
def0b8da05c56f04b65442cec0d5cf472ffa166c
686,230
import re def data_cleaner_cmd(TXT): """Return a list of tuples, that contains {function user name , function name, type of args, number of args} Keyword arguments: TXT -- a string that is all of the files already read to be processed """ regex = r" cmd_add\((.*),(.*),(.*),(.*)\);" Dirty...
402d2e04f11ff995cd3b0692105c0a28942764fb
686,231
def pad_sentences(sentences,padding_word="<PAD/>"): """ 填充句子,使所有句子句子长度等于最大句子长度 :param sentences: :param padding_word: :return: padded_sentences """ sequence_length=max(len(x) for x in sentences) padded_sentences=[] for i in range(len(sentences)): sentence=sentences[i] ...
123cf1a8d08eaba74792e6567e9d9b1512a29fcf
686,232
import argparse def parse_args(args): """Simple argument parser for the script""" parser = argparse.ArgumentParser(description='Populate local folders') parser.add_argument( '-t', '--token', type=str, help='Quip Access token') parser.add_argument( '-d', ...
f5c07897f4fa89077d86155524d7a865ec9aa395
686,233
def get_util2d_shape_for_layer(model, layer=0): """ Define nrow and ncol for array (Util2d) shape of a given layer in structured and/or unstructured models. Parameters ---------- model : model object model for which Util2d shape is sought. layer : int layer (base 0) for whic...
a56e00698b6d498800b895e83c84bed5b2ccc09d
686,234
import numpy def burst_dist(minimum, maximum, size=1): """ Generate an hrss drawn from the distance distribution \[ r + 50/r \] used for Burst allsky mock data challenges. Parameters ---------- minimum : float The lowest hrss to be produced. maximum : float The largest h...
b8603eaa55f4384cb575b47f584761f352a55893
686,237
def backtrack(bf): """ If this function is satisfiable, return a satisfying input upoint. Otherwise, return None. """ if bf.is_zero(): ret = None elif bf.is_one(): ret = frozenset(), frozenset() else: v = bf.top #v = random.choice(bf.inputs) upnt0 = fr...
591ebec8cc2ad15de5edcc7061a75942b753c005
686,238
def _urljoin(*parts): """Joins and normalizes URL path parts (not urls, like urlparse.urljoin).""" joined = '/'.join(part.strip('/') for part in parts) if parts[-1].endswith('/') and not joined.endswith('/'): joined += '/' if not joined.startswith('/'): joined = '/' + joined retur...
ee963ff5fdf3470cb0f64df7910a47f66210dfbb
686,240
from typing import Any def is_of_type_by_str(value: Any, type_str: str): """ Check if the type of ``value`` is ``type_str``. Parameters ---------- value: any a value type_str: str the expected type of ``value``, given as a str Examples -------- >>> is_of_type_by_...
d1090685bb2f0983481f3f1c9f355b1b3ed38adf
686,242
def default(base, deft): """Return the deft value if base is not set. Otherwise, return base""" if base == 0.0: return base return base or deft
98dd697f762acb056cb491d31c54e2d8ad47475e
686,243
def _is_windows_file(filepath): """ if file contains "\r\n", treat it as windows file, and return True, else False """ with open(filepath, 'rb') as f: content = f.read() if content.find(b'\r\n') != -1: return True return False
4b578142519e79f253a22dfe181221370c85a0d1
686,244
def _compute_welsh_performance(df, methods=('UPRN_ORIG', 'UPRN_PROTO', 'UPRN_SAS')): """ Compute performance for the Welsh dataset using SAS code UPRNs as a reference. :param df: dataframe containing UPRNs of methods as columns :type df: pandas.DataFrame :param methods: a tuple listing methods to a...
7fd2d65b6b0e66dd582fa4b2233a5a81027806a0
686,245
def points_to_svgd(p, close=True): """ convert list of points (x,y) pairs into a closed SVG path list """ f = p[0] p = p[1:] svgd = 'M%.4f,%.4f' % f for x in p: svgd += 'L%.4f,%.4f' % x if close: svgd += 'z' return svgd
9d9f9c94757d8f99d11c4d7959ca4baff2adc290
686,246
def __nnc_values_generator_to_list(self, generator): """Converts a NNC values generator to a list.""" vals = [] for chunk in generator: for value in chunk.values: vals.append(value) return vals
d2e269088fd93fc740c006cd69aad87695ca5a74
686,247
def get_kinyanjui_type(ita): """ This function will take a ita value and return the Fitzpatrick skin tone scale https://arxiv.org/pdf/1910.13268.pdf :param ita: :return: """ if ita <= 10: return "dark" elif 10 < ita <= 19: return "tan1" elif 19 < ita <= 28: re...
1cadf08a90ce62278ac67d42826f2b5f71ac505f
686,248
import re def camel_to_snake_case(in_str): """ Convert camel case to snake case :param in_str: camel case formatted string :return snake case formatted string """ return '_'.join(re.split('(?=[A-Z])', in_str)).lower()
a905bd2007fcaafed1e811a48c5fe14831e77631
686,249
def get_collection_fmt_desc(colltype): """Return the appropriate description for a collection type. E.g. tsv needs to indicate that the items should be tab separated, csv comma separated, etc... """ seps = dict( csv='Multiple items can be separated with a comma', ssv='Multiple items...
f9ac54559042a1f9ae3180e5c303f3a1aa29913e
686,250
def mode(request): """Yield a data mode.""" return request.param
dbf26893c266130f7ffc7e8e5e5318b615232ff2
686,251
from typing import Callable def interpolator(source_low: float, source_high: float, dest_low: float = 0, dest_high: float = 1, lock_range=False) -> Callable[[float], float]: """ General interpolation function factory :param source_low: Low input value :param ...
c1c399459157cb4d16527add9b058b17eda38cc3
686,252
import struct def of_slicer(remaining_data): """Slice a raw bytes into OpenFlow packets""" data_len = len(remaining_data) pkts = [] while data_len > 3: length_field = struct.unpack('!H', remaining_data[2:4])[0] if data_len >= length_field: pkts.append(remaining_data[:length...
77bd851e4b3fc1111c5142fab1439820c165989b
686,253
import os import json def create_json_corpus(filepath='corpus.json'): """ Creates a list of sentences from the BBC dataset and saves it as a JSON file. The main BBC folder should be located in the article-summarizer folder. :param filepath: The location at which to save the JSON file. :type filep...
568575cc85d67bf1cbfa50d262faecef64f57edd
686,254
def no_trajectory_vehicle_data(): """ No trajectory vehicle data """ return ()
8c2fff053af9b8b68dbacd0642ab703ff67e76f5
686,255
def samples_each_node_for_iteration(it_before, ot_before, num_nodes, graph, num_train): """ Parameters ---------- it_before: list initial status for whole samples ot_before: list final status for whole samples graph: graph num_nodes: int num_train: int Returns --------- ...
9ab1d037da24a4df5a1c0b125908ad9f46e425d4
686,256
import torch def score_fn(Z): """ We evaluate the sparse code's L0 norm, specifically the average L0 norm, the standard deviation and the top 99% value. :param Z: Sparse code to evaluate. :return: Float, Float, Float. L0 norm mean, L0 norm std, top 99% L0 norm value. """ norm = torch.norm(Z, p...
0e51eecbc18dadd2f1a09417539580962722b498
686,257
import re def _intermediate_to_final(script_data): """All shell blocks are first compiled to intermediate form. This part of code converts the intermediate to final python code :param script_data: the string of the whole script :return: python script ready to be executed """ intermediate_patt...
98529df0f566bcbed0d5d9fd5a269b00490f8291
686,258
def javaVarName(name): """Make a name like "asdf_adsf" into camel case at the locations of "_" and start with a lowercase letter.""" while "_" in name: idx = name.index("_") name = name[:idx]+name[idx+1:idx+2].upper()+name[idx+2:] #return name[0].lower()+name[1:] # allow user to actually spe...
9a36385f8ea4b26072e31bf4e476e9faa2a16127
686,259
def ne(value, other): """Not equal""" return value != other
27a1b98a96b184c359a2fe5ed4c6692e59632a71
686,260
def type_match(haystack, needle): """Check whether the needle list is fully contained within the haystack list, starting from the front.""" if len(needle) > len(haystack): return False for idx in range(0, len(needle)): if haystack[idx] != needle[idx]: return False return ...
7bb2c9db85647d8fff144a7ac23522cd624d9e79
686,261
import importlib def create_model(hypes): """ Import the module "models/[model_name].py Parameters __________ hypes : dict Dictionary containing parameters. Returns ------- model : opencood,object Model object. """ backbone_name = hypes['model']['core_method']...
92585d88aeef12783846334bdce037a59d696de4
686,262
def _matchfinder(start_idx, gs, data_len): """ Finds the shortest not repeating sequences according to the Lempel-Ziv algorithm :param start_idx: starting point in the array from which search will be started :param gs: symbol series :param data_len: data length :return: current starting index and the shortest non...
8be3fade12d2b45767a00d3e98493e766c64b0ce
686,263
def get_range(xf, yf, low, high): """Gets the values in a range of frequencies. Arguments: xf: A list of frequencies, generated by rfftfreq yf: The amplitudes of frequencies, generated by rfft low: Lower bound of frequency to capture high: Upper bound of frequency to capture ...
e213008fd3bd4e2db9b3326a23f6db6c0c1c2612
686,265
def instruction(): """ 打开软件时给的直观指示 :return: """ return """ ==课程网站小助手 V2.5.0== 输入数值范围,在国科大课程网站中搜索本科生/研究生课程 [使用实例] 1)先运行测试(T)并理解所生成的文件 2)在默认模式输入 163564 到 164505 搜索2019秋季学期本科课程 3)如果运行闪退,重开软件并读档(L) 4)运行结束后,用 Excel 的筛选功能选出感兴趣的课 5)将感兴趣的课末尾的“选中”列设为1,其他的课删掉或者将“选中”值清空 6)保存到原文件,然后重开软件进入打印模式(P)一路回车,生成课程表预览 [...
5cfff62b678a232815768e6a0747c43f5e2d4250
686,266
def webattack_vector(attack_vector): """ Receives the input given by the user from set.py """ return { '1': "java", '2': "browser", '3': "harvester", '4': "tabnapping", '5': "webjacking", '6': "multiattack", }.get(attack_vector, "ERROR")
c5b3415c8dd7d6ac5790c5e699a88b44dd2288a1
686,267
import pickle def pickle_load(path): """Un-pickles a file provided at the input path Parameters ---------- path : str path of the pickle file to read Returns ------- dict data that was stored in the input pickle file """ with open(path, 'rb') as f: return...
8d68e349118eb2fa2d5c1ce5b31b65cbc29a382f
686,268
def get_children(nodeData, wsChildrenDic=dict(), firstChild=None, word2ballDic=None): """ get all children of a node if firstChild is given, order the children list :param nodeData: :param wsChildrenDic: :param firstChild: :return: """ if word2ballDic: chlst = [ch for ch in ...
905e440f8095828b15ed1624fdc1fd38fac1ca61
686,269
import re def preprocess_for_tweet(input_text: str) -> str: """前処理""" # Tweet内の改行コードの削除 input_text = input_text.replace('\n', '') # ハッシュタグ削除 input_text = re.sub(r'#.*', "", input_text) return input_text
7c89c5de7a573d181a3594e63ac2c8bc47046b38
686,270
from typing import Any import json def is_json_serializable(obj: Any) -> bool: """Check if the object is json serializable Args: obj (Any): object Returns: bool: True for a json serializable object """ try: json.dumps(obj, ensure_ascii=False) return True except: return False
4cbc7c1a0f40bbf29d7b1a54d3dff83c04c8c44a
686,271
def shortest_path(g, start, goal): """ Complete BFS via MIT algorith g -> Graph represented via Adjacency list (Dict of sets) start -> start vertex goal -> end vertex Returns shortests path from start to goal """ # level will contains shortest path for each vertex to start level = {sta...
d2eb7e4daa567040b19e3f187334d0552f23f325
686,272
def get_table_list(args): """ Generates the ncols x nrows list of files to show in the table """ ncols = 1 nrows = len(args.column1) table_list = [args.column1] col_idx = 2 while True: column_name = f"column{col_idx}" if getattr(args, column_name, None) is not None: ...
714698e2f9332d647984cb4cb140f91492f4baca
686,273
from typing import OrderedDict def parsed_aggregate_reports_to_csv_rows(reports): """ Converts one or more parsed aggregate reports to list of dicts in flat CSV format Args: reports: A parsed aggregate report or list of parsed aggregate reports Returns: list: Parsed aggregate rep...
cf9d4ec758c377264c0d187f229e37be978d498d
686,274
import numpy def collect_peak_pairs(spec1, spec2, tolerance, shift=0, mz_power=0.0, intensity_power=1.0): # pylint: disable=too-many-arguments """Find matching pairs between two spectra. Args ---- spec1: numpy array Spectrum peaks and intensities as numpy array. ...
551fff7fc34ac9b745eca53267377b597bee8711
686,275
import re def fix_links(chunk, tag2file): """Find and fix the the destinations of hyperlinks using HTML or markdown syntax Fix any link in a string text so that they can target a different html document. First use regex on a HTML text to find any HTML or markdown hyperlinks (e.g. <a href="#sec1"> or ...
5816ba69c2ee04427fbde8f355eb8c4c379805fb
686,276
def is_numeric(value): """Test if a value is numeric.""" return isinstance(value, int) or isinstance(value, float)
6aed83b3c21554a79d3d11719cf200bdac1645c1
686,277
def value_of(column): """value_of({'S': 'Space Invaders'}) -> 'Space Invaders'""" return next(iter(column.values()))
9a18923c805bdd71c7bf94c933f96f4384e9fb02
686,278
import six import json import zlib import base64 def send_request(req_url, req_json={}, compress=False, post=True, api_key=None): """ Sends a POST/GET request to req_url with req_json, default to POST. Returns: The payload returned by sending the POST/GET request formatted as a dict. """ # Get the...
323ed8230e1fecae16f3b3307658aa2457d7cc7b
686,279
import re def isEndStoryText(string): """ Return True if reach the end of stories. """ match = re.search(r'^\*\*\*', string) if match == None: r = False else: r = True return r
36f2b8f333c4188c2c3a53a6da036308e8a8152e
686,281
def datedDirPath(buildid, milestone): """ Returns a string that will look like: 2009/12/2009-12-31-09-mozilla-central """ year = buildid[0:4] month = buildid[4:6] day = buildid[6:8] hour = buildid[8:10] datedDir = "%s-%s-%s-%s-%s" % (year, month...
9cc0f64ba467527aa6a42490b67e87ed0f8c5e39
686,282
def offensive_contribution(team_yards, player_yards): """ Calculate a percentage for the percentage of team yards that a player contributes to. Input: - Dataframe to use in the calculation Output: - New dataframe column with the desired contribution score """ ...
38ecbd9265b7a3b6c9938d5eae2d644ec455e106
686,283
def depth(obj): """ Calculate the depth of a list object obj. Return 0 if obj is a non-list, or 1 + maximum depth of elements of obj, a possibly nested list of objects. Assume: obj has finite nesting depth @param int|list[int|list[...]] obj: possibly nested list of objects @rtype: int ...
6a1605b9bad8ba9255ef786dd8108c293bfd0205
686,285
def rank_zero_output_only(func): """ Wrapper function that detects whether mpi4py is available and forces all ranks to output from rank 0 only. Intended to be used as a decorator where mpi-enabled MCMC kernels are deployed. Example use case: in the built-in mpi implementation of MCMC (ParallelM...
e31667b7375c1d52e74587ad5681e8b25bdb3a7d
686,286
def example(self): """Get and cache an example batch of `inputs, labels` for plotting.""" result = getattr(self, '_example', None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache it for next time self._example = resu...
6e8c55892ce199794b5b8b73837b6475a339f0d5
686,287
def get_rel_pos(abs_pos, ex_num, rel_starts): """Convert absolute position to relativ.""" if len(rel_starts) == 1: return abs_pos ex_num_0 = int(ex_num) - 1 rel_pos_uncorr = abs_pos - rel_starts[ex_num_0] rel_pos = rel_pos_uncorr if rel_pos_uncorr >= 0 else 0 return rel_pos
9196d6f212920425fd6bdeebbf32fb4d8578b641
686,288
from typing import List def _get_name_matches(name: str, guess_words: List[str]) -> int: """ Return the number of common words in a str and list of words :param name: :param guess_words: :return: number of matches """ matches = sum(word in name for word in guess_words) return matches
c73335ea6c186626e1823e2a4775ed987d78adaf
686,289
def repo_url_to_full_name(url): """Convert a repository absolute URL to ``full_name`` format used by Github. Parameters ---------- url : str URL of the repository. Returns ------- url : str Full name of the repository accordingly with Github API. """ return "/".join(u...
b7deb19b97929b2286d7e1ea5005b8674bdf9f50
686,290
def compute_trunc_basis(D,U,eng_cap = 0.999999): """ Compute the number of modes and truncated basis to use based on getting 99.9999% of the 'energy' Input: D -- dictionary of singular values for each system component U -- dictionary of left singular basis vector arrays eng_cap -- fraction of en...
64b6772a693926f1721366763ff4e04d6c0cc6bc
686,291
def calculate_variance(n, p): """ Calculate the sample variance for a binominal distribution """ return p * (1 - p) / n
b5aeaf0201a1a0c2b0de0359165f4cc746c40291
686,293
def _is_image_available(context, image): """Check image availability. This check is needed in case Nova and Glance are deployed without authentication turned on. """ # The presence of an auth token implies this is an authenticated # request and we need not handle the noauth use-case. if has...
312a08bf0047117288cf659b6562ece03ed7ab09
686,294
def _arguments_str_from_dictionary(options): """ Convert method options passed as a dictionary to a str object having the form of the method arguments """ option_string = "" for k in options: if isinstance(options[k], str): option_string += k+"='"+str(options[k])+"'," ...
6f0cf1176f0bcada81dc8dbe17cb57e760fd4d8c
686,295
def get_result_expressions(resultMap, tp): """ Returns the expression that needs to be evaluated :param resultMap: :param tp: :returns: """ def expr(row): try: return row[4](tp) except AttributeError: return "(undefined)" return list(map(expr, res...
68ed2d015e959e02f4ff8c1878c8a1179c80da37
686,297
def transpose(matrix): """ Takes transpose of the input matrix. Args: matrix: 2D list Return: result: 2D list """ result = [[matrix[col][row] for col in range(len(matrix))] for row in range(len(matrix[0])) ] return result
a7d0394170077775b5846953c5f17184665ac09d
686,298
def _parse_errors(error_string): """ Parse the returned error data string from the Tesseract process. Any line that contains the keyword "Error" will be returned. """ result = error_string if error_string: lines = error_string.splitlines() error_lines = tuple(line for line in l...
4821bb1d497618dfd487cc78fb5a6a635df98734
686,299
from typing import Optional from typing import Dict from typing import Any import jinja2 def merge_template(template_filename: str, config: Optional[Dict[str, Any]]) -> str: """Load a Jinja2 template from file and merge configuration.""" # Step 1: get raw content as a string with open(template_filename) a...
f3edcf327ba4b35aa9a6f5a063c4a735848387d0
686,300
def unique2(s): """Return True if there are no duplicate elements in sequence s.""" temp = sorted(s) # create a sorted copy of s for j in range(1, len(temp)): if temp[j - 1] == temp[j]: return False # found duplicate pair return True
e5d0de37aa2b1967261df067bb720cd9e5965d85
686,301
def anonymise_max_length_pk(instance, field): """ Handle scenarios where the field has a max_length which makes it smaller than the pk (i.e UUID). """ if hasattr(field, "max_length") and field.max_length and len(str(instance.pk)) > field.max_length: return str(instance.pk)[:field.max_length]...
6530563a04548008c98596de0d1d22f7d1c8f5c3
686,302
import torch from typing import List def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor: """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc:location predictions for loc layers. Shap...
afed28303a045edc6c9f6fc30da4efd051ea0858
686,303
def s_hex_dump(data, addr=0): """ Return the hex dump of the supplied data starting at the offset address specified. :type data: Raw :param data: Data to show hex dump of :type addr: int :param addr: (Optional, def=0) Offset to start displaying hex dump addresses from :rtype: str :r...
cb75811057adfe8c02cef51a27a4f28d5061786b
686,305
def wrap_argument(text): """ Wrap command argument in quotes and escape when this contains special characters. """ if not any(x in text for x in [' ', '"', "'", '\\']): return text else: return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), )
e398e91a1ae3b218ba0ad88f6aeba9be7dc3ebdd
686,306
import time def epoch_to_utc(epoch=0, time_format='%Y-%m-%dT%H:%M:%SZ'): """ :param epoch: :param time_format: :return: """ return time.strftime(time_format, time.gmtime(epoch))
6eb9b7ec21be439130c2ba7fdef4882f49c470b3
686,307
def exp_lr_scheduler(optimizer, epoch, init_lr=0.001, lr_decay_epoch=500): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr + 1e-4*epoch #(1.0001**epoch) #* (0.65**(epoch // lr_decay_epoch)) """c = init_lr b = 0.1 d = 200 lr = c + b - (b/d)*abs(d - epoc...
bd56123ee0f6187f1152442cbac86b3de888aa3f
686,308
def filter_dict(pred, d) : """Return a subset of the dictionary d, consisting only of the keys that satisfy pred(key).""" ret = {} for k in d : if pred(k) : ret[k] = d[k] return ret
e51bae7cdd663287b9f90b95f12025a51fdaadc5
686,309
def loader_cgd(path: str, spliter: str='-'*20) -> list: """Load code gadget file from path cgd file is a file looks like: ... title function name code block label '-'*n, n>5 title ... Args: path (str): path of the file """ sa...
c0e8fa8e891fbcf02f246761de4769bb8d50fe2f
686,310
def validate_ranges(ranges): """ Validate ASN ranges provided are valid and properly formatted :param ranges: list :return: bool """ errors = [] for asn_range in ranges: if not isinstance(asn_range, list): errors.append("Invalid range: must be a list") elif len(a...
a1e716b1a4f81bc426d8765dbdc7d2fff7816e7a
686,311
from typing import Dict from typing import Any def color_menu(colno: int, colname: str, entry: Dict[str, Any]) -> int: """Find matching color for word :param word: A word to match :type word: str(able) """ if colname in ["__name", "title", "inventory_hostname"]: return 10 if colname =...
8eba5411d669439137d30b62c593ae5336be3c75
686,312
import random def hash_function2(hash_string, hash_dict_length) -> str: """Calculates a different hash index to hash_function1.""" seed = int.from_bytes(hash_string.encode("utf-8"), "big") random.seed(seed) hash_index = random.randint(-(2 << 64), (2 << 64)) % hash_dict_length return str(hash_index...
0d86c9ff931c784adef85758019134833150c022
686,313
import json def df_to_dict(df, orient='None'): """ Replacement for pandas' to_dict which has trouble with upcasting ints to floats in the case of other floats being there. https://github.com/pandas-dev/pandas/issues/12859#issuecomment-208319535 see also https://stackoverflow.com/questions/37897527...
684cb946dd59c5e30084f61435bd9e7d349d3940
686,314
def should_crawler_wait(db): """Check if crawler can terminate or not""" result = db['Urls'].find_one({'$or': [ {'$and': [ {'visited': False}, {'queued': True}]}, {'$and': [ {'visited': False}, {'queued': False}, {'timeout': {'$exists':...
03be43e1376663018473f2a08dbe1cf06f5fb326
686,315
def create_data_model(distancematrix): """ Create a dictionary/data model Parameters: distancematrix (float[][]): array of distances between addresses Returns: dictionary: data model generated """ # initiate ORTools data = {} data['distance_matrix'] = distancematrix ...
de4968895a15793c1981e18f6731233323752526
686,316