content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load_trajectory_to_npy(filename, name="", begin=0, end=None, stride=None): """ Loads the trajectory into four numpy arrays containing: * the number of particles per frame (shape=(n_frames,)) * the positions of the particles for each frame (shape=(n_frames, max_n_particles_per_frame, 3)) * the t...
06d60f0d673c47e2b2fbc907f179b40c10a86f60
44,200
def recurse(gentle_output, audio_file, anchor_length): """ Recursively align the unaligned segments of a given Gentle output. Parameters ---------- gentle_output : list of Word objects outputted by previous Gentle run audio_file : PyDub object representing the entire audio file anchor_lengt...
e285a5367e7810037fa9fd87d0d09d06b0dcf43c
44,201
import json import urllib def get_released_versions(package_name): """ Fetches the released versions & datetimes of the specified Python package. Examples -------- >>> get_released_versions("scikit-learn") {'0.10': '2012-01-11T14:42:25', '0.11': '2012-05-08T00:40:14', ...} """ url = "...
53116bb1cc6a91938aaf7710e6b6ed416d95f84a
44,202
def total_loss_function(c_image,s_image,g_image,alpha,beta): """ Args: c_image_path (str): To take the content image path s_image_path (str): To take the style image path g_image_path (str): To take the generate image path Returns: int: The totoal loss...
11c99b1199a726823838f59329599e276174a836
44,203
def cartesian_to_spherical(x, y, z): """ Convert cartesian coordinates to spherical in the form (theta, phi[, r]) with the origin remaining at the center of the original spherical coordinate system. """ r = np.sqrt(x**2 + y**2 + z**2) #theta = np.arccos(z / r) theta = np.arctan2(y, x) p...
b6b2f88a36c1459e445bf8ca1ff1cdf9d5824191
44,204
def logistic(z: np.ndarray, a: float, b: float) -> np.ndarray: """ Compute logistic function Inputs: a: exponential parameter b: exponential prefactor z: numpy array; domain Outputs: f: numpy array of floats, logistic function """ den = 1.0 + b * np.exp(-...
61ae563b89b33cc7581bb8537ce885cadaf176d7
44,205
import logging import re def get_diamond_predicted_domains(predicted_domains, protein_accession): """Retrieve the CAZyme domains predicted by DIAMOND, from the overview.txt file. :param predicted_domains: list of strings, each string contains a unique CAZyme domain prediction :param protein_accession: st...
5c6aa1ba54777ad49ed91a7b50fcaa1d39b356d7
44,206
import time def review(): """ user wants to toggle a paper in his library """ # make sure user is logged in if not g.user: return 'NO' # fail... (not logged in). JS should prevent from us getting here. idvv = request.form['pid'] # includes version if not isvalidid(idvv): return 'NO' # fail, malf...
1dda1faeaf599651e310b6d13c584564ccac9bef
44,207
async def find_busy_consumers(engine): """Returns a list of busy consumers that can be used to run.""" Consumer = namedtuple('Consumer', ['ip', 'status', 'port', 'job_chunk_id']) try: async with engine.acquire() as connection: query = sa.text(''' SELECT ip, status, port,...
e9be4fefe889a6da8818b0f53175fcc32407b54b
44,208
def mlp_missing_biology_occurrences(): """ Function to identify occurrences that should also be biology but are missing from biology table :return: returns a list of occurrence object ids. """ result_list = [] # Initialize result list # Biology occurrences should be all occurrences that are ite...
e93cdbe038ae18fe6540b84907406415572912cf
44,209
import base64 def print_anycli(**kwargs): """ List the number of deployed scripts on remote device :param kwargs: keyword value: value to display :return: display the result of AnyCLI :Example: result = cli(url=base_url, auth=s, command="show vlan") print_anycli(result) """ ...
3d0d34da4e1f6ca347d4503fb242b8485268641a
44,210
def create_virus_total_headers_from_config(): """ Creates a dictionary called virus_total_headers that contains the formatted header needed to submit an query to VirusTotal. Requires an VirusTotal API Key to use. It is free to sign up for one but has restrictions on daily limits. Reads in the Vir...
02552b1c03108a137dd1e314f3d1e1c318e51eb4
44,211
import select from operator import and_ def add(existing_account_customer, new_account_customer, Session): """Add a second customer to the account of an existing customer.""" with Session() as session: # get existing account firstname, lastname = split_name(existing_account_customer) ...
6ff604a7d18ca40d8dbb911c33a4b79eab80db38
44,212
import json def query_builder(title, city, state): """This function will be called from view to build the search query """ # TODO the query body has to be in a separate json file in utils and not hard coded here # Also if you dont want to check city name against a full list of all cities you can use Fuzz...
12f41694920030129a3ee100581418ce1d16a7a4
44,213
def get_shape_not_match_message(shape_error_type, value): """ Function Description: get shape not match message Parameter: input:the value shape_error_type: the shape error type Return Value: not match message """ message = "" if shape_error_type == InputShape...
a20b51a36b723aea0a3bd5bd26b60d5934a70ce3
44,214
def extract_projstring(proj_string): """ Import an OSR supported projection string into a spatial reference object Parameters ---------- proj_string : string Projection String in some OSR supported format Returns ------- srs : object OSR spatial referenc...
65b32e02803e7549359bff4fe6a9f4750101c10e
44,215
def scrape_katportal_log(logfile, keystring): """Retrieve timestamps and values for a katportal log entry containing a particular string. Examples of logfile lines: [2020-06-19 19:31:43,347 - INFO - katportal_server.py:108] {'msg_channel': 'array_1:subarray_1_observation_acti...
2e15d33d17a21c0ca4dfd478d1a46a87677936ca
44,216
def show_bookmarks_related(context, title, url, object, description=""): """ Displays the bookmarks with counter. """ if not isinstance(object, models.Model): raise TypeError, "object must be a valid Model" if not url.startswith('http'): url = context['request'].build_absolute_...
653fd96dbf522bc6c2713ceb803ed85b86262321
44,217
def is_service(hass, entry): """check whether config entry is a service""" domain, service = entry.split(".")[0], ".".join(entry.split(".")[1:]) return hass.services.has_service(domain, service)
d244dc15be20a7e56a17695dbf7df4c1811650a5
44,218
from typing import Tuple def state_to_th_vel(config: PendulumConfig, state: int) -> Tuple[float, float]: """Convert a state id to the angle and the angle velocity. Args: config (PendulumConfig) state (int) Returns: theta and vel_theta values. """ th_res, vel_res = config....
d987f5004f3fe44b4d05b3f119600c9edd93bccc
44,219
def _dnorm(W, norm='ave'): """ Normalizes a symmetric kernel `W` Parameters ---------- W : (N, N) array_like Similarity array generated by `SNF` norm : str, optional Type of normalization to perform. Must be one of ['ave', 'gph']. Default: 'ave' Returns ------- ...
770ee7cea3ba98714c43ab9cebbe189381852def
44,220
def parse(html, path): """ parsing html content :param html - string with html content: :param path - strind with xpath query: :return: parsered lxml objects """ try: html_tree = lxml.html.fromstring(html) result = html_tree.xpath(path) except Exception: abort(500...
a440e0806d529414c53305b87ca465974da8740e
44,221
def image_loader(image_path: str, img_size: tuple = (128, 128)) -> Tensor: """ Loading and preprocessing an image :param image_path: path to image :param img_size: image size :return: image format torch.Tensor """ loader: transforms.Compose = transforms.Compose([ transforms.Resize(im...
0dca00365a4dc26862239ebc81bb1dce05cefd23
44,222
def slurm_parse_timestr(s): """ A slurm time parser. Accepts a string in one the following forms: # "days-hours", # "days-hours:minutes", # "days-hours:minutes:seconds". # "minutes", # "minutes:seconds", # "hours:minutes:seconds", Returns: Time in se...
f5a3dd5db492d78d34741a3a15ad6bebed8c8628
44,223
import json def lambda_handler(event, context): """ handles request to the lambda function from frontend. parses json request and sends to update_table function. """ bucket = event['bucket'] path = event['path'] response = list_all_objects(bucket, path) # ACTUALLY USE RESPONSE HERE TO ...
02d6ca029e70829990b01026d061d7b1dd9b26e9
44,224
def window_add_dataframe_date(date, df): """ Add data from a a dataframe. Dataframe has data only from a day Remove seconds from T_Hora_C, where time are store :param date: day :param df:data :return: """ def filter_time(row): return row["T_Time"][:5] df["T_Time"] = df.ap...
176802a1837ee8ad5c55f61edfb2aaa42636cf46
44,225
def any_in(collection, values): """ Check if any of a collection of values is in `collection`. Returns boolean. """ for value in values: if value in collection: return True return False
a8d4471940e96d2b6a307c8ccf48caaaecb10f98
44,226
def __virtual__(): """ Only load if requests is installed """ if HAS_LIBS: return __virtualname__ else: return ( False, 'The "{0}" module could not be loaded: ' '"requests" is not installed.'.format(__virtualname__), )
8bfb59e44d346147be70e450581cecab10d44ccc
44,227
def cdsem_straight(w, dw, spacing=5.0, length=20.0): """ w dw """ c = pp.Component() c.move(c.size_info.cc, (0, 0)) return c
5f6498f2d0d7d705d7d5742bb4fd7b8f92c9940c
44,228
def interpolate( input, size=None, scale_factor=None, mode='nearest', align_corners=False, ): """Resize input via interpolating neighborhoods. Specify either ``size`` or ``scale_factor`` to compute output size: ```python x = torch.ones((1, 2, 3, 4)) y = F.interpolate(x, size=6)...
21895b272cb430a4a07aa66c0c09cacc179cef96
44,229
def log_poisson_binomial(log_q0, log_q1): """ Computes the events log probabilities w.r.t. a batch of Poisson Binomial R.V. The computation is numerically stable. Parameters ---------- log_q0 : torch.tensor (dtype=torch.float) The log probability of each bits to be zero. The Poisson...
e465112e4caf3ef53bfea0a7bf49af5e08b1b218
44,230
def has_rings(): """ Determine if we can see the ring logo. """ pos = pyautogui.locateOnScreen('rings.png', confidence=0.5) if not pos: pos = pyautogui.locateOnScreen('rings2.png', confidence=0.5) print(f"Found at: {pos}") return pos is not None
83bb6d16433ae8515f5caab688e36bac0ad9e6b4
44,231
import os import zipfile import fnmatch def get_zip_names(path, dir, infold=True): """Loads the filenames for the data matching 'path' in the location 'dir' ('dir' does not have to end with '.zip'). Returns a list of filenames and the zip archive.""" folder = os.path.split(dir)[1] if infold else '' ...
cb23d3c630feb6c49b4aefbd6c06a7847dc96768
44,232
def custom_tokenizer(nlp): # pragma: no cover """ Creates a custom spaCy tokenizer. :param nlp: a spaCy Language object :return: """ prefix_re = spacy.util.compile_prefix_regex(nlp.Defaults.prefixes) suffix_re = spacy.util.compile_suffix_regex(nlp.Defaults.suffixes) infix_re = spacy.ut...
354de8cd229f6c43c843b09afb9302a920ebc72e
44,233
def choose_barrier(x, reverse=False): """ Choose the scenario where the AV hits the barrier. If there is no such scenario, abstain. :param reverse: If false, choose to hit the barrier. Else choose not to. """ if x["Passenger_noint"] == 0 and x["Passenger_int"] == 0: return -1 if x["Passenge...
5ca785d2e69b3f1dba4e38a0d95d3cf3b4e90cd8
44,234
def _find_user_traceback_depth(tb): """Returns the depth of user-specific code in a traceback. This is the depth from wich we find a frame where __name__ is '__p1__'. Args: tb: A traceback object. """ depth = 0 while tb: # Find the topmost frame frame = tb.tb_frame ...
fcfd3227430f51b3120f2d84d6d2d3c9e45c968c
44,235
def load_config(cfg_path: str) -> DictConfig: """ Load configuration file. `base_config.yaml` is taken as a base for every config. :param cfg_path: Path to the configuration file :return: Loaded configuration """ base_cfg = OmegaConf.load('legoformer/config/base_config.yaml') curr_cfg = ...
39eab3a3802eb6f849b93696f128789618a4d87d
44,236
def source_vectors(theta, phi): """ Produces vectors along the polarization axes and the direction of GW propagation for sources at (theta, phi). """ # theta, phi is the direction to the source # everything below needs the direction of GW propagation theta_prop = np.pi - theta phi_prop =...
2d88c60b0e5ea09280dec8082e32dbd0d8132adc
44,237
def get_gradient_thresh(img): """ Calculate a gradient threshold of an image :param img: BGR image :return: Binary gradient threshold image """ ksize = 5 img = undistort_image(img, mtx, dist) #hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS).astype(np.float) #s_channel = hls[:, :, 2] g...
640615a0279a4f60a220bbf6a6030d9fa753724f
44,238
import logging def refresh(self, errorfile): """ Recompile all the entire blog. Put the result into a log file. """ # BUG FROM MAKEFLY WITH HYMBY: The refresh method is called at the same time than the post creation. #+ This way, the new post have the same date as the compilation. #+ In Ma...
57f430ad3b1e0ec40ae7328e2c5e43e35535d768
44,239
from typing import List def do_split(s, sep): """ Divides an input string into an array using the argument as a separator. split is commonly used to convert comma-separated items from a string to an array. https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/s...
84c2ce6d53adce7d3929bb1c56afb21df5bb6787
44,240
import csv from datetime import datetime def process_covid_csv_data(covid_csv_data: csv) -> tuple[int, int, int]: """ (For Test) Processes covid data from a csv file. Arguments: covid_csv_data: A csv file of all the data. Parameters: last7days_cases: The number of cases in the last 7 days wi...
ff0f8a355ba3ca4212fc561a36e2e0c499971826
44,241
def _FormatLabelsArgsToKeyValuePairs(labels): """Flattens the labels specified in cli to a list of (k, v) pairs.""" labels = [] if labels is None else labels labels_flattened = [] for labels_sublist in labels: labels_flattened.extend([label.strip() for label in labels_sublist]) labels_flattened_unique = ...
3a7bb78cf303498153828484e5c15a3a9add4cf9
44,242
def get_syncitems(): """Run the loop to get all 'syncitems' entries. Returns a list of (syncitem, time) tuples.""" syncitems = lj.run('syncitems') items = [] total = int(syncitems['sync_total']) print '%d/%d syncitems' % (len(items), total) lastsync = None while len(items) < total: ...
2909cf0506019146883b11122fe503ffd5b87168
44,243
def router_id(conn, ref, required=True): """Fetch ID of Router identified by reference dict `ref`. Use OpenStack SDK connection `conn` to fetch the info. If `required`, ensure the fetch is successful. Returns: the ID, or None if not found and not `required` Raises: openstack's ResourceNotFound whe...
60c0e8b07012554846fdbb6dd2cced0d1dcd7722
44,244
def read_examples(examples, is_training, shuffle_examples, skip_n_initial_records, hparams): """Returns a tf.data.Dataset from TFRecord files. Args: examples: A string path to a TFRecord file of examples, a python list of serialized examples, or a Tensor placeholder for serialized examp...
56a9692af7641e866fc717bd8d0edfc78642a213
44,245
from typing import Optional def model_data( train_samples: int, targets: Optional[list[str]] = None ) -> tuple[list[str], Data]: """ Get the training and testing data to be used for the model. Inputs ------ train_sample : int How many samples per example targets : Optional[list[st...
2f503eeadd38fc6a2b32556e7250789783535e57
44,246
def retention(retention): """ Parses a retention object give in JSON to Retention type :param retention: retention in JSON :return: PropertyInstance.Retention """ if retention is None: return None context = None if retention.get('context') is not None: context = Property...
0f88fbc36cbc75feb959970ae42127a16c6556d4
44,247
def get_ansible_vars(host): """Define get_ansible_vars""" repository_role = "file=../../vars/main.yml name=repository_role" tomcat_role = "file=../../../tomcat/vars/main.yml name=tomcat_role" java_role = "file=../../../java/vars/main.yml name=java_role" common_vars = "../../../common/vars/main.yml n...
04300ced184729d4eda3ee5e62ff269ed553ab89
44,248
from functools import reduce from typing import Union def ReduceToAlgebra(left,right): """ Converts a parsed Group Graph Pattern into an expression in the algebra by recursive folding / reduction (via functional programming) of the GGP as a list of Basic Triple Patterns or "Graph Pattern Blocks" ...
00bc59f25013454aed8ffda2541a63b0b8edf0c7
44,249
import sys def get_upgrade_command(latest_version=None): """ Get GridCal update command :return: """ if latest_version is None: latest_version = find_latest_version() cmd = [sys.executable, '-m', 'pip', 'install', 'GridCal=={}'.format(latest_version), '--upgrade',...
294008296da901d18bb25c60cbef240fbde0fbe9
44,250
import warnings from typing import Concatenate def DilatedSpatialPyramidPooling(dspp_input, num_filters=256, dilation_rates=[1,6,12,18]): """ Instantiates the Atrous/Dilated Spatial Pyramid Pooling (ASPP/DSPP) architecture for the DoubleU-N...
cd8430eeec713f991454679c0fd700e00d690edb
44,251
import re def cleanup_whitespace(text_content): """clean up junk whitespace that comes with every table cell""" return re.sub(REGEX_WHITESPACE, ' ', text_content.strip())
05ceb282e763cca2b03c60fad0c4858930659857
44,252
def filter(request, site, condition, val): """ 分类显示 :param request: :param site: :param condition: :param val: :return: """ user_home = models.Blog.objects.filter(site=site).select_related('user').first() if not user_home: return redirect('/') template_name = "home_su...
a490238f96ca0e1833a6216e23c931498003601f
44,253
def sst_ERSSTv5(): """ get the sea surface temperature from the ERSST-v5 data set """ data = xr.open_dataset(join(rawdir, 'sst.mnmean.nc')) data.sst.attrs['dataset'] = 'ERSSTv5' return data.sst
20469451b55bbf48a77f096a15999500663a090b
44,254
from datetime import datetime def _week_value(dt, as_string=False): """ Mixpanel weeks start on Monday. Given a datetime object or a date string of format YYYY-MM-DD, returns a YYYY-MM-DD string for the Monday of that week. """ dt = datetime.datetime.strptime(dt, '%Y-%m-%d') if isinstance(dt, comp...
ce65657fa47623ca5f9bc6bbf36dbae2471db8e7
44,255
def swap_AL(peptide:str)->str: """ Swaps a A with L. Note: Only if AA is not modified. Args: peptide (str): peptide. Returns: str: peptide with swapped ALs. """ i = 0 while i < len(range(len(peptide) - 1)): if peptide[i] == "A": peptide[i] = peptide[i + 1...
9f5410de25e00712a69876917a69d76d1130f115
44,256
import torch def mpgm_loss(target, prediction, l_A=1., l_E=1., l_F=1., zero_diag: bool=False, softmax_E: bool=True): """ Modification of the loss function described in the GraphVAE paper. The difference is, we treat A and E the same as both are sigmoided and F stays as it is softmaxed. This way we can...
fe90570a84b41eea2da2582ba0f1ac003be43c4b
44,257
def loss(y, y_hat): """ Evaluates cross-entropy loss for the given next-node distributions and predicted distributions # todo fix """ y_hat_log = np.log(y_hat) y_hat_log[y_hat_log == -np.inf] = 0 return -np.sum(y_hat_log * y) / y.shape[1]
51a04dbc22ab5fc5dd08e0efa629d44fba9627e2
44,258
def show_menu_item_by_id(item_id): # noqa: E501 """Info for a specific menu item # noqa: E501 :param item_id: The id of the menu item to retrieve :type item_id: str :rtype: MenuItem """ if (item := models.MenuItem.query_by_id(int(item_id))) : return item.serialize() else: ...
6831e3e57bf31d0d36cf730b7daafcecf5484cb6
44,259
import numpy def get_minmax(Data): """ Get daily minima and maxima on days when no 30-min observations are missing. Days with missing observations return a value of c.missing_value Values returned are sample size (Num), minimum (Min) and maximum (Max) Usage qcts.get_minmax(Data) ...
89e273288e70c1bad8e4f83c753ae3b12f755adb
44,260
def padding_box(rect, padding): """ Get a new Rect where rect is enlarged by padding width. :param Rect rect :param int padding :return enlarged Rect :rtype Rect """ top_left, bottom_right = rect return (add_positions(top_left, (-padding, -padding)), add_positions(bott...
7b9a29ec9350ad92858e9442056c8f9e82b14360
44,261
def binarize(y, label): """Binarize array-like data according to label.""" return (np.array(y) == label).astype(int)
62cb481208ffd685b64507ab24fab266d450efe4
44,262
def buy(): """Buy shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": if not request.form.get("symbol"): return apology("must provide stock’s symbol", 400) elif not request.form.get("shares"): return apolo...
62bc97cc7e4bbac0a3bb44a02006bd74498f169f
44,263
from bokeh.transform import linear_cmap def bokeh_bands(bandsdata, *, k_label='kpath', eigenvalues='eigenvalues_up', weight=None, xlabel='', ylabel=r'E-E_F [eV]', title='', special_kpoints=N...
d2afcb7e0b432e0d2ac72d0012c49e4af56a0e93
44,264
def monitor_saturation(model): """Monitor the saturation rate.""" monitors = {} for name, p in model.named_parameters(): p = F.sigmoid(p) sat = 1 - (p - (p > 0.5).float()).abs() monitors['sat/' + name] = sat return monitors
8c84b5e57e218985dec1d70d3e48d582244ac977
44,265
def ensure_job_exists_in_s3(job_id): """_ensure_job_exists_in_s3 :param job_id: """ try: inputs = S3_CLIENT.list_objects(Bucket=tfvars.S3_JOBS_BUCKET, Prefix=job_id+'/inputs') if inputs.get('Contents'): return True return False...
a4511493b1e922117307a09739b2785e751a37cf
44,266
def dict2kvtable(obj, env): """Generate an HTML table from a dictionary""" return "XXX table"
4cb88b5259e7bab7ad3f106251371c5f80bcccd9
44,267
import math def u_law_expend(arr): """ Expend compressed array. :param arr: given array :return: expended array """ u = 255 max_in_arr = np.amax(arr) out = np.array(arr, dtype=float) for i in range(0, len(arr)): p = math.log(256) * abs(arr[i]) / max_in_arr o = max...
9150d2c54e36eb63c2e22ad855f68b49b5017ad6
44,268
async def get_attentions_and_preds( model: str, sentence: str, layer: int, request_hash=None ) -> api.AttentionResponse: """For a sentence, at a layer, get the attentions and predictions Args: request['model']: Model name request['sentence']: Sentence to get the attentions for r...
c4a1ef4b193121a067454dccf92881a2761ccc46
44,269
import os def initDatabase(): """ Initialize the to-do list database """ scriptPath = os.path.dirname(os.path.realpath(__file__)) databasePath = scriptPath + "/../data/todo_list.sqlite" database = TodoDatabase(databasePath) return database
0a6cd0384c76312d7c13dd00ebe0f3f0c4967d2a
44,270
def dynamic_lisa_composite(rose, gdf, p=0.05, figsize=(13, 10)): """ Composite visualisation for dynamic LISA values over two points in time. Includes dynamic lisa heatmap, dynamic lisa rose plot, and LISA cluster plots for both, compared points in time. Parameters --...
1c950b2f96e834b8ae47b332db01b4cde9ce49e1
44,271
def brick_get_connector_properties(multipath=False, enforce_multipath=False): """Wrapper to automatically set root_helper in brick calls. :param multipath: A boolean indicating whether the connector can support multipath. :param enforce_multipath: If True, it raises exception when mul...
1f00e446d0effd6fbc077c464a83575d8ec49ee9
44,272
def vandermond(X): """ Create a vandermond matrix(nxn) by x values Parameters ---------- X : list list of x values Returns ------- np.array vandermond matrix """ n = len(X) V = np.zeros((n, n)) for i in range(n): V[i, :] = [X[i...
9912601b0cfae4b0b380585f8a6f7541336a436f
44,273
from sys import version def bbknn( adata, batch_key="batch", use_rep="X_pca", approx=True, use_annoy=True, metric="euclidean", copy=False, **kwargs ): """ Batch balanced KNN, altering the KNN procedure to identify each cell's top neighbours in each batch separately instead ...
a36395e37a1b90fa9bca8aa5b3fc047f85f8e20d
44,274
import sys def point_on_line(p1, p2, point): """Checks if a point falls along a given line segment. Args: p1 (tuple): The (x, y) coordinates of the starting point of the line. p2 (tuple): The (x, y) coordinates of the end point of the line. point (tuple): The (x, y) coordinates to tes...
13c5746c306ad122b5ac27bc77b25afd0f80ac7b
44,275
def fn_col_mapping_dict_for_rename(df): """Return a column mapping dictionary with column name and associated column index number. This can be used to assign new column names""" return {c[1]:c[1] for c in enumerate(df.columns)}
973dbbc6cb5ae6bb52dcc0e5cec3b310b139ec96
44,276
import yaml def do_query(archives, config_file=None, logger=None, context=None): """ Gets concordance and collocation analysis for keywords giving a target word, and it groups the results by date. The window variable can be used for specifying the number of words to the right and left to take. ...
3db0398dbcf0fe531e76615dc8544e3b2bf2b48f
44,277
def first_inside_quotes(s): """ Returns the first substring of s between two (double) quotes A quote character is one that is inside a string, not one that delimits it. We typically use single quotes (') to delimit a string if want to use a double quote character (") inside...
77a43d8bc2a88c44051f653add184d2bb705425f
44,278
def pc_upsampling(xyz_upsample, xyz, feat, scope='upsampling'): """ Fully connected layer with non-linear operation. Args: xyz_upsample: 3-D tensor B x N2 x 3 xyz: 3-D tensor B x N x 3 feat: 3-D tensor B x N x C Returns: feat_upsample: 3-...
a1544d542138d3294b84e4823f6a3054098154e1
44,279
import random from os.path import join, expanduser import cv2 def get_background_training_patches2( ibs, target_species, dest_path=None, patch_size=48, patch_size_min=0.80, patch_size_max=1.25, annot_size=300, patience=20, patches_per_annotation=30, global_limit=None, train...
244f7158a63f853e598dd00b7f328c90df173cca
44,280
def prob3(num=600851475143): """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ a = [] b = 1 i = 3 while True: if b == num: break elif num % i == 0: b *= i a.append(i)...
f0689232bf53152d87a6e28ffe4cce98908bca4f
44,281
def save(eid): """ Saves the coworker to the database. This function calls on the `app.utils.update_coworker_info` function. :param eid: The `eid` of the song to be saved. :type eid: int :returns: Redirects to the `/coworkers/` page (master table). """ update_coworker_info(request=requ...
d7a3155589dfd3aea0598dcd5b4f61e65e8434ca
44,282
from typing import Type from pydantic import BaseModel # noqa: E0611 def is_compatible_type(type: Type) -> bool: """Returns `True` if the type is opyrator-compatible.""" try: if issubclass(type, BaseModel): return True except Exception: pass try: # valid list type...
09383adcc4c93f05e1509cc97b181ae1ba98cec6
44,283
from typing import Sequence from typing import Tuple def get_all_namespaces_for_service( service: str, soa_dir: str = DEFAULT_SOA_DIR, full_name: bool = True ) -> Sequence[Tuple[str, ServiceNamespaceConfig]]: """Get all the smartstack namespaces listed for a given service name. :param service: The servic...
595efe335de763069257f00d5bcb05b75cf6bbdc
44,284
def normal(shape, mean, stddev, seed=0): """ Generates random numbers according to the Normal (or Gaussian) random number distribution. It is defined as: Args: shape (tuple): The shape of random tensor to be generated. mean (Tensor): The mean μ distribution parameter, which specifies th...
1d5422b2f9fe742ab27aeabb81ac5598626270fd
44,285
def circle(**kwargs) -> Expando: """ Draw a circle. See https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle Args: kwargs: Attributes to use for the initial render. SVG attributes, snake-cased. Returns: Data for the graphical element. """ return _el('c', kwargs)
2f52334cc232d45bcce9b47aba0954312c189625
44,286
import subprocess def merge_windows_in_cc(cc_idx, opts): """ Merge the consensus sequences from all windows into one sequence (contig). Parameters ---------- cc_idx : int (index of the connected component) opts : dict (keywords arguments for global parameters) """ # Parse arguments T...
70329cbe18eab18b2ec9e16216ab4fb3f366af1e
44,287
def display_loss_curve(losses, save_location: str=None): """ Plots and displays the loss curve (usually for Neural Network models) Parameters ---------- save_location : str the location to save the figure on disk. If None, the plot is displayed on runtime and not saved. losses : numpy.a...
901d7f2e01ece1a62e7e2b92b6bae7334be6ddbc
44,288
def is_turkish_id(x): """ checks if given id is valid TC ID """ if len(str(x)) != 11: return False str_id = str(x) # first 10 digit sum mod 10 equals 11th digit control lst_id = [int(n) for n in str_id if n.isdigit()] if lst_id[0] == 0: return False # first 10 digit...
c24b233fd74b5c45f6aff752bb57ae12a296d6b5
44,289
def L_p ( x ): """ Calculates the sound pressure level from the sound pressure squared: L_p = 10 lg x/4e-10 Parameters ---------- x: array of floats The squared sound pressure values Returns ------- array of floats The corresponding sound pressure levels...
286ed236b9414ac2ab040a1cda9a4acfa429b0b7
44,290
def get_abs_path(path: str) -> str: """ Returns absolute path Parameters ---------- path : str . """ return os_path.abspath(path) if path else None
3b6fd0aba5eaafc9e1ed8239a9eca9fcd0ee1599
44,291
import time def index(): """ This function renders the Index page for application. It shows list of all messages logged by all bots and also provides a form for filtered messages. Upon filtering, it redirects to a page showing filtered messages. :return: ../index """ # get all messages. ...
61f23e94dd25732f4bae9092b5c978b4fecbf323
44,292
def _make_unique(l): """Check that all values in list are unique and return a pruned and sorted list.""" return sorted(set(l))
18ae627f2a8f5dc8c61a332b73d8bd99c41d5ced
44,293
import ast def parse_preproc_line(line, preproc_defs): """Parse a preprocessor line into a tree that can be evaluated""" # Scan line and translate to python syntax inchar = None # Character context line_len = len(line) pline = "" index = 0 while index < line_len: if (line[index] ==...
ce15b82d1162d7b064204dee45fed048b66e9ffa
44,294
def group_by_area(units): """Create a dictionary containing lists of UnitGroup objects by area.""" areas = [ID_area(i.ID) for i in units] groups = {i: [] for i in sorted(set(areas))} for a, u in zip(areas, units): groups[a].append(u) return groups
8f12827411ea0656bd3eefd13ea99d736f16a571
44,295
def render_to_mail(template, context, **kwargs): """ Renders a mail and returns the resulting ``EmailMultiAlternatives`` instance * ``template``: The base name of the text and HTML (optional) version of the mail. * ``context``: The context used to render the mail. This context instance ...
8c587535f202d8b66996d075704b64a6df2f3549
44,296
def filledprf(x0, y0, sigma, n=0.2, res=100): """ Fill the pRF centered in x0, y0 and radius sigma Arguments --------- x0 : int column for center y0 : int row for center sigma : float standard deviation of the pRF n : float power exponent res : int ...
1a5c3c903f63a9ffda2f23b13e2c23752470d7c8
44,297
def post_info(request, post, put_content=False): """Return a hash with post fields (content is omitted for performance).""" data = { 'title': post.title, 'subject': post.subject, 'publication_date': post.pub_date, 'author': post.author.username, 'path': post.path, ...
4092b20a76c8a1b140a9b6faa534ffe9e5c2aac4
44,298
def get_CommodityDef(): """ get commodity definition settings """ file_country = "../Input/2_commodity/01_MainCommodity.csv" dt_data = genfromtxt(file_country, dtype = str, skip_header=1, delimiter=',') lsCommodity = list() for row in dt_data: lsCommodity.append(cls_misc.Commodity(...
f7516e94a451b0f7e89d4ead735cac0fff60eb24
44,299