content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def requires_site(site): """Skip test based on where it is being run""" skip_it = bool(site != SITE) return pytest.mark.skipif(skip_it, reason='SITE is not %s.' % site)
b436e6390828af2ffdca6e972b5a55fccafed64b
13,000
import traceback def handle_error(e): """ Handle errors, formatting them as JSON if requested """ error_type = type(e).__name__ message = str(e) trace = None description = None status_code = 500 if isinstance(e, werkzeug.exceptions.HTTPException): status_code = e.code ...
c2b1b3d3e9b97c9c28896d2ef04e2f33b64d6a18
13,001
def iou(bbox_1, bbox_2): """Computes intersection over union between two bounding boxes. Parameters ---------- bbox_1 : np.ndarray First bounding box, of the form (x_min, y_min, x_max, y_max). bbox_2 : np.ndarray Second bounding box, of the form (x_min, y_min, x_max, y_max). Re...
c076290d386a2c6740f7cd6aaee18a42f9c850ce
13,002
def GetIntensityArray(videofile, threshold, scale_percent): """Finds pixel coordinates within a videofile (.tif, .mp4) for pixels that are above a brightness threshold, then accumulates the brightness event intensities for each coordinate, outputting it as a 2-D array in the same size as the video frame...
720b50da3eb04698c62b2afa67ca3cd7b4f3661d
13,003
def _check_data(handler, data): """Check the data.""" if 'latitude' not in data or 'longitude' not in data: handler.write_text("Latitude and longitude not specified.", HTTP_UNPROCESSABLE_ENTITY) _LOGGER.error("Latitude and longitude not specified.") return Fals...
829681db92b0b7a6368ca143b6c656b46c972430
13,004
import requests from bs4 import BeautifulSoup def get_soup(page_url): """ Returns BeautifulSoup object of the url provided """ try: req = requests.get(page_url) except Exception: print('Failed to establish a connection with the website') return if req.status_code == 404: ...
d837e3b6aa6184285857428b2c796172379f3a1f
13,005
def foreign_key_constraint_sql(table): """Return the SQL to add foreign key constraints to a given table""" sql = '' fk_names = list(table.foreign_keys.keys()) for fk_name in sorted(fk_names): foreign_key = table.foreign_keys[fk_name] sql += "FOREIGN KEY({fn}) REFERENCES {tn}({kc}), ".fo...
0883050d2b9d302ab9099ef27abd400e4d4fe69e
13,006
from typing import Optional def expandDimConst(term: AST.PPTerm, ntId: int) -> Optional[AST.PPTerm]: """ Expand dimension constant to integer constants (Required for fold zeros) """ nt = ASTUtils.getNthNT(term, ntId) if type(nt.sort) != AST.PPDimConst: return None s...
b048d8ed0ec743a88c17a1f120a57d5e548e7d69
13,007
from scipy.optimize import minimize_scalar def _fit_amplitude_scipy(counts, background, model, optimizer='Brent'): """ Fit amplitude using scipy.optimize. Parameters ---------- counts : `~numpy.ndarray` Slice of count map. background : `~numpy.ndarray` Slice of background map....
51faafd7a81ff70196075bacac6b36db6b7e09f8
13,008
import psutil import subprocess def account_key__sign(data, key_pem=None, key_pem_filepath=None): """ This routine will use crypto/certbot if available. If not, openssl is used via subprocesses :param key_pem: (required) the RSA Key in PEM format :param key_pem_filepath: (optional) the filepath t...
bc7ee73fe71a54937ef8626f2b54d14f800badd1
13,009
from pathlib import Path def get_world_paths() -> list: """ Returns a list of paths to the worlds on the server. """ server_dir = Path(__file__).resolve().parents[1] world_paths = [] for p in server_dir.iterdir(): if p.is_dir and (p / "level.dat").is_file(): world_paths.app...
bf1c23c6a1c928dc66470db2e11b49ad2fc9e5d9
13,010
def derivative_p(α_L, α_G, ρ_G, v_L, v_G): # (1) """ Calculates pressure spatial derivative to be pluged into the expression for pressure at the next spatial step (see first equation of the model). It returns the value of pressure spatial derivative at the current time step and, hence, t...
e2aa8a4967b121b798058aa963b0685080b7eb8b
13,011
def fit_sigmoid(colors, a=0.05): """Fits a sigmoid to raw contact temperature readings from the ContactPose dataset. This function is copied from that repo""" idx = colors > 0 ci = colors[idx] x1 = min(ci) # Find two points y1 = a x2 = max(ci) y2 = 1-a lna = np.log((1 - y1) / y1) ...
2024e32cd454cb27cf3d0fef9f270a22abba5ea0
13,012
def deprecated(func): """Decorator for reporting deprecated function calls Use this decorator sparingly, because we'll be charged if we make too many Rollbar notifications """ @wraps(func) def wrapped(*args, **kwargs): # try to get a request, may not always succeed request = get_cur...
d01f53acd584faa3c3b15771c76a00210ffbeb83
13,013
from sys import path def read_file(path_file: path) -> str: """ Reads the content of the file at path_file :param path_file: :return: """ content = None with open(path_file, 'r') as file: content = file.read() return content
0a49a13ddc855abfdbb4cefd2396a7832c1e26a8
13,014
import bisect def absorptionCoefficient_Voigt(Components=None,SourceTables=None,partitionFunction=PYTIPS, Environment=None,OmegaRange=None,OmegaStep=None,OmegaWing=None, IntensityThreshold=DefaultIntensityThreshold, OmegaW...
6c4b909999ea4e6cc14bae7fbda04f2b6ba6ddb8
13,015
def stellar_mags_scatter_cube_pair(file_pair, min_relative_flux=0.5, save=False): """Return the scatter in stellar colours within a star datacube pair.""" hdulist_pair = [pf.open(path, 'update') for path in file_pair] flux = np.vstack( [hdulist[0].data for hdulist in hdulist_pair]) noise = np.sq...
b1f823a9ab33f7deadb1651aaa728690b0a08cf6
13,016
import os def get_data_filename(relative_path): """Get the full path to one of the reference files shipped for testing In the source distribution, these files are in ``examples/*/``, but on installation, they're moved to somewhere in the user's python site-packages directory. Parameters ----...
3e400d6b386c5b5a1be7c6f89bd219329258514f
13,017
import hmac import hashlib def is_valid_webhook_request(webhook_token: str, request_body: str, webhook_signature_header: str) -> bool: """This method verifies that requests to your Webhook URL are genuine and from Buycoins. Args: webhook_token: your webhook token request_body: the body of the...
1ce1ef0a9e1386ebbea7773d8cd9d40df2544792
13,018
import torch def logsigsoftmax(logits): """ Computes sigsoftmax from the paper - https://arxiv.org/pdf/1805.10829.pdf """ max_values = torch.max(logits, 1, keepdim=True)[0] exp_logits_sigmoided = torch.exp(logits - max_values) * torch.sigmoid(logits) sum_exp_logits_sigmoided = exp_logits_sigmo...
d7f6c2ef4279d511ff81fc30cfa1db5875c5ea4a
13,019
def multi(dispatch_fn): """Initialise function as a multimethod""" def _inner(*args, **kwargs): return _inner.__multi__.get( dispatch_fn(*args, **kwargs), _inner.__multi_default__ )(*args, **kwargs) _inner.__multi__ = {} _inner.__multi_default__ = lambda *args, *...
29023826b3e67ccc39a458fc90bd817cd725c35f
13,020
def choose_key(somemap, default=0, prompt="choose", input=input, error=default_error, lines=LINES, columns=COLUMNS): """Select a key from a mapping. Returns the key selected. """ keytype = type(print_menu_map(somemap, lines=lines, columns=columns)) while 1: try: us...
d3c2438c85afae48980f772a06a7e622866197c5
13,021
import os def image_model_saver(image_model, model_type, output_directory, training_dict, labels1, labels2, preds, results1, results2): """ Saves Keras image model and other outputs image_model: Image model to be saved model_type (string): Name of model output_directory: Directory to fo...
044674f289a73be4e285ccd472fc5428e419e080
13,022
from typing import Tuple def predicted_orders( daily_order_summary: pd.DataFrame, order_forecast_model: Tuple[float, float] ) -> pd.DataFrame: """Predicted orders for the next 30 days based on the fit paramters""" a, b = order_forecast_model start_date = daily_order_summary.order_date.max() future...
48f79b1076c32f93bdf148d1b986c6892cd3a8af
13,023
import subprocess def _try_command_line(command_line): """Returns the output of a command line or an empty string on error.""" _logging.debug("Running command line: %s" % command_line) try: return subprocess.check_output(command_line, stderr=subprocess.STDOUT) except Exception as e: _print_process_err...
b37c67fbcaf28a7fdd7b7cd5fbafc2b2e9561f9f
13,024
import torch import tqdm def eval_loop(model, ldr, device): """Runs the evaluation loop on the input data `ldr`. Args: model (torch.nn.Module): model to be evaluated ldr (torch.utils.data.DataLoader): evaluation data loader device (torch.device): device inference will be run on ...
ca96192b1cd104ea3c86b5c5234ab5bf708613c8
13,025
def get_total_frts(): """ Get total number of FRTs for a single state. Arguments: Returns: {JSON} -- Returns headers of the columns and data in list """ query = """ SELECT place.state AS state , COUNT(DISTINCT frt.id) AS state_total FROM ...
0f054ef795f09ea01b28c139fd353bf237ed10a4
13,026
def newton_sqrt(n: float, a: float) -> float: """Approximate sqrt(n) starting from a, using the Newton-Raphson method.""" r = within(0.00001, repeat_f(next_sqrt_approx(n), a)) return next(r)
4d7186bd55e4f4d4511078bcb0fff4959a182a3b
13,027
def prismatic(xyz, rpy, axis, qi): """Returns the dual quaternion for a prismatic joint. """ # Joint origin rotation from RPY ZYX convention roll, pitch, yaw = rpy[0], rpy[1], rpy[2] # Origin rotation from RPY ZYX convention cr = cs.cos(roll/2.0) sr = cs.sin(roll/2.0) cp = cs.cos(pitch/2...
898db39d01a7b26daf2657c69c42af12bd8fef60
13,028
def markov_chain(bot_id, previous_posts): """ Caches are triplets of consecutive words from the source Beginning=True means the triplet was the beinning of a messaeg Starts with a random choice from the beginning caches Then makes random choices from the all_caches set, constructing a markov chain ...
652690d61c97de420e88f53cfd05c5d59e9229af
13,029
from re import T def SurfaceNet_fn_trainVal(N_viewPairs4inference, default_lr, input_cube_size, D_viewPairFeature, \ num_hidden_units, CHANNEL_MEAN, return_train_fn=True, return_val_fn=True, with_weight=True): """ This function only defines the train_fn and the val_fn while training process. ...
47734ee865738706a68bc62a1d0c51db3b1b4c46
13,030
def _assign_data_radial(root, sweep="sweep_1"): """Assign from CfRadial1 data structure. Parameters ---------- root : xarray.Dataset Dataset of CfRadial1 file sweep : str, optional Sweep name to extract, default to first sweep. If None, all sweeps are extracted into a list. ...
7734917c8b4aced4812896e3269981c984241202
13,031
def get_memory_usage(): """This method returns the percentage of total memory used in this machine""" stats = get_memstats() mfree = float(stats['buffers']+stats['cached']+stats['free']) return 1-(mfree/stats['total'])
27bcf8866b6b57253acf6a282265949dcfd3af61
13,032
def gamma0(R, reg=1e-13, symmetrize=True): """Integrals over the edges of a triangle called gamma_0 (line charge potentials). **NOTE: MAY NOT BE VERY PRECISE FOR POINTS DIRECTLY AT TRIANGLE EDGES.** Parameters ---------- R : (N, 3, 3) array of points (Neval, Nverts, xyz) Returns -----...
c3ed9c624a5f14922d3c76a3eb2ae2f616f82cac
13,033
def is_even(x): """ True if obj is even. """ return (x % 2) == 0
f19563063515eb4d39b8b607cf68f6f188af409e
13,034
def get_http_proxy(): """ Get http_proxy and https_proxy from environment variables. Username and password is not supported now. """ host = conf.get_httpproxy_host() port = conf.get_httpproxy_port() return host, port
f04dc8580d9fdd3d867c5b28fa3694fe82a6739a
13,035
def get_parser_udf( structural=True, # structural information blacklist=["style", "script"], # ignore tag types, default: style, script flatten=["span", "br"], # flatten tag types, default: span, br language="en", lingual=True, # lingual information lingual_parser=None, strip=True, r...
cf12b36fe9219aabfd746b2ad1f1f39e62ad7fe9
13,036
def img_preprocess2(image, target_shape,bboxes=None, correct_box=False): """ RGB转换 -> resize(resize不改变原图的高宽比) -> normalize 并可以选择是否校正bbox :param image_org: 要处理的图像 :param target_shape: 对图像处理后,期望得到的图像shape,存储格式为(h, w) :return: 处理之后的图像,shape为target_shape """ h_target, w_target = target_shap...
e950e0e8cca4f31449feb12203ee9a9ef74baa8c
13,037
def pivot_timeseries(df, var_name, timezone=None): """ Pivot timeseries DataFrame and shift UTC by given timezone offset Parameters ---------- df : pandas.DataFrame Timeseries DataFrame to be pivoted with year, month, hour columns var_name : str Name for new column describing da...
914ba75929caacd16da5170e98a95f2135a1682f
13,038
def _preprocess_stored_query(query_text, config): """Inject some default code into each stored query.""" ws_id_text = " LET ws_ids = @ws_ids " if 'ws_ids' in query_text else "" return '\n'.join([ config.get('query_prefix', ''), ws_id_text, query_text ])
bc63391724773cd4a60f3dc9686d243d6d733b40
13,039
def handler_request_exception(response: Response): """ Args: response (Response): """ status_code = response.status_code data = response.json() if "details" in data and len(data.get("details")) > 0: data = data.get("details")[0] kwargs = { "error_code": data.get("err...
8847b4a1fd6f90d6e25d0ef8dc33a32e38e81617
13,040
import abc import sys def n_real_inputs(): """This gives the number of 'real' inputs. This is determined by trimming away inputs that have no connection to the logic. This is done by the ABC alias 'trm', which changes the current circuit. In some applications we do not want to change the circuit, but just...
ed4f87bc9a380df4d650019b5c60a836eeeeea30
13,041
import os def get_stats_for_dictionary_file(dictionary_path): """Calculate size of manual and recommended sections of given dictionary.""" if not dictionary_path or not os.path.exists(dictionary_path): return 0, 0 dictionary_content = utils.read_data_from_file( dictionary_path, eval_data=False) dic...
f149e4cfcde6b61345b15d773bca8d4f7a32410b
13,042
def mlrPredict(W, data): """ mlrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of size...
18bf0c86195cf144eb63f5b6c440f92c57d2fe9b
13,043
from .error_pages import add_error_pages from .global_variables import init_global from .home import home_page from .rules import rule_page from .create_game import create_game_page, root_url_games from .global_stats import global_stats_page, page_url from .utils.add_dash_table import add_dash as add_dash_table from .u...
665ab7beda7ff79e4b81c22d5f28409a31dc896f
13,044
def process_integration(request, case_id): """Method to process case.""" try: case = OVCBasicCRS.objects.get(case_id=case_id, is_void=False) county_code = int(case.county) const_code = int(case.constituency) county_id, const_id = 0, 0 crs_id = str(case_id).replace('-', ''...
bd383b624a072fec634bc28bbba71c2d635eeac2
13,045
def get_aabb(pts): """axis-aligned minimum bounding box""" x, y = np.floor(pts.min(axis=0)).astype(int) w, h = np.ceil(pts.ptp(axis=0)).astype(int) return x, y, w, h
68cffaf0b1cacf702a2dd3c6c22af6323d220e93
13,046
from re import S def _solve(f, *symbols, **flags): """Return a checked solution for f in terms of one or more of the symbols. A list should be returned except for the case when a linear undetermined-coefficients equation is encountered (in which case a dictionary is returned). If no method is imp...
af2c8de5f2ee7cdfc41856ffe438c2bf0fcaee78
13,047
import numpy def get_object_ratio(obj): """Calculate the ratio of the object's size in comparison to the whole image :param obj: the binarized object image :type obj: numpy.ndarray :returns: float -- the ratio """ return numpy.count_nonzero(obj) / float(obj.size)
fd18e460be32037c73fe75c8fa5eef5ba6c1c217
13,048
def get_region(ds, region): """ Return a region from a provided DataArray or Dataset Parameters ---------- region_mask: xarray DataArray or list Boolean mask of the region to keep """ return ds.where(region, drop=True)
102b672f8040b722ec346435775cba1056485ae2
13,049
def read_borehole_file(path, fix_df=True): """Returns the df with the depths for each borehole in one single row instead instead being each chunck a new row""" df = pd.read_table(path, skiprows=41, header=None, sep='\t', ...
50c3df5a3d2aae2a0f58b555380efb9fd63a90e1
13,050
def cpl_parse(path): """ Parse DCP CPL """ cpl = generic_parse( path, "CompositionPlaylist", ("Reel", "ExtensionMetadata", "PropertyList")) if cpl: cpl_node = cpl['Info']['CompositionPlaylist'] cpl_dcnc_parse(cpl_node) cpl_reels_parse(cpl_node) return cpl
a025bf82bdeac13d6c7cfbca95d667f2ae58c8f9
13,051
def notfound(): """Serve 404 template.""" return make_response(render_template('404.html'), 404)
d81d794bad67c8128b8f6e55dbc5383bda7a1405
13,052
from typing import Tuple from typing import List def read_network(file: str) -> Tuple[int, int, List[int]]: """ Read a Boolean network from a text file: Line 1: number of state variables Line 2: number of control inputs Line 3: transition matrix of the network (linear representation of...
217bd86f8d00cf27cf80d1a199b76b023a374f10
13,053
import os import fnmatch import shutil def copy(srcpath, destpath, pattern=None, pred=_def_copy_pred): """ Copies all files in the source path to the specified destination path. The source path can be a file, in which case that file will be copied as long as it matches the specified pattern. ...
daa4487e77642319f04a0556c238f84e47f513cf
13,054
def bundle_products_list(request,id): """ This view Renders Bundle Product list Page """ bundle = get_object_or_404(Bundle, bundle_id=id) bundleProd = BundleProducts.objects.filter(bundle=id) stocks = Stock.objects.all() context = { "title": "Bundle Products List", "bundle": b...
3afef4fdd2886300bc2fbda306bc05b499a47d0f
13,055
def rot_x(theta): """ Rotation matrix around X axis :param theta: Rotation angle in radians, right-handed :return: Rotation matrix in form of (3,3) 2D numpy array """ return rot_axis(0,theta)
d4a892ed5ede6ffd2353b0121bec640e81c23ec7
13,056
def ValidateEntryPointNameOrRaise(entry_point): """Checks if a entry point name provided by user is valid. Args: entry_point: Entry point name provided by user. Returns: Entry point name. Raises: ArgumentTypeError: If the entry point name provided by user is not valid. """ return _ValidateArgum...
7175e63562b04aba430044e0898db7368b68fb23
13,057
def park2_4_z(z, x): """ Computes the Parkd function. """ y1 = x[0][0] y2 = x[0][1] chooser = x[1] y3 = (x[2] - 103.0) / 91.0 y4 = x[3] + 10.0 x = [y1, y2, y3, y4] if chooser == 'rabbit': ret = sub_park_1(x) elif chooser == 'dog': ret = sub_park_2(x) elif chooser == 'gerbil': ret = sub_p...
458ba79ada010b3c93419719b68f7a953908b184
13,058
import re def get_string_coords(line): """return a list of string positions (tuple (start, end)) in the line """ result = [] for match in re.finditer(STRING_RGX, line): result.append( (match.start(), match.end()) ) return result
a8fd7443ce242ce4f84196947fb4d82c2ff0d20e
13,059
def array_from_pixbuf(p): """Convert from GdkPixbuf to numpy array" Args: p (GdkPixbuf): The GdkPixbuf provided from some window handle Returns: ndarray: The numpy array arranged for the pixels in height, width, RGBA order """ w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channel...
da2e980d804c283e2993049c63e3dacf67f7f0bd
13,060
def entropy(x,k=3,base=2): """ The classic K-L k-nearest neighbor continuous entropy estimator x should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ assert k <= len(x)-1, "Set k smaller than num. samples - 1" d = len(x[0]) N...
41d55d2bef2475ece27a487afb1e54d433bad5f0
13,061
import logging def respond_to_command(slack_client, branch, thread_ts): """Take action on command.""" logging.debug("Responding to command: Deploy Branch-%s", branch) is_production = False if branch == 'develop': message = "Development deployment started" post_to_channel(slack_client, ...
b008456d94cdd7e52e626ddd386ed2606cb22f02
13,062
from typing import Optional def s3upload_start( request: HttpRequest, workflow: Optional[Workflow] = None, ) -> HttpResponse: """Upload the S3 data as first step. The four step process will populate the following dictionary with name upload_data (divided by steps in which they are set STEP 1...
b3fc1ac6c3754df836d8c219b0fb416f9d5973ce
13,063
def search_explorations(query, limit, sort=None, cursor=None): """Searches through the available explorations. args: - query_string: the query string to search for. - sort: a string indicating how to sort results. This should be a string of space separated values. Each value should start ...
bead5de6f9803a7715ad497bb1f5c22da1faf296
13,064
import pkgutil def find_resourceadapters(): """ Finds all resource adapter classes. :return List[ResourceAdapter]: a list of all resource adapter classes """ subclasses = [] def look_for_subclass(module_name): module = __import__(module_name) d = module.__dict__ for...
3aab6e6b28fa69cf9e7b1c8bc04589c69e43a3ee
13,065
def print_scale(skill, points): """Return TeX lines for a skill scale.""" lines = ['\\cvskill{'] lines[0] += skill lines[0] += '}{' lines[0] += str(points) lines[0] += '}\n' return lines
c88de0c6db9e7b92dbcee025f42f56817a4aa033
13,066
from typing import Union from typing import TextIO from typing import BinaryIO import os import io def getsize(file: Union[TextIO, BinaryIO]) -> int: """ Overview: Get the size of the given ``file`` stream. :param file: File which size need to access. :return: File's size. Examples:: ...
3b88fc21c52b53ad13dcbfd074542f4b392450d8
13,067
def print_(fh, *args): """Implementation of perl $fh->print method""" global OS_ERROR, TRACEBACK, AUTODIE try: print(*args, end='', file=fh) return True except Exception as _e: OS_ERROR = str(_e) if TRACEBACK: cluck(f"print failed: {OS_ERROR}",skip=2) ...
8289aba67cb81b710d04da609ea63c65fa986e21
13,068
def _expm_multiply_interval(A, B, start=None, stop=None, num=None, endpoint=None, balance=False, status_only=False): """ Compute the action of the matrix exponential at multiple time points. Parameters ---------- A : transposable linear operator The operator whose exponential is of ...
941c4e2d51f0bf524beff52350466a743b51eadf
13,069
def subprocess(mocker): """ Mock the subprocess and make sure it returns a value """ def with_return_value(value: int = 0, stdout: str = ""): mock = mocker.patch( "subprocess.run", return_value=CompletedProcess(None, returncode=0) ) mock.returncode.return_value = value ...
4b7140127eeb2d9202ed976518a121fed5fac302
13,070
def ljust(string, width): """ A version of ljust that considers the terminal width (see get_terminal_width) """ width -= get_terminal_width(string) return string + " " * width
e9c6ab8bbeeb268bc82f479e768be32f74fab488
13,071
import operator def device_sort (device_set): """Sort a set of devices by self_id. Can't be used with PendingDevices!""" return sorted(device_set, key = operator.attrgetter ('self_id'))
92a22a87b5b923771cd86588180a8c6eb15b9fdf
13,072
def _ontology_value(curie): """Get the id component of the curie, 0000001 from CL:0000001 for example.""" return curie.split(":")[1]
7ef1f0874e698c498ccef16294c0469f67cd5233
13,073
import os def get_current_joblist(JobDir): """ -function to return current, sorted, joblist in /JobDir """ if os.path.exists(JobDir): jobdirlist = os.walk(JobDir).next()[1] jobdirlist.sort() return jobdirlist
79f8feb20ccdcb2984b81a236ddcd3cac6fcc351
13,074
def readpacket( timeout=1000, hexdump=False ): """Reads a HP format packet (length, data, checksum) from device. Handles error recovery and ACKing. Returns data or prints hexdump if told so. """ data = protocol.readpacket() if hexdump == True: print hpstr.tohexstr( data ) else: ...
d673e61974058fc73a47bd0e5856563c9f5370bf
13,075
def df_down_next_empty_pos(df, pos): """ Given a position `pos` at `(c, r)`, reads down column `c` from row `r` to find the next empty cell. Returns the position of that cell if found, or `None` otherwise. """ return df_down_next_matching_pos(df, pos, pd.isna)
79fdba60e6a5846c39fb1141f3d21430230c2a31
13,076
def optimise_f2_thresholds(y, p, verbose=False, resolution=100): """Optimize individual thresholds one by one. Code from anokas. Inputs ------ y: numpy array, true labels p: numpy array, predicted labels """ n_labels = y.shape[1] def mf(x): p2 = np.zeros_like(p) for i in...
5f1ad6dda86229cffb7167f5cc3365c601048937
13,077
def holding_vars(): """ input This is experimental, used to indicate unbound (free) variables in a sum or list comprehensive. This is inspired by Harrison's {a | b | c} set comprehension notation. >>> pstream(holding_vars(),', holding x,y,z') Etok(holding_vars,', holding x , y , z') ...
5566bc97e2fa972b1ccde4d24f30fb06635bdcb7
13,078
import re def select_with_several_genes(accessions, name, pattern, description_items=None, attribute='gene', max_items=3): """ This will select the best description for databases where more than one gene (or other at...
04df56e64259aafd1e0d5b0d68839d8016514cb7
13,079
def list_messages_matching_query(service, user_id, query=''): """List all Messages of the user's mailbox matching the query. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. query:...
a6ec376d7cfb4a6c724646a0e4d9ac1b86526ae7
13,080
def write_to_string(input_otio, **profile_data): """ :param input_otio: Timeline, Track or Clip :param profile_data: Properties passed to the profile tag describing the format, frame rate, colorspace and so on. If a passed Timeline has `global_start_time` set, the frame rate will be set automatical...
36a0e7fe741b4c216bd068b8544d68c63176d679
13,081
import re def parse_IS(reply: bytes, device: str): """Parses the reply to the shutter IS command.""" match = re.search(b"\x00\x07IS=([0-1])([0-1])[0-1]{6}\r$", reply) if match is None: return False if match.groups() == (b"1", b"0"): if device in ["shutter", "hartmann_right"]: ...
827b5ebf5c98bcc65b823276d5ab5b8086a2c069
13,082
def quatXYZWFromRotMat(rot_mat): """Convert quaternion from rotation matrix""" quatWXYZ = quaternions.mat2quat(rot_mat) quatXYZW = quatToXYZW(quatWXYZ, 'wxyz') return quatXYZW
2a0a736c3950dca481c993e9801e14b362f78940
13,083
import sqlite3 def schema_is_current(db_connection: sqlite3.Connection) -> bool: """ Given an existing database, checks to see whether the schema version in the existing database matches the schema version for this version of Gab Tidy Data. """ db = db_connection.cursor() db.execute( ...
183502c292f9bb92e18a4ea7767028bea4e746fb
13,084
import xattr def xattr_writes_supported(path): """ Returns True if the we can write a file to the supplied path and subsequently write a xattr to that file. """ try: except ImportError: return False def set_xattr(path, key, value): xattr.setxattr(path, "user.%s" % key, val...
4992f2f5808575eac1f816aa09d80ff881286368
13,085
def _lovasz_softmax(probabilities, targets, classes="present", per_image=False, ignore=None): """The multiclass Lovasz-Softmax loss. Args: probabilities: [B, C, H, W] class probabilities at each prediction (between 0 and 1). Interpreted as binary (sigmoid) output wit...
c46006c921d1f40b5b86ff861750a9d89ec4bbdc
13,086
def encodeDERTRequest(negoTypes = [], authInfo = None, pubKeyAuth = None): """ @summary: create TSRequest from list of Type @param negoTypes: {list(Type)} @param authInfo: {str} authentication info TSCredentials encrypted with authentication protocol @param pubKeyAuth: {str} public key encrypted wit...
bba9ed483eec2ef39927689a8924cbcc15a2093e
13,087
import os def generate_s3_strings(path): """Generates s3 bucket name, s3 key and s3 path with an endpoint from a path with path (string): s3://BUCKETNAME/KEY x --> path.find(start) returns index 0 + len(start) returns 5 --> 0 + 5 = 5 Y --> path[len(start):] = BUCKENAME/KEY --> .find(end) l...
601b20514c93e2159f9d5747063ce70d265d6e6e
13,088
def hierholzer(network: Network, source=0): """ Hierholzer's algorithm for finding an Euler cycle Args: network (Network): network object source(int): node where starts (and ends) the path Raises: NotEulerianNetwork: if exists at least one node with odd degree NotNetworkNod...
9a1fb1107e9a2b086d1716cea7708dba9849fb4e
13,089
def fit1d(xdata,zdata,degree=1,reject=0,ydata=None,plot=None,plot2d=False,xr=None,yr=None,zr=None,xt=None,yt=None,zt=None,pfit=None,log=False,colorbar=False,size=5) : """ Do a 1D polynomial fit to data set and plot if requested Args: xdata : independent variable zdata : dependent variable to be f...
0c40a2b1af72c0df8523a92cd5cc80c99f631472
13,090
import torch def nucleus_sampling(data, p, replace=0, ascending=False, above=True): """ :param tensor data: Input data :param float p: Probability for filtering (or be replaced) :param float replace: Default value is 0. If value is provided, input data will be replaced by this value if data m...
6332e9f5e04fa2ec0130fa2db7dd5a8aad26caec
13,091
from datetime import datetime import json def mark_ready_for_l10n_revision(request, document_slug, revision_id): """Mark a revision as ready for l10n.""" revision = get_object_or_404(Revision, pk=revision_id, document__slug=document_slug) if not revision.document.allows(r...
64d7d84ceab204a3d3fea98e9753fde486c4490c
13,092
def is_all_maxed_out(bad_cube_counts, bad_cube_maximums): """Determines whether all the cubes of each type are at their maximum amounts.""" for cube_type in CUBE_TYPES: if bad_cube_counts[cube_type] < bad_cube_maximums[cube_type]: return False return True
23332712b46d33a1a8e552ecf30389d4b0a10c90
13,093
def get_local_vars(*args): """ get_local_vars(prov, ea, out) -> bool """ return _ida_dbg.get_local_vars(*args)
ebed21c8b90c48e76734f07a5e83c11bf5b9dd0c
13,094
def gcc(): """ getCurrentCurve Get the last curve that was added to the last plot plot :return: The last curve :rtype: pg.PlotDataItem """ plotWin = gcf() try: return plotWin.plotWidget.plotItem.dataItems[-1] except IndexError: return None
2f9226c51a84d39b43f1d8ef83969b94a2c308cd
13,095
import requests import json def searchDevice(search): """ Method that searches the ExtraHop system for a device that matches the specified search criteria Parameters: search (dict): The device search criteria Returns: dict: The metadata of the device that matches ...
9b65346054f099e4a2aa78035802b2de799850ac
13,096
def regularmeshH8(nelx, nely, nelz, lx, ly, lz): """ Creates a regular H8 mesh. Args: nelx (:obj:`int`): Number of elements on the X-axis. nely (:obj:`int`): Number of elements on the Y-axis. nelz (:obj:`int`): Number of elements on the Z-axis. lx (:obj:`float`): X-axis length. ...
1c0050b8c48438f548e67f7776194a067c77ae39
13,097
def only_t1t2(src, names): """ This function... :param src: :param names: :return: """ if src.endswith("TissueClassify"): # print "Keeping T1/T2!" try: names.remove("t1_average_BRAINSABC.nii.gz") except ValueError: pass try: ...
60116fbc602bbe03f7c18776b623ef3680b9dfc1
13,098
def distanceEucl(a, b): """Calcul de la distance euclidienne en dimension quelconque""" dist = np.linalg.norm(a - b) return dist
572d98aecf17cd1f0e34dcad9e07beb3bcf6d06d
13,099