content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pathlib import Path import os import zipfile def main(args): """Main entry point""" args.archive = expand_path(args.archive) args.files = expand_path(args.files) def additions(search_path): """Generate a list of (lpath, arcname) for writing to zip-file""" aname = Path(args.arch...
f4ba59a73a3c0491829df87dad79ece7a6fcdfbc
3,657,200
import time def execution_duration(fun): """ Calculates the duration the function 'fun' takes to execute. execution_duration returns a wrapper function to which you pass your arguments. Example: execution_duration(my_function)(my_first_param, my_second_param) The result of the wrapper function w...
b824ce8e1448a65bd932ec8344b1976d2a86dd09
3,657,201
def return_origin_and_destination(): """Return origin and destination from session's waypoints key.""" waypoints = session['waypoints'] if len(waypoints) <= 1: return 'Please enter at least 2 destinations for your trip.' else: origin = session['waypoints'][0] destination = sess...
db8764fc32fe1367f303fa44b9c5c0c113a8c9ee
3,657,202
def attempt_move(piece): """ Attempts to make a move if the target coordinate is a legal move. Returns: True if the move is made, False otherwise """ x, y = pygame.mouse.get_pos() x = x // 100 y = y // 100 if (piece is not None) and (x, y) in piece.legal_moves: piece.move...
36c2b7764f6bb13765cf2eed7270f90f1cb338d1
3,657,203
def give(user_id, text, group): """construct a message to be sent that mentions a user, which is surprisingly complicated with GroupMe""" nickname = group.members().filter(user_id=user_id).first.nickname mention = attachments.Mentions([user_id], [[0, len(nickname)+1]]).as_dict() message = '@{}...
f9d36042b3ab5a2681fe065ac935321d8d398085
3,657,204
def integrate_audio_feat(features, audio_h5, mxm2msd): """ """ # TODO: this part should be moved to MFCC feature extraction # and stored in the feature file for better integrity n_coeffs = 40 audio_feat_cols = ( ['mean_mfcc{:d}'.format(i) for i in range(n_coeffs)] + ['var_m...
f346cf69a0a4b1aef0fc7dc7b7b603e02952ae6b
3,657,205
def make_annotation_loader_factory(): """Generate a factory function for constructing annotation loaders. Invoke the returned factory function by passing the name of the annotation loader class you want to construct, followed by the parameters for the constructor as named arguments (e.g., factory('...
70e6d9834a903a614a41510b6d97b62c3d1d5b3f
3,657,206
def test_arma(): """arma, check that rho is correct (appendix 10.A )and reproduce figure 10.2""" a,b, rho = arma_estimate(marple_data, 20, 20, 40) psd = arma2psd(A=a,B=b, rho=rho, NFFT=None) psd = arma2psd(A=a,B=b, rho=rho) try: psd = arma2psd(A=None, B=None, rho=rho) assert False ...
b1db09017fe060746ae1b503315bfaa6f3a44a58
3,657,207
from typing import Union def chunks_lists_to_tuples(level: Union[list, int, float]) -> Union[tuple, int, float]: """Convert a recursive list of lists of ints into a tuple of tuples of ints. This is a helper function needed because MongoDB automatically converts tuples to lists, but the dask constructor wa...
49cc7923211d50fdf6a386016af12b80a2f821df
3,657,208
def oid_pattern_specificity(pattern): # type: (str) -> Tuple[int, Tuple[int, ...]] """Return a measure of the specificity of an OID pattern. Suitable for use as a key function when sorting OID patterns. """ wildcard_key = -1 # Must be less than all digits, so that e.G. '1.*' is less specific than ...
7d1b4304791076fca42add7a8b9aeb31f85359f9
3,657,209
def extract_entities(text, json_={}): """ Extract entities from a given text using metamap and generate a json, preserving infro regarding the sentence of each entity that was found. For the time being, we preserve both concepts and the entities related to them Input: - text: str, ...
15f8b88e430c451a517f11b661aa1c57a93288fe
3,657,210
def gaul_as_df(gaul_path): """ Load the Gaussian list output by PyBDSF as a pd.DataFrame Args: gaul_path (`str`): Path to Gaussian list (.gaul file) """ gaul_df = pd.read_csv( gaul_path, skiprows=6, names=GAUL_COLUMNS, delim_whitespace=True, ) return gaul_df
806f8c386344c5380109705b053b89a82db62e66
3,657,211
def normalize_matrix(mat, dim=3, p=2): """Normalize matrix. Args: mat: matrix dim: dimension p: p value for norm Returns: normalized matrix """ mat_divided = F.normalize(mat, p=p, dim=dim) return mat_divided
35ac155a51818d2b93fc12a0c91ce35c0dfd9fe2
3,657,212
from typing import List import math def species_to_parameters(species_ids: List[str], sbml_model: 'libsbml.Model') -> List[str]: """ Turn a SBML species into parameters and replace species references inside the model instance. :param species_ids: List of SBML species...
a7cb9df992bad98584124320bc485aa978495050
3,657,213
import warnings def gaussian_filter_cv(array: np.ndarray, sigma) -> np.ndarray: """ Apply a Gaussian filter to a raster that may contain NaNs, using OpenCV's implementation. Arguments are for now hard-coded to be identical to scipy. N.B: kernel_size is set automatically based on sigma :param arr...
f39223111ff6624756491b37c32b7162ae8f3e5c
3,657,214
import inspect import functools def refresh_cache(f): """Decorator to update the instance_info_cache Requires context and instance as function args """ argspec = inspect.getargspec(f) @functools.wraps(f) def wrapper(self, context, *args, **kwargs): res = f(self, context, *args, **kwa...
6ca9449f1ae222052f89da9a8baa611b42b47fe4
3,657,215
import time import os import logging def get_timestamped_export_dir(export_dir_base): """Builds a path to a new subdirectory within the base directory. Each export is written into a new subdirectory named using the current time. This guarantees monotonically increasing version numbers even across multiple r...
f4848f97f6176aa990a8a40de42b92e2e74d46a3
3,657,216
import sys def calculate_density(temp, pressure): """Returns density in g/cm^3 """ if (temp < 161.40): raise ValueError("Solid phase!") if (temp < 289.7): VaporP_bar = pow(10, 4.0519 - 667.16 / temp) else: VaporP_bar = sys.float_info.max if (pressure < VaporP_bar): ...
e5222e4f552a9f4b82ea13be874985406e4a3b2f
3,657,217
def cross_validation(df, K, hyperparameters): """ Perform cross validation on a dataset. :param df: pandas.DataFrame :param K: int :param hyperparameters: dict """ train_indices = list(df.sample(frac=1).index) k_folds = np.array_split(train_indices, K) if K == 1: K = 2 ...
72cdf91efa029eb8c029eb84d596057d13a7c515
3,657,218
from typing import List from typing import Dict def solve_cities(cities: List, gdps: List, sick: List, total_capacity: int, value_r=0, weight_r=0, num_reads=1, verbose=False) -> Dict: """ Solves problem: "Which cities should I should I shut down in order to stay within healthcare resource...
52bef06069ee6975fbc5dea50cbb44349c96b9db
3,657,219
def catalog(): """Render the mapping catalog page.""" if request.args.get(EQUIVALENT_TO): mappings = current_app.manager.get_mappings_by_type(EQUIVALENT_TO) message = Markup("<h4>You are now visualizing the catalog of equivalent mappings</h4>") flash(message) elif request.args.get(I...
b28904fff79b978225eda1bb3ed4f6e04c817737
3,657,220
import logging def detect_counterexample(algorithm, test_epsilon, default_kwargs={}, event_search_space=None, databases=None, event_iterations=100000, detect_iterations=500000, cores=0, loglevel=logging.INFO): """ :param algorithm: ...
4a4fecd74743895abd9bc1c6ab617736758d5c64
3,657,221
def apply_inverse_rot_to_vec(rot, vec): """Multiply the inverse of a rotation matrix by a vector.""" # Inverse rotation is just transpose return [rot[0][0] * vec[0] + rot[1][0] * vec[1] + rot[2][0] * vec[2], rot[0][1] * vec[0] + rot[1][1] * vec[1] + rot[2][1] * vec[2], rot[0][2] * ve...
1108ac6caa30b3562a2af1bcc83e1c1a1bfd8d4d
3,657,222
def gsl_blas_dsdot(*args, **kwargs): """gsl_blas_dsdot(gsl_vector_float const * X, gsl_vector_float const * Y) -> int""" return _gslwrap.gsl_blas_dsdot(*args, **kwargs)
6b8f45a773fca936913b2653df9ab8c96f1e974a
3,657,223
def cost(weights): """Cost function which tends to zero when A |x> tends to |b>.""" p_global_ground = global_ground(weights) p_ancilla_ground = ancilla_ground(weights) p_cond = p_global_ground / p_ancilla_ground return 1 - p_cond
3b33292c63b42d110efe0d7cbe4dae85f095472f
3,657,224
import time def runOptimization( cfg, optimize_cfg, n_iter=20, split_runs=1, model_runs=1, filename="optimize_result", ): """Optimize the model parameter using hyperopt. The model parameters are optimized using the evaluations on validation dataset. Args: cfg(di...
ef2e2c85f5b0b8f6889da49ed1e964d432bb1886
3,657,225
def _capabilities_for_entity(config, entity): """Return an _EntityCapabilities appropriate for given entity. raises _UnknownEntityDomainError if the given domain is unsupported. """ if entity.domain not in _CAPABILITIES_FOR_DOMAIN: raise _UnknownEntityDomainError() return _CAPABILITIES_FOR_...
5fe541778ede415020377a0c989fa47ad2ae4d05
3,657,226
import os import click def check_missing_files(client): """Find missing files listed in datasets.""" missing = defaultdict(list) for path, dataset in client.datasets.items(): for file in dataset.files: filepath = (path.parent / file) if not filepath.exists(): ...
f3a167e72871ef05baa217a7d10dfe4be113da21
3,657,227
def apply_torsion(nodes, suffix=""): """ Torsion energy in nodes. """ if ( "phases%s" % suffix in nodes.data and "periodicity%s" % suffix in nodes.data ): return { "u%s" % suffix: esp.mm.torsion.periodic_torsion( x=nodes.data["x"], ...
37310291ddb769587d9d14a8dedcda3b528a78f3
3,657,228
import decimal def parse_summary_table(doc): """ Parse the etree doc for summarytable, returns:: [{'channel': unicode, 'impressions': int, 'clicks': int, 'ctr': decimal.Decimal, 'ecpm': decimal.Decimal, 'earnings': decimal.Decimal}] """ for t...
7d188478dc5539b4c8020af09cb052140def63c9
3,657,229
import math def tileset_info(hitile_path): """ Get the tileset info for a hitile file. Parameters ---------- hitile_path: string The path to the hitile file Returns ------- tileset_info: {'min_pos': [], 'max_pos': [], 'tile_size': 1024,...
3ea467898e15ac6aca21c219398aa1249b795e55
3,657,230
def delete_user(): """ Deletes the current user's account. """ DB.session.delete(current_user) DB.session.commit() flash("Account deleted", 'success') return redirect('/login')
bc22d6287738c676cec3c780a9fb01513ddd5530
3,657,231
def setup_code_gen(no_of_accessories): """ Generate setup code """ try: invalid_setup_codes = ['00000000','11111111','22222222','33333333','44444444','55555555',\ '66666666','77777777','88888888','99999999','12345678','87654321'] setup_code_created = [] ...
253272cc27de1ead05d12f2e1798d91a3c4571dd
3,657,232
def letter_difference(letter_1: str, letter_2: str) -> int: """ Return the difference in value between letter_1 and letter_2 """ assert len(letter_1) == 1 assert len(letter_2) == 1 diff = letter_to_value[letter_2] - letter_to_value[letter_1] if diff > 13: diff -= 27 return diff
66d88efff92acebef06275d244d560ca5071e974
3,657,233
import requests def refresh_access_token(request): """Updates `accessToken` in request cookies (not in browser cookies) using `refreshToken`. """ try: refresh_token = request.COOKIES['refreshToken'] url = urljoin(settings.TIT_API_HOST, '/api/auth/token/refresh/') response = requests....
378f4129fa9cc6af8cc961560e3e4063fcd0495b
3,657,234
def ngrams(string, n=3, punctuation=PUNCTUATION, **kwargs): """ Returns a list of n-grams (tuples of n successive words) from the given string. Punctuation marks are stripped from words. """ s = string s = s.replace(".", " .") s = s.replace("?", " ?") s = s.replace("!", " !") s = [w....
1e0e99f01c8aa46f4c44cca02d9bdb2b1c52d4c5
3,657,235
def binstringToBitList(binstring): """Converts a string of '0's and '1's to a list of 0's and 1's""" bitList = [] for bit in binstring: bitList.append(int(bit)) return bitList
d8ff10651d9fc2d02aba3b4a57a0a768032783b7
3,657,236
def file_revisions(request, repo_id): """List file revisions in file version history page. """ repo = get_repo(repo_id) if not repo: raise Http404 # perm check if check_folder_permission(request, repo_id, '/') is None: raise Http404 return render_file_revisions(request, rep...
c9ec0e1c159a4efdd8f4c3287cb9d8339ba9a9d2
3,657,237
def textctrl_info_t_get_tabsize(*args): """ textctrl_info_t_get_tabsize(self) -> unsigned int """ return _ida_kernwin.textctrl_info_t_get_tabsize(*args)
7aff89906aebacb3664a73d26f52dd4317031790
3,657,238
def node_is_hidden(node_name): """ Returns whether or not given node is hidden :param node_name: str :return: bool """ if python.is_string(node_name): return not maya.cmds.getAttr('{}.visibility'.format(node_name)) return not maya.cmds.getAttr('{}.visibility'.format(node.get_name(n...
0927d2424b64b9b81b52ced335823963d7ec9fe2
3,657,239
import torch def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor, PS: int = 32) -> torch.Tensor: """Helper function for affine grid generation. Args: img: image tensor of shape :math:`(B, CH, H, W)`. LAF: laf with shape :math:`(B, N, 2, 3)`. PS: patch size...
288572e4ff8577a8bd664732c79408b71ec58c0d
3,657,240
from typing import Union from typing import Tuple def _resolve_condition_operands( left_operand: Union[str, pipeline_channel.PipelineChannel], right_operand: Union[str, pipeline_channel.PipelineChannel], ) -> Tuple[str, str]: """Resolves values and PipelineChannels for condition operands. Args: ...
fde07e14af8f9ae610cfcd64e6a3f2219f0ee8e9
3,657,241
import json import os import random import base64 import zlib def format_record(test_record): """Create a properly formatted Kinesis, S3, or SNS record. Supports a dictionary or string based data record. Reads in event templates from the test/integration/templates folder. Args: test_record:...
719d398353c50ec2fdb48db933b0322027f744c1
3,657,242
def int_to_bitstr(int_value: int) -> str: """ A function which returns its bit representation as a string. Arguments: int_value (int) - The int value we want to get the bit representation for. Return: str - The string representation of the bits required to form the int. """ ...
cafbf151ce0404081a0a8e1327d85e61ea7ddc52
3,657,243
def target_reached(effect): """target amount has been reached (100% or more)""" if not effect.instance.target: return False return effect.instance.amount_raised >= effect.instance.target
0101cd9c3c51a1e03ba7cfd8844c3821a156e2fe
3,657,244
def resid_mask(ints, wfs_map=read_map(wfs_file), act_map=read_map(act_file), num_aps=236): """ Returns the locations of the valid actuators in the actuator array resids: Nx349 residual wavefront array (microns) ints: Nx304 intensity array (any units) N: Number of timestamps """ # Check input...
98c818db8d2d5040c5a20857693f3f3116ab8e13
3,657,245
import requests def session(): """Sets up a HTTP session with a retry policy.""" s = requests.Session() retries = Retry(total=5, backoff_factor=0.5) s.mount("http://", HTTPAdapter(max_retries=retries)) return s
d5cb89f04017718983834a0b4008972f393f56ae
3,657,246
def fit(df, methodtype='hc', scoretype='bic', black_list=None, white_list=None, bw_list_method='enforce', max_indegree=None, epsilon=1e-4, max_iter=1e6, verbose=3): """Structure learning fit model. Description ----------- Search strategies for structure learning The search space of DAGs is super-ex...
865dd11638a8e9444818678b3e8d83f90647ce9b
3,657,247
def handle_index(): """ Kezeli az index oldalat, elokesziti es visszakulti a html-t a kliensnek. :return: """ return render_template("index.html")
eaaa2c3028983c1e5ed29a45fe6ff3db0a8a7482
3,657,248
def get_polynomial_coefficients(degree=5): """ Return a list with coefficient names, [1 x y x^2 xy y^2 x^3 ...] """ names = ["1"] for exp in range(1, degree + 1): # 0, ..., degree for x_exp in range(exp, -1, -1): y_exp = exp - x_exp if x_exp == 0: ...
9369841215045e925a3453b83be9dc49c9be7b92
3,657,249
from typing import Dict import pickle def _get_configured_credentials() -> Dict[str, bytes]: """ Get the encryupted credentials stored in disk """ path = get_credentials_path() credentials: Dict[str, bytes] with open(path, "rb") as file_handle: credentials = pickle.load(file_handle) ...
824aeb18f4e5bed609008c6594d86666502b2339
3,657,250
def open(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Create a temporary project from a single source. This view allows for all users, including anonymous users, to create a temporary project which they can later save as a permanent project if they wish. It aims to be a quick way to ...
f9c98eb829ec8d46b889c04308c4ea59fc2c4eb6
3,657,251
def kabsch_rotate(P, Q): """ Rotate matrix P unto matrix Q using Kabsch algorithm """ U = kabsch(P, Q) # Rotate P P = np.dot(P, U) return P
2be9c94901b27205ec4720b16ab6e81f34b1c6d6
3,657,252
def matrix( odoo=ODOO_VERSIONS, pg=PG_VERSIONS, odoo_skip=frozenset(), pg_skip=frozenset() ): """All possible combinations. We compute the variable matrix here instead of in ``.travis.yml`` because this generates faster builds, given the scripts found in ``hooks`` directory are already multi-versio...
034e791d2e10e9f691df3e6c458722549c59a89a
3,657,253
import copy def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank va...
bc51bd946d8fc617222303ffe30507695ee5ae33
3,657,254
def user_enabled(inst, opt): """ Check whether the option is enabled. :param inst: instance from content object init :param url: Option to be checked :return: True if enabled, False if disabled or non present """ return opt in inst.settings and inst.settings[opt]
3b2a5a1534ff779178eb4bd6b839b66c0b07864f
3,657,255
async def get_buttons_data(client: Client, message: Message): """ Get callback_data and urls of all the inline buttons of the message you replied to. """ reply_message = message.reply_to_message if reply_message and reply_message.reply_markup: if reply_message.reply_markup.inline_keyboard: ...
6567455d95781515fc6236bf867a042ba550736f
3,657,256
def update_document( *, db_session: Session = Depends(get_db), document_id: PrimaryKey, document_in: DocumentUpdate ): """Update a document.""" document = get(db_session=db_session, document_id=document_id) if not document: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, ...
15dc23aeb10950da19a6732c43d7675447f6a45c
3,657,257
def from_jabsorb(request, seems_raw=False): """ Transforms a jabsorb request into a more Python data model (converts maps and lists) :param request: Data coming from Jabsorb :param seems_raw: Set it to True if the given data seems to already have been parsed (no Java class hin...
78e8eefc0b234a5b6cd09cebff76e5cb716b54c2
3,657,258
def write_board_to_svg_file(board, file_name, hex_edge=50, hex_offset=0, board_padding=None, pointy_top=True, trim_board=True, style=None): """ Writes given board to a svg file of given name. :param board: 2 dimensional list of fields, each represented as a number :param fil...
4cbf895a4a91e0434e31fdad459c3354927c5e2b
3,657,259
def ensure_conf(app): """ Ensure for the given app the the redbeat_conf attribute is set to an instance of the RedBeatConfig class. """ name = 'redbeat_conf' app = app_or_default(app) try: config = getattr(app, name) except AttributeError: config = RedBeatConfig(app) ...
673680aafbc4d76b1ae7f7740e53fd7f54740acf
3,657,260
def check_if_process_present(string_to_find): """Checks if process runs on machine Parameters: string_to_find (string): process we want to find Returns: found (bool): True if found process running """ output = check_output(["ps", "-ax"], universal_newlines=True) if string_to_find in ...
3a153e2160000ec1c9d4c0c28d1631179f9e88c3
3,657,261
def consulta_dicionario(nivel): """ Entrada: Parâmetro do nível selecionado (fácil, médio, difícil) Tarefa: Determinar qual dicionário a ser consultado Saída: Parâmetros do dicionário (texto, lacunas, gabarito) """ nivel_dicionario = nivel if nivel_dicionario == 'facil': texto = dici...
1453298f791cca010f75abad9d0d37a28c1c8ae5
3,657,262
from typing import List def stats_check( main_table: Table, compare_table: Table, checks: List[OutlierCheck] = [], max_rows_returned: int = 100, ): """ :param main_table: main table :type main_table: table object :param compare_table: table to be compared :type compare_table: table...
39f0c0b2bad74a7878453a3fe11def36f1971a5f
3,657,263
async def get_collectible_name(collectible_id: int, db: AsyncSession = Depends(get_db_session)): """Gets the collectible name""" result = await destiny_items.get_collectible(db=db, collectible_id=collectible_id) return NameModel(name=result.name) if result else NameModel(name=None)
18fd3856d5145a004cf20343b5e8782a13a35845
3,657,264
def prime_factors(n): """ Return a list of prime factors of n :param n: int :return: list """ # check if 2 is the largest prime all_factors = set() t = n while t % 2 == 0: t /= 2 all_factors.add(2) # check the divisors greater than 2 d = 3 while d < n ** ...
09aad44a7b04492c225447eaa15590fa630a43cd
3,657,265
def calculate_central_age(Ns, Ni, zeta, seZeta, rhod, Nd, sigma=0.15): """Function to calculate central age.""" Ns = np.array(Ns) Ni = np.array(Ni) # We just replace 0 counts with a low value, the age will be rounded to # 2 decimals. That should take care of the zero count issue. Ns = np.wher...
29b360ce1df7cfa376a86b989fb7899137d110cc
3,657,266
import requests def _get_cross_reference_token(auth_cookie: str) -> str: """Gets a new cross reference token affiliated with the Roblox auth cookie. :param auth_cookie: Your Roblox authentication cookie. :return: A fresh cross reference token. """ session: requests.Session = _get_session(auth_co...
63041ddeb31ccdc0a72a721d000968588580e816
3,657,267
def erase_not_displayed(client): """Erase all non-displayed models from memory. Args: client (obj): creopyson Client. Returns: None """ return client._creoson_post("file", "erase_not_displayed")
c3981fcce00b5d5440fcbdbe8781e9e6229a8fa7
3,657,268
def reset_position_for_friends_image_details_from_voter(voter, twitter_profile_image_url_https, facebook_profile_image_url_https): """ Reset all position image urls in PositionForFriends from we vote image details :param voter: :param twitter_profi...
e2483bf781029a7481dead0a168775b1a9223978
3,657,269
def get_analysis(panda_data): """ Get Analysis of CSV Data :param panda_data: Panda dataframes :return: panda data frames """ # Create Object for Analysis0 sentiment_object = SentimentConfig.sentiment_object ner_object = SentimentConfig.ner_object # Get list of sentences list =...
014bc1543f67dfe561bce62d9b5e5f974b28db2a
3,657,270
def create_coordinate_string_dict(): """31パターンのヒモ。""" w = 120 h = 120 return { 47: (0, 0), 57: (1*-w, 0), 58: (2*-w, 0), 16: (4*-w, 0), 35: (5*-w, 0), 36: (6*-w, 0), 38: (0, 1*-h), 13: (1*-w, 1*-h), 14: (2*-w, 1*-h), 15: (3*...
4abc2b246345569780db2dc9f6ef71c56ae86528
3,657,271
def all_but_ast(check): """Only passes AST to check.""" def _check_wrapper(contents, ast, **kwargs): """Wrap check and passes the AST to it.""" del contents del kwargs return check(ast) return _check_wrapper
71f3e3b8649a3a9885ded7eec248894cca8083c4
3,657,272
import readline def get_history_items(): """ Get all history item """ return [ readline.get_history_item(i) for i in xrange(1, readline.get_current_history_length() + 1) ]
b3600ca6581c11a46c2ea92d82b9d5aefcded49b
3,657,273
from typing import List from pathlib import Path from typing import Tuple def generate_nucmer_commands( filenames: List[Path], outdir: Path = Path("."), nucmer_exe: Path = pyani_config.NUCMER_DEFAULT, filter_exe: Path = pyani_config.FILTER_DEFAULT, maxmatch: bool = False, ) -> Tuple[List, List]: ...
28923f86762d73fcdd0a4f9681da09b6ab8368cb
3,657,274
def normalize(*args): """Scale a sequence of occurrences into probabilities that sum up to 1.""" total = sum(args) return [arg / total for arg in args]
49b0f998fe58b2c85da5a993e542d91bb5dd5382
3,657,275
import os def get_CZI_zstack(filename,frame,channel,filepath=None,img_info=None): """ Obtains a single z-stack from a 3D imaging time-series for a specified time and channel. Parameters ---------- filename : str Name of the file from which to retrieve the z-stack. frame : ...
dbbfaf7f9cc50c99cd025236dff2480be2ac6017
3,657,276
import requests def _make_request( resource: str, from_currency_code: str, to_currency_code: str, timestamp: int, access_token: str, exchange_code: str, num_records: int, api_version: str ) -> requests.Response: """ API documentation for cryp...
4da7c3cab42b742b106fafb4c1585e6ecb250121
3,657,277
def dependencies_order_of_build(target_contract, dependencies_map): """ Return an ordered list of contracts that is sufficient to sucessfully deploys the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph. """ if len(dependencies_map) == 0: ...
e5a67247aad8b37c29e274eac80f28414f59427f
3,657,278
def projective_error_function(params, args): """ :param params: :param args: :return: """ # fx fy cx cy k0 k1 project_params = params[0:5] f, cx, cy, k0, k1 = project_params K = eye(3, 3) K[0,0] = f K[1,1] = f K[0, 2] = k0 K[1, 2] = k1 ...
5b1fe8265478a379d91178474e392797798c9c0f
3,657,279
import warnings def _transform_masks(y, transform, data_format=None, **kwargs): """Based on the transform key, apply a transform function to the masks. Refer to :mod:`deepcell.utils.transform_utils` for more information about available transforms. Caution for unknown transform keys. Args: y ...
278615037d78b35cacb641eca89918010cf9b2fd
3,657,280
import os def root_dir(): """ Returns root director for this project """ return os.path.dirname(os.path.realpath(__file__ + '/..'))
c9346df7838dd0a528613a7069c55d910373fe86
3,657,281
import os import json def query_subgraph(seeds, genes_top, output_path): # pylint: disable=too-many-locals """ This function queries the data, writes the resulting subgraph and returns a dictionary containing the number of nodes and edges. seeds: list genes_top: dict whose keys are genes and valu...
eace2fb32ec6488e3ad096f9570e3eefe97d042a
3,657,282
def get_cur_version(): """ Get current apk version string """ pkg_name = cur_activity.getPackageName() return str( cur_activity.getPackageManager().getPackageInfo( pkg_name, 0).versionName)
015d3368238edc10344c633d9cc491c79569f5f6
3,657,283
def checkpointload(checkpointfile): """Loads an hyperoptimizer checkpoint from file Returns a list of tuples (params, loss) referring to previous hyperoptimization trials """ try: with open(checkpointfile, "rb") as f: return pkl.load(f) except (FileNotFoundError, EOFError): ...
906df00fcb209c979fd57c49a426f4c752b45753
3,657,284
from time import time from array import array import hmac import base64 import os def encrypt_password(password, key): """ Encrypts the password using the given key. Args: password (str): password to be encrypted key (str): key to be used to encrypt the password """ h_hash = get...
c267cfbd59f1859f999602f19c85af8eba47421b
3,657,285
import os def prepare_test_data(datapath): """ Wrapper function to load the test dataset """ print("Loading and encoding the test dataset") depth_test = np.array(pd.read_csv(os.path.join(datapath,'test_depth.txt'),sep="\t", header = None)) depth_test = depth_test.reshape(depth_test.shape[0],depth_tes...
e34eb64d2297b5cd8194af292abfb022722d0885
3,657,286
def get_case_color_marker(case): """Get color and marker based on case.""" black_o = ("#000000", "o") teal_D = ("#469990", "D") orange_s = ("#de9f16", "s") purple_v = ("#802f99", "v") bs = case["batch_size"] sub = case["subsampling"] mc = case["mc_samples"] if sub is None and mc =...
4a42fc784b9034e3996753bc6da18fbfebc66b16
3,657,287
def clean_integer_score(x): """Converts x from potentially a float or string into a clean integer, and replace NA and NP values with one string character""" try: x = str(int(float(x))) except Exception as exc: if isinstance(x, basestring): pass else: raise ...
9ff2c911653421d51738bdb1bf8f381d3aa59820
3,657,288
def do_stuff2(): """This is not right.""" (first, second) = 1, 2, 3 return first + second
dbb6f503e73cc0365dfa20fca54bebb174fcdadd
3,657,289
def rule_block_distributor(rule_param, src_cortical_area, dst_cortical_area, src_neuron_id, z_offset): """ This rule helps to take a set of unique inputs from one cortical area and develop synaptic projections that can lead to a comprehensive set of unique connections that covers all the combinations of the...
b9201bfce68dc22b47bd20fc687b20f78ef1a08e
3,657,290
def get_extra(item_container): """ liefert die erste passende image_url """ if item_container.item.extra != '': return get_extra_data(item_container) item_container = item_container.get_parent() while item_container.item.app.name == 'dmsEduFolder': if item_container.item.extra != '': return get_ex...
c9ac2ad65d05d13deaad8a6031f2f9ee8ab8aee4
3,657,291
import torch def pt_accuracy(output, target, topk=(1,)): """Compute the accuracy over the k top predictions for the specified values of k.""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() c...
5c0ddcd57163987b00e09a6677ddc41928810874
3,657,292
from typing import Counter def compute_phasing_counts(variant_to_read_names_dict): """ Parameters ---------- variants_to_read_names : dict Dictionary mapping varcode.Variant to set of read names Returns ------- Dictionary from variant to Counter(Variant) """ read_names_to...
ba13a6d6c76e018cb1072e9fba635aad5593437b
3,657,293
def _inputs_and_vae(hparams): """Constructs a VAE.""" obs_encoder = codec.MLPObsEncoder(hparams) obs_decoder = codec.MLPObsDecoder( hparams, codec.BernoulliDecoder(squeeze_input=True), param_size=1) inputs = context_mod.EncodeObserved(obs_encoder) vae = vae_mod.make(hparams, ...
0e6af8a7d17312f99435426907a0dca062981225
3,657,294
def read_grid_hdf5(filepath, name): """Read a grid from HDF5 file. Parameters ---------- filepath : string or pathlib.Path object Path of the HDF5 file. name : string Name of the grid. Returns ------- x : numpy.ndarray The x-coordinates along a gridline in the x...
f9ad79da36cfa24028562cdaeefba8ca9b48e572
3,657,295
def string_to_version(verstring): """ Return a tuple of (epoch, version, release) from a version string This function replaces rpmUtils.miscutils.stringToVersion, see https://bugzilla.redhat.com/1364504 """ # is there an epoch? components = verstring.split(':') if len(components) > 1: ...
4dca34ce0f30e66eff6dad784cd684fb39b665ee
3,657,296
import xml def cff2provn(filename): """Parse cml xml file and return a prov bundle object""" #filename = "/Users/fariba/Desktop/UCI/freesurfer/scripts/meta-MC-SCA-023_tp1.cml" tree = xml.dom.minidom.parse(filename) collections = tree.documentElement g = prov.ProvBundle() g.add_namespace(xsd) ...
c8e44bd627173a17d45eadcc5ab73062c4e27ff6
3,657,297
def optional(idx, *args): """A converter for functions having optional arguments. The index to the last non-optional parameter is specified and a list of types for optional arguments follows. """ return lambda ctx, typespecs: _optional_imp(ctx, typespecs[idx], args)
e5491588090beaf4730f18c1b54193104a8f62be
3,657,298
def calc_plot_ROC(y1, y2): """ Take two distributions and plot the ROC curve if you used the difference in those distributions as a binary classifier. :param y1: :param y2: :return: """ y_score = np.concatenate([y1, y2]) y_true = np.concatenate([np.zeros(len(y1)), np.ones(len(y2))])...
428aa54ebe92ff1df6df4ebcae800a0b692f09d5
3,657,299