content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def clean_string_dots(str_to_clean=None): """ this function try to clean a string like "Media. . . . . . . . . . . " it will eliminate all the dots and blanck spaces :param str_to_clean: <string> :return: <string> """ if str_to_clean is None: raise("Error, We need a string") ...
6d64bc10a26af5cbd11ccfcbfb3cbd7b2775f6be
37,300
def delete_multiple( request ): """ Delete multiple posts. Variables required in the POST request: - api_key : User identifier. - id[] : A list with the posts identifiers. """ posts = _get_post_list( request ) if isinstance( posts, HttpResponse ): ret...
d7fe7f973b3809285382f6489b64933cc264b889
37,301
import os def current_umask() -> int: """Get the current umask which involves having to set it temporarily.""" mask = os.umask(0) os.umask(mask) return mask
8d24ace1eba3746cb4f38f91c127075c0bce6aaf
37,302
from .model_store import get_model_file import os def get_seresnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join('~', '.keras', 'models'), **kwargs): """ C...
aebe8cf811501c79b82f5da90d2376663ffd302a
37,303
def plot_round(logs): """ Plot round growth """ dfs = {k : v.round for k,v in logs.items() if not v.round.empty} # fig,ax = figure_with_legend() plt.title("Round vs T") plt.grid() plt.xlabel("Time") plt.ylabel("Round") for k,v in dfs.items(): plt.plot(v['at'], v['R'],...
df1aa45cf7e208dbc0ad07f04f4a9b93b1c915c4
37,304
def r_example(y0=None, ymax=None, xi=0.01): """https://rdrr.io/rforge/bvpSolve/f/inst/doc/bvpTests.pdf""" L = np.eye(1, 2) R = np.eye(1, 2) y0 = np.array([1.0]) if y0 is None else y0 ymax = np.array([1.5]) if ymax is None else ymax t0 = 0.0 tmax = 1.0 return BoundaryValueProblem( ...
b725f2a76b2291ed7a6f3fd1ec87a98253434bcf
37,305
def get_languages() -> dict[str, str]: """ This method is used to get all the languages available for translation with googletrans :return: dict of languages """ return LANGUAGES
3a1ff4c00edaaac350dd2a8317ad3460df788a24
37,306
import pickle def train(sound_dir, noise_dir=None, neural_network=None, n_files=None, val_split=0.15, ext='mp4', **train_kwargs): """ Train model using a simpler pipeline that is mostly automated for the user. The user simply has to point to the directory with pure sound videos and directory ...
bf4cc7db313f3f75f4cf461d30dcddc79ccdbd70
37,307
from typing import List from typing import Tuple def get_random(building_list: List[str]) -> Tuple[str, str]: """ Get 2 random element from the given list. Parameters ---------- building_list: List[str] A list containing all the remaining building that haven't been pla...
b91b6560f68e33a6d59abd0ed8af7514f36128d6
37,308
import os import multiprocessing def build_basetools(cmd=''): """build the C-Lang executable binaries in BaseTools.""" if cmd[:2] == ['build', 'clean']: return 0 home_dir = os.environ['EDK_TOOLS_PATH'] cmds = [UDKBUILD_MAKETOOL] if UDKBUILD_MAKETOOL == 'make': cmds += [ ...
7b0468bc96ab34fdbc0eb076912a0d9313bb4b1d
37,309
from typing import Union from typing import List from typing import Optional from typing import Dict from typing import Tuple import shlex import os import subprocess import fcntl import errno import time def cmd_gather(cmd: Union[str, List], set_env: Optional[Dict[str, str]] = None, realtime=False, strip=False, log_...
aa55fcda6bc1d73f87ce35234a38f75ecadc7f90
37,310
import torch def perturb_explanation(image='images/flute.jpg', arch='alexnet', layer='input', perturbation='blur', perturbation_dimension='spatial', interpolate=False, num_pe...
af83b06516bd18ceccb1ecccd9f48ef358ca7f40
37,311
import collections def average_over_transforms(func, geometric_transforms, state): """Average a function over transformations to achive rotation invariance.""" result_list = collections.defaultdict(list) for transform in geometric_transforms: output = transform.inverse(func(transform.forward(state))) f...
4f1a6ec9f660bcc6470ac7afe41bf45f1b7b6a8f
37,312
from typing import Dict def translate_reweight_dict(reweight_dict: Dict) -> Dict: """ Checks a dict assigning desired weight changes in the matrix and if needed translates the exterrnal db xrefs to internal db ids :param reweight_dict: dict of instructions to re-assign weights :return: reweigt_di...
1c529eae386a7f873b0f524fc02e4d1253b2aec8
37,313
import json def encode_json(struct): """Encode a structure as JSON bytes.""" return bytes(json.dumps(struct), "utf-8")
6724c0a687a98230a32fef81b3a4447c12d164fc
37,314
def categories_to_errors_dict(): """Categories to error dictionary function maps common error substrings to categories. The categories are keys in the dictionary and the values are arrays of strings or arrays of list. Some error categories, such as User Errors, has many subcategories. Thus, ...
4b59fc9775d3d5d808ecedee7756dad5d302848a
37,315
def extract_comments(filename, mime=None): """Extracts and returns the comments from the given source file. Args: filename: String name of the file to extract comments from. mime: Optional MIME type for file (str). Note some MIME types accepted don't comply with RFC2045. If not give...
d0f2de5b4935b5fad6b525d5e6bd83efe453d073
37,316
def cov(arr : np.ndarray): """Compute the sample covariance matrix for a matrix arr, assumed to be given in (samples x features) form for data fitting applications. Parameters ---------- arr : np.ndarray matrix in (samples x features) form """ n, _ = arr.shape return...
9727922a984d4e27b4de0f92d9ec94328231a34b
37,317
def is_rdn_equal(rdn1, rdn2): """Returns True if and only if the RDNs are equal. * RDNs must have the same number of AVAs. * Each AVA of the RDNs must be the equal for the same attribute type. The order isn't significant. Note that an attribute type will only be in one AVA in an RDN, otherwise ...
8f2710aa33f251020841b0f86b2f2f61cbf64cc6
37,318
from dataset.cub import CUBTasks, CUBDataset from dataset.inat import iNat2018Dataset import os def cub_inat2018(root, config): """This meta-task is the concatenation of CUB-200 (first 25 tasks) and iNat (last 207 tasks). - The first 10 tasks are classification of the animal species inside one of 10 orders o...
a539947c181ece38e64d87a4ca7e2c99513f1ad2
37,319
import os def load_wlist(datadir_path:str): """Given the path of the directory containing the simulation files, load the kernel-integrals file aka "w_list.txt" and return a dataframe""" print("finished loading kernel-integrals file.") return pd.read_csv(os.path.join(datadir_path,"w_list.txt"), header...
b05d7e881f561e02f6f13b43d96fa4be28386cb6
37,320
def EMetaclass(cls): """Class decorator for creating PyEcore metaclass.""" superclass = cls.__bases__ if not issubclass(cls, EObject): sclasslist = list(superclass) if object in superclass: index = sclasslist.index(object) sclasslist.insert(index, EObject) ...
7e84de2daa4b8bc08843e63295aa540de0a907d6
37,321
def _first_defined(*args): """Return the first non-null argument (PRIVATE).""" for arg in args: if arg is not None: return arg return None
0e0fc10e5ef14d9b445dae5b5dbb5ce467e1cb1b
37,322
import os import yaml def get_token(yamlName = "token.yaml"): """ 从token.yaml读取token值 :param yamlName: 配置文件名称 :return: token值 """ path = os.path.join(current_path, yamlName) file = open(path) text_read = file.read() t = yaml.load(text_read) file.close() return t
0c35d536ea54f82084d5fd2141df73e1ce1119f1
37,323
import re def rhyme_analyser(str, rhyme_db): """ Rhyme Analyzer - Print out the rhyme scheme of a poem. Given: A string - like If you want to smell a rose You must put it to your nose. If you want to eat some bread You must not eat it in bed Or I will eat your toes. Output: Rhyme s...
0fb166c92b2e60d1739638b23a3de5dae18ce26b
37,324
def show_log() -> list: """ Отоброжает содержимое log_tab. :return: список кортежей со всеми данными из таблицы. """ try: with DatabaseConnection(app.config['log_db_config']) as cursor: _SQL = """SELECT * FROM log_tab ORDER BY ts DESC LIMIT 1000;""" cursor.execute(...
1d47b4adf178656a7c63ff23a91337a6eb6ed171
37,325
def gate_neighbours(current, grid, path): """ Generate a heatmap for gates so that A star can avoid gates. This consists of all direct neighbours, diagonal neighbours, and every coordinate straight above the gate in question """ neighbours = list() # Generate all other coordinates around the ...
a3055ee81756c147a44335b219da194471b4fe4c
37,326
import os import configparser def check_dust_database() -> str: """ Function to check if the dust data is present in the database and add the data if needed. Returns ------- str The database path from the configuration file. """ config_file = os.path.join(os.getcwd(), "specie...
3ac065fa61d37b33a556b3541d8c89b3490fa899
37,327
import logging def _NeedANewAnalysis(normalized_test, original_test, flake_key, bug_id=None, allow_new_analysis=False, force=False, user_email='', triggering_source...
8f2e9927aaf5f6d86d5c84ca4b26adfb38a12a67
37,328
def is_chosen(bbox, area_threshold=None) -> bool: """ Calculate area of bounding boxes and return True if area >= threshold Args: bbox: (x1, y1, width, heigh) area_threshold: Returns: True/False """ are = bbox[2] * bbox[3] if area_threshold is not None: if ...
091fda7a389a74e92703c6eeca05aec413bc65a5
37,329
import pymess def pymess_dae2_cnt_riccati(mmat=None, amat=None, jmat=None, bmat=None, wmat=None, z0=None, mtxoldb=None, transposed=False, aditol=5e-10, nwtn_res2_tol=5e-8, maxit=20, verbose=False, linesearch=False, **kw): """ solv...
7de34ce6106ba5c0cb1f13e2ad9c2f79327ce829
37,330
def is_unary_operator(oper): """returns True, if operator is unary operator, otherwise False""" # definition: # memeber in class # ret-type operator symbol() # ret-type operator [++ --](int) # globally # ret-type operator symbol( arg ) # ret-type operator [++ --](X&, int) symbols = [...
fa563cb7bc24462779ddcb0a61dbf6f93903a1d8
37,331
def map_advanced_param(param, value): """ Maps an advanced parameter value to the value expected on the krdict website. """ return _get_advanced_param(_ADVANCED_PARAM_MAP[param], str(value), True)
39d174e897ecde71d6185db815caa2c272e292ea
37,332
def basin_to_gridcell_dict(df_reference): """Generate a dictionary of gridcell id to basin id {grid_id: basin_id} :param df_reference: Input data reference dataframe containing grid to basin info :type df_reference: dataframe :return: dict. {grid_id: basin...
730823f7c2f1da2bbf5a114c5b270ab741dfdb24
37,333
def fitness_coeff_constant(N_site,N_state,h_0,J_0): """ creating the mutational fitness coefficients for the simulated sequences in the case of constant fields and constant couplings Parameters: N_site: int sequence length N_state: int number of states per site ...
811c248de631d91c8bafd0617f05f7b02a07289c
37,334
def add_to_user_path(new_path: str, ): """ Add **one** path into PATH of current user """ assert ';' not in new_path old_fixed_paths = get_user_path() for p in old_fixed_paths: if is_same_file(p, new_path): return old_paths = get_user_path() return set_user_path([new_...
51dec120301296847dbfbc4da17f20581dfa6c2b
37,335
def generate_1d_scatter(data, variables, class_data=None, class_names=None, nrows=None, ncols=None, sharex=False, sharey=False, show_legend=True, outliers=False, cmap_class=None, **kwargs): """Generate 1D scatter plots from the given data and v...
9b09b2fbc92bd888b060cd7d3b751783030bc8f7
37,336
def methods_context(interface, component_info): """Creates a list of Jinja template contexts for methods of an interface. Args: interface: An interface to create contexts for component_info: A dict containing component wide information Returns: A dictionary with 3 keys: 'it...
dd73f89558aa58bb76a4c1327f45b8a8522a27a4
37,337
def create_translator_instance(): """Create IBM Translator Instance.""" authenticator = IAMAuthenticator(apikey) language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator ) language_translator.set_service_url(url) return language_translator
0e6124be33d8a783937a09980b25bcdfe09e3c2b
37,338
def shot(**kwargs): """ Adds a shot entity under the shots table in the `wgid` database. Args: kwargs(dict): Reference alfred configs Returns: True if successful """ key = "shot" cmd = _create_from_config(key) cmd += _create_entity(key, **kwargs) # Submit SQL ...
747cb2623a3ea197ea1f6b1a96d5104d26cfbe23
37,339
def symmAndRefl(t, ipt=False): """ Return the transducer t | t.inverse, if ipt is True; return the transducer t | t.inverse | id, otherwise :type t: SFT :type ipt: bool :rtype: SFT""" t1 = t | t.inverse() if ipt is True: return t1 t2 = SFT() s0 = t2.addState() ...
81f088bd27aa25a6d8104912ace56306873aa8ac
37,340
import logging def show( document: vp.Document, classic: bool, force: bool, show_pen_up: bool, show_points: bool, outline: bool, colorful: bool, show_axes: bool, show_grid: bool, hide_legend: bool, unit: str, ): """Display the geometry in an graphical user interface. ...
a0e1e1819c5ed3e1d73bdaa427afefe1ca8e4300
37,341
def _float(value): """Return env var cast as float.""" return float(value)
254b1e3a542c5a74153cd58d3f43e86dab964028
37,342
import copy import warnings from datetime import datetime def correctMSdataset(data, window=11, method='LOWESS', align='median', parallelise=True, excludeFailures=True): """ Conduct run-order correction and batch alignment on the :py:class:`~nPYc.objects.MSDataset` instance *data*, returning a new instance with cor...
b7f7cd1ffc8c01520b8a0231f83db5cbdf7f35b6
37,343
def create_assignment_registry(): """Create the registry for course properties.""" reg = FieldRegistry( base.OfflineAssignmentBase.NAME, description=base.OfflineAssignmentBase.DESCRIPTION) # Course level settings. reg.add_property(SchemaField( 'key', 'ID', 'string', editable=Fa...
f26fd224133c059e734029cfd8add042ac16b718
37,344
def do_s3_media_url(parser, token, static=False): """ This is for use with ``CloudFrontURLs`` and will return the appropriate url if a match is found. Usage:: {% s3_media_url path %} For ``HTTPS``, the ``cuddlybuddly.storage.s3.middleware.ThreadLocals`` middleware must also be used. ...
db8d740a7c3b8406694a53494c9835c3986d2536
37,345
def wavlm(refresh=False, *args, **kwargs): """ The default model - Base-Plus refresh (bool): whether to download ckpt/config again if existed """ return wavlm_base_plus(refresh=refresh, *args, **kwargs)
371ccdf7f955142b2f8343d59998323fbe4f02e9
37,346
def add_area_from_serialized_data( annotation_model, area_id, serialized_area_data, lv0_height ): """Add point annotation data to annotation model from serialized_data""" serialized_area_data = AreaAnnotationSerializedData( *serialized_area_data ) flag, area_record = create_area_annotati...
2d03640a7674e0a7e5af5cf6a05ea77424c05f97
37,347
def select_largest_3prime_footprint(transcripts): """Select transcript(s) with largest 3' footprint""" ret = [transcripts[0]] furthest = transcripts[0].utr3_end for i in range(1, len(transcripts)): t = transcripts[i] utr3footprint = t.utr3_end if utr3footprint == furthest: ...
35a437351a886c00c431b2adf61fad42118e94f8
37,348
def read_mutation_matrix(file_in): """Create a table from a mutation matrix provided by SNPad Returns ------- tbl : Pandas.table A table containing the mutation probability for base at each position of a read. sn : list of dict The list contains the highest probability for which we ...
28a397d25ce6afb2d9b06534c2e8780a44253508
37,349
def ctc_cost(acts, labels, input_lengths = None): """ Given sequences of output layer activations and labels, compute the softmax output at each timestep, and then compute the CTC cost of each sequence with respect to its corresponding label sequence. :param acts: Tensor of pre-softmax activations, with shape=...
e12183a91ab146e123be58e82ad54c9284db67d5
37,350
import torch def center_size(boxes): """ Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data. Args: boxes: (tensor) point_form boxes Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. """ wh = boxes[:, 2...
8e2cc32aa59aeae2e8ef7ffd9489420b94a105a2
37,351
def train_network(data, supervisor): """ This function abstracts out the learning process for the Fuzzy ARTMAP algorithm. :param data: The data of the training set :param supervisor: The supervisor data, to train against :return: new_network, the trained ARTMAP network utilised in classification and...
29d71e51590c8407c994db067cd25f8ee16422a4
37,352
def add(user_obj): """Add a User""" user_obj.set_password() return crud.add(user_obj)
433e8fe8ecc44e66008a403ba26a666de6870b60
37,353
def perspective_transform(img): """ This class takes in the Gradient and Color Space thresholded binary image, and perspective transforms the Binary image to halp make view the lanes to be viewed from the top (as like in Bird's eye view). We take 4 source points that are assumed to form a Quadrilat...
b6c18fff72d403b13ec8dd392237b88102ebf0d7
37,354
def numericise(value, empty_value=''): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input string, empty or not, ...
4faff17b9434cfa9c57556c335b8fbf2463842ea
37,355
def test_likelihood_value(): """Just a sanity check to show we get the right likelihood values""" config = test_conf_reparam(events_per_day=1) conv_config = deepcopy(BASE_CONV_CONFIG) # initialize the old likelihood first # this is an input for the reparameterized likelihood lf_old = UnbinnedLog...
b6f2d369846a5eb36760e9bffbe660d4747be590
37,356
import os def auto_delete_files(sender, instance, **kwargs): """ Delete task's file from system after delete. """ try: task_file = instance.file except Task.DoesNotExist: return False if task_file: if os.path.isfile(task_file.path): os.remove(task_file.pa...
fa66ef4121c5f42e9be01ce874e5f2c9113e9857
37,357
def show_booking_page(): """Show booking page.""" return render_template('booking.html') # will need another route to process the booking form
930726776fb226e9d066e89e21e96d32bd1aeb43
37,358
def axis(*v, **kwargs): """ Convenience method to get or set axis properties. Calling with no arguments:: >>> axis() returns the current axes limits ``[xmin, xmax, ymin, ymax]``.:: >>> axis(v) sets the min and max of the x and y axes, with ``v = [xmin, xmax, ymin, ymax]``.:: ...
7b28f933be0d60a708ae9fe7fc817dcbe92a86d0
37,359
def split_data(data, num_folds, fold): """ Partitions and returns selected partition :param data: data :param num_folds: num folds to make :param fold: selected fold :return: data_fold, data_rest """ X = data['X'] t = data['t'] xJoinT = np.c_[X, t] rows = np.size(xJoinT, 0) ...
f79094ca5065c79e11514fbb912c8ce30df685d8
37,360
import typing import requests def buy( symbol: str, quantity: int, duration: str = "gtc", order_type: str = "market", price: typing.Any = None, stop: typing.Any = None, brokerage: typing.Any = USER_BROKERAGE, access_token: str = USER_ACCESS_TOKEN, ...
e04fe21778634af8c24a83a1e694a976c2ac96cf
37,361
def get_provider_info(provider_name): """Get provider info matching given provider name""" return PROVIDERS_INFO.get(provider_name)
6f95c632ad8842777390751a1bc5f7cf5a62b4e0
37,362
def manage_sell(request): """ manage page """ #TODO judge whether the user is the super user return RTR('manage_sell.html', {})
ae7394c6bd6b26c8e4f6281efe18db722297b2aa
37,363
def close_ticket(session, ticket_id, return_type=None, **kwargs): """ Closes a support ticket for the VPSA. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type ticket_id: int :param ticket_id: The support ticket 'id' value as return...
79f5f2dba8ab993ddfa3fecb110a205cb3ded066
37,364
import re def verify_mpls_ping( device, address=None, mask=None, expected_max_success_rate=100, expected_min_success_rate=0,count=None, source=None, vc_id=None, tunnel_id=None, vrf=None, max_time=60, check_interval=10,): """Verify ping Args: device ('obj'): Device object ...
3efc533d5c97caf577c32efd5cc784816a1b9949
37,365
def get_module_mappings(label, attrs, srcs = [], workspace_name = None, mappings_attr = "es6_module_mappings"): """Returns the module_mappings from the given attrs. Collects a {module_name - module_root} hash from all transitive dependencies, checking for collisions. If a module has a non-empty `module_roo...
2decc2a4e94303c6719db4d6f18df5c4eac0bb5b
37,366
def cryoscope_v2_processing( time_ns: np.array, osc_data: np.array, pnts_per_fit_first_pass: int = 4, pnts_per_fit_second_pass: int = 3, init_guess_first_pass: dict = {}, fixed_params_first_pass: dict = {}, init_guess_second_pass: dict = {}, max_params: dict = {}, min_params: dict = ...
8540da6a1458c84a88bbde6a58aceaaea883444e
37,367
import logging import os def map_reads(reads, genome_index, out_dir, annotation='', multimax=10, mismatches=2, threads=1): """ Map FASTQ file reads to reference genome. TODO Parameters ---------- reads : str Sequencing reads to map to genome. genome_index : str Folder wit...
8227d36896c228a876c88e9aa8fbc8cc9eb6d701
37,368
def getCurrentSettingsAsDict(): """ Returns the current babylon parameters saved in the root node as a dict \nout: dictionary key: pymxs user property string value: var """ sceneRoot = sceneUtils.getSceneRootNode() newDict = dict() for val in BabylonPYMXS.babylonParame...
aeb36e9a4cc456c5ff46eb0503db14de423ddf49
37,369
def isjsonclass(class_: type) -> bool: """Check if a class is jsonclass. Args: class_ (type): The class to check. Returns: bool: True if it's a jsonclass, otherwise False. """ return hasattr(class_, '__is_jsonclass__')
3234cf62beb03aa968888dd8ec3b65f4c5f4cab3
37,370
import math def mu_from_pdiv(pdiv, nobj=3): """ Get population count based on divisions per objective for NSGA-III """ h = int(math.factorial(nobj + pdiv - 1) / (math.factorial(pdiv) * math.factorial(nobj - 1))) mu = int(h + (4 - h % 4)) return mu
b4087bcab34a0fe03c6a1d5c9e2d9fb1f47d79f0
37,371
def on_reload_plugins(branch='master'): """ `[branch]` - reload plugins in debot """ resp = [] try: git_plugins_manager = current_app.extensions['git_plugins_manager'] except KeyError: pass else: resp.append(git_plugins_manager.reload(branch)) dispatcher = current...
17b521b3812a3c5130e7595df63389d4abac9fdb
37,372
import copy def _get_model_cfg(fname): """Grab configs necessary to create a model. These are deep copied to allow for safe modification of parameters without influencing other tests. """ config = _get_config_module(fname) model = copy.deepcopy(config.model) return model
9f64d51e20a60c61388b2488dbfa9c640c103d84
37,373
def make_inference_request(serving_name, data, verb=":predict"): """ Submit an inference request Example use-case: >>> from hops import serving >>> serving.make_inference_request("irisFlowerClassifier", [[1,2,3,4]], ":predict") Args: :serving_name: name of the model being served ...
ee59fb0949390c91ee53200447b290f87fa0742a
37,374
import tqdm def online_variance(paths): """ Calculate mean and variance in an online way (Welford's algorithm) :param paths: :return: """ mean = np.zeros((conf.img_h, conf.img_w, conf.dest_channels)) M2 = np.zeros((conf.img_h, conf.img_w, conf.dest_channels)) i = 0 for i, path in ...
67b09232c0518ea60b6f2fbfe439f2bd607b9c02
37,375
def check_requires(request): """ This call checks whether a certain value requires another input to be filled. """ values = map(int, request.POST.getlist('value[]')) model = apps.get_model(request.POST.get('app'), request.POST.get('model')) required_values = model.objects.filter(**{ requ...
cca52b6d7b02d9deb05e3f72aa5dd3186e404f5d
37,376
def room2blocks(data, label, num_point, block_size=100.0, stride=50.0, random_sample=False, sample_num=None, use_all_points=False): """ Prepare block training data. Args: data (array-like): N x F numpy array, where N is t...
45e6f63107f5aff757a6722164a2e43e0b6dc31e
37,377
def triggerBackup(locationKey, config, tokenData, args): """ Make a API request to start a backup. Returns True on success and False on failure """ if config["locations"][locationKey]["enabled"] is False: if args.verbose: print "INFO: Skipping disabled location %s" % locatio...
e105d2ac3af4644525ac91ba78f7be4d462c9547
37,378
def start(name): """ Start running a recipe. :param name: The recipe name. Must be one of the items returned by /list :return: object response One of: ok error message Only present if response is "error" and there is a ...
34615ec7e2b8832f2458275116c423adf5b344ad
37,379
def get_conversion_factor(old_units, new_units): """ Use the conversion factors table to figure out the factor between these two units. Parameters ---------- old_units: Unit object The current units. new_units : Unit object The units we want. Returns ------- con...
6805f113054ea87664c4eaef5299420f552d4e1d
37,380
def ate_exploitability(dist, payoff_tensor, p=1, aggregate=np.mean): """Compute Tsallis regularized exploitability of dist for non-symmetric game. Args: dist: list of 1-d np.arrays, current estimate of nash distribution payoff_tensor: (n x A1 x ... x An) np.array, payoffs for each joint action assume...
a7b119c3f38c3bcacc075abbc1457a6cb57058eb
37,381
def angular_cl_cov_SSC(cosmo, cltracer1, cltracer2, ell, tkka, sigma2_B=None, fsky=1., cltracer3=None, cltracer4=None, ell2=None, integration_method='qag_quad'): """Calculate the super-sample contribution to the connected non-Gaussian covarian...
1abac47d2414ba7fd297fc829285285749e811e4
37,382
def locals_in_putty(): """Hard-coded information regarding local variables """ locals_d = { # k: index # v: dict of local properties 0x14007DA84: { 6: {'name': 'v6', 'size': 8, 'type_name': '__int64'}, 7: {'name': 'v7', 'size': 8, 'type_name': '__int64'}, ...
52398e84aa324f8f751e2ca50bee9ad33be6eeb5
37,383
def _post_apply_columns( pydf: "PyDataFrame", columns: ColumnsType, ) -> "PyDataFrame": """ Apply 'columns' param _after_ PyDataFrame creation (if no alternative). """ pydf_columns, pydf_dtypes = pydf.columns(), pydf.dtypes() columns, dtypes = _unpack_columns(columns or pydf_columns) if ...
7373b774b5e76da1b8820feff4ccc7d37e6a572f
37,384
import torch def join_blocks(splitted, final_shape): """Join blocks to reobtain a splitted image Attribute: splitted (tensor) = image splitted in blocks, size = (N_blocks, Channels, Height, Width) final_shape (tuple) = size of the final image reconstructed (Height, Width) Return: ...
e6cf7382011e7f1ce0463f949e227e677cd0e8f2
37,385
def log_agg_function_alpha(alpha, cent1, cent2): """ Allows additional scaling of log_agg_function with a parameter alpha to roughly get retain factors for BA use retain factor 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 alpha 1.7, 1.0, 0.7, 0.5, 0.4, 0.26, 0.2, 0.1, 0.015 """ return np.cli...
e488468838987bc95ea12789e6abd4b7fe499843
37,386
from typing import Type from re import T def from_yaml(c: Type[T], s: str, de=YamlDeserializer, **opts) -> T: """ Take yaml string and return deserialized object.. >>> from dataclasses import dataclass >>> from serde import deserialize >>> >>> @deserialize ... @dataclass ... class Set...
5eb24a55ec63dbe01e4efa8c536c84e120b875f2
37,387
from ..interfaces.nibabel import Binarize def init_n4_only_wf( atropos_model=None, atropos_refine=True, atropos_use_random_seed=True, bids_suffix="T1w", mem_gb=3.0, name="n4_only_wf", omp_nthreads=None, ): """ Build a workflow to sidetrack brain extraction on skull-stripped dataset...
d8708f3d1d4c93dafd901bbf89704c6677473657
37,388
def dvi( redchan, nirchan ): """ DVI: Difference Vegetation Index dvi( redchan, nirchan ) """ redchan = 1.0*redchan nirchan = 1.0*nirchan result = ( nirchan - redchan ) return result
afa5ffffccc3053598cd3597de1efd3dcfc4cd8f
37,389
def needs_min_max_values(mode, buckets): """ Returns True, if an encoding mode needs minimum and maximum column values, otherwise False """ return not buckets and mode in ['one-hot', 'one-hot-gaussian', 'one-hot-gaussian-fluent', ...
50ae2b899e5957347061dd59905290506c460093
37,390
def _rolling_player_f(player, gfcf, **kwargs): """ Creates a graph with CF% or GF% (on plus off). Use gfcf to indicate which one. :param player: str or int, player to generate for :param gfcf: str. Use 'G' for GF% and GF% Off and 'C' for CF% and CF% Off :param kwargs: other filters. See scrapenhl2....
6d3ef2716f5d72c7599c6fd68fdb0d09ce7a148f
37,391
def param(myval=None): """Parameterised decorator example""" if myval: print(f"Param: {myval}") def decorator(func): # real decorator decorated["param"].append(func) name = func.__name__ @wraps(func) def wrapparam(*argv): # inner to return arg_str = ",...
9b709bb0fca9d8efbbcd489161c39dcfc9c84dbc
37,392
import os def asset_spec_from_abspath(abspath, package): """ Try to convert an absolute path to a resource in a package to a resource specification if possible; otherwise return the absolute path. """ if getattr(package, '__name__', None) == '__main__': return abspath pp = package_path(pa...
7c05e88ac4eb9171c96756690db607bbf0788566
37,393
def listed_list(list_list): """Return presentable string from given list """ return '{} and {}'.format(', '.join(list_list[:-1]), list_list[-1]) if ( len(list_list) > 1) else list_list[0]
da35296196fff56816fe7b0427985ee278238dab
37,394
import re def remove_plus_signs(_s: str) -> str: """Removes plus signs from string""" return re.sub(pattern=r'\+', repl=r'', string=_s)
53cf3117221ce82578a20d75e7eb807c2d41b8fc
37,395
def has_more_than_two_occurence(x): """creating a function for finding words with more than 2 occurences""" if(x[1]>1): return(x)
6e39c6cf4b473480786add14e76112c122ce439f
37,396
def compute_gas_flux(gas_coords, star_data, times, params, bins, fig_name, plot_flag=True): """Calculate the flux contribution from each point particle. Assumptions: light travel time from stars to gas plus the recombination time is shorter than the time it takes the stars to move ...
1f643946723f60b366795c44242796aeceeb984b
37,397
def evaluate(predictions, answerss): """ Returns a tuple of (F1 score, EM score, sentence score) The sentence score is our evaluation method for determining the effectiveness of finding the correct sentence within the context paragraph that may contain the answer. This metric is much softer than the F1 or...
f5edd23faf0a46cfd1407285b8d7d38d8b2b955c
37,398
from typing import Any from typing import Union from typing import List def style( text: Any, *, fg: Union[str, fg] = '', bg: Union[str, bg] = '', bold: bool = False, dim: bool = False, underline: bool = False ) -> str: """ Apply ANSI colors and/or styles to a string and return it....
bf1ad5b0d88f74a2496d4ad7e4951e4b89414916
37,399