content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _is_file_a_directory(f): """Returns True is the given file is a directory.""" # Starting Bazel 3.3.0, the File type as a is_directory attribute. if getattr(f, "is_directory", None): return f.is_directory # If is_directory is not in the File type, fall back to the old method: # As of Oct....
d2d98fcdcc4b8baabd3846a2b1c0e93553f48eb6
682,728
import os def tree(base_dir, padding=' ', print_files=True, is_last=False, is_first=False): """ Return a list of strings that can be combined to form ASCII-art-style directory listing :param base_dir: the path to explore :param padding: a string to prepend to each line :param print_files: True to...
f216398d811d4b84c5ca71c57c64b1801cebf8d0
682,729
def correct_bounding_box(x1, y1, x2, y2): """ Corrects the bounding box, so that the coordinates are small to big """ xmin = 0 ymin = 0 xmax = 0 ymax = 0 if x1 < x2: xmin = x1 xmax = x2 else: xmin = x2 xmax = x1 if y1 < y2: ymin = y1 ymax ...
fdf585fd4a37811b2797042feb828191ff2bac79
682,730
import os import sys import random def random_line_from_file(filepath, default=''): """ Looks for text file at filepath and returns a random line from it.""" if os.path.isfile(os.path.join(sys.path[0], filepath)): path = os.path.join(sys.path[0], filepath) elif os.path.isfile(filepath): ...
f626b47c64354a2b6a1a6275e7c3d2e67236bd6e
682,731
def gate(self=str('h'), targetA=None, targetB=None, targetC=None, angle=None, theta=None, Utheta=None, Uphi=None, Ulambda=None, custom_name=None, custom_params=None): """Generate a gate from it's name as a string passed to sel...
af73980c34299693cc7843f63d37f1fa7b4a1ed9
682,733
import secrets def generate_token(length=32): """ generates a token with the specified length (default 32), this is being used as access token :return: """ return secrets.token_hex(length)
1411f3120560ffa9e48bd7d38bd2e89add46642b
682,734
def generate_message_text(post: dict) -> str: """Принимает тело поста и генерирует на его основе текст поста""" return f'<a href="{post["url"]}">{post["title"]}</a>\n\n#{post["source"]}'
32b9a809f9b16be41e9ef9f8dcfa74303a270762
682,735
def train_test_split_features(data_train, data_test, zone, features): """Returns a pd.DataFrame with the explanatory variables and a pd.Series with the target variable, for both train and test data. Args: data_train (pd.DataFrame): Train data set. data_tes (pd.DataFrame): Test data set. z...
889889fc1c8ee4ba2758e35f70a8d23d66b5274d
682,736
def prime_factors(n): """Here's a docstring!""" factors = set() primes = [] for i in range(2, n+1): if i not in factors and n % i == 0: primes.append(i) factors.update(range(i*i, n+1, i)) return primes
c66578535c5da90d22537525c9de2465cd946a8b
682,737
import torch def create_random_binary_mask(features): """ Creates a random binary mask of a given dimension with half of its entries randomly set to 1s. :param features: Dimension of mask. :return: Binary mask with half of its entries set to 1s, of type torch.Tensor. """ mask = torch.zeros...
4f98743fc27d4abec219b9317dd16e9c61a0eac9
682,738
def pbar(val, maxval, empty='-', full='#', size=50): """ return a string that represents a nice progress bar Parameters ---------- val : float The fill value of the progress bar maxval : float The value at which the progress bar is full empty : str The character us...
ff3bfa9a170bce1a25adfef1df792550b4c20326
682,739
def hasShapeType(items, sort): """ Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`. :param shape: :class:`list` :param sort: type of shape """ return any([getattr(item, sort) for item in items])
9a1c8dbe0a850cc45d4be0ac9d1327b778dc987a
682,740
def bisection(l, x): """ Returns the index of the last element smaller than x. """ if len(l) == 0: return 0 else: middle = len(l) // 2 l1 = l[:middle] l2 = l[middle:] if l[middle] >= x: # Element is in the first half return bisection(l1, x) else: ...
96215483bb3b30f8e29e5b873035bb8c8287d643
682,741
def reestructure_areas(config_dict): """Ensure that all [Area_0, Area_1, ...] are consecutive""" area_names = [x for x in config_dict.keys() if x.startswith("Area_")] area_names.sort() for index, area_name in enumerate(area_names): if f"Area_{index}" != area_name: config_dict[f"Area_...
fa875e950a6d1e049418716d7a535cf03369e873
682,742
import argparse def get_input_arguments(): """Wrapper for reading input arguments from command line (via argparse). Return dictionary object with parsed arguments. """ # Add more options if necessary parser = argparse.ArgumentParser(description="Command line interface for FMI-PPN") parser.add...
6867b3d7c21c1a1917ae5b7a4f3118c74f087c9d
682,743
def floodfill(graph): """ Given a graph, performs a flood fill. The result is undefined on directed graphs. Group numbers (i) start at 1. Result: (n, {node => i}) >>> g = GridGraph([[1, 1], [0, 0], [1, 1]]) >>> n, d = floodfill(g) >>> n 2 >>> sorted(d.items()) [((0, 0), 1), ((...
06057a7646efab565938c86021164d018896d21e
682,744
def get_section_markups(document, sectionLabel): """ Given a ConTextDocument and sectionLabel, return an ordered list of the ConTextmarkup objects in that section""" tmp = [(e[1],e[2]['sentenceNumber']) for e in document.getDocument().out_edges(sectionLabel, data=True) if e[2].get('category') == 'mar...
705766d2c155cb3afe7f0bc3582ae3b719e237e2
682,745
def absolute_min(array): """ Returns absolute min value of a array. :param array: the array. :return: absolute min value >>> absolute_min([1, -2, 5, -8, 7]) 1 >>> absolute_min([1, -2, 3, -4, 5]) 1 """ return min(array, key=abs)
2cd53c58d6d03a3f9238cf3aed8b66d9399497dd
682,747
def serialize_drive(drive) -> str: """ Serialize the drive residues and calibration state to xml. """ drivexml = drive.state_to_xml() return drivexml
e331abd406e383c7fb310d1ba15d89147f130d4e
682,748
def return_list_smart(func): """ Decorator. If a function is trying to return a list of length 1 it returns the list element instead """ def inner(*args, **kwargs): out = func(*args, **kwargs) if not out: return None if len(out) == 1: return...
520dd849dd3dbbc9c02efd0084b09561dbe1433a
682,749
def vec_bin(v, nbins, f, init=0): """ Accumulate elements of a vector into bins Parameters ---------- v: list[] A vector of scalar values nbins: int The number of bins (accumulators) that will be returned as a list. f: callable A function f(v)->[bo,...,bn] that maps ...
9de0ad00389cf35c619f3121104929d7d2dd6bea
682,750
def fastmode(mode): """Returns True if mode for the detector is one of the high speed readout modes mode--detectormode returns boolean """ mode=mode.strip().upper() if mode in ['VIDEO MODE', 'SLOT MODE', 'SLOTMODE', 'SLOT', 'VIDEO']:...
0479c3eb6cf74cf3ff5a28e8f0bff3500e25364d
682,751
def __get_dummy_html_source(): """テスト中に何度もスクレイピングをかけるのは気が引けるので、 ローカルに DL した html source を返します。 """ with open('./dummy.html', 'r') as f: return f.read()
b7d75024416483f56c0a330642e111bba30234f9
682,752
def diff(n, l): """ Runtime: O(n) """ occurences = {} count = 0 for i in l: if i in occurences.keys(): occurences[i] += 1 else: occurences[i] = 1 for i in occurences.keys(): if i + n in occurences.keys(): c1 = occurences[i] c2 = occurences[i+n] count += c1 * c2 ...
23c5069c244a28cfdd8fc5e24fec60ddebe30aaa
682,753
import requests from bs4 import BeautifulSoup def get_soup(url): """ input url, output a soup object of that url """ page=requests.get(url) soup = BeautifulSoup(page.text.encode("utf-8"), 'html.parser') return soup
078ac5096adfc1302690d117b356378b13318d96
682,754
import functools def if_inactive(f): """decorator for callback methods so that they are only called when inactive""" @functools.wraps(f) def inner(self, loop, *args, **kwargs): if not self.active: return f(self, loop, *args, **kwargs) return inner
dbcf634463e8aa118610f2398ab88e0214f13540
682,755
def who_dreamed_a_dream(Zhuangzhou, Butterfly): """ 不知周之梦为胡蝶与,胡蝶之梦为周与?周与胡蝶,则必有分矣。此之谓物化。 -- 《庄子·齐物论》 """ Zhuangzhou.magically_change_to = Butterfly Butterfly.magically_change_to = Zhuangzhou return Zhuangzhou != Butterfly
d145a643e7891f4ef30e8be64c84654512f2176f
682,756
import asyncio import functools def async_test(loop=None): """Wrap an async test in a run_until_complete for the event loop.""" loop = loop or asyncio.get_event_loop() def _outer_async_wrapper(func): """Closure for capturing the configurable loop.""" @functools.wraps(func) def _in...
cc3e6597c6c93c9e6f6715de22b562e1a61aa3db
682,757
def get_strains(output_file): """ Returns a dictionary that maps cell id to strain. Takes Biocellion output as the input file. """ strain_map = {} with open(output_file, 'r') as f: for line in f: if line.startswith("Cell:"): tokens = line.split(',') cell = int(tokens[0].split('...
a4ce24cd0f4cb213ee42e611f178b1415a5506be
682,758
def is_iterable(x): """Returns True for all iterables except str, bytes, bytearray, else False.""" return hasattr(x, "__iter__") and not isinstance(x, (str, bytes, bytearray))
176a0682260c754b467425a99b2885f00b590f24
682,760
def get_relation(int_my_uid, list_users): """ 获取关注关系,注意source和target的正确性 :param int_my_uid: :param list_users: :return: """ list_relations = [] for v in list_users: list_relations.append({'source':int_my_uid, 'target':v.get('id')}) return list_relations
2ad0dcfa3b829f102c03f3f1468d36995b6de78b
682,761
def bprop_scalar_log(x, out, dout): """Backpropagator for primitive `scalar_log`.""" return (dout / x,)
7813b2d9464d6cd03e2f6e0c19f709cd1c250130
682,762
def sql_where(*filter_strs): """ 生成where部分, 头部加WHERE,将多个filter字符串使用AND连接。 参数: """ where_block = '' need_and = '' for filter_str in filter_strs: if where_block != '': need_and = 'AND ' if filter_str != '': where_block = where_block + nee...
1973fec26e5213352c8698b253e1c619757daebf
682,764
def _get_drive_distance(maps_response): """ from the gmaps response object, extract the driving distance """ try: return maps_response[0].get('legs')[0].get('distance').get('text') except Exception as e: print(e) return 'unknown distance'
ca0fabec0931fd8816a7ca7554b81a19a84c4010
682,765
def calc_tcp(gamma, td_tcd, eud): """Tumor Control Probability / Normal Tissue Complication Probability 1.0 / (1.0 + (``td_tcd`` / ``eud``) ^ (4.0 * ``gamma``)) Parameters ---------- gamma : float Gamma_50 td_tcd : float Either TD_50 or TCD_50 eud : float equivalen...
bdf54c53da1863ca03db0d909d5e7dd740dd388d
682,766
def get_enrollment(classroom, enrolled_only=False): """Gets the list of students that have enrolled. Args: classroom: The classroom whose enrollment to get. enrolled_only: If True, only return the set that are enrolled. Default is False. Returns: Set of Enrollment entries for the classroom. ...
b3af3085a804b0b7098fcfa0981c8978993a207b
682,769
def mtoft(m): """ Convertie les meters en feets note: 12 [in] = 1 [ft] and 1 [in] = 25.4 [mm] and 1000 [mm] = 1 [m] :param m: length [m] :return ft: length [ft] """ ft = m * (12 * 25.4 / 1000) ** -1 return ft
c3e4158aca171cec0954e4925780710e35940523
682,771
def get_price_for_market_state_crypto(result): """Returns the price for the current state of the market for Cryptocurrency symbols""" ## Crypto always on REGULAR market state, as it never sleeps ZZzzZZzzz... return { "current": result['regularMarketPrice']['fmt'], "previous": result['regular...
327339bd8d907f289e0cfaa129c29f63c58fc76d
682,772
from datetime import datetime def get_latest_archive_url(data: dict) -> str: """ Use the given metadata to find the archive URL of the latest image. """ metadata = data[-1] img = metadata["image"] date = datetime.strptime(metadata["date"], "%Y-%m-%d %H:%M:%S") archive_path = f"{date.year:0...
f9c73147dd3ce8e7a5f93a633679d658df58b0bc
682,773
import shlex def generate_input_download_command(url, path): """Outputs command to download 'url' to 'path'""" return f"python /home/ft/cloud-transfer.py -v -d {shlex.quote(url)} {shlex.quote(path)}"
d12c7d662dfe96467c43be3e42567fc2b06626f9
682,774
def entity_getstate(entity): """Return the state of an SQLAlchemy entity In: - ``entity`` -- the SQLAlchemy entity Return: - the state dictionary """ state = entity._sa_instance_state # SQLAlchemy managed state if state.key: attrs = set(state.manager.local_attrs) # SQLAl...
1c443d7542f5702bf27b5b1ce85608d764f93c42
682,775
def m4p(x=0.0): """From the paper by Chaniotis et al. (JCP 2002). """ if x < 0.0: return 0.0 elif x < 1.0: return 1.0 - 0.5*x*x*(5.0 - 3.0*x) elif x < 2.0: return (1 - x)*(2 - x)*(2 - x)*0.5 else: return 0.0
a883cb8d5a78f0814347b46f58392c6214600c5a
682,776
def foo(required, *args, **kwargs): """ foo :param required: :param args: :param kwargs: :return: """ print(required) if args: print(args) if kwargs: print(kwargs) return True
841c7a905ef550f9db500fb4589af77d5cfbd1b6
682,778
def _calculate_shrinking_factor(initial_shrinking_factor: float, step_number: int, n_dim: int) -> float: """The length of each in interval bounding the parameter space needs to be multiplied by this number. Args: initial_shrinking_factor: in each step the total volume is shrunk by this amount s...
f8f99842e91ba59ba345e7bd2d608b0b0c56bef0
682,780
def _byte_string_to_bit_string(byte_string): """ Converts byte_string (b_string) to a string of 0's and 1's @param byte_string: <b_string> byte-string @return: <str> bit-string but just a a string of 0's and 1's """ result_string = '' byte_string = byte_string.decode('UTF-8') for ch in b...
35ebcabadfccdd216d526787db6d9143ba00ad8e
682,783
def calc_grv(thickness, height, area, top='slab', g=False): """Calculate GRV for given prospect Args: thickness [float]: average thickness of reservoir height [float]: height of hydrocarbon column area [float]: area of hydrocarbon prospect top: structure shape, one of `{'slab', '...
71e7d257cc0bc4fd73a36e728d69b3599f902f9d
682,784
def has_address_keywords(ustring): """是否含有地址的标识字符""" if (u'地址' in ustring) or \ (u'店址' in ustring) or \ (u'坐标' in ustring) or \ (u'坐落' in ustring) or \ (u'地处' in ustring) or \ (u'位于' in ustring) or \ (u'地点' in ustring) or \ (u'位置' in ustring): return True...
62d6af29b0af1d442708e0291200377500db2015
682,785
import struct def decode_override_information(data_set): """decode result from override info :param tuple result_set: bytes returned by the system parameter query command R_RI for override info :returns: dictionary with override info values :rtype: dict """ overri...
38236b3676cfd8c05b2b13c1a637d5d428662fc1
682,786
def get_bool_arg(arg): """Parse boolean argument.""" return arg in ["true", "True", "TRUE", "on", "On", "ON", "1"]
9c7548dad1c0076382ecc0e7b75558206fd75b85
682,787
def is_link_displayed(link: str, source: str): """Check if the link is explicitly displayed in the source. Args: link: a string containing the link to find in the webpage source code. source: the source code of the webpage. Returns: True is the link is visible in the webpage, False...
129a3f006ccf47fe9eae219f69f4b746ec707bdf
682,788
import codecs def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except: return text
703f136602bf128f875590142e9c6abb3de7b890
682,789
def create_user2(django_user_model): """ create another user """ user = django_user_model.objects.create_user( username='user_2', email='another@gmail.com', password='pass123' ) return user
ecfc30dd0ec55ee0e14c3d3d50930f17a5055d58
682,790
def probability_matrix(motifs, k): """returns probability matrix""" nucleotides = {'A': [0]*k, 'T': [0]*k, 'C': [0]*k, 'G': [0]*k} t = len(motifs) for motif in motifs: for index, nucleotide in enumerate(motif): nucleotides[nucleotide][index] = nucleotides[nucleotide][index] + 1 #...
8202101c4f5e9db598c916250af9f7027af8642b
682,791
import os def make_smspec_list(path, key): """ Iterate over all files in a given path and fetch SMSPEC files which comply with a certain string filter Parameters: path (string): path to the cases folder key (string): filtering string, the file name MUST contain the string in order t...
0f13349db24a8ca5676b30712c98171814da7d42
682,792
import weakref def _new_viewport(): """ Create and return a new viewport set. """ return weakref.WeakSet()
5d3a83c2a68b89ebe8d524f71825e94e3b24c4f0
682,793
from datetime import datetime def _time_stamp_filename(fname, fmt='%Y-%m-%d_{fname}'): """ Utility function to add a timestamp to names of uploaded files. Arguments: fname (str) fmt (str) Returns: str """ return datetime.now().strftime(fmt).format(fname=fname)
f5b5780b86a1dc958ce6dc012b3fe84f49a19bdb
682,795
import struct def readExtension(byteStream): """An extension token. For now - look in extensions.py for their mappings""" extNo, unused, extToken = struct.unpack('>2bH', byteStream.read(4)) return 6, (extNo, extToken)
2ed8740910a2d0f6ccc7556e054550022db880f7
682,796
def _format_size(x: int, sig_figs: int = 3, hide_zero: bool = False) -> str: """ Formats an integer for printing in a table or model representation. Expresses the number in terms of 'kilo', 'mega', etc., using 'K', 'M', etc. as a suffix. Args: x (int) : The integer to format. sig_fi...
db72f2e6db8ef32ad9ce011e8aac8d6877c0f8f8
682,797
def make_ratios(cred, cgreen, cblue): """ get ratios of colors """ maxcolor = max(cred, cgreen, cblue) return float(cred)/float(maxcolor), \ float(cgreen)/float(maxcolor), \ float(cblue)/float(maxcolor)
357f04ad12b304251aa2ea8778afd34c0538481a
682,798
def get_artists_in_group(artist_database, group_id, alt_members_id=0): """ Return a list of every artists in a group (recursively) ie. Prism Box -> [Prizmmy, list, of, member, in, prizmmy, W/E, list, of, member, in, w/e] TrySail -> [Sora Amamiya, Momo Asakura, Random] Kana Hanazawa -> [Kana...
badc73cfebb55c6ad216192c2c4aa5388e0e2e0b
682,799
def is_close_conditional(enclosed: str) -> bool: """ True if {{$enclosed}} corresponds to the end of an 'if' statement on the Anki card template. """ return enclosed.startswith("/")
66331df5acf4f5792a2df37a2c91155c0c56027b
682,800
def normalize(df, col_name, replace=True): """Normalize number column in DataFrame The normalization is done with max-min equation: z = (x - min(x)) / (max(x) - min(x)) replace -- set to False if it's desired to return new DataFrame instead of editing it. """ col = df[col_name] ...
e9e458977677f09ce53f08a8e83b004ce0c043e4
682,802
import torch def csv_collator(samples): """Merge a list of samples to form a batch. The batch is a 2-element tuple, being the first element the BxHxW tensor and the second element a list of dictionaries. :param samples: List of samples returned by CSVDataset as (img, dict) tuples. """ imgs ...
f4dedd5829ea7c434a662730ae7de5ea6ef56553
682,803
def in_box(coords, box): """ Find if a coordinate tuple is inside a bounding box. :param coords: Tuple containing latitude and longitude. :param box: Two tuples, where first is the bottom left, and the second is the top right of the box. :return: Boolean indicating if the coordinates are in the box....
ed4082b6311929e4982b4196ceaa566b05dfd714
682,804
def batch_delete(query, session): """ Delete the result rows from the given query in batches. This minimizes the amount of time that the table(s) that the query selects from will be locked for at once. """ n = 0 query = query.limit(25) while True: if query.count() == 0: ...
eb10e259267882011581a46409a5464520304852
682,805
def _promote_events_to_columns(transcript_group): """Promote the events values as columns Args: transcript_group (pandas.DataFrame): The transcript dataset Returns: pandas.DataFrame: The modified transcript with the events promoted as columns """ transcript_group["received"] = tra...
b47eb9d720f3da9df8e20dad83d4086b00ac749c
682,806
def to_triplets(colors): """ Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three. """ try: colors[0][0] return...
809a8c57d2f590fb2984124efe86814850bb8921
682,807
import random import string def random_text(n) : """Generate random text 'n' characters""" return ''.join([random.choice(string.digits + string.ascii_letters) for x in range(n)])
c8f6b14983a5f5712d6da8f6374dca8f5997ed07
682,808
def get_k8s_context(client, container_id: str) -> dict: """通过containder_id获取pod, namespace信息""" resp = client.get_pod(field="resourceName,data.status.containerStatuses,namespace") pods = resp.get("data") or [] context = {} for pod in pods: namespace = pod["namespace"] pod_name = pod[...
cbfd4facf634d7407af4ea363a4203b14c8edec8
682,809
import six import re def to_bytes(value): """Convert numbers with a byte suffix to bytes. """ if isinstance(value, six.string_types): pattern = re.compile('^(\d+)([K,M,G]{1})$') match = pattern.match(value) if match: value = match.group(1) suffix = match.gro...
a2e686d56bd2bed9918ea4e8a165de36d54994e8
682,810
from typing import Tuple from datetime import datetime def _unparse_time_range(time: Tuple[datetime, datetime]) -> str: """ >>> _unparse_time_range(( ... datetime(1986, 4, 16, 1, 12, 16), ... datetime(2097, 5, 10, 0, 24, 21) ... )) '1986-04-16T01:12:16/2097-05-10T00:24:21' """ ...
364179f740f5d55cef8f5861194f882c6047131a
682,811
def is_perfect_slow(n): """ decides if a given integer n is a perfect number or not this is the straightforward implementation """ if n <= 0: return(False) sum = 0 for i in range(1,n): if n % i == 0: sum += i return(sum == n)
efd570f4d4e7eb4d6fde87705f4f0e515d0abe24
682,812
def get_type_by_name(context, name, *types_dict_names): """ Gets a type either by its full name or its shorthand name or type-qualified name. Works by checking for ``shorthand_name`` and ``type_qualified_name`` in the types' ``_extensions`` field. See also :class:`~aria_extension_tosca.v1_0.present...
7af6ceafeff1c5f90237ac7cb194dd1b3063870a
682,813
def longMessage(message): """Use this to prevent the bot from trying to send messages over 2000 characters.""" if len(message) > 2000: return "hey!! you tricked me into making a big message!! no fair :((" else: return message
8cc01c1259064518c82e9b561aa7a2b48aa05504
682,814
import functools def cached(method=None, name=None): """A decorator allowing for specifying the name of a cache, allowing it to be modified elsewhere.""" if method is None: return functools.partial(cached, name=name) @functools.wraps(method) def g(self, *args, **kwargs): if not hasatt...
7445748ccee076f8950b918e53b5c7153f88c9fb
682,815
def licence_name_to_file_name(licence_name: str) -> str: """ Converts a licence name to the name of the file containing its definition. :param licence_name: The licence name. :return: The file name. """ return licence_name.lower().replace(" ", "-") + ".txt"
d74bd90f5b6c65cd662b88dc69f361507dc47bb2
682,817
def rev(s): """concatenates inside out""" return len(s) != 0 and rev(s[1:]) + s[0] or s
535519a64cadf8eea06e6ba87f75dbc590c1bb9e
682,818
def normalise(word): """Normalises words to lowercase and stems and lemmatizes it.""" word = word.lower() #word = stemmer.stem(word) #word = lemmatizer.lemmatize(word) return word
102c0e004cef7dfc48d14151ff4666f0debbcdc1
682,819
def format_position(variant): """Gets a string representation of the variants position. Args: variant: third_party.nucleus.protos.Variant. Returns: A string chr:start + 1 (as start is zero-based). """ return '{}:{}'.format(variant.reference_name, variant.start + 1)
215534a2905622835a99f6945b73ac4fbe13e1f1
682,820
def get_graph_ql_query(typed, user, pages=None) -> str: """ :param typed: internal script query type :param user: username or user_id :param pages: cursor of next page :return: string on graphql query object """ if typed == 1: """ { "userId":"", "coun...
287609954a8830f808a35fdfdae40bf547d901c1
682,821
def fix_date(date): """ Make sure the date has a uniform format. """ if len(date.split('-')[0]) == 2: date = '20' + date # Add century if '.' in date: date = date.split('.')[0] # Remove milliseconds return date
43bf14c05ed527a3c3740a3a7b646e9165a9b20b
682,822
def preload_dicom(): """ This method is essential for the module to run. MIPPY needs to know whether the module wants preloaded DICOM datasets or just paths to the files. Most modules will probably want preloaded DICOM datasets so that you don't have to worry about different manufacturers, enhanced vs non-enhance...
242e9d4cd37d96600db43adbae8b038d950ede85
682,823
def handle_was_beer_scanned(): """check if the trasaction was scanned""" return {"msg": "hi beautiful"}
f963edbdbac2cd1ac02f02acc45ca6aac78d6212
682,825
from pathlib import Path from typing import List from typing import Optional import os import re def adjust_includes( fname: Path, basepath: Path, directives: List[str], encoding: str, dstpath: Optional[Path] = None, ) -> None: """Adjust included content paths. Args: fname: File t...
546f155696694ddc3397fb3623c1ee8d81c319db
682,826
def score(goal, test_string): """compare two input strings and return decimal value of quotient likeness""" #goal = 'methinks it is like a weasel' num_equal = 0 for i in range(len(goal)): if goal[i] == test_string[i]: num_equal += 1 return num_equal / len(goal)
c50a2c3f2ff95d129e8816e4384d9b39ebd0e44b
682,827
import torch def assign_obj_and_reg_out(): """Construct assignment objective with a few planted columns with small objective values.""" cache_size, r, k = 200, 8, 4 assign_obj = torch.randn(cache_size, r, k).abs() assign_obj[:100, 1, 0] = torch.randn(100).abs().mul(1e-6) assign_obj[100:150, 3, 2] = torch....
d8d59c448984e27bf5b384aa268c3b23f792d898
682,828
async def get_team(gh, team_name): """ Get a team by name (slug) """ return await gh.getitem(f"/orgs/python/teams/{team_name}")
6830b972f0715638578dbf8715198ff6d2c55316
682,830
import copy def pad_1d_list(data, element, thickness=1): """ Adds padding at the start and end of a list This will make a shallow copy of the original eg: pad_1d_list([1,2], 0) -> returns [0,1,2,0] Args: data: the list to pad element: gets added as padding (if its an object, ...
2228307755053728f3ab11540d6673f5d6e8fa1f
682,831
def texture_coord(x, y, n=2): """Return the bounding vertices of the texture square. E.g. for texture.png, (0, 0) means the black-white tile texture. """ m = 1. / n dx = x * m dy = y * m return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
5b3e9d62c2443fb6421acd5982a944e9356cf6e2
682,832
def process_single(word): """ Process a single word, whether it's identifier, number or symbols. :param word: str, the word to process :return: str, the input """ if word[0].isnumeric(): try: int(word) except ValueError: raise ValueError("Expression {} no...
0a08fd6ed7402fb4351adff8fb7f59106fbe4ca8
682,833
def calc_f_measure(precision, recall, b=1): """ Choose b such that recall is b times more important than precision """ return (1 + b**2) * (precision * recall) / ((b**2 * precision) + recall)
e4a60fd2cf37c10173734ea66154ed40acff223f
682,834
import os def get_fws(typ): """ 获取固件包, 根据相应的类型 :param typ: 类型, 可以是 1、flash 2、 pm3 3、 stm32 :return: """ path = os.path.join("res", "firmware", typ) fw_list = [] try: files = os.listdir(path) if len(files) == 0: ...
84ed6da5bacc02d338f0ea0700406313eba0de38
682,835
def remove_non_seriasable(d): """ Converts AnnotationType and EntityType classes to strings. This is needed when saving to a file. """ return { k: str(val.name).lower() if k in ('annotation_type', 'entity_type') else val for k, val in d.items() ...
30a9b50685ca5140ff99c7c98586fdee86d21212
682,836
import os def extractDoFiles(file): """ EXPERIMENTAL Uses Unix commands to search for and extract datasets from do files. Args: file (str): Path to a .R or .Py file Returns: list: A list of strings containing the datasets saved and read """ # Grepping commands # forea...
f45a9deb6729db5fdef90200715685ee3ae58472
682,837
def merge_dictionaries(dict1, dict2): """Merge dictionaries together, for the case of aggregating bindings.""" new_dict = dict1.copy() new_dict.update(dict2) return new_dict
cd1445c458a42414a90b7d8c3810885ab351b46e
682,838
def mention_bis(note : float) -> str: """ ... cf. ci-dessus ... """ if note >= 16: return 'TB' elif note >= 14: return 'B' elif note >= 12: return 'AB' elif note >= 10: return 'Passable' else: return 'Eliminé'
367802d0fb0aa3437c2bf187cda60a9bcb55761c
682,839
def random_seed(): """ For repeatability. """ return 1994
628ec63cebd209e78ff0b91ff0fb8dccd7c96ac8
682,840
import math import torch def cal_alignment_grid(viewport_resolution, lat, lon, P): """ Calculate the grid for viewport alignment according to the center of the viewport. :param viewport_resolution: Tuple. (height_of_viewport, width_of_viewport) :param lat: Latitude of the center of the viewport (i.e.,...
e3c4bcc61b326cf82965c3d78e00a8dbc2a05b74
682,841
def transpose(matrix): """ Compute the matrix transpose :param matrix: the matrix to be transposed, the transposing will not modify the input matrix :return: the transposed of matrix """ _transposed = [] for row in range(len(matrix)): _transposed.append( [matrix[i...
2dd0db2737fe1691d414c207c88fd8419c1860b6
682,843
import click import re def tor(ctx, control, host, port, socket, auth_cookie, password): """Settings to configure the connection to the Tor node to be monitored.""" if control in ['port', 'proxy']: if host is None or port is None: raise click.BadOptionUsage( option_name='c...
229dd206ed067ccf1667d2c755994dd0a32d98f6
682,844