content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def voxel_content_mesh_index(batch_idx: int, mesh_idx: int) -> int: """Sets the voxel content to the mesh index.""" _ = batch_idx return mesh_idx + 1
2922605191daf544c64baaa038c97f1440459b4f
636,402
def get_conn_str(db_name): """Returns the connection string for the passed in database.""" return f'postgresql://postgres:postgres123@localhost:5432/{db_name}'
0197fada49a60f22bc716e65692db4c96f91a0af
636,403
def convert_km_to_length(length): """Convert length like '1' to 1000 or '30M' to 30""" try: if length[-1:] == "M": t_length = int(length[:-1]) # Trim off the 'M' else: t_length = int(float(length) * 1000) # Convert to meters length_str = str(t_length) exc...
7e5e8d86a67c9038696e1d5a6198b4a499f8cb23
636,404
def clean_seq(seq: str) -> str: """ Cleans the sequence: every letter is in 'ATCGN'. :param seq: Input sequence """ seq = seq.upper() assert lambda char: char in ['A', 'T', 'C', 'G', 'N'], set(seq) return seq
008f0169f870afb1e1472593790933118b9776c7
636,405
def calc_SST(X_act): """ This function returns the Sum of Square of actual values. """ return (X_act ** 2).sum()
b8da81ae2d9fc530643d3659fe89c773e1aa8b03
636,407
def placement(board, current_player): """Prompts for input and does input verification""" spot = input(current_player + ", Enter a number 0 through 8 for placement: ") valid = False while not valid: try: spot = int(spot) if 8 >= spot >= 0 and board[spot] == " ": ...
df587d4e8ed41b0fbbf44db256217ece008bba50
636,408
def download_sources(seq_sources): """ Takes list of labels (including BioSamples) and list of allowed databases Returns a dictionary of which database to download each sample from Which looks like: {database1:[SAMN01, SAMN02], database2:[SAMN03], database3:[SAMN04]} """ ...
fc20f6ed3252f5bc2e46ca5d9d355ece4f0d7b7b
636,409
def get_version(): """ Return version string containing global version number and 'build' date """ return "Revision 4265, Tue Aug 30 16:43:02 EST 2011"
6e2bb9222581c13fe8ff7afc217ca9a22d751c3e
636,410
def transform(addon_df, threshold, num_addons): """ Converts the locale-specific addon data in to a dictionary. :param addon_df: the locale-specific addon dataframe; :param threshold: the minimum number of addon-installs per locale; :param num_addons: requested number of recommendations. :return: a...
58645f967f1bc43e3f7078b878e6d5a46f5261a1
636,412
def In(a, b): """ **In** In(b) <=> lambda a: a in b Returns a partial function which when executed determines whether the argument partially applied contains the value being passed down. ** Examples ** from phi import P assert False == P.Pipe( 3, P * 2, #3 * 2 == 6 P.In([1...
feb3b9babfc65aa61ee31e50bc58ec5bbd2cec80
636,413
import aiohttp async def get(url): """A simplest GET using aiohttp.""" async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await (response.text())
0c7b55c31097cf79971bde54b990d3df52de0ba3
636,414
def _debian_dist_name(env): """ Determine Debian dist name (e.g. squeeze). """ return env.safe_run_output("lsb_release -a | grep Codename | cut -f 2")
1d545bd0229474d8440adaf78432729b7faf549d
636,415
import six def _get_exec_table_data(headers): """Extract a stats table from execution HTTP response headers. Stats include things like node name, execution time, number of reads/writes, bytes read/written, etc. :param dict headers: `dict` of response headers from a job execution request. It ...
9724e8c24b2a7e3b6872ac3982d5383bb97721d3
636,416
import requests import logging def recently_traded(symbol): """Check if a ticker was recently traded on thetagang.com.""" url = "https://api.thetagang.com/trades" params = {"ticker": symbol} trades = requests.get(url, params=params).json()['data']['trades'] # Skip this message if nobody has trade...
2224a8b449dc6cae96b2488f032297387db9ed1b
636,417
import math def f_1(scores): """Compute the corpus-wide F1 score represented by the scores. Each score should contain four entries. Consider: - first/second entry numerator/denominator for recall, - third/fourth entry numerator and denominator for precision. Then define r = sum(first ent...
ba4c0648223a1f0ad15ff1870d801a7f64296380
636,418
def value(args): """ For better development readability. Used by found functions of parser. """ return args[0]
3d829a769da24b4193d4d27192139b466ba35f0b
636,419
def sorted_values(x): """Returns the sorted values of a dictionary as a list.""" return [x[k] for k in sorted(x)]
2d8d3156b8f4ba7b3f13a967c61a341bea39b808
636,420
def reverse_url(context, name, **parts): """ jinja2 filter for generating urls, see http://aiohttp.readthedocs.io/en/stable/web.html#reverse-url-constructing-using-named-resources Usage: {{ 'the-view-name'|url }} might become "/path/to/view" or with parts and a query {{ 'item-details...
963737f6fe4ee2fb3a79bb419051e815295253ef
636,421
import platform def getSystemBitness() -> int: """ Solution adapted from https://stackoverflow.com/questions/2208828/detect-64bit-os-windows-in-python """ machine = platform.machine() if machine.endswith('64'): return 64 else: return 32
7ee0c5095b4f34dbb8cc11d52a52ef51ead40dff
636,422
def urlencode(s): """urlencodes a string""" return ''.join(['%%%02x' % ord(c) for c in s])
652344fbf2b22b62b539068299e175c1154507c5
636,424
def seatsInTheater(nCols, nRows, col, row): """ Given the total number of rows and columns in the theater (nRows and nCols, respectively), and the row and column you're sitting in, return the number of people who sit strictly behind you and in your column or to the left, assuming all se...
294167558d0a9a2e2616670b4a81854ecb8c3a19
636,425
def binary_mode_to_cascade_mode(binary_list, num_cascade): """ Parameters ---------- binary_list: list num_cascade: int Returns --------- cascade_mode: int """ cascade_mode = 0 if binary_list == [0] * num_cascade: cascade_mode = 0 count = 1 for ele in binary_l...
4052c0cf8d55e0d5a595c58890a464db7f3e86a9
636,426
import torch def xyxy2xywh(boxes): """Transform the bbox coordinate to [x,y ,w,h]. :param bbox: the predict bounding box coordinate :type bbox: list :return: [x,y ,w,h] :rtype: list """ xmin, ymin, xmax, ymax = boxes.unbind(1) return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin),...
a84a921fc561db8f5e5b2eb1b5c36d1f8ce1ceaa
636,427
import os def load_key_to_decrypt_anon(anon_path): """ Load the string containing the key from the key file.""" return open(os.path.join(anon_path, "anon-DB.key"), "rt").read()
fdad837d9ce54c3a7eceee2280324df6ef359b26
636,428
def prepend_license(license_text, src_text, file_extension): """Prepend a license notice to the file commented out based on the extension. Args: src_text (str): The text which will have the license prepended. file_extension (str): The relevant file extension. Returns: str: The full...
eda1cf92ac5469fe3879a4884fdadf3cf199eefe
636,429
from typing import Any from datetime import datetime def json_encoder(obj: Any) -> Any: """json encoder function supporting datetime serialization. Args: obj: object to encode to JSON Returns: json encoded data """ if isinstance(obj, datetime): return obj.isoformat() ...
202f77c4be8acd8e51584a32f49419c8feaa7bba
636,430
def _fit_transform_one(transformer, X, y, weight, message_clsname='', message=None, **fit_params): """ Fits ``transformer`` to ``X`` and ``y``. The transformed result is retu...
1f1048f200668dfa274769d4f38c5f7568841cab
636,431
def declr_has_sym(declr, sym): """Check if the given declr has sym""" for existing in declr: if existing["kind"] == sym["kind"] and existing["name"] == sym["name"]: return True return False
4fb3919d5a83c6173c338b07f916e82948d858ac
636,432
def get_orbit_node(aos_lat, los_lat, oi): """Return the orbit node - ascending or descending, based on time of AOS and LOS latitude """ if (aos_lat > los_lat): print("PASS = descending") node = "descending" else: print("PASS = ascending") node ...
cc5c0ccf2318d100fd5d455301be9b8832682ba8
636,434
def term_code(term: str, session: str) -> tuple: """ Convert CUNYfirst term code (CYYM) and session code (1, WIN, 4W1, etc) into a QC term_code string "YYYY.TT", and term name string, "YYYY.Abbr". The idea is that the term code strings are in chronological order but the term name strings are more descript...
57ba3a856b9e6f16fb2c4fe9a8e54b225460cf0a
636,435
def TSA_h_g( temperature_ground, temperature_vegetation, temperature_air, roughness_ground, roughness_vegetation, roughness_air ): """ Chen et al., 2005. IJRS 26(8):1755-1762. Estimation of daily evapotranspiration using a two-layer remote sensing model. Sensible heat flux for ground TSA_h_g( temperature_ground, t...
d049295ff86e11978afdbf782ee80c62078a2f45
636,436
def candidate_certificates_fixture(signed_data_fixture): """Returns the certificates from the apple pay token.""" return signed_data_fixture['certificates']
305e74fc343ce12d6204ae824856a105007efef9
636,437
import random import bisect def bisect_choice(items): """Returns a function that makes a weighted random choice from items.""" added_weights = [] last_sum = 0 for weight in items: last_sum += weight added_weights.append(last_sum) def choice(rnd=random.random, bis=bisect.bisect): ...
cca0efe9adbc763b414bb24a6e8fcac6976e50d6
636,438
def generate_headers(sdfg) -> str: """ Generate a header file for the SDFG """ proto = "" params = (sdfg.name, sdfg.signature(with_types=True, for_call=False)) proto += 'extern "C" int __dace_init_%s(%s);\n' % params proto += 'extern "C" int __dace_exit_%s(%s);\n' % params proto += 'extern "C" v...
6f1de8bfc11858d6b86609e697839376ab9078b2
636,440
def create_p_yaw_model_tf(d, gp): """ Create transfer function for fly yaw dynamics model with proportional controlller. Arguments: d = damping gp = proportional gain Returns: tf = transfer function. """ def tf(s): return gp/(s + d + gp) return tf
3b7673565a225036932c1e232d6e29112948d3dc
636,441
def _calculate_insertion_point(existing_knob_list, knob_point=None, insert_before=False): """Encapsulates logic on working out where to insert in a the knob list Returns an integer index which tells us where to insert. For example in list [A,B,C]: - before A is 0 - ...
0e383e26b996fc803404007e482d2dfb71b41d35
636,442
def clean_lines(input_list): """ Clean the final output lines """ output_list = [] for line in input_list: output_list.append(' '.join(line.split()[:5])) return output_list
fd1d6854acf2175042e3b8902c1a0070b2ec6965
636,443
def create_and_list(list): """ Given a list of 1 items, return item Given a list of 2 items, return item[0] and item[1] Given a list of n items, return item[0], item[1], ..., and item[-1] """ if len(list) == 1: return list[0] elif len(list) == 2: return list[0] + " and " + l...
934b9ac2dc32a45cd63b96c836babefb5db551c3
636,444
def brute_force(data): """Loop through twice to get the answer. It ain't pretty but it works.""" for j in data: for k in data: for n in data: if j == k: continue if j == n: continue if k == n: ...
9f2cea708f74b99b3fa2091930497f52543ebe4f
636,446
import subprocess import re import plistlib import os def _extract_codesign_data(bundle_path, output_directory, unique_id, codesign_path): """Extracts the codesigning data for provided bundle to output directory. Given a bundle_path will extract the entitlements file to the provided ...
cb4fec6fc57f7307a4c682854a653ce11fcd1870
636,447
def db_list_fields(con, tabel): """Return all column names for a specified table""" cursor = con.cursor() cursor.execute(f"select * from {tabel} limit 1;") return [name[0] for name in cursor.description]
e053fa419bdb04006799550adfad2bc0ad8850da
636,448
import argparse def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="SEAN") parser.add_argument("--data_dir", type=str, default='/data/yonghao.xu/SegmentationData/cityscapes/', ...
538ebfbc49bc2dacb74e828891e8fe12b05e3603
636,450
def _replace_choonpu(lst: list) -> list: """choonpu indicates that the previous vowel is extended""" return [lst[idx - 1] if str(item) == "ー" else str(item) for idx, item in enumerate(lst)]
07d2b476b57cc1a3aae55d9ae81c73b7274cd887
636,451
import six def has_digit(string_or_list, sep="_"): """ Given a string or a list will return true if the last word or element is a digit. sep is used when a string is given to know what separates one word from another. """ if isinstance(string_or_list, (tuple, list)): list_length = len...
2fc03d44134f2255476c083f9323e815ff12007e
636,452
import re def parse_basename(bname): """return tuple (tsh, axis, ddd, hh, this_file, total_files) given basename""" # input like BXM00018.15R m = re.match('(?P<tsh>.)(?P<axis>.)(.)(?P<day>\d{3})(?P<hour>\d{2})\.(?P<this_file>\d)(?P<num_files>\d).', bname) if m: return m.group('tsh'), m.group('...
37ebba5d929d863ab245019b0d539100f89d395d
636,453
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter def get_parser(): """Get parser for view script.""" parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("--hypes", dest="hypes_...
1106543b223a5849f680d12e5aeb31c7a6ae22f8
636,454
def check_subtraction_file_type(file_name: str) -> str: """ Get the subtraction file type based on the extension of given `file_name` :param file_name: subtraction file name :return: file type """ if file_name.endswith(".fa.gz"): return "fasta" else: return "bowtie2"
8522a79c6a8e65439c7b1e998b37987ee99c303a
636,455
import copy def strip_dev_suffix(env_config: dict): """ Parameters ---------- env_config : dict dictionary representing the contents of valid anaconda environment.yml. Returns ------- env_config : dict Returns a dictionary representing the parsed yaml file, curtailing all...
8455df87373ceeca06e453ba7206f4dbd7854955
636,456
def get_configuration_tag(api): """ Return tag value for the configuration. :param ConfigurationAPIUserV1 api: API instance. :return: Tag as ``bytes``. """ return api.persistence_service.configuration_hash()
a8b1ecc8196dc3f1df3e1e456aedadf298959416
636,457
import random def yes(specifier=0): """ Decide if we should perform this action, this is just a simple way to do something I do in tests every now and again :Example: # EXAMPLE -- simple yes or no question if testdata.yes(): # do this else: # don't do i...
c8c961648b91fe937aca49100da23b5b2992490d
636,458
def partition(array: list, beginning: int, end: int) -> int: """ Go through the array from left to right. If the number in position i is bigger than the pivot (i.e. the last number of the array) and the number in position j is smaller than or equal to the pivot, then swap the two numbers and increas...
bc0120fbfe78ce6890c77092ae9dcceab20e0809
636,459
def _extended_euclidean(a, b): """Helper function that runs the extended Euclidean algorithm, which finds x and y st a * x + b * y = gcd(a, b). Used for gcd and modular division. Returns x, y, gcd(a, b)""" flip = b > a if flip: a, b = b, a if b == 0: return 1, 0, a x, y, gcd = _extended_eucl...
4ff6bb3679d9b08337b555d4271ed97041ef8b0b
636,460
def group_aggregation(df, group_var, agg_var): """ We need to group the Auto MPG Dataset on the basis of a column. Then we have to calculate the mean of the grouped data according to another column parameters df: A dataframe containing the dataset in the form of a matri...
3c54aa6ef7d2c421fb58cd7b9e60b9f8ec31b066
636,461
import os def _get_data_paths(dirname): """Returns configuration file paths.""" # Home configuration paths = [] ipath = os.path.join(os.path.expanduser('~'), '.proplot', dirname) if os.path.exists(ipath) and ipath not in paths: paths.insert(0, ipath) # Global configuration ipath = ...
5e68451573750017910cff8f86476bc568a2a032
636,462
import torch def disagreement(logits_1, logits_2): """Disagreement between the predictions of two classifiers.""" preds_1 = torch.argmax(logits_1, dim=-1).type(torch.int32) preds_2 = torch.argmax(logits_2, dim=-1).type(torch.int32) return torch.mean((preds_1 != preds_2).type(torch.float32))
82d12bb657018c4b446fd05c94c8f5834ce4fd59
636,464
def get_formatted_place (city, country, population): """Generate the name of a place and it's population.""" place = f"{city} {country}-Population: {population}" return place.title()
9ae4c9bb4898406d2737c003045d5f05384fcddf
636,465
import os import tempfile def get_tempdir(): """Gets the temporary directory to be used by genshin.py""" directory = os.path.join(tempfile.gettempdir(), "genshin.py") os.makedirs(directory, exist_ok=True) return directory
9e4e02067b6db83821704e5b1995b9832503bfac
636,466
def parse_password_file(file_name): """ parse the apache password file into usernames and passwords """ passwords = {} for line in open(file_name, 'r'): username, password = line.split(':') passwords[username] = password.strip() return passwords
cb3e5837ee0266af6facf3b825ba9fb6c6dcb918
636,467
def generate_pairs(n_rex): """Generate list of pairs that will attempt to swap configurations during replica exchange Monte Carlo. """ pairs = list(zip(range(n_rex), range(1,n_rex))) return pairs[::2], pairs[1::2]
4f6fde753629a1ad08f57d83c643f380964ce4a4
636,468
def find_base_articles(articles): """ Return the base articles from a list of articles :param articles: list of articles :type articles: [str] :return: bases :rtype: [str] """ base_articles = [] for a in articles: a = a.split('+')[0] if 'p' not in...
38a0598d7d27acd68115df9d553bf669b9cc96b5
636,470
def count_letters_except_first_cap(sent_list): """ :param sent_list: :return (total letters - capital letters at beginning of sentences): """ letter_count = 0 for sent in sent_list: #if sent[0].isalpha() is True and sent[0].islower() is True: # if the first letter is not capitalized ...
7a13a17c90b55a13bc9e6ac903d5d3334a07f7ca
636,471
def _num_extracted_rows_and_columns( image_size: int, patch_size: int, stride: int, num_scales: int, scale_factor: int, ) -> int: """The number of rows or columns in a patch extraction grid.""" largest_patch_size = int(patch_size * (scale_factor**(num_scales - 1))) residual = image_size - larg...
dacea42438adf9e128d13ecceb6c576da855e75c
636,473
from functools import reduce import operator def get_in(keys, coll, default=None, no_default=False): """ Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ...
24a2086a9643f5302cba2245e588def09a5c74ce
636,474
def knapsack_recursive(items, capacity): """Return the maximum value that can be stored in the knapsack using the items given.""" if len(items) is 0 or capacity is 0: return 0 first_item = items[0] value_with = 0 if capacity - first_item[1] >= 0: value_with = first_item[2] + kn...
d1d4125d6df55625b5671f00becd202e9ac69e6d
636,475
import copy def pipe_wait(popens): """ Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/ """ # Avoid mutating the passed copy p...
fd202a1f2f162818c827dd2f8a21f61921889e76
636,476
def _make_equal_size(a: str, b: str): """ Make the strings a and b equal size, by right-padding with spaces the shortest string """ max_length = max(len(a), len(b)) a = a.ljust(max_length).upper() b = b.ljust(max_length).upper() return a, b
6bc50ecbb1b5a178ede833c0b0587685081fe030
636,477
def play(start_num): """You choose number N. Tom and Jerry will play the game alternatively and each of them would subtract a number n [n< N] such that N%n=0. The game is repeated turn by turn until the one,who now cannot make a further move looses the game. The game begins with Tom playing fi...
cd5666a15e4086334c2d6835cbafd0c2379ce8bd
636,478
import traceback import functools import sys import time def retry(times=5): """一个装饰器,可以设置报错重试次数 :param times: 最多重试次数 :return: """ def _retry(func): @functools.wraps(func) def __retry(*args, **kwargs): retry_times = 0 while retry_times <= times: ...
d4df663fbae9a509ce389f4d5a5d86d67f21f4ec
636,479
import shlex def parse_file(file_path): """Parse input file and return list of programs with thier dir annd shares""" retval = [] with open(file_path) as pfile: count = 1 local = [] for line in pfile: if line[0] == '#': # Adding comments in file ...
471e0358a433c0f791c0dc7dc0c6b9f3ce28b227
636,480
import numpy as np def ccht2(x, y, binsize, corrected=False, smooth=0, normed=False, xaxis='time', **kwargs): """ .. note:: Same as ccht() [in turn deprecated]. Should be faster, but is slower...deprecated. Use cch() instead .. See also:: cch() """ # Convert t...
7f719f017a018a076393debdac814da686c207df
636,481
import os def example_data(infile='functional.nii'): """returns path to empty example data files for doc tests it will raise an exception if filename is not in the directory""" filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) outfile = os.path.join(basedir, 'data', infile)...
b299cda8c9a23ed9373d26fbb3478d1f3722cc78
636,482
import socket def create_socket(port, host=None, connect=True): """Creates and returns a socket Args: port (int): port number to use connect (bool, optional): whether socket should be connected (default=True) host (str, optional): hostname to connect to (default="localhost") Retu...
da1dd329599882591a8440f9b47dffc6ec83fce0
636,483
from functools import wraps import warnings def suppress_warnings(function): """ Decorate the given function to suppress any warnings. Parameters ---------- function : function Function to be decorated. Returns ------- decorated function Decorated function. """ ...
2f47d470d364cb1e5fbfd869af0351348e2f43c3
636,484
import argparse def float_tuple(argument): """ This function ... :param argument: :return: """ try: a, b = map(float, argument.split(",")) return a, b except: raise argparse.ArgumentTypeError("Tuple must be of format a,b")
1949933068fcd3ec0129e999ae05d76b310b6464
636,485
def get_LDA_potential(vxct, kxct, s): """Evaluating the potential of LDA functional in a batch of spherical projection directions. Parameters ---------- vxct: tuple of (vrho, vs), where vrho and vs are np.ndarray with shape (Ngrid) The exchange-corelation energy of original LDA function. ...
f2bbefc36587a3db2049f0c16535137096a8b845
636,486
def suitable_for_extrusion(context): """Checks selection is not none and is homogenous. """ selection = context.selected_objects n_objs = len(selection) if n_objs == 0: return False # In object mode? if selection[0].mode != 'OBJECT': return False # Homogenous? first...
37c9883e9443ea9ff70f1f73743e983b85c5644f
636,487
def TypeCodeToType(typeCode): """ Convert a type code to the class it represents """ if typeCode in ["b", "d", "f", "s"]: return float elif typeCode in ["i", "l"]: return int elif typeCode in ["c"]: return str else: raise Exception("Unrecognised type code: " + typeCode) return
7ac115f94958842c47168dc6ff9e432caac48404
636,488
def definition(): """ Quantifies office space deficit. """ NET_REQ = """ CASE WHEN req.requirement > rt.available_hours_per_week THEN req.requirement - rt.available_hours_per_week ELSE 0 END / rt.hours_accessible_per_week""" sql = f""" SELECT req.acad_year, req.set_cat_id, rt.available_hou...
61e94c993bc4cff830b800611bfea55fe64d82fc
636,489
def _build_extension_tree(extensions, deep): """ Builds a tree of extensions. Parameters ---------- extensions : `list` of ``Extension`` A list of extension to build the tree form. deep : `bool` Whether the extension with all of it's parent and with their child should be ret...
da467888a957b88cb44b47f2571eeae725692a55
636,490
from pathlib import Path import click def validate_existing_dir(ctx, param, value: Path) -> Path: """ Callback for click commands that checks that a given path is a directory """ if not value.is_dir(): raise click.BadParameter(f"{value} is not a directory") return value
76cb4b62a964a6192fb34d862005ec7d8ddca977
636,491
def _fake_dequeue_deleted(): """for monkeypatching with a DELETED status""" new_msgs = [] # insert some that don't exist to make sure nothing blows up pay = b'{"policy_type_id": 20666, "policy_instance_id": "admission_control_policy", "handler_id": "test_receiver", "status": "DELETED"}' fake_msg =...
756b23fda97b1f9dbd9081595f446397b134b8f3
636,492
import argparse def parse_args(): """parse command line arguments""" prsr = argparse.ArgumentParser(description="Simple visualization of task hierarchy") prsr.add_argument("suite_config_file", help="yaml file") prsr.add_argument("--indent", help="default=4", default=4, type=int) prsr.add_argument(...
b562faee76ef2c04e75450f5f8723c2c8ab0dbe2
636,493
import imp import os def get_version(): """Obtain the version number""" mod = imp.load_source( 'version', os.path.join('skprocrustes', 'version.py') ) return mod.__version__
cdd4d308f829403197507ca9341a856eeb2da2a6
636,494
import os def get_all_symbols(): """ Returns ------- list A list of paths to json files which are recordings. """ current_folder = os.path.dirname(os.path.realpath(__file__)) symbol_folder = os.path.join(current_folder, "symbols") symbols = [ os.path.join(symbol_folder,...
1d5a06e5e9e178e3fac6f43ac391ec004030491f
636,495
import os def load_readme(folder_path): """Returns the text content of the README.md Parameters ---------- folder_path : str parent folder of README.md """ with open(os.path.join(folder_path, 'README.md'), 'r') as f: return f.read()
67c5e1741ea30db604c77ecdc13faf8ebcb4f928
636,496
def abbreviation_in(abbreviations): """Constrain the course to given abbreviations.""" def _satisfies(course): return course.abbreviation in abbreviations return _satisfies
708d98eb5af039504f3425b947d2918a42350428
636,497
import shutil def center_text(message:str) -> str: """Takes a string and returns the centered result as a string. Parameters ---------- message: (str) The message to center Examples -------- Printing someones name centered in terminal. ``` from sdu.cli import center_text...
9e5d4f1512f3fdc0af95093c0ff5222b5f41aa5f
636,498
def mul(x, n): """ mul(x, n) Multiplication function. """ return x * n
0663c02ab693dac228b56817df7051c400adb0cc
636,499
import math def CalculateHydrophilicityFactor(mol): """ ################################################################# Calculation of hydrophilicity factor. The hydrophilicity index is described in more detail on page 225 of the Handbook of Molecular Descriptors (Todeschini and Cons...
06799e3565a9900bba70f5646ca1f244bf128c0d
636,500
import base64 def serialize_bytes(b: bytes) -> str: """ Takes a bytes object and serialize it. Must be reversible with `deserialize_string()`. """ return base64.b64encode(b).decode("utf-8")
ab153397125771647f75721e757a7a0daddee89a
636,501
import os def dirname2(path): """Returns the directory part of a path. The difference from os.path.dirname is that if the directory part is empty, it is converted to '.' (the current directory).""" d = os.path.dirname(path) if d == '': d = '.' return d
be318a46e1a487defdfa50fac16ad10e9fa04461
636,502
import string def ceasarcipher(sentence, shift): """ uses ceasar cipher to decrypt sentence """ alphabet = string.ascii_lowercase * 2 newsentence = [] for word in sentence: newword = [] for let in word: index = ord(let) - 97 newindex = index + shift ...
1048349cb866e6f03f624bc945c00ef4e6545ab3
636,503
def _get_interval_result(result): """Parse the raw output of the REST API output and return the timestep Args: result (dict): the raw JSON output of the ESnet REST API Returns: int or None """ value = result.get('agg') if value: return int(value) value = result.get...
a2f73870034863e034255a696e950ec53f67284d
636,505
def decodeFontName(font_name): """ Presume weight and style based on the font filename. """ name = font_name.split('-')[0] font_name = font_name.lower() weight = 400 style = 'regular' weights = {'light': 300, 'extralight': 200, 'bold': 700, ...
1a8a32b7c49e4a0a2dc557504b97745328d3aba7
636,506
def getClusterData(hd_halo, cluster_params, redshift_limit): """ Function to get relavant data for classified clusters @hd_halo :: table with all relevant info on halos, clusters, and galaxies within them @cluster_params :: contains the minimum mass for a central halo to be classified as a cluster (sol...
347f6da450f732a794c32df3aabf7e7b53e54377
636,507
def file_tasks(tasks, api, ws): """ File tasks to asana. """ res = [] for task in tasks: res.append(api.create_task(task, ws)) return res
a1df1521e724f0d6b2024c72b069643a6bcbd724
636,509
def _string_to_numbers(input_string) -> list: """Convert comma-separated floats in string form to relevant type. Parameters ---------- input_string : string Comma-separated floats values encoded as a string. Returns ------- list of numbers Returns converted list of floats o...
6c53ed2571251e872b30b8238e18ae6209523fdd
636,510
def check_references(V, F): """ Check that face is referenced to existing vertex """ for face in F: lenV = len(V) for v in face: if v > lenV or v < 0: return False return True
f2b6945133a00ec9cf7e8803de3fc257df521acb
636,511
def hits(origin, res): """ calculate the hit number of recommend result :param origin: dict {user:[item,...]} the user click or behave items :param res: dict {user:[item,...]} the algorithm recommend result :return: int the number of res result in origin """ hitCount = {} for user, items...
6663c125a0c12692eaddac0cc6aeed5eab04b9d6
636,512
import base64 def encode_password(shortcode, passkey, timestamp): """Generate and return a base64 encoded password for online access. """ data = shortcode + passkey + timestamp data_bytes = data.encode('utf-8') return base64.b64encode(data_bytes).decode()
20a1f1eee0c25b55457fa9fd532621cfda1d2677
636,514