content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def create_seed(type_seed): """renvoie la seed r_pentomino""" if type_seed=="r_pentomino": return [[0, 1, 1], [1, 1, 0], [0, 1, 0]]
68bc055512c52c1040a05484056f92d69711af98
659,725
import pickle def load_pickle(file_path = "data.pickle"): """ Loads a pickle file created with `create_pickle()` :param file_path: Path of pickle file :type file_path: str :return: Serialized object :rtype: object """ with open(file_path, "rb") as readFile: data = pickle.load(...
1611bef0e2af40efe6f720c247d4a36d26142454
659,726
def plotFinal(solPlot,aSolPlot,tn,test,tpars,problems, mlMesh,mlScalarTransport,testOut): """ plot out solution and mesh at last step in a couple of formats """ if tpars['DG'] == False: solPlot.hardcopy(testOut+'_sol.eps', eps=1,enhanced=1,color=1) aSolPlot.hardcopy(testOut...
413a5d110b557f60cd7155a5edf9a83bc0a1658a
659,727
import re import yaml def parse_front_matter_and_content( contents: list[str], ) -> tuple[dict[str, str], list[str]]: """ Parse a list of all lines in a file into: front matter (merged result of existing ones and title + preview image) all markdown lines in the content apart from the recipe na...
85a2a49dac688d07427394ec4d2b3a7a3e546693
659,728
import sys def pars2idx(pars, vocabulary, verbose = True): """ Convert paragraphs to word indexes of a vocabulary :param pars: list of paragraphs :type pars: list Return: list of word-indexed paragraphs """ pars_idx = [] npars = len(pars) for i in range(npars): p_i...
a3ed5c9e4f4117835699894930e1f4d9e653ff96
659,729
def get_mean_and_med_age(d): """ Calculate mean and median age of passengers :param d: data frame :return: rounded mean amd median """ return round(d['Age'].mean(), 2), d['Age'].median()
9a8478ffb654a1981fed8ede651c988a110102bd
659,730
def hzip(x): """ Zips the first and second half of `x`. If `x` has odd length, the last element will be ignored. >>> list(hzip([1, 2, 3, 4, 5, 6])) [(1, 4), (2, 5), (3, 6)] >>> list(hzip([1, 2, 3, 4, 5, 6, 7])) [(1, 4), (2, 5), (3, 6)] """ N = int(len(x) // 2) return zip(x[:N...
c99214a2f8e3110b0d070ed5fa3fdd428cb0dd6b
659,731
def human_readable_number(number: float) -> str: """Print a large number in a readable format. Return a readable format for a number, e.g. 123 milions becomes 123M. Args: number: a float to be printed in human readable format. Returns: readable_number: a string containing the formatted number. """ ...
70febc0c4ffe38bf2592209d1b490ae335d442f4
659,732
from typing import Mapping import six def make_vocab(texts, normalize=lambda x: str(x).lower().strip()): """Convert gender strings into integers and return translation dict >>> make_vocab(list('MFMMF')) == {'F': 0, 'M': 1} True """ return dict([(t, i) for (i, t) in enumerate(sorted(set(texts)))])...
7df9977e49b10f4a3a110621a5c35e4b849661e4
659,733
def write_dot(g): """Replacement for pygraph.readwrite.dot.write, which is dog slow. Note: This isn't a general replacement. It will work for the graphs that Rez generates, but there are no guarantees beyond that. Args: g (`pygraph.digraph`): Input graph. Returns: str:...
01b34ff8644ece4d3204e59b934040e66eecdd08
659,734
import sqlite3 import pandas import os def get_cdr_cluster_df(db_path): """ Get a dataframe with typical cluster info in it, which was generated by the features reporter framework. :param db_con: sqlite3.con :rtype: pandas.DataFrame """ query="SELECT "\ "structures.input_tag," \ ...
6f39e7db68b0838f37eb8b2f3edf985870fe78a3
659,735
def is_batch_over__linear(cnt, stop): """Dummy function as linear sampling ends when it's corresponding index generator `get_linear_index` stops. `cnt` and `stop` are ignored. value. :return bool: always False """ return False
a5796f5b223206bfc8aa03ffc3027074b2bcfacf
659,736
def simplify(conc_results): """Turn concordance output into something slightly more human-readable""" out = [] for r in conc_results: if len(r) == 3: out.append( [r[1][0], r[1][1]] + [r[0][i] for i in r[0][-1]] ) else: # Have context a...
f46e6406ed50c1c47f2eb8d4c5ef90beb8c89274
659,737
import re def _results_from_main_index(fields, query_regex, time_series_stem=''): """_results_from_main_index Returns dictionary mapping elasticsearch field names from fields to pairs containing that field's values that match query_regex, and a boolean indicating if the field is a time series fie...
dccc0160cae9eaba8131f20653db3b08572d936f
659,738
def getFrameIndex(t, fs): """ calculates and returns the frame index of at a given time offset within a signal @param t the time offset [s] @param fs sampling frequency [Hz] """ return int(round(float(t) * float(fs)))
b541ef24f5825089624223ebedbb195e858167c0
659,739
import re def get_filename(cd: str) -> str: """Returns filename from content disposition header.""" return re.findall(r'filename\*?=[\'"]?(?:UTF-\d[\'"]*)?([^;\r\n"\']*)[\'"]?;?', cd)[0]
3646bca9173aa3e5c37b82e6b1cbedc1bb14b9dd
659,741
import random import os def _random_slug(rng=random) -> str: """ >>> rng = random.Random(42) >>> _random_slug(rng) 'earsplitting-apricot' """ here = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(here, 'adjectives.txt')) as f, open(os.path.join(here, 'food_names.txt'...
7338e9e816d4c561302b74f4bcae72b42266b1a6
659,742
import re def natsort(s): """ Natural sorting, e.g. test3 comes before test100. Taken from https://stackoverflow.com/a/16090640/3110740 """ # if not isinstance(s, (str, bytes)): return s x = [int(t) if t.isdigit() else t.lower() for t in re.split('([0-9]+)', s)] return x
3bc4b9aaec3e4eba149f728fd826a68a7574b42f
659,743
def GetAdapterName(): """ Required module function. @returns The name of the adapter. This is the name by which a client registration protocol is matched. """ return "spacepacket"
51e07866deb4f369d4794ae36a379cf6f57e394c
659,744
def size_from_shape(shape): """Returns size from the shape sequence """ size=1 for d in shape: size*=d return size
86b45daa7b93baec8d361066f900780b7cfbae61
659,745
def remove_suffix(x, suffix=" "): """ Remove a specific suffix from the end of a string. """ if x.endswith(suffix): x = x[: -len(suffix)] return x
3953e90dec3042fa6167b29bcbf4da3b9a53ff84
659,746
def collatzSeq(n, outputSeq = None): """ collatzSeq(int, list) -> list accepts two inputs: - n (required): the integer against which the conjecture is about to be tested - outputSeq (optional): only used during ricursion to store the state of the current test """ if outputSeq is None: ...
44e18ef019b76b1aac1ce145551bc5cc78ac8baa
659,747
def is_boolean(op): """ Tests whether an operation requires conversion to boolean. """ return op in ['or', 'and', '!']
5989c5db1befe76e61baa22a313b2d2e8f201553
659,748
def notas(*notasalunos, sit=False): """ Função para analisar notas de alunos e situações da turma. :param notasalunos: uma ou mais notas de alunos. :param sit: (valor opcional). Se True, mostra a situação da turma. :return: dicionário com várias informações sobre a situação da turma. """ con...
fdb8efe9ad27403f0c6f670bcbf8610095c6d1a9
659,749
def dumps(name, namelist): """ Writes a namelist to a string. Parameters ---------- name : str The name of the namelist namelist : dict Members of the namelist Returns ------- str String representation of the namelist """ # start with the opening mar...
6347d26bb07be8172ea04c193e2f077a77218d75
659,750
import argparse def get_args(): """Parse commandline arguments.""" parser = argparse.ArgumentParser(description='Export.') parser.add_argument( '--config_path', type=str, required=True, default='', help="json file for dataset" ) parser.add_argument( ...
88fec5825307690604551aca6cf47448665c038f
659,751
def trimquotes(s): """ Remove the single quotes around an expression:: trimquotes("'test'") == "test" :param s: expression to transform :type s: string :rtype: string """ if not s: return '' s = s.rstrip() if s[0] == "'" and s[-1] == "'": return s[1:-1] return s
d65786fa51b65db09906c644c206ff6f89398f0d
659,752
def js_in_head(request, registry, settings): """Should ``<script>`` tags be placed in ``<head>`` or end of ``<body>``. """ on_demand_resource_renderer = getattr(request, "on_demand_resource_renderer", None) if on_demand_resource_renderer and on_demand_resource_renderer.is_js_in_head(request): r...
f6b6cee36da0a0a9933e29f48fb19395e6ed75f5
659,753
def callback_UpdateMap(cm, mod_units, window): """ Updates the biomap after newVal is selected and applied Parameters ------------- cm = dictionary, Current Modular Units of bioprocess mod_units = list of str, list of Modular Unit names window = GUI object Returns None ----------...
7d8e50d565fb68684c78536502b8fbdc455ca6d0
659,754
import subprocess import re def is_nano(editor): """Check whether editor is nano by running ``nano --version`` and checking regular expression for output. Shown below is the expected output, we will check if output contains "GNU nano" .. code-block:: console  ~/ nano --version GNU nano...
5074d19ddf8670da3f09d864bf0e0bf83e037420
659,755
def get_client_previous_url(request): """ :param request: :return:访问用户的前一个地址 """ try: url = request.META.get('HTTP_REFERER') except: url = None return url
7e21c7a8522779f4c194f03efaafa83b75149cb5
659,756
def sumall(*args): """ Take any number of arguments and return their sum """ sumall = 0 sumall = sum(args[0], *args[1:]) return sumall
e78f683cde5e01be88fa6c5e35cdf1b4f7a20586
659,757
from typing import Any from typing import MutableSequence def ensure_list(value: Any, convert_csv: bool = False, delimiter: str = ',') -> MutableSequence[Any]: """Convert an object, response, or (optionally) comma-separated string into a list""" if not value: return [] elif isinstance(value, dict)...
76262a0620e4988071eac3a28bd504801b938915
659,758
import os def _is_go_yaml(file_path): """Whether or not this is a go yaml path.""" return os.path.basename(file_path).startswith('go-')
6fe46507683d50a1eb3877afd6c408e06cad12ec
659,759
def normalize(params, norm=1): """Normalize the model""" base = len(params) % 6 assert base in (0, 1), 'Invalid params length.' normalized = params.copy() oldnorm = params[base::6].sum() normalized[base::6] *= norm / oldnorm return normalized
10b75f6350c179e5daa717f948fc51b8d8607beb
659,760
import re def set_initial(layout): """Process given layout info and generate a representative list.""" micro_regex = re.compile(r'a (\w)\w+-compatible microchip') gen_regex = re.compile(r'a (\w)\w+ generator') floors = [] for floor in layout: chips = micro_regex.findall(floor) gens...
816a424dd111feccd0fb29fbcdc2982e43269fee
659,761
import numpy def objListUtility_xAxis( featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() """ xaxis = numpy.linspace( start=0, stop=featLen, num=numBins ) return xaxis
907d70a4379ecd5cf9fcb46ed2d48eef7d891229
659,762
def _player_n_frame(base_df, n): """Create a dataframe of player level results for the nth player in a game frame This just gets called in player_level_df, doesn't need to be called directly Properties ---------- base_df: pd.DataFrame game level dataframe n: int the player ...
4aa3666cae22eb9be8ded796f6ee7e1d6f916610
659,763
import torch def warp_homography(sources, homography): """Warp features given a homography Parameters ---------- sources: torch.tensor (1,H,W,2) Keypoint vector. homography: torch.Tensor (3,3) Homography. Returns ------- warped_sources: torch.tensor (1,H,W,2) ...
c99e4e00606604dea152b5de7c513f69eb646d2e
659,764
def edges_to_line(edges, N): """ Returns a list of integers corresponding to a relabellign of the edge tuples by mapping (i,j) --> to N*i + j as per my convention for labelling of lineP, lineT. """ def relabel(edge): return N*edge[0] +edge[1] newlist = list(map(relabel, edges)) retu...
e5c0fe985e5b82e324467e74fd4b46314893cc50
659,765
def _build_efi_transition_impl(settings, attr): """ Transition that enables building for an EFI environment. Currently ony supports C code. """ return { "//command_line_option:crosstool_top": "//build/toolchain/llvm-efi:efi_cc_suite", }
998710087684fbbcdcf4e28a8bfca2782ef09d12
659,767
def tanh_derivative(x): """ Actual derivative: tanh'(x) = 1 - (tanh(x))^2 but logic same as sigmoid derivative """ return 1 - x ** 2
634ca05b16f223c21943d26fd8c4541a355adede
659,768
def decode_ed25519(limbs): """ Decodes hexcoded limbs with 25.5 radix to Zmod(2^255-19) integer :param n: :return: """ n = 0 c = 0 shift = 0 bits = [26, 25, 26, 25, 26, 25, 26, 25, 26, 25] for i in range(10): n += ((limbs[i] & ((1 << bits[i]) - 1)) + c) << shift ...
dd70b526afe4289d98c7910032ed4d2ade6d3384
659,769
import re def search_re(out, l): """ Search the regular expression 'l' in the output 'out' and return the start index when successful. """ m = re.search(l, out) if m: return m.start() return None
c20c5df306c9f0914825fb1e2c10d0ef5590dda6
659,770
import doctest def test_suite(): """Test doctest as unittest.""" # This should help with https://github.com/pytest-dev/pytest/issues/1862 return doctest.DocFileSuite('../../../../README.rst')
098e4e93489c85880a3438fa9f68e09baa6eec0c
659,771
from typing import Union import multiprocessing import re def parse_num_processors(value: Union[str, int, float]): """Convert input value (parse if string) to number of processors. Args: value: an int, float or string; string value can be "X" or "MAX-X" Returns: An int of the number of pro...
174f825c00946e80a64ce998508d34149e01bf14
659,772
import os def get_ansys_bin(rver): """Identify the ansys executable based on the release version (e.g. "201")""" if os.name == 'nt': ans_root = 'c:/Program Files/ANSYS Inc/' mapdlbin = os.path.join(ans_root, 'v%s' % rver, 'ansys', 'bin', 'winx64', 'ANSYS%s.exe' ...
e5d4bb6e3fd13cf0ffca14371e2a7994631807b5
659,773
def TagValues(d, lstTagValues): """ Return TRUE if you have a match within the list of tags (strings) """ bool = False if d['TAG'] in lstTagValues: bool = True return bool
978e1d7b0060339c3b9e4c92998096788cd7c8ab
659,775
def i_from_jk(j, k, olist): """ Inverse operation of jk_from_i: gives one list index from 2 Args: j, k: indices corresponding to the location of an element in the organized list olist: the organized list of Wyckoff positions or molecular orientations Returns: i: one...
cd8f6476c947c009dd5d3451c1f32011fd9d28f0
659,776
def shift_TTD_dailyconservation_idx_rule(M): """ Index is (window, day, week, tour type). The index set gets used in the TTD_TTDS_con and TTD_TT_UB constraints. :param M: :return: Constraint index rule """ return [(i, j, w, t) for i in M.WINDOWS for j in M.DAYS for ...
07a65fe45bab32eaf53bd8f1182df32fb2930038
659,777
def valid_input_devices(self): """ See which devices can be opened for microphone input. call this when no PyAudio object is loaded. """ mics=[] for device in range(self.p.get_device_count()): if self.valid_test(device): mics.append(device) ...
81e2c2e692b6263e8a22d97eb4e85ea7a70ce77e
659,778
def create_moodle_professor() -> str: """Return the query responsible for creating the moodle professor table on the database which is used to get the status of assignments""" return ( "CREATE TABLE IF NOT EXISTS moodle_professors (" "course varchar(3)," "semester varchar(2)," ...
432d1777cf5abcad6dd452a0b6b202968253f1c8
659,780
import os def normalize(path): """Normalize paths from git, handling non-ASCII characters. Git for Windows, as of v1.7.10, stores paths as UTF-8 normalization form C. If path contains non-ASCII or non-printable chars it outputs the UTF-8 in octal-escaped notation, double-quoting the whole path. Doubl...
782f95706af563345a12fe03b7e5fdbf4f7d7b0e
659,781
def complete(tab, opts): """ get options that start with tab :param tab: query string :param opts: list that needs to be completed :return: a string that start with tab """ msg = "({0})" if tab: opts = [m[len(tab):] for m in opts if m.startswith(tab)] if len(opts) == 1: ...
feb5e813d9cfa4d83eb2fa4be32730fb296b1cdb
659,782
def containsExploit(text: str) -> bool: """ Returns whether or not the given str contains evidence that it is a sqli exploit """ return ('or' in text.lower() or 'and' in text.lower() or 'select' in text.lower() or 'from' in text.lower() or 'where' in text.lower())
e8c48013eb1bda4d2037132e602183f33a4050c8
659,783
def snake_to_camelcase(name: str) -> str: """Convert snake-case string to camel-case string.""" return "".join(n.capitalize() for n in name.split("_"))
a98c751ec3ff6b31a9c7c85ad8484c13c52cb695
659,784
def create_curl_command(authorization, payload, command, url, curl_options, show_api_key, content_type='application/json'): """ cURL command generator :param authorization: Authorization part e.g Bearer API key :param payload: Payload data :param command: GET, PUT, etc :p...
422d11c3837844111a1ef10a537ef4a52d0a988d
659,785
def dictionary(fileList): """ Get the contents of dictionary file Params: fileList - Your File List """ dict = {} infile = open(fileList, "r") for line in infile: word = line.split("\n")[0] word = word.lower() dict[word] = 1 infile.close() return dict
8cdb486e73a031d65bc69ba161502772ac7a6b49
659,787
def extended_euclidean_gcd(a, b): """Copied from http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm""" x,y, u,v = 0,1, 1,0 while a != 0: q,r = b//a,b%a; m,n = x-u*q,y-v*q b,a, x,y, u,v = a,r, u,v, m,n return b, x, y
70a9076492275c8dddfd65f59c7c0c34d704714f
659,788
def getFullPath(request): """Get full URL path from the request """ # When testing, there is no request.META['HTTP_HOST'] in Django test client host = request.META.get('HTTP_HOST', 'none') full_path = ('http', ('', 's')[request.is_secure()], \ '://', host, request.path) return '...
726ca7205d4ad7537655853a7062ea07cc4814ef
659,789
def is_point_inside_rect(point: tuple, rect:tuple): """Returns whether a point is inside a rectangular region Args: point (tuple): The point to be tested rect (tuple): A rectangular region coordinates (up_left_x,upleft_y,bottom_right_x,bottom_right_y) Returns: boolean: If true then ...
d63e07d31191bdd3affa3fa4443111f7431376e3
659,790
import json def load_json(filename): """load a json file from the input argument array.""" with open(filename) as f: return json.load(f)
5259b30f6509147dd349a128905be11d46c2523d
659,792
def create_chi_squared_statistic(gene_sets, gene_universe): """ @return: A function that takes a set of genes and sums chi squared statistics against the gene sets """ # make everything into sets gene_universe = set(gene_universe) gene_sets = [set(gs).intersection(gene_universe) for gs in gene_s...
aa4ff87af3ad74b10b017e617bfbe2e82d7bd34b
659,793
def longest_valid_parentheses(ls): """ Question 22.13: Given a string, find the longest substring of matching parentheses """ max_length = 0 end = -1 stack = [] for idx, elt in enumerate(ls): if elt == '(': stack.append(idx) elif not len(stack): ...
cdc479ea04d0729dc29be84537cc6b2364617b6f
659,794
import optparse def Options(): """Returns an option parser instance.""" p = optparse.OptionParser() p.add_option( '--known-words', dest='known_words', help='List of words like /usr/share/dict/words') p.add_option( '--more-than-bash', dest='more_than_bash', type=int, default=0, help='Ex...
8f01fbf390aecee4b83afec188255453a83e5da5
659,795
def parse_requirements(filename): """ Parse a requirements file ignoring comments and -r inclusions of other files """ reqs = [] with open(filename, 'r') as f: for line in f: hash_idx = line.find('#') if hash_idx >= 0: line = line[:hash_idx] line = line.strip() if line: ...
1a6007ec3e71b2d1d5fdef6ba334f5d1a0f28646
659,796
def is_list(value): """ Tests the value to determine whether it is a list. :param any value: :return: True of the value is a list (an instance of the list class) >>> is_list( 'Hello' ) False >>> is_list( ['Hello'] ) True """ return isinstance(value, list)
bffc34bdfe9421418e36f303c3cd5afc7ed3c8dd
659,797
def iobes2bio(tags): """IOBES标签转BIO标签""" ntags = [] for tag in tags: if tag == "O": ntags.append(tag) continue tag, label = tag.split("-") if tag == "E": tag = "I" if tag == "S": tag = "B" tag = tag + "-" + label ...
447ba87533c9194d847f89ef50ee13edc75d8032
659,798
def sents_sync(ck_sents, sj_sents): """ check if two sentences are same. if there're differences, return the list to banish. :param ck_sents: :param sj_sents: :return: """ # ck_sents = mk_sents_with_lemma(ck_file, 3) # sj_sents = mk_sents_with_lemma(sj_file, 2) # ck_sents = mk_s...
202fd3d7dcfd84c3c5f5cdcc84b13f8cb2dc722c
659,799
def is_callable(fn): """ >>> def fn(): ... pass ... >>> x = 5 >>> is_callable(x) False >>> is_callable(fn) True """ return hasattr(fn, "__call__")
3d421cc2f0c37bf10c281ff2bdc541eb1f1a3032
659,800
import torch def compute_similarity_transform(S1: torch.Tensor, S2: torch.Tensor) -> torch.Tensor: """ Computes a similarity transform (sR, t) in a batched way that takes a set of 3D points S1 (B, N, 3) closest to a set of 3D points S2 (B, N, 3), where R is a 3x3 rotation matrix, t 3x1 translation, s ...
405c2656929551d843aefa458ae6348e297995b6
659,801
import re def _process_text(text): """Remove URLs from text.""" # Matches 'http' and any characters following until the next whitespace return re.sub(r"http\S+", "", text).strip()
6daea73170599f8600c8bfd0f1866a0f49380e20
659,802
def pchange(x1, x2) -> float: """Percent change""" x1 = float(x1) x2 = float(x2) return round(((x2 - x1) / x1) * 100., 1)
25dbc8b94a275aed8914458020f3e24649c61c9e
659,803
def update_config(config): """Some python2 versions use native logging Args: config (dict): logging config Returns: dict: logging config. """ config['handlers']['file']['class'] = 'logging.handlers.RotatingFileHandler' return config
8bc464f6829c00fc106ebda8c82243df2f7ce0a6
659,804
def upd_p_tlm_srl_rigid(I_t, I_b, I_l, I_r): """ Simplified version of the TLM calculation, good for free field propagation inside a rigid frame. Diffusion matrix, connexion laws and boundary condition for 2D TLM network. :param I_t: incident pulse from the top :type I_t: 2D numpy array of floa...
1c50652e1965cd7da2394af7bad463a9824b76d4
659,805
def insertinpostingslist(tokensindoc, fname, postingslist): """ Inserts all the given tokens of each doc into the postings list, in a suitable format, for later retrieval """ if any(postingslist): for token, term in [(token, term) for token in tokensindoc for term in postingslist.keys()]: ...
a259969562d90bdd31b3e3a3291e3b3a69724530
659,806
def _get_instance_id_from_arn(arn): """ Parses the arn to return only the instance id Args: arn (str) : EC2 arn Returns: EC2 Instance id """ return arn.split('/')[-1]
bac33ae4ce79e5a83325dcf303c6d77c05482fdd
659,807
def check_categories(categories_str, category_list): """ Check if at least one entry in category_list is in the category string :param categories_str: Comma-separated list of categories :param category_list: List of categories to match :return: """ req = False if isinstance(categories_st...
a3a0f68d1d6dbc9f1ff71ad80e26794c582c4130
659,808
import zlib import base64 import json def json_unzip(compressed_dict, insist=True): """ Internal function. It receives a compressed dict and returns the original one.""" try: assert (compressed_dict['b64_data']) except: if insist: raise RuntimeError("JSON not in the expected fo...
40dd11715a3243168214bc76a0d384ec78c0356e
659,809
def isIsomorphic(s,t): """ Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characte...
4a32379d16779f1b5e025df39e63155efd9805d3
659,810
from typing import Optional def get_taxon(d: dict, focus_rank: str, priority: list) -> Optional[str]: """与えられた生物のtaxon dictを調べ、優先順位が上でfocus_rankが含まれているものを返す Args: d (dict): taxon dict focus_rank (str): 調べる対象の分類階層. ex. class, phylo priority (list): データベースの優先順位 Returns: Op...
0f5b78f4f804a0e91e297e1b2e409300c772fca9
659,811
def as_rolling(df, other, width=0, dropna=True): """enqueue next dataframe to a sliding window of fixed width of columns""" df = df.join(other, how='outer', sort=True, lsuffix='l', rsuffix='r') if width and len(df.columns) > width: # if wider than width df = df.iloc[:, (len(df.columns)-widt...
f23f913718f99625326ec25d88ba8beea2892bb3
659,812
def orion_version_resolution(orion_version_conflict): """Create a resolution for a new orion version""" return orion_version_conflict.OrionVersionResolution(orion_version_conflict)
40a471f7591850f7b815ee87b3521bdf29d71345
659,813
def nextpow2(i: int) -> int: """returns the first P such that 2**P >= abs(N)""" return i.bit_length()
1c98858c6f7d6bb2201459f8f2ba215c8629cf8f
659,814
import re def short_urs(upi, taxid): """ Create a truncated URS. This basically strips off the leading zeros to produce a shorter identifier. It will be easier for people to copy and use. """ name = "{upi}_{taxid}".format(upi=upi, taxid=taxid) return re.sub("^URS0+", "URS", name)
4efb2556b60fe6397c76ea6a7fb403543fd3eab5
659,815
from pathlib import Path def get_suffix(path: Path) -> str: """Extracts full extension (as in everything after the first dot in the filename) from Path :param path: Original Path obj :return: String representation of full filename extension """ return f".{'.'.join(path.name.split('.')[1:])}"
80e3d90437d75f6162617973ab4cb8bf2cf76be3
659,816
def filter_cancel_by_oid(cancel, oid): """ :param cancel: :type cancel: :class:`tests.testapp.testapp.trading.models.Cancel` :param oid: Order ID :type oid: int """ return cancel.xtid == oid
a3985f7d62bc8f8d498c94686e719f1f8d51ceb2
659,817
import six import functools def command_aware_wraps(f): """ Decorator passing the command attribute of the wrapped function to the wrapper This needs to be used by decorators that are trying to wrap clicmd decorated command functions. """ additional = () if hasattr(f, 'command'): addi...
7161e7ee60a6f73304712f2e52b1c59e81ddf402
659,818
def set_parameter_requires_grad(model, requires_grad=False): """https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html""" for param in model.parameters(): param.requires_grad = requires_grad return None
94d81cadd56309ee5e27263432ac2db23801db88
659,821
def flatten(obj): """ Flattens a json object into a single level using dot notation. """ out = {} def _flatten(x, name=''): if type(x) is dict: for a in x: _flatten(x[a], f"{name}{a}.") elif type(x) is list: for i, a in enumerate(x): ...
f02ba4773f23c1e586ae28f09dde9d4d36008f62
659,823
def encode(data): """ Encode string to byte in utf-8 :param data: Byte or str :return: Encoded byte data :raises: TypeError """ if isinstance(data, bytes): return data elif isinstance(data, str): return str.encode(data) else: return bytes(data)
77b2a070f6b436671e6d6074f37fe0e10ebff98d
659,824
def text_of_segments(segments): """ >>> segments = ['Hi there! ', 'My name is Peter.'] >>> text_of_segments(segments) 'Hi there! My name is Peter.' """ return "".join(segments)
db18a3be8b65f96a39c4f8d18aaa7c1c5a538a79
659,825
import math def get_lng_lat_coord(origin_lnglat, xy_pt): """ Get the (lng, lat) from a given eucledian point (x,y). The origin point is given by origin_lnglat in (longitude, latitude) format. We assume (x,y) is "x" kilometers along longitude from the origin_lnglat, and "y" kilometers along the lat...
90cbbd1fa4c9f28415c5fcd49cfd2a2b6def540d
659,826
from typing import Type from typing import Callable def raiser(exception_class: Type[Exception], *args, **kwargs) -> Callable: """Function which raises given exception type with provided args. For example: ``` validate = iffy(equals(2), raiser(ValueError)) validate(1) == 1 validate(2) # Rais...
86045ed48753e554eb137f5fc1865a60faeb8907
659,827
def getTokensMap(iterTokens, defaultTokens=('<SOS>', '<EOS>', '<UNK>')): """ :param iterTokens: tokens iterator. :param defaultTokens: default tokens to be add. <SOS>: Start of sentence <EOS>: End of sentence <UNK>: Unknown :return: """ tokens2Index = {} index2To...
84829d58fe9020bfb3799bf34815dc9dc40e94f8
659,828
def sqrt(x): """Return square root of x""" return x ** (0.5)
fb1b12a98f5c10dc04fce7827c8acd5be814926c
659,829
def _preamble(layout='layered'): """Return preamble and begin/end document.""" if layout == 'layered': layout_lib = 'layered' elif layout == 'spring': layout_lib = 'force' else: raise ValueError( 'Unknown which library contains layout: {s}'.format(s=layout)) docum...
2cb40fe7d48aa713f01ff79c093794156bff0c96
659,830
def isdistinct(seq): """ All values in sequence are distinct >>> isdistinct([1, 2, 3]) True >>> isdistinct([1, 2, 1]) False >>> isdistinct("Hello") False >>> isdistinct("World") True """ if iter(seq) is seq: seen = set() seen_add = seen.add for item ...
cc7b9c41b3942c1e117e7bd8e8c859be935a8efd
659,831
def latitude_and_longitude_convert_to_decimal_system(*arg): """ 经纬度转为小数 :return: 十进制小数 """ return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
e4f0c02db883279302cf81f0b40589f4e4e0d847
659,832
import requests def checkBucketWithoutCreds(bucketName, triesLeft=2): """ Does a simple GET request with the Requests library and interprets the results. bucketName - A domain name without protocol (http[s]) """ if triesLeft == 0: return False bucketUrl = 'http://' + bucketName + '.s3.amazon...
1baef40a3647bc3b8d336c24db0c4b17baebe8aa
659,835