content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def xmlout(fasta, genome): """Parses variables from supplied tuples? dictionaries?""" global path # Extract the variables from the passed variables gene = fasta.split('/')[-1] # split file from path, could use os.path.split genename = gene.split('.')[0] genomename = os.path.basename...
dd8e0836a1d0d85d43b7052bd201d7ef3f6b56cf
47,300
def clamp(x, lower, upper): """ Naive Clamping in [2] A [[ x ]]_b = min(max(u,b_lower),b_upper) :param x: :param lower: :param upper: :return: """ # Not None assert x.shape == lower.shape assert x.shape == upper.shape assert (lower.array <= upper.array).all(), " lower is larg...
a50bb4ce270422cad194ed66a0c77f2c498af68f
47,301
import math import time def main(lr=None, log_path_end='', bs=None, train_epoch=None, lambda_list=None, random_mirror=False, random_scale=False, model_weight=None): """Create the model and start the training.""" tf.reset_default_graph() args = get_arguments() """ Get configurations here....
3dd4e9f97a850fe871a64500b8eb407bf36c0cec
47,302
from typing import Dict from typing import List import collections def make_category_to_builders_dict() -> Dict[ str, List[tfds.core.DatasetBuilder] ]: """Loads all builders with their associated category.""" datasets = _all_tfds_datasets() print(f'Creating the vanilla builders for {len(datasets)} datasets....
50a1aa7c4584f151daa5be2ef58f5c288b84c733
47,303
def trajnet_sample_eval(pred, gt): """Calculate ADE, FDE, Pred_Col, GT_Col for one sample. pred = Num_ped x Num_timesteps x 2 gt = Num_ped x Num_timesteps x 2 """ return ade(pred, gt), fde(pred, gt), pred_col(pred, gt), gt_col(pred, gt)
9e4c02d7d39955ee127e400118cb367d900dae36
47,304
def bbox_hflip(bboxes, img_width): """horizontal flip the bboxes ^ ............. . . . . . . . . . . . . ............. ^ Args: bbox (ndarray): bbox ndarray [box_nums, 4] flip_code (int, optional): [description]. Defaults...
00e45f69a517ccb15623afb813fc05ad1c7c7eee
47,305
import argparse def create_arg_parser(): """" Creates and returns the ArgumentParser object. """ parser = argparse.ArgumentParser(description='Parses git log output object for change-log generation.') parser.add_argument('-b', '--branch', default='dev', help='current git bran...
167bcf54b079583b10e4ef72ff2c1a6e82ded6bc
47,306
def _pathjoin(a, b): """ POSIX-like path join for Globus Transfer paths As with _normpath above, this is meant to behave correctly even on Windows systems """ if not b: # given "" as a file path return a elif b.startswith("/"): # a path starting with / is absolute return b ...
20079d97be4e07499a9b0dfa80458a7e151826c3
47,307
import os import re def extract_kernel_version(deb_package): """ Read filename for linux-image Debian package and return only the kernel version it would install, e.g. "4.4.4-grsec". """ # Convert to basename in case the filter call was not prefixed with '|basename'. deb_package = os.path.bas...
34fd3e33611dc2d2e89cebaa08017fbae18ec496
47,308
def is_current_user_admin(request): """Checks whether the current user is an admin.""" user = get_current_user(request) if user: return user.is_superuser else: return False
3b25bf2d5640b6d52d58aad8e3a57efe3bae9f17
47,309
def _load_fidel_to_opt_parameters(param): """ Loads fidel_to_opt parameters. """ if isinstance(param, (list, tuple)): ret = [] for elem in param: ret.append(_load_fidel_to_opt_parameters(elem)) else: ret = param # just return the param if isinstance(param, unicode): ret = unicode_to_st...
22d8358ba599e5f7161a29bf60bd6ece07314b3f
47,310
def get_sans(names): """ :param SubjectAltNames names: :rtype: dict[str, bool] """ sans = dict() if names.dns_allowed is not None: sans[RPA.TPP_DNS_ALLOWED] = names.dns_allowed if names.ip_allowed is not None: sans[RPA.TPP_IP_ALLOWED] = names.ip_allowed if names.email_all...
625b10531b9ca03005242ffd3d6c74198084eff3
47,311
def get_observed_I_and_R(country: str, is_country: bool = True): """ Gets the data for the number of confirmed cases and the number of recovered. :param country: The country or province for which to get the cases :param is_country: Whether the country variable is for a country or for a province :re...
bb2b632b77cfc8646754920573f25cb144d0265b
47,312
def ClearChannelRequestHeader(sid, cid): """ Construct a ``MessageHeader`` for a ClearChannelRequest command. Clears a channel. This command will cause server to release the associated channel resources and no longer accept any requests for this SID/CID. Parameters ---------- sid : ...
fbd80892006211dd82e0e3313f9e0cb9ee0fe889
47,313
def refine_pic_group_msg(ctx: GroupMsg) -> _PicGroupMsg: """群图片/表情包消息""" if not isinstance(ctx, GroupMsg): raise ContextTypeError('Expected `GroupMsg`, but got `%s`' % ctx.__class__) if ctx.MsgType == MsgTypes.PicMsg: return _PicGroupMsg(ctx) return None
d8529e461bc9af7292bc899db183a8bb1812c44d
47,314
def crunch_samples(standards, standards_exclude, timestamps_standard, signal_standard, peaks_idx_standard, peaks_area_standards, samples_filename=None, samples_directory='samples', ...
987c968d97855d66b41e1172968f094179a8e075
47,315
def str_static_gen(size): """Returns an encoded static string of length 'size'.""" msg = '\n' msg += '__________Hello_World__________' while (len(msg)) < (size): msg += num_to_char(len(msg) % 16) msg = (msg[:size]) if len(msg) > size else msg return msg.encode('ascii', 'replace')
cf5d3fb8211802e0e05dff299861b0d9e328d763
47,316
def rank(M,pref=None): """ Rank solutions: - By Pareto front subpopulation - Distance to ideal vector """ distance = dist(M,pref=np.abs(pref)) fr, fix = fronts(M) strata = np.zeros(shape=len(distance),dtype=int) for i in np.arange(0,len(fix)): for j in fix[i]: ...
b171fa8bbd7db0cb08d0116d93af6785f999ec85
47,317
from typing import Tuple def calculate_temperature_factor( temperature_active: float, power_ratio: float, ) -> Tuple[float, float]: """Calculate the temperature factor (piT). :param temperature_active: the ambient operating temperature of the resistor in C. :param power_ratio: the ratio o...
3eefcf31978d0f20ecfab8c485e05b6a318cb574
47,318
def probability(vector, x, t): """ Finds the probability of vector[x] in t occurnences If x is not in vector then the probability is .001/t @param {Vector} vector {int} x {float} t @return {float} """ t = t*1.0 return vector[x] / t or 0.001 / t
bb6c731a157104a653669730be0569f555402167
47,319
def create_testing_eeg_data(): """Create testing data with HFO and a spike.""" freqs = [2.5, 6.0, 10.0, 16.0, 32.5, 67.5, 165.0, 250.0, 425.0, 500.0, 800.0, 1500.0] random_state = 0 fs = 5000 n = fs * 10 data = np.zeros(n) hfo_samps = [] # basic_amp = 10 x = np.arange(n...
bfa9cc9c5ba510c637c3215d02c05e035c54a0e7
47,320
def getNodeDictVlans(nodesInfo, hostname, switchName): """Get Node dictionary.""" if not nodesInfo: return None, {} for _, nodeDict in list(nodesInfo['nodes'].items()): if nodeDict['hostname'] == hostname: for intf, intfDict in list(nodeDict['NetInfo'].items()): p...
1113f0eb1829c9e84791ed151ce05c7165168b10
47,321
from rasterio._io import windows_intersect def intersect(*windows): """Test if windows intersect. Parameters ---------- windows: list-like of window objects ((row_start, row_stop), (col_start, col_stop)) Returns ------- boolean: True if all windows intersect. """ ...
a4113022e6ffc1bb38d2427c9ede0496271205d3
47,322
import numbers def check_state(seed): """Turn seed into a np.random.RandomState instance Parameters ---------- seed : None | int | instance of RandomState If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded wi...
d7083e6ddfb094272b12f920d85bf8617bb1719d
47,323
def gen_edo(x, DBplot=False): """Generate EDO Γ[x(n)] from simple formula in the time domain: Γ[x(n)] = y(n)² + H[y(n)]² where y(n) is the derivative of x(n) using the central-finite method and H[.] is the Hilbert transform. Parameters ---------- x: ndarray input signal DBplot...
b190618ba48f8f63fe6c1c97768fb3d427bef407
47,324
def fetch_mps_government_roles_raw(): """Fetch government roles for all MPs.""" return members.fetch_government_roles_raw( house=constants.PDP_ID_HOUSE_OF_COMMONS)
25be217fdb2d957be4f1fa12c74781a0bbe37bcf
47,325
import time def delayed_plus1(x): """Sleeps for 100ms then returns x+1.""" time.sleep(0.1) return x + 1
aa63eb61e112342be3bcd0f7a5e0118006b76c07
47,326
def view_link(url, args, appended='', text='View'): """ Helper function for generating view links """ return '<a href="' + reverse(url, args=args) + appended + '">' + text + '</a>'
73e0a24c1a064fb5d9928ed342c5ac0b798ddb74
47,327
def rob(nums): """ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent...
9bfb631b2781bbf95fa299a6474e0b1fe36ac19b
47,328
def dashboard(): """Displays the dashboard template. Returns: str: HTML Template """ data = {} try: data = { 'experiments': Experiment.get_status(current_app.config.get('container')), 'migrations': get_migration_status(), } except InvalidRequestE...
79ddb0acbe87df63afb8af0f60dd8c41548a5830
47,329
def tamiz1(m): """Algoritmo clásico para el tamiz de Eratóstenes""" l, n = [i for i in range(2, m+1)], 2 while n: for i in l[l.index(n)+1:]: if i % n == 0: l.remove(i) if l.index(n) +1 < len(l): n = l[l.index(n) + 1] else: return l
3063e5007360cfbbda53e10b84e7ca141473a552
47,330
def _sincfunc(x, dx, dampfac=3.25): """sinc helper function for sincshift()""" if dx != 0.0: xx = (x+dx)*np.pi #- cache shifted array for 30% faster evals return np.exp( -(xx/(dampfac*np.pi))**2 ) * np.sin(xx) / xx else: xx = np.zeros(len(x)) xx[len(x)//2] = 1.0 retu...
d642f4e9ed4e97d4ea3ffa837ddd2dbb9efe13d4
47,331
import os from sys import path def scanDatasets(): """ Retrieves the name of each dataset present in the framework :return: list with name of each dataset as element :rtype: List """ datasets = os.listdir(str(os.path.join(path, "preprocessed_datasets"))) datasets.remove("README.rst") ...
f090699a99dbd86d78bff3048a3a0f9416c15155
47,332
def data_preprocess(data): """ Perform data procession """ field_list = [] ### On `param_1`(76% is null), `param_2`(86% is null), `param_3` (89% is null) # This three params are text-type, and most of them are empty. # Concat `description`+`title`+`param_1`+'param_2'+`param_3`+`city` ...
71c5f554677320ee99a51116dbed3b4073b81e51
47,333
import string import random def get_random_string(length=5): """ Generates a random string of fixed lenght """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length))
bf3d8734f414065cea93940c8ad1d46d4158813f
47,334
import networkx as nx def FragGraph(G, bondOrderThreshold=1.2): """ Fragment all bonds with Wiberg Bond Order less than threshold Parameters ---------- G: NetworkX graph bondOrderThreshold: int thershold for fragmenting graph. Default 1.2 Returns ------- subgraphs: list o...
e19d211fb1173a72f3c19017654565014cbd421d
47,335
from typing import Tuple def compute_conv_idx( counts_gene: np.ndarray, knn: int, p_zeros: float, ) -> Tuple[np.ndarray, np.ndarray]: """ Given a GENE x CELL matrix, and an index to select from, calculates the convolution of reads for that gene index. The function returns the """ y_probs = np....
d56d178f38224fbf8a895282334a4e43da6cd5b9
47,336
def plot_referendum_map(referendum_result_by_regions): """Plot a map with the results from the referendum. * Load the geographic data with geopandas from `regions.geojson`. * Merge these info into `referendum_result_by_regions`. * Use the method `GeoDataFrame.plot` to display the result map. The result...
97db169d88e5fffa2c5a68986ef37d45ab80bbaf
47,337
def keep(attrs, tweets): """Strip each tweet so as to keep only the given attributes. Attributes are given as a list of the form: ['text', 'user.screen_name', 'user.name'] where the dot notation represent embedded dicts: tweet = { 'text': "This is a tweet." 'user':...
36c914246ea97b51993efd78f9059a2cd5f7d9d9
47,338
import struct def get_payload() -> bytes: """This function returns the data to send over the socket to the server. This includes everything - the 4 bytes for size, the nop slide, the shellcode, the return address (and the zero at the end). WARNINGS: 0. Don't delete this function or change it's n...
f5e697e2d7f344b13ce19ea0cf465931b6c4bdac
47,339
def get_density_plots(estimators_list, simulators_dict, path_to_results, exp_prefix="question1_noise_reg_x", task_ids=None): """ This function allows to compare plots from estimators and simulators (i.e. fitted and true densities). Two modes are currently available: 1) by specifying estimators and simulator, the ...
4ad9068c128913e4fe8a0307dfeaababda9b0adf
47,340
def _get_last_playthrough_information(last_playthrough_model): """Returns an ExpUserLastPlaythrough domain object given an ExpUserLastPlaythroughModel loaded from the datastore. Args: last_playthrough_model: ExpUserLastPlaythroughModel. The last last playthrough information loaded from ...
48ce04d882e35392a99f66b33fbcd8fd23da0135
47,341
import re from bs4 import BeautifulSoup def process_html(html): """Processes HTML for embedded code using SyntaxHighlighter Determines languages used by checking class attribute of pre tags with name="code". Args: html: HTML to be processed for embedded code Returns: The modifie...
a35c0fa79ad387d6df564d7c556cd408423b2c55
47,342
from typing import Tuple def get_movie_info(cap: cv2.VideoCapture) -> Tuple[int, int, int, float]: """get movie information Args: cap (cv2.VideoCapture): cv2 video object Returns: Tuple[int, int, int, float]: W, H, total frame, fps of movie """ W = int(cap.get(cv2.CAP_PROP_FRAME_WIDT...
3cf95dec3730bad0f46af494556b8272fffbea05
47,343
import os import logging def delete_file(filename): """delete file and catch any exceptions while doing it""" try: if os.path.exists(filename): os.remove(filename) logging.debug("Deleting " + filename) return {'success': True} except Exception as e: logg...
9212c40c05acf54001f9d32b4cec99eb6a368305
47,344
import numpy import warnings def getMetrics(sector, symbols): """Returns a 2xN numpy.Array of metrics for the given symbols from the given sector. """ metrics = [ # hard-coded for now, could easily be parameterized "Price Performance (52 Weeks)", "Standard Deviation (1 Yr Annualized...
df00d21031056bb2faf3ad9d420c308cdf075b5a
47,345
def get_prediction_datas(date=None): """ retourne les donnees predictes """ if not date: # on prend partant de la date actuelle #date = datetime.datetime.now() pass date = config.TEST_DATE # datas datas_df = model_request.get_prediction_datas(date) # data...
0949acb1b7a9ec5bcd83cc595e20bd95689da441
47,346
def testConnection(base_url=server_address): """ :param base_url: String; server address with port number. :return: Boolean; True if connection is done, false otherwise. """ try: get(base_url, timeout=5) return True except ConnectionError or Timeout: return False
eafe1d4fe5f54e868912f264f21a55f491b99ddc
47,347
def getUser(username: str): """Get user login and url.""" return getGithubApiRequestJson("users/" + username)
e68b977e4083776f5e8299113e8bf049790701de
47,348
def initStandard(cls, init=None): """ Standard initialization for population distributions, inserted by :class:`PopulationDistributionMeta`. Will call the provided initialization method as well. :param cls: The class being initialized :type cls: A class of type :cl...
2d81363fa86ecc5a2456de037307df1fdab40169
47,349
def get_best_downloader(downloader=None): """Choose among a set of 4 popular downloaders, in the following order: - wget - curl - powershell - insecure (Python) Args: downloader (str, optional): Use a given downloader. One of wget|curl|powershell|insecure. Defaults to None. ...
00a5f07485fbcc3944533a2798a864fe20fd18da
47,350
def np_parse_pcap_worker(filename): """Parse a pcap file into a numpy matrix. Inputs: - filename : a pcap file that contains packets to parse Returns: - a numpy matrix where each row is a packet and each column is a different field - a numpy column array containing the correspondi...
73d651e4d0e0524f7fe2c4e8415f213d64566edc
47,351
def get_btis(gtis, start_time=None, stop_time=None): """ From GTIs, obtain bad time intervals, i.e. the intervals *not* covered by the GTIs. GTIs have to be well-behaved, in the sense that they have to pass ``check_gtis``. Parameters ---------- gtis : iterable A list of GTIs ...
5197776b1351f1c657c4d2b526cd12086b9aa489
47,352
def greedy_find_clique(graph, progress=False, nodes=None, ordering_func=None, node_deletion=True): """Finds the graph's clique (largest complete subgraph) """ graph_order = graph.order() if graph_order == 0: return [] if nodes is None: nodes = list(graph.nodes...
bb9389019a5a7d3d3c7c442bc36e32a4a8c154d1
47,353
import json def patch_truck(client, truck_id, **kwargs): """ attempts to change the specified row in truck :param client: the client to make the request with :param truck_id: the id of the truck to change :param kwargs: the data that needs to be changed :return: """ return client.patch...
b416a9a2662ae0b44adde8d1d361bad54706e90a
47,354
def to_klio_message(incoming_message, kconfig=None, logger=None): """Serialize ``bytes`` to a :ref:`KlioMessage <klio-message>`. .. tip:: Set ``job_config.allow_non_klio_messages`` to ``True`` in ``klio-job.yaml`` in order to process non-``KlioMessages`` as regular ``bytes``. This func...
c8ad358252ad9de695f01d810fd2731d67ac7816
47,355
def get_lists(tab=None, cfg="tlut"): """ Returns: loss_list, acc_list """ if cfg == 'tlut': # loss = get_cell_vals(tab, 'B6:B20') loss = [0.0296, 0.044, 0.0612, 0.0997, 0.1713, 0.2981, 1.6251, 1.9081, 2.0437, 1.8245, 2.1162, 2.2531, 2.2789, 2.3028, 2.3035] # acc = get_ce...
48048c32f612086796545392f35d5145bdf0fc5c
47,356
def import_models(config, checkpoints_logdir, device, verbose=1): """Import model from configuration file """ model_manager = models.ModelManager(checkpoints_logdir, config['task_ids']) model, last_ckpt = model_manager.load_model( model_name=config['models']['name'], model_weight...
295dd11c4f7734fc529b0bfe31d908b60dfcdd89
47,357
from typing import Union def greater_than_equal_to_validator(start) -> Validator: """ Validate that a given value is greater or equal to a number. Can be used with int, float or BaseImageContainer. :param start: the value to be greater than or equal to """ if not isinstance(start, (float, int)...
0c6b026727c3c4dab5c58b259562c8aad95b9fed
47,358
def single_text_phrase(context, slug=None, language=None): """ for using this template tag you must enable one of the text_phrase context_processors. this templatetag will return the first text phrase object, if there is more then one object. if you want single text phrase in special language se...
7e9b5a28cbf1ae0215e201e3af0f22631aad9ac2
47,359
def slow_trajectory(robot, joints, path, min_fraction=0.1, ramp_duration=1.0, **kwargs): """ :param robot: :param joints: :param path: :param min_fraction: percentage :param ramp_duration: seconds :param kwargs: :return: """ time_from_starts = instantaneous_retime_path(robot, joi...
22de73888ec8f34d9df9f7793b3e8b0acd4fd596
47,360
from typing import Callable def make_request(func: Callable) -> Callable: """ Allows clients to customize how they want to make a request to the service undergoing fuzz testing. """ get_abstraction().request_method = func return func
7f8ddeea6b38d4716f253941ebd77ce184439933
47,361
import os def _find_files(root_dir, should_include): """ Return a list of paths to all modules below the given directory. Arguments: should_include: a function that accepts a file path and returns True or False. """ paths = [] # Return value. is_module = lambda path: path.endswith("...
0f572880279a28914ad99f7635c0f573fa01044a
47,362
def renderScene( background_plane, assembly, component_poses, camera_pose=None, camera_params=None, object_appearances=None): """ Render a scene consisting of a spatial assembly and a background plane. Parameters ---------- Returns ------- """ # Start by rendering the back...
3ededcb5caaead0eaff8aaa799dffb98f7a770ad
47,363
def split_train_test(): """ Import the dataset via sklearn, shuffle and split train/test. Return training, target lists for `n_clients` and a holdout test set """ print("Loading data") diabetes = load_diabetes() y_raw = diabetes.target X_raw = diabetes.data # print(type(y_raw)) y...
7bb6dfe8fe2afbae28f4303a0fa5312cda1da3eb
47,364
import os def load_np_arr(save_path, file_name): # type: str -> str -> () """ Load array from <save_path/file_name.npy>. """ with open(os.path.join(save_path, file_name + '.npy'), 'r') as f: return np.load(f)
d737e66c29b0ac8de22c3d4f92ad3972116ab61f
47,365
def markdown_loader(text, metadata): """A loader function for markdown.""" # TODO: Remove debug code here # if metadata['basename'] == "DH_Materials": # print(text) # print(markdown.markdown(text)) return markdown.markdown(text)
1597aee9240a98fb70b78a9bfa50ceb6e4161e8d
47,366
def plot_dist_mat_multi_row(D, figsize=(3,3), titles=None, ylabels=None, wspace=0, hspace=0, sharex=False, sharey=False, cmap='Greys'): """Plots distaince matrices in a multi column and multi row manner (square matrix).""" nr = len(D) nc = len(D[0]) titles = titles or [None] * nc ylabels = ylabels...
8a99f6c9ed555a09857078acdd3e27566e62aa57
47,367
def read_several_fasta(input_files): """ Read several fasta files Note that each fasta file may contain several sequences. Parameters ---------- input_files: a list of fasta file paths. Returns ------- pb_name: a list of the headers pb_seq: a list of the sequences """ ...
7eabeb44625c65e1bd1fe3c98d0d507b783dae8a
47,368
def load_objects_from_xl(file_name): """ Loads the excel file worksheets into dictionaries Args: object: excel file names Returns: object: dictionaries """ # global excel_info SAT_dict = {} TRSP_dict = {} VSAT_dict = {} EARTH_COORD_GW_dict = {} GW_dict = {} ...
d557a94c816cd4a74a5a97d794b2490605713509
47,369
import json import os def list_file_data(): """ Function: list_file_data\n Parameters: None\n Return: list of data in output file\n """ epsilon = 0.0 learning_rate = 0.0 decay_factor = 0.0 with open('input_files/scenario_input.json', 'r') as file_pointer: file_data = json.l...
7d99899318f53a79779e41984f552b5ace99c15f
47,370
import os def _pip_cmd(env): """Retrieve pip command for installing python packages, allowing configuration. """ anaconda_pip = os.path.join(env.system_install, "anaconda", "bin", "pip") if env.safe_exists(anaconda_pip): to_check = [anaconda_pip] else: to_check = ["pip"] if "pi...
ad751721dd118f8e867ae6f296bbf6ce1d811d66
47,371
def collect_sim_params(aperiodic_params, periodic_params, nlv): """Collect simulation parameters into a SimParams object. Parameters ---------- aperiodic_params : list of float Parameters of the aperiodic component of the power spectrum. periodic_params : list of float or list of list of fl...
a39343bd307cc2e1b4194495da9177ef7ce1495d
47,372
def dut_addr(dut, execute_helper): """Fixture to return the DUT address.""" return get_dut_address(dut, execute_helper)
a8ebc74a2b827e383c0f605b8e87edcf840cd161
47,373
import array def encodeDPID (vendor,role, location, id): """ Generates a DPID that is encoded as follow: DPID format: byte7 byte6 byte5 byte4 byte3 byte2 byte1 byte0 vendor type reserved <--- ASCII Name ------> id :param location: 4 letters max. location (i.e. STAR, LBNL). ...
b5dbf8530c0f9b5d06d9da75ed8e10145ebc935e
47,374
def smooth_segmentation(data_img, seg_img, fwhm, noise_img=None, inplace=False): """Filter each compartment of a segmentation with an isotropic gaussian. Parameters ---------- data_img : nibabel image 3D or 4D image data. seg_img : nibabel image 3D label imag...
1536ca1733692dc94d8c40e57ea32f018fdad0a1
47,375
def remove_node(**kwargs): """ 删除节点任务 """ code, res = SaltClient.operate_cetus_node(kwargs.get('id'), 'abort') if not code: TbCetusNodeInfo.objects.filter(pk=kwargs.get('id')).delete() PeriodicTask.objects.filter(name='node_%s_monitor' % kwargs.get('id')).delete() return '删除...
a5213996824fea1e5a1012880234b78706585438
47,376
def setup_training(layer_info,prob, trinit=1e-3,refinements=(.5,.1,.01),final_refine=None ): """ Given a list of layer info (name,xhat_,newvars), create an output list of training operations (name,xhat_,loss_,nmse_,trainop_ ). Each layer_info element will be split into one or more output training operations...
8d17f8651fe6e2cb1b3d157e10589beab2433df7
47,377
import collections def permute_Ediag_inplace( ABCDE, Nst=None, Nco=None, location="upper left", nonzero_test=nonzero_test, rank_nonzeroE=rank_nonzeroE, ): """ Permutes the E matrix to be on the location='upper left' or 'upper right' and as diagonal as possible. return ABCDE, a...
0fa80a083d70dbe00dc5b35b6f7882dcdf343cc9
47,378
def update_messages_incoming( messages_outgoing: jnp.ndarray, nodes_factor_masks: jnp.ndarray, nodes_indices: jnp.ndarray, nodes_factor_indices: jnp.ndarray, perturbation_configurations: jnp.ndarray, ): """update_messages_incoming. Args: messages_outgoing: Array of shape (n_nodes, n...
6b17f8efc7d9b070e83c6a704de79a6b4c0ea2d4
47,379
import uuid import time def convert(req: SongMetadataForDownload, background_tasks: BackgroundTasks, request: Request): """Start download and conversion of song with given metadata in the background""" uid = uuid.uuid4() jobs[uid] = DownloadJob(request_id=uid, status=Status.WAITING, percentage_done=0.0, l...
3c657cf34f9ba3ea1bbd3c6542fa1dfa7be29427
47,380
def linear_scale(input, in_low, in_high, out_low, out_high): """ (number, number, number, number, number) -> float Linear scaling. Scales old_value in the range (in_high - in-low) to a value in the range (out_high - out_low). Returns the result. >>> linear_scale(0.5, 0.0, 1.0, 0, 127) 63.5 ""...
caeab8e992caca2dba96f48b0eb617fd361bb9eb
47,381
import random def meme_rand(): """ Generate a random meme """ img = random.choice(imgs) quote = random.choice(quotes) path = meme.make_meme(img, quote.body, quote.author) return render_template('meme.html', path=path)
02bff0fb08244eec61ecb10cd2f565d441a3b182
47,382
def magma_snrm2(n, dx, incx): """ Euclidean norm (2-norm) of vector. """ return _libmagma.magma_snrm2(n, int(dx), incx)
c10b482ef5e8353da9b85606946abd71b9dc9e0d
47,383
def lowerCase(length: int = 1) -> str: """ returns random lowercase letter strings :parameters: length: defines the length of the character sequence if length is not given, the function returns only a single character """ return "".join(choice(lowercase) for i in range(length))
1354d1d361e499b5338c27901bdd4a362a310f34
47,384
from typing import List from typing import Dict from typing import Tuple def process_commits( commits: List[CommitInfo], check_merge_commits: bool, ) -> Dict[str, List[str]]: """ Process commit information to detect DCO infractions. :param commits: the list of commit info :param check_merge_c...
e1155e51f11bed54f53fd6c1e48162bd2729a57a
47,385
from typing import Optional def single_time_vis(channel: dict, bt=0, tt=0, chart_type: Optional[str] = None, enable_playback: bool = True, height: int = 50, params=None, title: s...
8291bbaee0b4679211b5f92e050bfb217ce1a30f
47,386
from typing import Callable def once(): """ TODO: Documentation """ def wrapped(func: Callable): if hasattr(func, '_type') and not hasattr(func, '_thread'): # only declare once on existing hooked functions that aren't threads func._once = True return func ...
2e0c944a55492302701951290d749616925229c3
47,387
def cart_contents(request): """ Ensures that the cart contents are available when rendering every page """ cart = request.session.get('cart', {}) cart_items = [] total = 0 destination_count = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, p...
03dd02318cf498005c5050d80eaac6f101175a7b
47,388
from cp_documento import Documento def main(): """Funçao index""" print('Init do main_route') #window_id = str(get_window_id()) #print('1') #set_base_context(window_id) #print('2') #ctx_dict = get_context(window_id) ctx_dict = {'titulo':'Portal de Compras Públicas'} resQueryDocLeis...
e7cba8d516a4f1f376e3092fb4df0b1547fb132d
47,389
def lastweek_homes_avg(): """ Returns the average of homes we reached last week """ # find last week monday # iter over tail checking dates lastweek_monday = date.today() - timedelta( 6 + date.today().isoweekday() % 7) homes = [0] * 7 for line in Popen(('tail', '-12', settings.DOMICILIOS...
13344d11142306afaa9d966033821d4f3f1eb7b8
47,390
from sparktk.frame.frame import Frame def top_k(self, column_name, k, weight_column=None): """ Most or least frequent column values. Parameters ---------- :param column_name: (str) The column whose top (or bottom) K distinct values are to be calculated. :param k: (int) Number of entries to r...
2e196ebab45e42774bf45b25083689249084f250
47,391
def connect(server_name, aedt_client_port): """Connect to an existing aedt server session. Parameters ---------- server_name : str name of the remote machine to connect. aedt_client_port : int port on which rpyc_server is running inside AEDT Returns ------- rpyc object....
9804413d97271cde6eacf5e4bbd9ee9de6c92899
47,392
def _slice(iterable, pattern): """ a custom built slice method that can be used inside jijna template enginer :param iterable: string :param pattern: string ex (::-1) :return: string """ if iterable is None or isinstance(iterable, Undefined): return iterable # convert to lis...
be77930aeb4fa3edab306fa7fdb23e39f366810b
47,393
import inspect def inline_c_precompile(source): """Precompile C/C++ code and run it in-line""" fr = inspect.currentframe().f_back (lib, code) = _load_func(fr) return _call_func(lib, code, fr)
802befa0f8fb3ea903de1f954755526af8a501d7
47,394
def docs(node, manifest, config, column_name=None): """Return a function that will process `doc()` references in jinja, look them up in the manifest, and return the appropriate block contents. """ current_project = config.project_name def do_docs(*args): if len(args) == 1: doc_p...
3504b572f02b37679e4b1d91f7a2b7b6cf9fa47c
47,395
import os import toml def get_config(path: str) -> EasyDict: """Load the configuration file found at ``path``. Raises: RuntimeError: when no configuration exists at ``path``. """ if not os.path.isfile(path): raise RuntimeError('cannot locate config at path, %s' % path) with open(p...
462d97328d01012965aca7ffb1244a12fefc5d8e
47,396
def Footer(*content, **attrs): """ Wrapper for footer tag >>> Footer().render() '<footer></footer>' """ return KWElement('footer', *content, **attrs)
cf13a602c246d918a3fda2fd5a6a24d8777a93e7
47,397
from pathlib import Path def preprocess_src_dir(dp_config: DatapaneCfg) -> Path: """Preprocess source-dir as needed""" old_mod = dp_config.proj_dir / dp_config.script # TODO - pass mod_code via classvar in dp_config if old_mod.suffix == ".ipynb": log.debug(f"Converting notebook {dp_config.scr...
2b4c6c4d486d63a9fccf7e1497a95dc4ae058179
47,398
def dKT(counts, lower_quantile=0.25, upper_quantile=0.75): """ Parameters: 1-D array_like, int Vector of counts. lower_quantile : float, optional Lower bound of the interquantile range. Defaults to lower quartile. upper_quantile : float, optional Upper bound of the interquantile range. Defau...
c8b8bccbc164ce1cf5dde8761fe3c346077c79f9
47,399