content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def match_post_filter(record: dict, post_filter: dict, positive: bool = True) -> bool: """Determine if a record value matches the post-filter. Args: record: record to check post_filter: filter to apply (empty or None filter matches everything) positive: whether matching all filter crite...
9e5f0b42e9f5b27fd378f416042cb9719c0f04d5
633,232
import os def strip_template_path_suffix(template, marker_string): """ Removes the filename from a path template and strips the remaining suffix until the folder that contains the given marker string. If the marker string is not found, the path without the filename is returned. """ template_fo...
ac8059fd97e8526dcaea3bc9aa4ff2a7687920d5
633,234
def filter_missing_rna(s2bins, bins2s, rna_cov): """ remove any bins that don't have 16S """ for bin, scaffolds in list(bins2s.items()): c = 0 for s in scaffolds: if s in rna_cov: c += 1 if c == 0: del bins2s[bin] for scaffold, bin in l...
d8e8ab1750c5f17fa07dc2413d5e1ffd47546e36
633,235
def FindSubstr(subseq, seq, expAt, wobble): """ Here we search for model parts pre and post barcode within a sequence from reads. subseq (str) Subsequence within string we're looking for seq (str) Full sequence to search subseq within expAt (int) expected at location of subseq wobble (int) ...
aaa92ea326b3a34e629c205066121f6a4bc61b08
633,236
def extract_relevant (msg): """ Extracts relevant (to the app) headers & info from a GMail message """ headers_to_extract = set (["subject", "from", "message-id"]) headers = msg["payload"]["headers"] data = dict () data ["id"] = msg ["id"] data ["thread_id"] = msg ["threadId"] for heade...
afcf4010c7e989899fecddcc444cbc76b802a917
633,237
import torch def mul_edge_softmax(indices, values, shape): """ Args: indices: Tensor, shape=(2, E) values: Tensor, shape=(E, d) shape: tuple(int, int) Returns: Softmax values of multi-dimension edge values for nodes """ device = values.device values = torch.exp...
446597abc0962c7ad79f650fb78464c8e3b7179b
633,238
def getDomainID(conn,domain): """Get the ID of the domain to be updated from the Database""" c=conn.cursor() r=c.execute("select * from domains where domains.name=%s" , domain) try: domID=c.fetchone()[0] except: exit("No such domain") return domID
3eeab9bd4a7f946f20ac9f2982b71fa4e96fe168
633,239
def url_is_image_or_css_link(url): """ checks if url has image link in it """ IMAGE_EXTENSIONS = [ '.png', '.jpg', '@md.x', '.pdf', '.calendar.google.com' ] for ext in IMAGE_EXTENSIONS: if ext in url: return True return False
ea41fb89d4f53a57020381e80443f3e5c78b81b8
633,240
import re def stringify_segments(sent_dict_list, segment_type): """ Converts a list of sentences (Doc objects) into strings based on their segment number, to pass to a model. :param sent_dict_list: The dictionary list containing the list of sentences. :param segment_type: The type of segment to conver...
047d52af3994285c3a16c3efe5d1bdad8fa307e9
633,242
def insertion_sort2(l, ordem='asc'): """ Faz a ordenação de uma lista de números em ordem ascendente ou descendente utilizando o algoritmo de INSERTION SORT. A lista que é recebida como parâmetro é modificada in-place. Descrição: esta função implementa o algoritmo de INSERTION SORT ...
85fc57e9b07384916772d79b6d6d396d8f8af279
633,243
import requests def session(): """Return the HTTP session. Correct operation of tests requiring authentication requires they use the same HTTP session. """ return requests.Session()
a19447f430a9c8d36ce53b7df7bdb87a5ccd6f12
633,244
import ntpath def extract_filename(path_filename): """ In case the customer uses a path instead of a filename, we extract the filename If it is just a filename, then we return it back directly. Using ntpath to make sure it works on all platforms. Note the filename could be empty :param path_f...
6223984119bc758953fa518a0f7e2e216ed56fd5
633,245
def twin_list(titanic_data): """Returns a list of tuples of pairs of passengers who are likely to be twin children, i.e., same last name, same age, same place of embarkment, and age is under 18; each tuple has the following format: (person1's "last name" + "first name", person2's "last name" + "first name") """...
9206ef06e2cd7e17fe67846a6a4716b8559d0c7b
633,246
import numpy def min_or_none(x): """ Given an array x, returns the min value. If x = [], returns None. """ if len(x) == 0: return None else: return numpy.min(x)
4250dead451be856949142204c8a10fffb3fa832
633,248
def extract_coord(var_name): """Assuming prefix_R_C format, return (prefix,row,column) tuple. prefix is of type string, row and column are integers. The "nowhere" coordinate has form prefix_n_n. To indicate this, (-1, -1) is returned as the row, column position. If error, return None or throw exc...
a0f51761d3865e78cecd1d74a87a03b7ddf10c71
633,249
import os def with_cwd(new_cwd, func, *args): """ Wrapper util to run some function in new Current Working Directory :param new_cwd: path to the new CWD :param func: callback :param args: args to the `func` :return: result of `func` """ old_cwd = os.getcwd() try: os.chdir(n...
2e56a05f17dbebf4825386daaff123d9c4ffb270
633,250
import os import posixpath def prepare_path(path, replace_space, replace_sep, expandvars, expanduser): """ Performs `os.path` replacement operations on a path string. :param path: Path string :type path: unicode :param replace_space: Mask spaces with backslash. :param replace_sep: Replace pot...
95a6913e39706bb337b8d72c8fd9e6b9b8142e58
633,251
import json def _read_city_name(path: str) -> str: """read city name from json file in the log folder Args: path: path to the json city_name in the log folder Returns: city_name: city name of the current log, either 'PIT' or 'MIA' """ with open(path, "r") as f: city_name = ...
d758be33e25cf36260f97dbb23be4441c9f4ae75
633,252
def my_tables (): """ Table creation queries are implemented here """ """ creates meetups table """ meetups_table = """CREATE TABLE IF NOT EXISTS MEETUPSTABLE ( meetup_id SERIAL PRIMARY KEY, meetup_topic VARCHAR(50) NOT NULL, meetup_happening_on VARCHAR(50) NOT NULL, meet...
82daa8e9ca14bf81f655e87ed9934229078ce0c9
633,253
import requests import time import os def download_file(url: str, indir: str) -> str: """Download a file at a given URL and save it in a given directory. This function downloads a file from a web site and saves it in a directory. Then it returns the file path. Parameters ---------- url : str ...
291d3290d6225277381e593bc327e2ae9997df12
633,254
def user_input_reference_schema(): """ Return datamodel reference schema for user input Returns ------- dict with user input reference schema """ return { "REFERENCE": { "VERSION": { "type": "str", "required": True } ...
115860f4dbc4b10b09d35e723206029659970b96
633,255
def complex_product(a_re, a_im, b_re, b_im): """ Computes the complex product of a and b, given the real and imaginary components of both. :param a_re: real component of a :param a_im: imaginary component of a :param b_re: real component of a :param b_im: imaginary component of a :return: tu...
4e17df4023ff9d6042105dc7d57cdb124cbafec6
633,256
def get_species_counts(individuals): """ Returns a dictionary with species name as the key and the number of individuals in that species as the value. :param individuals: :return: """ species_counts = {} for individual in individuals: species = individual.split("_")...
694660d7519b20560bc3ea173aa2d49261d8c0cf
633,257
from typing import Callable from functools import reduce def pipe(*fns: Callable) -> Callable: """ Returns a function invoking 'fns' in sequence left to right, the first with the initial arguments, each thereafter with the last return value. >>> pipe(lambda x, y, z: x + y + z, lambda x: x + 1)(1, 2, ...
7bf42d461524c2af85760562c3cf74f952e2933a
633,258
import re def entities_textcleaning(string, lowering=True): """ use by entities recognition, pos recognition and dependency parsing """ string = re.sub('[^A-Za-z0-9\\-() ]+', ' ', string) string = re.sub(r'[ ]+', ' ', string).strip() original_string = string.split() if lowering: st...
42948f26f774967149938c63283c0a39b6046af8
633,259
import torch def cross_broadcast(x: torch.Tensor, y: torch.Tensor): """ Cross broadcasting for 2 tensors :param x: torch.Tensor :param y: torch.Tensor, should have the same ndim as x :return: tuple of cross-broadcasted tensors x, y. Any dimension where the size of x or y is 1 is expa...
e19ed1a821905f2ee9deeddb9712621fcd2399e2
633,260
def remove_country_code(language): """ Returns only the ISO-639-1 language part of the provided language string, that may also contain a ISO-3166 country part as suffix. :param language: :return: """ if '-' in language: return language.split('-')[0] if '_' in language: re...
5ee9fbb6e05aa00ae10945177f2f02c34a750ddf
633,261
def first_line(text, keep_empty=False, default=None): """First line in 'data', if any Args: text (str | list | None): Text to examine keep_empty (bool): When False skip empty lines (+ strip spaces/newlines), when True don't filter (strip newlines only) default (str | None): Default to r...
7090aca1d7e5e187d41ff0c39ec78a3866f4d3a1
633,262
def index_nest(nest, index): """Index a nested object, using a tuple of indices or keys in the case of dicts. Parameters ---------- nest The nested object to index. index A tuple of indices for indexing. """ ret = nest for i in index: ret = ret[i] return ret
e4dff364f86e83cf59fc1e5c3737c16b9b9e3319
633,263
import os import re def listChildDirs(jobDir): """Directories of child jobs for given job (not recursive). """ return [ os.path.join(jobDir, f) for f in os.listdir(jobDir) if re.match("t[0-9]+$", f) ]
ecb7585ecac992bc4182c0197d5ec3b0810100e8
633,264
import torch def to_categorical(y: torch.Tensor) -> torch.Tensor: """ Transform input tensor to categorical. :param y: input tensor. :return: Categorical tensor """ if y.min() < 0: y = torch.nn.Sigmoid()(y) if len(y.shape) == 2 and y.shape[1] > 1: # one hot encoding to cat...
627635a108554dd54af261991a20c4f6b0bc6df9
633,266
def bbox_flip(bboxes, img_shape): """Flip bboxes horizontally. :param bboxes: shape (..., 4*k) :type bboxes: ndarray :param img_shape:(height, width) :type img_shape: tuple :return: the bbox after flip :rtype: ndarray """ w = img_shape[1] flipped = bboxes.copy() flipped[...,...
abb7e4511763f0e1961f0f02555fd3c7965a0926
633,267
import inspect def get_method_docstring(cls, method_name): """ return method docstring if method docstring is empty we get docstring from parent @param method: @type method: @return: @rtype: """ method = getattr(cls, method_name, None) if method is None: return doc...
aa96b85b387c8ddd3befadd63faa8e3c2cea5817
633,269
def column_field(values, fields): """Returns a set of possible field names given column values.""" possible = set() for k in fields.keys(): if all([any([(l <= val <= h) for (l, h) in fields[k]]) for val in values]): possible.add(k) return possible
b97c3ae34fb5b9ac4fafa1cd1639d114f72e40a2
633,270
def pn_cli(module, switch=None, username=None, password=None, switch_local=None): """ Method to generate the cli portion to launch the Netvisor cli. :param module: The Ansible module to fetch username and password. :return: The cli string for further processing. """ cli = '' if username an...
97aadbb00af4493ceee78ef1d9ddc8793b833f37
633,271
import os def get_path(cmd, venv=None): """Return path to cmd.""" path = cmd if venv: path = os.path.join(venv, "bin", path) return path
1cfd8febab41d8bb2ae0f932cda59be732131a75
633,272
import numbers def is_integral(x): """Any integer value""" try: return isinstance(int(x), numbers.Integral) and \ not isinstance(x, bool) and int(x) > 0 except ValueError: return False
32f9f92ed06efeb10aec9c48fdf49b6d0c0ef192
633,273
def get_experience_count_by_technologies(db): """ data dict schema data = {'technology': {'experience_lvl': 'count'}} for each technology """ df = db.groupby(['Experience']).agg({'Tags': 'sum'}).reset_index() data = {} def _sum_experiences(exp, tags): for tag in tags: l...
6696f52b29e6542a2abd0356f9b500a3ffd7d031
633,274
def get_common_characters(character_counter, coverage=1.0): """ Get the most common characters of a language. Parameters ---------- character_counter : collections.Counter coverage : float, optional (default: 1.0) Take the most common characters that make up `coverage` of the dataset ...
c53fa456ff3b656173cc58b94dc76f983e65519a
633,275
def final_leaf_dict(leaf, left_right): """Generate a dictionary used in evaluating the policy tree. Parameters ---------- leaf : List. left_right : string. Returns ------- return_dic :dict. """ if leaf[5] is None or leaf[6] is None or leaf[7] is None or ( left_righ...
66d95b6a968568b6418f94eb00ed1803accca5aa
633,276
def replace(text, from_string, to_string): """Replace a string.""" return text.replace(from_string, to_string)
ffba99b78b05b4262d013244abae282d2e31e932
633,277
def numeric2bool(df, inplace=False): """ Convert columns with numerical dtypes to boolean """ if not inplace: df = df.copy() num_cols = df.select_dtypes(float).columns df.loc[:, num_cols] = df.loc[:, num_cols].astype(bool).astype(int) return df
5226127df4e86f9a3cf359311d287adb350da5a3
633,279
def stationary(t): """Probe is stationary at location h = 2, v = 0""" return 0.*t, 2/16 + 0*t, 0*t
984734db7045bbc49850b0b641882b8812bcbe18
633,280
from typing import Type from typing import Dict from typing import Any from typing import List from typing import Tuple def create_wrapped_env(env_cls: Type, env_kwargs: Dict[str, Any], wrappers: List[Tuple[Type, Dict[str, Any]]]): """Creates a wrapped environment.""" env = env_cls(**en...
c8200d191bcc09bcb402bca98230e640704f0705
633,281
def _fmt(x, pos): """Formatting for plot_heatmap function""" if x == 0: return '0' else: return format(x, '1.0e').replace("e-0", "e-")
22628e0f00e6c71b00747ca7716de35c34455a76
633,282
def private_gpg_key() -> str: """ gnupg_instance.export_keys(key.fingerprint, secret=True, expect_passphrase=False) """ return """-----BEGIN PGP PRIVATE KEY BLOCK----- lQOYBFzRgy8BCADbrsCtPWqVWTNkl3U1LK3YWLnKiZIIMELv305s6Lfj8lTtFlAT GXuIfalAqN18Rv6h+/aMXW872Gwk6Iv9hdkSF9e04YGqdrr7H/rw8976NogvhR73 aTi1...
d3fbee37f339927bda33f521654d967b2f3702f5
633,283
import requests import json def get_possible_category_keys(language='nl-NL', clientname="rolandisshopping"): """ Returns possible category keys you can use to filter results. Client name does not really matter, but you have to fill it in. Note that as I am located in the Netherlands all m...
db2905eda22244627676dba80402293bb5711c59
633,284
def options_string_builder(option_mapping, args): """Return arguments for CLI invocation of kal.""" options_string = "" for option, flag in option_mapping.items(): if option in args: options_string += str(" %s %s" % (flag, str(args[option]))) return options_string
331ef485e63f267796ceb85766241ba9d562e7b4
633,285
from typing import List from typing import Dict from typing import Tuple def simplify_experiments(experiments: List[Dict]) -> List[List[Tuple[str, ...]]]: """Converts a list of experiments into a list of lists of tuples, where each tuple represents a crossing in a given experiment. :param experiments: ...
daccc28faf2be25115ea18091ccbca5153b11a1f
633,286
def signature_parse(content: str, signature: str) -> bool: """Parses given text looking for the presence of a given signature. Returns ``True`` if the signature was found, ``False`` otherwise. :param content: str :param signature: str :return: bool """ if content.find(signature) != -1: ...
9b60fe034f5717813483a82a063086b95c5ffd89
633,287
import string def parse_a3m(filename): """Load a3m file to list of sequences Parameters: ----------- filename : str path to a3m file Returns: -------- seqs : list list of seqs in MSA """ seqs = [] table = str.maketrans(dict.fromkeys(string.ascii_lowercase)) ...
83521867a7ec244616c9e7aebb7900c3b1cf2025
633,290
import argparse def parse_arg(): """Creates a parser for command-line arguments. """ parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, default='stylegan', choices=['vanilla', 'stylegan']) parser.add_argument('--mode', type=str, default='draw', choices=['sample', 'project...
c10bcab14ff78110cc70d66948f8eb85b11a3d31
633,292
import torch def R_op(ys, xs, vs, retain_graph=True, detach=True): """ Multiplies the vector `vs` with the Jacobian of `ys` w.r.t. `xs`. """ if isinstance(ys, tuple): ws = [torch.zeros_like(y).requires_grad_(True) for y in ys] else: ws = torch.zeros_like(ys).requires_grad_(True) ...
9b098bbffffb8375653d26f9757e52f0781f1aac
633,293
import random def generate_id(): """Generate a unique identifier for the database""" return int(random.getrandbits(48))
4c1dec134adff3749f3cd9bbd3dd01cad3a68750
633,294
def in_fridge(fridge, wanted_food): """Checks if fridge has a food. Fridge has to be a dictionary populated outside of this function""" try: count = fridge[wanted_food] except KeyError: count = 0 return count
2d2657a92735f21d6fad3296b8fb5f49b3f69ed8
633,295
def plot_param(city,country,plot_parameter='main.temp'): """ placeholder function to put graphics generation code """ response = '' return response
50ec46c3d44804c68220957327814283bb488bc0
633,296
from typing import List def can_place_flowers(flowerbed: List[int], n: int) -> bool: """ :param flowerbed: :param n: :return: >>> can_place_flowers([1,0,0,0,1], 1) True >>> can_place_flowers([1,0,0,0,1], 2) False >>> can_place_flowers([0,0,1,0,0], 2) True >>> can_place_flow...
3bfb3adec8a7b8514d41ff445e91aefa9cef538f
633,297
def frequency_text(hz): """ return hz as readable text in Hz, kHz, MHz or GHz """ if hz < 1e3: return "%.3f Hz" % hz elif hz < 1e6: return "%.3f kHz" % (hz / 1e3) elif hz < 1e9: return "%.3f MHz" % (hz / 1e6) return "%.3f GHz" % (hz / 1e9)
8c1e1ba3e07e7bd720b7a55bff85d528043697b8
633,298
def ex_io_err(): """Input/output error response in bytes.""" return b"SPAMD/1.5 74 EX_IOERR\r\n\r\n"
7baa3aba3045c5b6fafd88bede804411fbf7b670
633,299
def readFile(fileName): """ Function to read files """ fp_read = open(fileName,'r') data = fp_read.readlines() fp_read.close() return data
887b78704ae4242ace5f13d099a0f9c414076cb1
633,300
from typing import Tuple def rebase_donate_argnums(donate_argnums, static_argnums) -> Tuple[int, ...]: """Shifts donate to account for static. >>> rebase_donate_argnums((3, 4), (0, 1)) (1, 2) Args: donate_argnums: An iterable of ints. static_argnums: An iterable of ints. Returns: A tuple of u...
414f6d883c57438bd055039a7883abee320977f7
633,301
def old_vertex_from_dummy(dummy: int, key: int, biggest) -> int: """Old vertex ID from the dummy vertex ID""" if dummy < 0: return -(dummy + (biggest + 1) * (key - 1) + 1) return dummy
13bbca37effd44e21ce2d8ba8c49b5569b2c3ad5
633,302
def interval_start(DateTime): """Return the default start of the recurrence interval.""" return DateTime(2014, 4, 1, 0)
db1bcafccebe0518a45a500b45db9fe43219472f
633,303
import socket def is_connected() -> bool: """Check if connected to Internet.""" try: # connect to the host -- tells us if the host is actually reachable sock = socket.create_connection(('connectivitycheck.gstatic.com', 80)) if sock is not None: sock.close() return T...
83528dd54d0aed7683dd7430f16ab21e86562cdb
633,304
import threading def new_thread(name=None): """Creates new thread decorator. Args: name (str): Thread name. Returns: function: New thread decorator. """ def decorator(f): """Decorator which calls function on a new thread. Args: f (fun...
16d8017326c32215729a59b05c1d29c994566e2e
633,305
def r_to_p(r, d, rtype='EI'): """ Inverse of the p_to_r function. Parameters ---------- r : float The RB error rate d : int Number of dimensions of the Hilbert space rtype : {'EI','AGI'}, optional The RB error rate rescaling convention. Returns ------- ...
fbb7411d367684fbfabda8f937d3dd4a53ae6b0f
633,307
import re import logging import os def find_apps(top, regex=r'(run|main)\.py'): """ Search for applications. """ if isinstance(regex, str): regex = re.compile(regex) found = [] logging.info('looking for apps...') for root, dirs, files in os.walk(top): for f in files: ...
a42455ed080e3b963625df588d3a25f62494cc0d
633,308
import random def successfulStarts(eventProb, numTrials): """Assumes eventProb is a float representing a probability of a single attempt being successful. numTrials a positive int Returns a list of the number of attempts needed before a success for each trial.""" triesBeforeSuccess = [] for t ...
486dc50d4f9ebf69902cee25d157b3e9a5fc5f0c
633,309
import torch def loss_disc(disc, x_real, x_fake): """Compute the discriminator loss for `x_real` and `x_fake` given `disc` Args: disc: The discriminator x_real (ndarray): An array of shape (N,) that contains the real samples x_fake (ndarray): An array of shape (N,) that contains the fake samples R...
b01afae2ae2de9bc22f2dd24e7bc7ea7dcf9a576
633,310
def cross(a, b, c): """[Returns the 2D cross product of AB and AC vectors, i.e., the z-component of the 3D cross product in a quadrant I Cartesian coordinate system (+x is right, +y is up). Returns a positive value if ABC is counter-clockwise, negative if clockwise, and zero if the points ar...
a71dbc067a18aed002d6c077d28d4ed9adfcf69a
633,311
def default_step_condition_factory(target_version, step_name): """Create a default condition used by upgrade steps. The created condition checks if the step was already successfully ran and skip it if it is the case. """ def default_step_condition(alembic, failed_migration, *args): if faile...
b4b7dece059d05df3650d5649f72760271b52c65
633,313
def _idempotent(method): """Return whether *method* is idempotent.""" return method in ('GET', 'HEAD', 'PUT')
f9940276f1ebf112a4d53e17c632eb4fffb09c4d
633,314
def get_topologyby_version(topology_id, version): # noqa: E501 """Find topology by version Returns a single topology # noqa: E501 :param topology_id: ID of topology to return :type topology_id: int :param version: version of topology to return :type version: int :rtype: Topology """ ...
a076fb49b89b0519945c57c943795081049d369b
633,315
def requireUser(funcRef): """ _requireUser_ Decorator method to enforce setting a user attribute for another object """ def wrapper(self, *args, **opts): if getattr(self, "owner", None) == None: msg = "Group Attribute not present/set" raise RuntimeError(msg) ...
eca5981f75e95c68ce569f51ef58d8a32821da62
633,317
import re def get_contents (fname): """ Return the contents of the given file. Strip comments (lines starting with ;) """ if type(fname) == list: contents = '\n'.join(fname) else: fp = open (fname, "r") contents = fp.read() fp.close() return re.sub(r...
1ec8cce0c8e4a719691b8c7f802eb3a9152e34cc
633,318
from pathlib import Path import subprocess def crush_a_png(_pin): """crush the png at _pin""" saved = 0 pout = Path(_pin.parent, 'temp.png') was = _pin.stat().st_size completed = subprocess.run(['pngcrush_1_8_11_w64.exe', '-brute', _pin.resolve(), pout.resolve() ], check=False) if completed: ...
92cfc350951e5157b3d64d5df58a45b992575696
633,319
def adjust_coordinates(start_position, end_position): """The purpose of this function is to determine whether the start position of a locus is greater than the end position of the locus. If so, this will return False. This function will be helpful for determining whether coordinates need to be swapped for extractin...
fd8ff84a5fa2d2c7885970c761f3c632859e7bb3
633,320
def isiter(x): """ Returns `True` if the given value implements an valid iterable interface. Arguments: x (mixed): value to check if it is an iterable. Returns: bool """ return hasattr(x, '__iter__') and not isinstance(x, (str, bytes))
6b2e5a6e4d676cf6c749fbac6f1e3ba64057f8e9
633,321
def Latentc(tempc): """Latent heat of condensation (vapourisation) INPUTS: tempc (C) OUTPUTS: L_w (J/kg) SOURCE: http://en.wikipedia.org/wiki/Latent_heat#Latent_heat_for_condensation_of_water """ return 1000 * (2500.8 - 2.36 * tempc + 0.0016 * tempc ** 2 - 0.00006 * tempc ** 3...
7e74ad7de405272cb385ddb085179890da9d0171
633,322
import os def resin_data_dir(tmpdir): """ Create a directory with correct filetree to be the equivalent of /data in a running container. """ data = os.path.join(tmpdir, 'data') os.makedirs(data, exist_ok=True) open(os.path.join(data, 'fingerprint'), 'w').write( "this better be moved") ...
b02cddfb231999f0c4a6c8a3c5167872c69af894
633,323
def image_proc_normalize( image ): """ Normalize image pixel component values to 0-1 range. """ output_image = [] for row in image: output_row = [] for pixel in row: if isinstance( pixel, float ) or isinstance( pixel, int ): output_row.append( pixel / 255 ...
a8270775b2f2e259a0aec5855e28df9030aec51e
633,324
import subprocess import shlex def _work(cmd): """Returns the result of the process run from Command. A worker function to parallelize the sample tests. Args: cmd (Command): The command to run. Returns: tuple: A tuple containing the return code of the process and the output ...
c2b3c628e6e0cf54e94ce3221f1791c26e8a5686
633,325
def generate_client_fixture(app_cls, base): """ :param app_cls: an app class :param base: a delcarative base :returns: a test client fixture """ def client(request, tmpdir): f = tmpdir.join('testing.sqlite3') uri = 'sqlite:///' + f.strpath app = app_cls(__name__, uri=uri...
a860105cc50430c239a45f2f615814e33b085526
633,326
def rollout(tree, s, depth): """Rollout from the current state s. Parameters ---------- tree : :py:class:`ast_toolbox.mcts.MCTSdpw.DPWTree` The seach tree. s : :py:class:`ast_toolbox.mcts.AdaptiveStressTesting.ASTState` The current state. depth : int The maximum search d...
546493c1b24b3e196d25e8087253578c8c1021bc
633,327
def config(): """Supply a stock DesyVerifier component configuration.""" return { "COMPONENT_NAME": "testing-desy_verifier", "DEST_SITE": "DESY", "DESY_CRED_PATH": "/path/to/my/gridftp/cert", "DESY_GSIFTP": "gsiftp://kVj74wBA1AMTDV8zccn67pGuWJqHZzD7iJQHrUJKA.com:2811/path/to/file...
112a421375f21493ddf063f1ff86cf4bfe3c9582
633,328
import urllib.request import shutil def download(url, file=None): """ Pass file as a filename, open file object, or None to return the request bytes Args: url (str): URL of file to download file (Union[str, io, None]): One of the following: - Filename of output file ...
92edc9b3a4e529bd7f2975c1491f7629da18f92f
633,329
import os import subprocess def docs(): """ Build the docs. """ cwd = os.getcwd() os.chdir("docs") try: return subprocess.run(["cmd", "/c", "make.bat", "html"]).returncode except Exception: return 1 finally: os.chdir(cwd)
026a0e725601d0c92fe479e98ec31a578ff11c74
633,330
import torch def compute_classification_logits(pooled_output, output_weights_cls, output_bias_cls): """Computes logits for each classification of the sequence. Args: pooled_output: <float>[batch_size, hidden_dim] Output of the pooler (BertPooler) on top of the encoder layer. Returns: logit...
e4822875aa58bc6c0a57ea4a0275e88b9fe9dc77
633,331
def _get_base_step(name: str): """Base image step for running bash commands. Return a busybox base step for running bash commands. Args: name {str}: step name Returns: Dict[Text, Any] """ return { 'image': 'busybox', 'name': name, 'script': '#!/bin/sh\n...
6ca005e3c46007ee2b4a3c852fa0c657990cb87c
633,332
def parse_vocabulary(vocab): """ Create a dictionary mapping integers to terms """ type_to_index = {} index_to_type = {} for word in set(x.strip() for x in vocab): index_to_type[len(index_to_type)] = word type_to_index[word] = len(type_to_index) return type_to_index, index_...
ea75b9dc7880875c9d9ae6683e7b868a8d658d76
633,333
def create_tools(): """Generate random result for tools.""" return ['tool00', 'tool01']
39c31201f00112106b9c72cd9923e36feaf6f4b6
633,334
def string_list_in_query_matcher(r1, r2, list_keys=None, filter_keys=None): """ For here_now requests: /v1/auth/grant/sub-key/my_sub_key?channel=ch1,ch2&timestamp=123 /v1/auth/grant/sub-key/my_sub_key?channel=ch2,ch1&timestamp=124 NOTICE: The :filter_query_parameters: cassette param should be spec...
bc399fab227f3053ddeed1f061e9f9519af52e24
633,335
def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')): """Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered i...
a6f59aacdd58c6cc30532a260e03e3d24ac9bae8
633,336
import json def safe_parse(raw_json): """ Input is a String Output is a JSON object if the tweet is valid and None if not valid """ #CODE HERE try: json_obj = json.loads(raw_json) except ValueError: return None if 'created_at' not in json_obj.keys(): return...
65aa8a26d7ef93019446dfb265fb05cb91090ce1
633,337
def tabulate(lines): """ Add a tab before each line in the list """ out = [] for line in lines: out.append(" {}".format(line)) return out
a730d79f69fffda6ef530bb7586357180935bf81
633,338
def start_session(self, request, force = False, set_cookie = True): """ Starts a new session for the provided request, by default the session is created even if a previous one already exists in the request. An optional set cookie flag may control if the cookie value should be returned to the cl...
58f941eaa5cd29d4b927bd7453dbebf69c52c412
633,339
def is_2nd_after_1st(event_stat_1, event_stat_2): """Returns true if 2nd event has a later minute / second as the first""" min_1 = event_stat_1.minute sec_1 = event_stat_1.second min_2 = event_stat_2.minute sec_2 = event_stat_2.second return min_1 * 60 + sec_1 < min_2 * 60 + sec_2
dd2004c70a7b7bbb6fd79e8c50dc2aeb8e467277
633,340
import yaml from typing import OrderedDict import re def setup_yaml_with_canonical_dict(): """ https://stackoverflow.com/a/8661021 """ yaml.add_representer( OrderedDict, lambda self, data: self.represent_mapping( "tag:yaml.org,2002:map", data.items() ), Dumper=yaml....
c33f0e0396f32dde5fc236549d1ff84fd29d718f
633,341
import requests def live_url_check(url): """ This function takes an URL and check whether it is live or not. If it is live return True and False otherwise. :param url: a Uniform Resource Locator(URL) of a website :return: True or False """ r = requests.head(url) # print(r.status_code) ...
aaf88cc8eb5b5f9b906e1886ff7e8377b0161b11
633,342
def getkey(d,key,default): """gets key from dict (d), if key does not exist, return default""" if key in d: return d[key] else: return default
950636120f1cfc0e2437802a5a50d1cea56af496
633,343