content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from functools import reduce def arr2(value, *forms): """ Clojure's second threading macro implementation. The logic is the same as `thread_first`, but puts the value at the end of each form. See https://clojuredocs.org/clojure.core/->> :param value: Initial value to process. :type valu...
56dbefe686300ff0f9173d4b5c4c195486cb8178
666,995
def get_atoms_per_fu(doc): """ Calculate and return the number of atoms per formula unit. Parameters: doc (list/dict): structure to evaluate OR matador-style stoichiometry. """ if 'stoichiometry' in doc: return sum([elem[1] for elem in doc['stoichiometry']]) return sum([elem[1] for...
211ec973f27ee1ad4b3a8b37efa3027887423f6b
666,996
def parse_capability_lists(cls_str): """Parse list of capability lists in --capabilitylistindex option. Input string of the form: uri,uri """ return(cls_str.split(','))
6e8c897b99f1305aba9830fbf84ac2a64d1080e4
666,997
from typing import Iterable def _normalize_sequence(inp, rank): """If inp is a scalar, create a sequence of length equal to the rank by duplicating the inp. If inp is a sequence, check if its length is equal to the length of array. """ is_str = isinstance(inp, str) if not is_str and isinstanc...
e956314f2b78350089cd462c87fc6c6c0167ca15
666,998
def eval_grad_f(x, problem): """ Calculate the gradient of the objective function Assumptions: You can actually install ipopt on your machine Source: N/A Inputs: x [array] problem [nexus()] Outputs: grad [array] Pro...
5c2578e46a51818fbea34b15e36c560c2d9d5132
666,999
def batch_to_single_instance(X): """ Take the first instance of an array that contains a batch of items. Parameters ---------- X : nd array, shape: [batch_size, \\*instance_shape] A numpy array whose first axis is the batch axis. Returns ------- x : (n-1)d array, shape: [\\*in...
07e9b19211dcf9cc01b76174c62159925f3c3cdc
667,000
def _unpack_one_element_list(scalar_or_list): """If the value is a list and it only has one value, we unpack it; otherwise, we keep the list. This is used for size parameter inside tf.io.SparseFeature. """ if isinstance(scalar_or_list, list) and len(scalar_or_list) == 1: return scalar_or_lis...
67937c1abf2cf1bc6df7af8a48565884bccd8d69
667,001
import re def humansorted_strings(l): """Sort a list of strings like a human Parameters ---------- l : list A list of strings Returns ------- list The sorted list """ def alphanum_key(s): key = re.split(r'(\d+)', s) key[1::2] = map(int, key[1::2]) ...
d29f2e6b9b8a187531ea58529efdcb13c5890950
667,002
def make_ratings_hash(ratings): """ Make a hashtable of ratings indexed by (userid,itemid) @param ratings: pandas.DataFrame of ratings @return a hashed version of the input ratings, which maps (userid, itemid) tuples to the relevant rating. """ rhash = {} # for every 3-colu...
f9eae9b6b392fba101ebe41a133cc7c1cc9bd258
667,004
def cut_off(pvs, cutoff, move, color): """Keep move only if abs(bestmove-currentmove) < cutoff.""" if cutoff == None or len(pvs) == 0: return pvs return cutoff.cut_pvs(pvs, move, color)
0322104726fad39f5bb4b99a93a2287586769766
667,005
import argparse from sys import argv def parse_args(): """Count human and not human reads; slow, but ok memory usage""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--table", "-t", dest="class_tab", help="Unoise mapping to human UC output." ) ...
218769e01a4231e78b556695a096db7a5c1a0572
667,006
def argmax(list, score_func=None): """ If a score function is provided, the element with the highest score AND the score is returned. If not, the index of highest element in the list is returned. If the list is empty, None is returned. """ if len(list) == 0: return None scores = list...
566550aacf639121ddf96022e3154ba45d7cb4af
667,007
def get_loc_11(number=1): """Turn the the number for loc_11 into a string""" n = str(number) return n
3f7e492794bf017cbe95fb2e4d82f8f779c15438
667,008
def mark_backend_unsupported(func): """Mark a method as being not supported by a backend.""" func._oculy_backend_unsupported = True return func
5d1053dfcfeaf7a078a0b8cb87321152d9ee1111
667,009
def GetScriptToWaitForUnchangingDOM(): """Gets Javascript that waits until the DOM is stable for 5 seconds. Times out if the DOM is not stable within 30 seconds. Returns: Javascript as a string. """ return """ var target = document.body; var callback = arguments[arguments.length - 1] var ti...
fba0094d8d22d375353c2646b07c334c8dbefe5e
667,011
import io def fetch_image(session, url, timeout=10): """download the satellite image for a tile. Args: session: the HTTP session to download the image from url: the tile imagery's url to download the image from timeout: the HTTP timeout in seconds. Returns: The satellite ...
399d24be9a9ecad8d6d3f84da80243643bf23a1d
667,012
import numpy def init_props(nhaps, alpha=1.0): """ Initializes haplogroup proportions by random draw from Dirichlet with a uniform alpha parameter. Args: nhaps: number of haplogroups and length of the array to produce alpha: alpha parameter for dirichlet distribution Returns: ...
91edad9b4968b9cf463e03c58e699476d6770db8
667,013
def find_item(item_list, field, value): """ find_item() allows us to perform a query on a model and return a list and a single record without hitting the database twice; for example, we often need a list of shelters to generate the sidebar nav and also the name of a single shelter to place in a head...
8ef7c88293bd65e2b8dd7803a0ce9e7d17412f6b
667,014
def get_severity(severity): """ Returns Severity as per DefectDojo standards. :param severity: :return: """ if severity == "high": return "High" elif severity == "medium": return "Medium" elif severity == "low": return "Low" elif severity == "informational...
d869b8872d0c3e0b8670358ecba3fac9638bbb84
667,015
def weight_standardization_nd(dim, weight, eps): """ Note: input channels must be greater than 1! weight = torch.rand(3, 2, 1, 1) dim = 2 eps = 1e-5 weight_normed = weight_standardization_nd(dim, weight, eps) print('weight = {!r}'.format(weight)) print('weight_normed = {!r}'.format(weig...
fe26605b1307b3348dede1aa5310ea969b5bf22d
667,016
def make_double_digit_str(num: int) -> str: """ useful for file names, turns 9 into "09" but keeps 15 as "15" :param num: one or two digit number :return: two digit number string """ return str(num) if num > 9 else "0" + str(num)
8e07b2bdcc6d1cf7bbbc344ab1ed240000e23210
667,017
import math def get_es(temp): """ Reference page number: 29 Parameters ------------------------------ temp: (``float``) Air temperature in degrees Celcius Returns ------------------------------ es: (``float``) The saturation vapour pressure """ es = 0.6108 * mat...
df10dbc77df76095d2c5133d1386c5a0696ec363
667,018
def disp_hai(yama): """yama:u_int32[136] -> hai:str[][136]""" hai_disp = ["<1m>", "<2m>", "<3m>", "<4m>", "<5m>", "<6m>", "<7m>", "<8m>", "<9m>", "<1p>", "<2p>", "<3p>", "<4p>", "<5p>", "<6p>", "<7p>", "<8p>", "<9p>", "<1s>", "<2s>", "<3s>", "<4s>", "<5s>", "<6s>", "<7s>", "<8s>", ...
1fff42e5dd85b3b8bc4717db54ec59870756b5cb
667,019
def upper(name: str) -> str: """Convert the name value to uppercase. Arguments: name: name of the attr. Returns: The uppercase value. """ return name.upper()
435d1b81fbec5401a0c942be9a56c2afb7fb113d
667,020
def bubble_sort(some_list): """ https://en.wikipedia.org/wiki/Bubble_sort We continuously loop through the data set, swapping next-door-neighbors that are out of order. In this way, values will BUBBLE one spot towards their correct positions once per loop. O(N^2) """ iters = 0 did_swap ...
746930b4c083b803f64aa4afa6a461123f92e66f
667,021
async def __checkResponseFormat(response_text: str): """Known Control4 authentication API error message formats: ```json { "C4ErrorResponse": { "code": 401, "details": "Permission denied Bad credentials", "message": "Permission denied", "subCode": 0 ...
aa0afc6c38455f0a84aa6f6143cbd1335706137b
667,022
import pytz from datetime import datetime def is_scheduled(recipe, task = {}): """Wrapper for day_hour_scheduled that returns True if current time zone safe hour is in recipe schedule. Used as a helper for any cron job running projects. Keeping this logic in project helps avoid time zone detection issue...
4e8f338780281d71f4694bffa8d8bc7b7566130a
667,023
def get_selected_tests(args, tests, sources): """Return the selected tests.""" for exclude_test in args.exclude: tests_copy = tests[:] for i, test in enumerate(tests_copy): if test.startswith(exclude_test): tests.pop(i) sources.pop(i) return tests,...
bdcc861610ed28bdeee49bcfcae8f37bf59150f5
667,024
def check_renewal(renewal): """check into the auxiliary area is not expired""" if renewal == "yes" or renewal == "no": return True return False
4db676c9fdd6a14e5776d3c4b8f27202430a3c42
667,026
def unless_flag(flag, action): """Only take action is flag is not set""" def _inner(state, *args): if state.cpu.reg.getflag(flag) == 0: action(state, *args) return _inner
6fb5432b83fba36a5fd0e73ea620ea1db58b1a1f
667,028
def _inside_this_control_function(cf, file, line): """Determine action to which string belong.""" if cf['file'] == file and cf['begin'] <= line <= cf['end']: return True else: return False
7de7c9efb04d6770a9c9584c45793a28f48f9489
667,029
def read_file(path): """ Return the contents of a file Arguments: - path: path to the file Returns: - contents of the file """ with open(path, "r") as desc_file: return desc_file.read().rstrip()
146863066db83943d79de1ce6c43acecb46c8bac
667,030
def _param_check2(form: str, Do: int) -> bool: """ Para reducir la redundancia en el cuerpo de las funciones, esta función verifica que : 1.- La formulación de filtro especificada, 'form' se válida i.e. Alguna de las siguientes : 'ideal', 'btw', 'butterw...
d09af981549321279d473d0e612ecd72a6e68dd4
667,031
def parse_expression(tokens): """Parses a single S-sxpression from a token stream. Uses a simple iterative variant of a recursive descent parser with only a single parsing rule.""" stack = [] while True: tok = next(tokens) if tok == '(': stack.append([]) elif tok == ')': ...
494783e1eadcc310992be28c0b3529c9d2ada306
667,032
import textwrap import re def pytd_src(text): """Add a typing.Union import if needed.""" text = textwrap.dedent(text) if "Union" in text and not re.search("typing.*Union", text): return "from typing import Union\n" + text else: return text
5d5c9019f5cfde866a6b05e0f48febc17bfb1c09
667,033
import torch def KLD(mean, log_std): """ Calculates the Kullback-Leibler divergence of given distributions to unit Gaussians over the last dimension. See Section 1.3 for the formula. Inputs: mean - Tensor of arbitrary shape and range, denoting the mean of the distributions. log_std - T...
58a98846cf646c5f33079bdf438ed41833277152
667,034
def receive_hash_password(password): """ Get hash password from the tuple representation (remained after SQL query) and return it encoded (required by bcrypt checkpw function) """ if password == None: return None return "".join(password).encode("utf-8")
dd79a1be5a892089e2d5109a11811584e0bc2a95
667,035
from pathlib import Path import os import json def load_settings(): """Load seetings json file into a dict Settings will be loaded from ~/.mnisiscom/settings.json Returns: dict: A dictionary of settings for MNI SISCOM Returns an empty dict if no settings file exists. """ ...
e6bfac5263af31fdfca03d037881710eb9d7c914
667,036
def has_duplicates(lst: list) -> bool: """Checks if a list has duplicate values""" return len(lst) != len(set(lst))
6f6ac90894a96900af92177898d7e1a0151b2d03
667,037
import numpy def OPD(mp, rho, ti, pz, wvl, zd): """ Calculate phase aberration term. mp - The microscope parameters dictionary. rho - Rho term. ti - Coverslip z offset in microns. pz - Particle z position above the coverslip in microns. wvl - Light wavelength in microns. zd - Actual c...
bea242104b9a5df190848126789e1d83449536d3
667,040
def validation_metrics_v2(ground_truth, bowtie2_prediction): """Calculates the recall and specificity Find list instersection!! parameters ---------- ground_truth dict, contains the ground truth as obtained from the sim reads bowtie2_prediction dict, contains the predicted read m...
a215a6fcf6a43d90e3d99f64e5c0b5e351babe47
667,041
from dateutil import tz def datetime_to_isodate(datetime_): """Convert Python datetime to GitHub date string. :param str datetime_: datetime object to convert .. note:: Supports naive and timezone-aware datetimes """ if not datetime_.tzinfo: datetime_ = datetime_.replace(tzinfo=tz.tzutc(...
a2365e7d74fe3cf5aca96ceccb93020400f18700
667,042
def _encode_csv(iterable_items): """ Encodes CSVs with special characters escaped, and surrounded in quotes if it contains any of these or spaces, with a space after each comma. """ cleaned_items = [] need_escape_chars = '"\\' need_space_chars = ' ,' for item in iterable_items: n...
85978f2e7dad2eb56108c636545611f38e4a24d6
667,044
def willDigest(char): """ Overload this to try out other digests. Right now it just takes single character as an argument... and tells you if it's digest-able. Currently only a trypsin digest is encoded. """ if char == 'R' or char == 'K': return True return False
66fd1a9a944a2f30d4f2cf3cf41c3ca0303799e4
667,045
def acquisitions_from_ifg_dates(ifg_dates): """Given a list of ifg dates in the form YYYYMMDD_YYYYMMDD, get the uniqu YYYYMMDDs that acquisitions were made on. Inputs: ifg_dates | list | of strings in form YYYYMMDD_YYYYMMDD. Called imdates in LiCSBAS nomenclature. Returns: acq_dates | l...
7ee5a0bec594c9257bcfb0c61db3e8a8f6791ecb
667,046
def merge_dicts_into(target, *dicts): """Merge the provided dicts into the target dict.""" for d in dicts: target.update(d) return target
c2ff91a3f43158350150f223ee6987c75250a4ca
667,047
def prepareInfluenceDict(listLuNrs, listDynLus): """ Makes an empty 3D-dictionary which can hold lu:s influence at dist: infl[targetLu][affLu][dist] = someValue, defInfl[targetLu][affLu]["startY"] = someValue """ # Prepare the influence dictionary infl = {} listLuNrs.sort() # Only changeabl...
7260753180c08888aadab296ea750e1864a478d8
667,048
import platform import subprocess def has_strace(): """ Return True if this system has strace. """ if platform.system() == 'Windows': # even if windows has strace, it's probably a dodgy cygwin one return False try: subprocess.Popen('strace', stderr=subprocess.PIPE) return T...
9f04ef6a78e5082ab6f6c101120a07a2fdb426b6
667,049
import requests def get_asn(asn, limit, offset): """Данные мониторинга провайдера""" link = "https://api.ooni.io/api/_/website_urls?probe_cc=RU&probe_asn={}&limit={}&offset={}".format(asn, limit, offset) r = requests.get(link) return [i for i in r.json()['results']]
552f15e57163448d37bc9b078af2a8d21b83cee4
667,050
def find_cavities(grid): """ :type grid: list[list[str]] :rtype: list[list[str]] """ for i in range(1, len(grid) - 1): for j in range(1, len(grid[i]) - 1): if ( (grid[i - 1][j] != 'X' and int(grid[i][j]) > int(grid[i - 1][j])) and ...
82b72152044b139371dbf30c8a9431380ea0de99
667,051
from typing import Tuple def check_on_grid(position: Tuple[int, int]) -> bool: """Checks if a given position is on the grid.""" return all([-1 < coord < 10 for coord in position])
3143d25a604cb32dc92fc74f4da0dfb7a2944bb2
667,052
import pathlib def git_repo_kwargs(repos_path: pathlib.Path, git_dummy_repo_dir): """Return kwargs for :func:`create_project_from_pip_url`.""" return { "url": "git+file://" + git_dummy_repo_dir, "parent_dir": str(repos_path), "name": "repo_name", }
d3b48b23984f6a91130deb1ff4cc3d239e2dc03b
667,053
def _decrement_lower_bound(interval): """ Decrement the lower bound of a possibly inverted interval. i.e. turn (1, 5) into (0, 5) and (5, 1) into (5, 0). Intervals in m8 alignment files can be inverted. """ (bound_one, bound_two) = interval if bound_one < bound_two: return (bound_one...
d6e3581e8568ca021d7efd7e47892ab49a43fe2f
667,054
def format_exc(limit=0): """This is like ``print_exc(limit)`` but returns a string instead of printing to a file.""" return ''
ba63016c1aa192b909f37b329ffec017262bb4ca
667,055
def unique(seq): """ Function for/to <short description of `netpyne.sim.utils.unique`> Parameters ---------- seq : <type> <Short description of seq> **Default:** *required* """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(...
47698788803e0e3c1bc3edb77d38f00d8d3ca349
667,056
def _get_file_names(): """Returns the file names expected to exist in the input_dir.""" file_names = {} file_names['train'] = ['data_batch_%d' % i for i in range(1, 6)] file_names['eval'] = ['test_batch'] return file_names
efc49f1808776cc813b9007f172c45fdb3188847
667,057
async def create(context, name_or_id, neutronclient, external_gateway_info=None, use_existing=False): """ Creates router :param context: :param name_or_id: :param neutronclient: :param external_gateway_info: :param use_existing: :return: """ if n...
b6611146074c15c44e5f6dd4fae1dd48829f0dc2
667,058
def fetch_object(service, obj_type, obj_name, create=False, create_args={}, **fetch_args): """Helper function to fetch objects from the Watson services. Params ====== - service: a Watson service instance - obj_type: object type, one of: "environment", "configuration", "collection", "workspace" ...
46885b465c1dfe415ba48433856fd5144546030c
667,059
import os def check_perms(chain_file, log_list_file): """ check_perms verify that this script as read permission on the necessary files :param chain_file: the chain file containing the certificate chain to submit to a log :param log_list_file: the log_list.json file from www.certificate-transparency.org ...
bb7f333697c97cc29d27c17b9fbbec50a23ba774
667,060
import numpy def diag_indices(n, k=0): """ Return the indices corresponding to the kth diagonal of an n X n array in the form of a tuple of (x coords, y coords). Created since numpy does not provide this functionality. """ if k <= 0: x_coords = numpy.arange(-k, n) y_coord...
4df4555fe22d78b29dfbde62c018aa6b561fa531
667,061
def atof(text): """ helper for natural_keys attempt to convert text to float, or return text :param text: arbitrary text :return: float if succeeded to convert, the input text as is otherwise """ try: retval = float(text) except ValueError: retval = text return retval
c71568d1c9b37f271a82a9891c282c52786d90c5
667,062
def bgr_to_rbg(img): """Given a BGR (cv2) numpy array, returns a RBG (standard) array.""" dimensions = len(img.shape) if dimensions == 2: return img return img[..., ::-1]
b4b25566129a620905d429cc7f90e4bc0c31b467
667,063
def filter_instances(instances, filter_expr): """Filter instances using a lambda filter function.""" return list(filter(filter_expr, instances))
5003888f1536788fe8e4b2d1430f962983edee70
667,064
def _get_cbar_defaults(orientation): """get some cbar stuff based on orientation = 'horizontal' or 'vertical See commented out code for "inside" colorbar which was abandoned... """ cbar_kw = {'orientation':orientation,'shrink':0.6} if orientation == 'horizontal': cbar_kw['pad'] = 0.06...
0bfb63b4c81e6a0727a8fd6585e45050cb4db670
667,067
def build_path(options): """ Build the URI path needed to query the DNSDB API :param options: Dictionary :return: string """ if options["name"]: if options["inverse"]: path = "/lookup/rdata/name/{}/{}".format(options["name"], options["type"]) return path ...
2cf8c546df0e4c37292ac58e9ef5ee1c2dcbd993
667,068
def denormalize(x,centroid,scale): """Denormalize a point set from saved centroid and scale.""" x = x*scale + centroid return x
01ccf107edf569b771a9e97928ed49fc8184ff11
667,069
def get_config_constraints(): """ Returns constraints configuration as ``dict`` from which data requests will be stacked. Returns ------- split_dict : TYPE DESCRIPTION. """ c_dict = { 'year': { 'depth': 6000, 'geo': 200 }, 'month'...
0b23bde69b7e8b27616c0e4f7f24c79efd0fbdb9
667,071
def minmaxrescale(x, a=0, b=1): """ Performs a MinMax Rescaling on an array `x` to a generic range :math:`[a,b]`. """ xresc = (b - a) * (x - x.min()) / (x.max() - x.min()) + a return xresc
114b8f3f67338be432af82ab36769618c3140c51
667,072
from pathlib import Path def test_data_root_dir() -> Path: """Return the absolute path to the root directory for test data.""" return Path(__file__).resolve().parent / "test_data"
08a17b2c10ddec5ee4f3e21382f11723f90651c5
667,073
def caps(l): """Count the number of capital letters in a line. This can be useful for counting proper nouns, but is very sensitive to the properties of your edition. Use with caution. Args: l (bs4 <line>): Line to check Returns: (int): Number of uppercase letters """ retu...
92f8698b796697103e6aac101305da8452aff19f
667,074
from typing import List from typing import Tuple def flat(data: List[Tuple]): """ Removes unnecessary nesting from list. Ex: [(1,), {2,}, {3,}] return [1, 2, 3] """ if not data: return data return [d for d, in data]
0adea0c16cc7266cfba22b5afd2497192cc66eb3
667,075
def get_material_req_qty(doc): """count total quantity for specific MI""" total_qty =0.0 for row in doc.items: total_qty += row.qty return total_qty
d0c4bdfe1183803a4f7d03c019de7b7aa238f580
667,076
def is_number(num): """Tests to see if arg is number. """ try: #Try to convert the input. float(num) #If successful, returns true. return True except: #Silently ignores any exception. pass #If this point was reached, the i...
4a743c79fb94a24b5bf589a112145468ea23f59f
667,077
def rlshift(): """: Right operand shift left operator.""" class _Operand: def __rlshift__(self, other): return "{} and many 0s".format(other) return 1 << _Operand()
19e33cb897600eb624f8ef875c36427a494d9d49
667,078
from pathlib import Path import pickle def load_levels() -> list: """Loads all levels from the levels directory.""" p = Path("./levels") levels = list(p.glob("*.level")) for element in levels: index = levels.index(element) with open(element, 'rb') as f: levels[index] = pick...
8e920ba498e937b3e866984f14688fc3c75408fa
667,079
import inspect def get_caller(): """returns a nice string representing caller for logs Note: This is heavy""" curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) caller = "{} ({}#{})".format(calframe[2][3], calframe[2][1], calframe[2][2]) return caller
99a5b88e163f3fa0f7c8de29819cfc19ca6fdc34
667,080
import subprocess def hugo_version_cmd() -> bytes: """ Returns Hugo version :return: Hugo version """ return subprocess.check_output(["hugo", "version"]).strip()
0f536c37c631d25c58122a1871ca8c6094009fab
667,081
def subset(data, size): """Get a subset of the dataset.""" return { 'data': data['data'][:size, :], 'labels': data['labels'][:size], }
dc5116a7a84b49a516e18427ba373c5de2f03a15
667,082
def compute2x2(obs, pred): """Compute stats for a 2x2 table derived from observed and predicted data vectors Parameters ---------- obs,pred : np.ndarray or pd.Series of shape (n,) Returns ------- a : int True positives b : int False positives c : int Fal...
79c0483719d8f96b3895da25cab2d8fd27293bf6
667,083
import six def morph_dict(d, convert_function): """ Convert a nested dictionary from one convention to another. Args: d (dict): dictionary (nested or not) to be converted. convert_function (func): function that takes the string in one convention and returns it in the other one. ...
47e7c74f68b0eab57934449c9028b04f06a677b9
667,084
def make_ppLFER(pp): """Check if ppLFER system parameters are in the pp file, if not generate them. The order is l,s,a,b,v, c. """ #Aerosol-air ppLFER system parameters Arp (2008) if 'logKqa' not in pp.columns: pp['logKqa'] = [0.63,1.38,3.21,0.42,0.98,-7.24] #Organic Carbon - Water ppLFE...
fb376c611cabbf289df135d90aceb1245ad03083
667,085
def fixture_family_tag_name() -> str: """Return a tag named 'family'""" return "family"
fe55bb8fabf2888b0576320ea269f5aa122460dc
667,086
def conslice(sim_mat, sep): """Slices a confusion matrix out of similarity matrix based on sep""" images = sim_mat[:sep] slices = [] for i in range(len(images)): slices.append(images[i][sep:]) return slices
62e7591015beb317fab694089f5253f97cda7f34
667,087
import numpy def transform(xi, simplex): """Transform the points `xi` from the reference simplex onto `simplex`. """ # For n == 2: # x = ( # + outer(triangle[0].T, 1.0 - xi[0] - xi[1]) # + outer(triangle[1].T, xi[0]) # + outer(triangle[2].T, xi[1]) # ) shape_funs = ...
41e7b7f0021fbde549a0e55a501d5db2deb0e9ed
667,088
def decode_name(name, barcodemap): """ rename seq/taxon name, typically for a tree display, according to a barcode map given in a dictionary By definition barcodes should be distinctive. """ for barcode in barcodemap: if barcode in name: return barcodemap[barcode] retur...
d9a93cc3b0298a20a81c4b9a09172a847c605431
667,089
def summarize_columns(hdf5_file): """ Summarize read/write bytes for each column """ results = {} for index, column_name in enumerate(list(hdf5_file.get_columns('/datatargets/readbytes'))): if column_name not in results: results[column_name] = {} results[column_name]['rea...
091e0cf75a5d013a2989e8542d28c2670de2b986
667,090
def decode_word(word): """ Return the decoding of a run-length encoded string """ idx = 0 res = [] while idx < len(word): count = int(word[idx]) char = word[idx+1] res.append(char * count) idx += 2 return ''.join(res)
6288e9dabbb44626487f0ce1d733ad471676eedd
667,091
def _extents(f): """Helper function to determine axis extents based off of the bin edges""" delta = f[1] - f[0] return [f[0] - delta/2, f[-1] + delta/2]
5250cf68196a330dcc563d3d388b26cd5ccb1447
667,093
def nexus_from_alignment(aln, seq_type, wrap=50): """returns a nexus formatted string Parameters ---------- seq_type dna, rna, or protein wrap the line width """ if aln.is_ragged(): raise ValueError( "Sequences in alignment are not all the same " ...
e1ec0f38e1d1655eb7a2291f257b02012c94cef9
667,094
def remove_oneof(data): """ Removes oneOf key from a dict and recursively calls this function on other dict values. """ if 'oneOf' in data: del data['oneOf'] for key in data: if isinstance(data[key], dict): remove_oneof(data[key]) return data
8f43890c971464c186eb4c7ec1f098a99cae21f3
667,095
import argparse def parse_args(args): """Take care of all the argparse stuff. :returns: the args """ parser = argparse.ArgumentParser(description='Create synthetic observations.') parser.add_argument('simnum', help="Simulation Observation label") parser.add_argument('--suffix', default=None, ...
df41868982ef3b572b73fbbab773af712dd802e7
667,096
import re def clean_string_whitespace(text: str) -> str: """Clean whitespace from text that should only be a single paragraph. 1. Apply ``str.strip`` method 2. Apply regular expression substitution of the ``\\s`` whitespace character group with `` `` (a single whitespace). """ text = text....
7105129d461d827fba88b29d12ef89141772d305
667,098
import argparse def make_cli_parser(): """Creates the command-line interface. :returns: an :py:class:`argparse.ArgumentParser` instance """ cli_parser = argparse.ArgumentParser(description=__doc__) cli_parser.add_argument( 'length', type=int, help="length of sequence to generate") ...
959643b62a2ed981ecfa28b0f8f6669ec83cf789
667,099
import requests def get_release(catalog_id:str, results=None) -> list: """ Fonction qui récupère toutes les informations liés à une sortie """ if results is None: results=[] try: res = requests.get(f"https://www.monstercat.com/api/catalog/release/{catalog_id}").json() except Co...
09ecf946315e6984f875f6cb439df28ed52eb9d0
667,100
import requests import os def get_data_from_resource(location): """ Return the data from a specific resource. It can be a locally stored file or an internet url. """ if (location.startswith("http://") or location.startswith("https://") or location.startswith("www.")): resp = re...
bb64aab2a229cf142295f67f267f839bfc1e50a7
667,101
import logging import sys def setup_logger( name: str, level: int = logging.INFO ) -> logging.Logger: """Set up logger""" logger = logging.getLogger(name) logger.setLevel(level) if not logger.handlers: # Add stream handler for STDERR stream = logging.StreamHandler(sys.stderr)...
2b28b5b14f483209fdcb6bfa6f4e8c3568bb96e2
667,102
import os import requests def download_emoji(download): """Download a single emoji from slackmojis.com.""" dest_filename, href = download if not os.path.exists(dest_filename): response = requests.get(href, stream=True) if response.status_code == 200: with open(dest_filename, ...
a7858e7fbabf5a5f6ec2ab4e1247c4fca3c0f59a
667,103
def find_item(items, key, value): """Find an item with key or attributes in an object list.""" filtered = [ item for item in items if (item[key] if isinstance(item, dict) else getattr(item, key)) == value ] if len(filtered) == 0: return None return filtered[0]
b892353fab9cbdc7dba73b06f6a533b734aeb402
667,104
def get_collected_vertex_list_name(full_path_name): """Return the name of the list generated by folding vertices with name full_path_name.""" return "collected_" + full_path_name
46f3488ec47dab181df159e33d81d09fa91442a2
667,105
def has_won(player): """ Test to see if the player has won. Returns true if the player has the gold and is also at the tile (0,0). """ return player.x == 0 and player.y == 0 and player.has_gold
523fc89099099865a7a65c8250d62cc07c5268d1
667,106