content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple def _plot_seeds(ax, df_da: TfsDataFrame, da_col: str, interpolated: bool) -> Tuple[list, list]: """Add the Seed lines to the polar plots, if df_da is given. Args: ax: Axes to plot in df_da: DataFrame with DA information da_col: Dynamic Aperture column (ALOST1 ...
9be8ff987e931e1de471128a045ffa601be4a9c2
38,100
def sockaddr_convert(val: SockaddrConvertType) -> sockaddr_base: """Try to convert address into some sort of sockaddr""" if ( isinstance(val, sockaddr_in) or isinstance(val, sockaddr_in6) or isinstance(val, sockaddr_storage) ): return val if isinstance(val, IPv4Address): ...
14eaba762bcf1a82752b5c97fa53fcfba345bd95
38,101
def scharr3_dxz( input, output=None, full=True, mode="reflect", cval=0.0): """Scharr 3 point first derivative along the 1st and last (x and z) axis of input. Applies a 3 point Scharr first derivative filter along the 1st and last (x and z) axis of the input array as per: Scharr, 2005: Optimal derivative filter ...
cadbf1421b45f074613cdf9c8dd6a4c6b69deec7
38,102
def forward_hierarchical_differences(graph, weight=None): """Returns the forward hierarchical differences over the edges of a network in the form of a weighted adjacency matrix Parameters ---------- graph : Graph, array A NetworkX graph or numpy/sparse array weight : string ...
becb91a9f535b55d304cc6db9e9f94268c5779d5
38,103
def get_exact_match(user_input, groups): """Return an exact match from the groups """ lower_groups = [group.lower() for group in groups] if user_input.lower() in lower_groups: return groups[lower_groups.index(user_input.lower())]
8d28c05106f308bc3f65e07b011003e968cee99d
38,104
def compute_perc_id(aln): """ Compute percent identity of aligned region on read """ length = len(aln.query_alignment_sequence) edit = dict(aln.tags)['NM'] return 100 * (length - edit)/float(length)
7bc172649a452fc0c26d4e40d3240d709fb76534
38,105
from datetime import datetime def getXRDExpiration(xrd_element, default=None): """Return the expiration date of this XRD element, or None if no expiration was specified. @type xrd_element: ElementTree node @param default: The value to use as the expiration if no expiration was specified in t...
50afee7f3456bfe5441f26879ff50d029a153d8a
38,106
import sys def main(): """main routine for iphotoexport.""" parser = OptionParser(usage=USAGE) parser.add_option( "-a", "--albums", help="""Export matching regular albums. The argument is a regular expression. Use -a . to export all regular albums.""") parser.add_option( "-d", "--...
f4628737b384e058d0b71f33d7a67f995e211dbf
38,107
def patient_is_account_owner_with_email(method): """ Verify if patient is a owner of request with email """ def wrap(request, email, *args, **kwargs): is_patient = hasattr(request.user, 'patient') is_owner = email == request.user.email if is_owner and is_patient: retu...
4ac0c4871da98903d4e8977a9de7746836962bbd
38,108
def get_byte_to_char_offset_mapping(text): """Get mapping from bytes positions to unicode code point positions.""" if not text: return {}, {} bytes_per_char = [len(c.encode('utf-8')) for c in text] bytes_per_char_cumsum = np.cumsum(bytes_per_char) char_begin_offset = np.roll(bytes_per_char_cumsum, 1) ch...
4b6f05199bfde789998ab889359d17085ba97d80
38,109
def get_total_time(locations: [str]) -> int: """ Gets the total time required on a trip to all of the given locations :param locations: The locations to get the total trip time for :return: An integer that is the number of minutes required to travel to all the given locations """ response = _get...
615f24f01f6d1c2fd85c3982264b5492dcf771cc
38,110
def sscf(ao_int, scf_params, e_nuc, mode = "minvar", logger_level = "normal"): """ Solve the sigma-SCF problem given AO integrals (ao_int [dict]): - T: ao_kinetic - V: ao_potential - g: ao_eri - S: ao_overlap - A: S^(-1/2) and parameters for SCF (scf_params [dict]): ...
11ddea4ac2f2d5e085f8ce17ea719a2fd420525d
38,111
def fetch_entities(project, namespace, query, datastore): """A helper method to fetch entities from Cloud Datastore. Args: project: Project ID namespace: Cloud Datastore namespace query: Query to be read from datastore: Cloud Datastore Client Returns: An iterator of entities. """ return ...
c157656a60c0854296f7d41a62b09e1631530b1f
38,112
def _add_composite_operator(A: np.ndarray, B: np.ndarray) -> np.ndarray: """Add composite operator. For more information about the add composite operator, see `Cairo Compositing Operators <https://www.cairographics.org/operators/>`_. Args: A (np.ndarray): Source image represented as 4-channel ...
02acc1c7d58393cd4056cfbe9d99ac20ec8c87b7
38,113
def select_user(allow_root=False): """ Have the user select from a list of users with home directories. Args: allow_root - (optional) Include the root user in the list (True or False) """ user_list = get_user_list(allow_root) questions = [ inquirer.List('u', ...
2dea731aeb225df0a0ada60cdee3b0ca01c516ac
38,114
from .task import delete_task import shutil def delete_project(data, workspace): """删除project和与project相关的task Args: data为dict,key包括 'pid'项目id """ proj_id = data['pid'] assert proj_id in workspace.projects, "项目ID'{}'不存在.".format(proj_id) tids = list() for key in workspace....
499cf4d161f9658b6be7b24e3c6abb01783bd9a3
38,115
from datetime import datetime def roundTime(dt=None, roundTo=60): """Round a datetime object to any time lapse in seconds dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 1 minute. Author: Thierry Husson 2012 - Use it as you want but don't blame me. ...
314408b79196b96dba28fd23bf9656d63ebdb567
38,116
def neighborhood_tally(df_pop, pwmat, x_cols, df_centroids=None, count_col='count', knn_neighbors=50, knn_radius=None): """Forms a cluster around each row of df and tallies the number of instances with/without traits in x_cols. The contingency table for each cluster/row of df can be used to test for enrichments...
0adf685ca0199f0e094d1adf8d38098d1311336f
38,117
def prox_soft_plus(X, step, thresh=0): """Soft thresholding with projection onto non-negative numbers """ return prox_plus(prox_soft(X, step, thresh=thresh), step)
e96aca969d049352de5fe575b98fcda8a80ddb86
38,118
def axisym_u(Rcp, Zcp, r, z, omega_t, epsilon=0): """ Velocity field from distribution of tangential vorticity INPUTS: - Rcp, Zcp: array or control points coordinates, where velocity will be computed - r, z : 1d-array or points where vorticity is defined - omega_t : 2d-array consistent wi...
78c627eceb9b6b2a7cbd960b953c82f2cd748f96
38,119
def Expression(tokenizer, staticContext): """ Top-down expression parser for stylestyles. """ node = AssignExpression(tokenizer, staticContext) if tokenizer.match("comma"): childNode = Node.Node(tokenizer, "comma") childNode.append(node) node = childNode while True...
27dd3670a9623151df49c895c80c974317c836b2
38,120
def generate_guid(entry): """Generate missing guid for post entry.""" return md5sum("|".join(safe_encode(entry.get(key) or "") for key in GUID_FIELDS))
44238ec850d7df74fb5fa0a1430328fb8719fc56
38,121
import re def _validate_defn(value, path, val_type, val_opts): """ Validate a compound type definition. We want to validate a value against a definition like: :: cred_key: one_of: - str: str() - EnvironmentVar: str() - KeyVault: str(...
b3b2bcbfd569b95c33befb84fd6e57b5bc47d0db
38,122
from datetime import datetime def now(timeformat='date'): """ Returns the current time in the specified timeformat. :param timeformat: the target format for the time conversion. May be: '*date*' (default - outputs a ``datetime.datetime`` object), '*unix*' (outputs a long UNIXtime) or '*is...
6d390381adfe63ae4800311ec0c7b26533eccf35
38,123
from pathlib import Path def check_pfam_db(path): """Check if Pfam-A db exists else download Args: path: String, path where to check """ path = Path(path) if path.exists() and not path.is_dir(): raise FileExistsError("Expected directory") if not path.exists(): path.m...
93a5f8cd4d204e68ec32934d269fc55d145a0352
38,124
def geo_dist(point1, point2, units='deg'): """Function returns geographic distance between two points""" return np.linalg.norm(geog2ecef(point1, units) - geog2ecef(point2, units))
94558374ee788ccef29b1a2eeef6e1a21db5ff10
38,125
def prepare_models(encoder_config, transformer_config, replica_batch_size, verbose=0): """This function is used to initiate the Encoder and the Transformer with appropriate configs set by the user. After initiating the models this function returns the Encoder,Transformer and the optimizer. Args: ...
365d0f82d61d88be634cc44fc68b27a6c9dbd0eb
38,126
def part2(): """ >>> part2() 17202899 """ max_value = 50000000 buffer_size = 1 position = 0 current = None step = INPUT for value in range(1, max_value + 1): position = (position + step) % buffer_size + 1 buffer_size += 1 if position == 1: cu...
7a00628e1f4bdfde95f02f03efef55f05191e74c
38,127
import logging def test_default(): """ Example using the default settings """ logger = logging.getLogger(__name__) log_all_levels(logger) log_all_levels_decorated(logger) log_all_levels_loop(logger) return logger
ff49747ec06ff55dc2fa52d6beb75bd04d364a5d
38,128
import re def newsgroups_dictl( data_home="~/scikit_learn_data", to_remove=("headers", "footers", "quotes"), text_key="text", label_key="label", label_mapping=None, ): """ Load the 20 Newsgroups dataset into a list of dicts, deterministically. """ label_mapping = label_mapping or d...
b213014888c116a3fdfe612a42aa1afe21eba38c
38,129
def list_calendars(service): """ Given a google 'service' object, return a list of calendars. Each calendar is represented by a dict. The returned list is sorted to have the primary calendar first, and selected (that is, displayed in Google Calendars web app) calendars before unselected calenda...
4b1c0ec92343302951371844e8af15dd29e417e9
38,130
def minimise_master_output(summary_yaml, mode): """ Converts the master output to include issues and bugs. """ log.debug("Minimising output (mode=%s).", mode) if not summary_yaml: return summary_yaml filtered = {} if mode == 'short': filtered = _get_short_format(summary_yaml) e...
afc651a1dff6d7ed27b3a25d110a2298cd018b26
38,131
def deg2rad(angle: float): """Convert degree unit to radian unit Args: angle (float): input angle. Returns: float: output angle. Usage: rad_angle = deg2rad(deg_angle) """ return angle * ONE_DIV_180 * PI
e6bcf7e830c85d397c7be45d654b26061d1ad421
38,132
def init_gns_from_files(path): """ Run GNS3 from a given set of router configs, builds GNS3 topology as well as adjacency information and starts all routers in the GNS3 project :param path: path to the configuration files, router configs are located at path/configs/ :return: GNS3 project descriptor ...
7b35446d406b39a7d91c8623223b54b2d19bbb8e
38,133
from typing import Optional import os def from_hdf(symbol: str, interval: str) -> Optional[pd.DataFrame]: """Try to load a DataFrame from .h5 store for a given symbol and interval :param symbol: Binance symbol pair, e.g. `ETHBTC` for the klines to retrieve :param interval: Binance kline interval to retri...
72caccedb5c1201cf151a5e162c8ead2d8fe1133
38,134
from typing import Optional from typing import Any from datetime import datetime def parse_evergreen_datetime(evg_date: Optional[Any]) -> Optional[datetime]: """ Convert an evergreen datetime string into a datetime object. :param evg_date: String to convert to a datetime. :return: datetime version of...
33fd432a361db73b5a3d2f391a5be9bf4f0e7836
38,135
def dateToQuarter(string): """takes a string of the type YYYY-MM and converts it to YYY-QN basically from month to quarter""" y,m = string.split('-') return y + '-' + QUARTER_MAP[int(m)]
f8e767cc8784cd15135911e7a464b67079973633
38,136
from typing import Optional def get_main_container_network() -> Optional[str]: """ Gets the main network of the LocalStack container (if we run in one, bridge otherwise) If there are multiple networks connected to the LocalStack container, we choose the first as "main" network :return: Network name ...
6e67904bcf43e2b888f76cd7fadd51080a77bcf2
38,137
def tri3_Bmat(zi_px, zi_py): """ Computing the B-matrix for a 3-node beam element :param list zi_px: partial derivative of zeta with respect to x :param list zi_py: partial derivative of zeta with respect to y :return: B-matrix for a 3-node element """ B = np.matrix([ [zi_px[0],...
5532d3dabadbb49462c2a500ed87cbc55b6e3e25
38,138
def fixedcase_prefix(ws, truelist=None, phrase_truelist=None): """Returns a list of 1 or more bools: True if some prefix of the tuple 'ws' should be fixed-case, False if not, None if unsure.""" # phrase_truelist is sorted in descending order by phrase length if phrase_truelist is not None: for n...
8a20b4b9eda4261b57004c94b9756caf871af077
38,139
def pipeline_dict() -> dict: """Pipeline config dict. Updating the labels is needed""" pipeline_dict = { "name": "german_business_names", "features": { "word": { "embedding_dim": 16, }, }, "head": { "type": "TextClassification"...
9505692f13759f392b930dff33ecf7ff781dcd9c
38,140
import os import json def _read_chip(path, selection): """Reads content of a single classification chip.""" d = {'filename': os.path.basename(path)} for filename in tf.io.gfile.glob(path + '/*'): if filename.endswith('_labels_metadata.json'): with tf.io.gfile.GFile(filename, 'r') as fid: d['me...
dfd1899176c7bd1e57f1e8758966e1a2cd71d098
38,141
def isadmin(ctx): """Checks if the author is an admin""" if str(ctx.author.id) not in config['admins']: admin = False else: admin = True return admin
65c3039ced98ea2468afacc8e14b9c1e41c8ea38
38,142
def get_name_from_filename(filename): """Gets the partition and name from a filename""" partition = filename.split('_', 1)[0] name = filename.split('_', 1)[1][:-4] return partition, name
606cfcc998c4a8405c9ea84b95b2c63f683dd114
38,143
def threshold(threshold, utilization): """ Static threshold-based underload detection algorithm. The algorithm returns True, if the last value of the host's CPU utilization is lower than the specified threshold. :param threshold: The static underload CPU utilization threshold. :type threshold: fl...
76882479754a4b8dfaed6e6dff611b2ed0f59890
38,144
def process_html(html_page, this_parser): """ extract links from an html page """ this_parser.feed(html_page) return { "int_links": this_parser.int_links, "ext_links": this_parser.ext_links, "static_links": this_parser.static_links }
abd380ae2738bb98fdab4b5026d5cb9bdaa76efa
38,145
def sync_execute_run_grpc(api_client, instance_ref, pipeline_origin, pipeline_run): """Synchronous version of execute_run_grpc.""" return [ event for event in execute_run_grpc( api_client=api_client, instance_ref=instance_ref, pipeline_origin=pipeline_origin, ...
f81995b609e8dbd1a91b3defb80d888b729c54c0
38,146
def random_cutout_color(imgs, min_cut=10,max_cut=30): """ args: imgs: shape (B,C,H,W) out: output size (e.g. 84) """ n, c, h, w = imgs.shape w1 = np.random.randint(min_cut, max_cut, n) h1 = np.random.randint(min_cut, max_cut, n) cutouts = np.empty((n, c, h, w), ...
8861526bd34e40794d78c3aea4c341eb84dc648b
38,147
from datetime import datetime import sys def get_day(): """Function for retrieving the wanted day""" day = datetime.datetime.today().weekday() if len(sys.argv) == 3: if sys.argv[2] == "mon": day = 0 elif sys.argv[2] == "tue": day = 1 elif sys.argv[2] == "wed...
3718f3447fb24ce2d84a3a4fd938e1a51613e781
38,148
import spack.repo import spack.spec def _unknown_variants_in_dependencies(pkgs, error_cls): """Report unknown dependencies and wrong variants for dependencies""" errors = [] for pkg_name in pkgs: pkg = spack.repo.get(pkg_name) filename = spack.repo.path.filename_for_package_name(pkg_name)...
99bdfd70fe4c4d3308bef70fcc1d65a83ba8ecce
38,149
def bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)): """Forward transform that maps proposal boxes to predicted ground-truth boxes using bounding-box regression deltas. See bbox_transform_inv for a description of the weights argument. """ if boxes.shape[0] == 0: return np.zeros((0, deltas.shape[1]), ...
4397e8e837c4efb6d1338224b47ebb8876cdea8d
38,150
def _get_crop(cytomine, image_inst, geometry): """ Download the crop corresponding to bounds on the given image instance from cytomine Parameters ---------- cytomine : :class:`Cytomine` The cilent holding the communication image_inst : :class:`ImageInstance` or image instance id (in...
11f541ef7f5ef95b5e251c2ef1a8b23d51fb2651
38,151
def authorship_below_random_chance(X, classifier, numAuthors): """See if the user's document features fool the classifier """ randomChance = 1 / numAuthors authorProb = classifier.predict_proba(X) print("User probability: ", authorProb[0][0]) print("numAuthors: ", numAuthors) print("Highest ...
aff15247e338c99306fffd442a90ce85d58879c0
38,152
def fnr_func_multi(threshold, preds, labels): """False rejection rate or False negative rate.""" return tf.reduce_sum( tf.multiply(tf.cast(tf.less_equal(preds, threshold), tf.float32), labels), axis=0) / tf.reduce_sum( labels, axis=0)
4989e23bc697c56c616b2841eb4f53968267d6f6
38,153
def queue() -> RedisQueue: """An empty queue""" q = RedisQueue('localhost', topics=['priority']) q.connect() q.flush() return q
5c789167729dad241f2ac4e4556953a20f9820cd
38,154
import aiohttp import asyncio async def determine_building_main(dct_lst: list): """Async cadastre units' building main :param dct_lst: dictionary to be used :return: cadastre units w/ buildings and without """ connector = aiohttp.TCPConnector(limit=c.MAX_CONNECTIONS) async with aiohttp.Client...
1b3ac451504c3b5ae73826d611ae3fe26567b08d
38,155
def pre_tax(sale): """ Args: sale: 持股平台减持价格(元/股) Returns: 需交纳税金 """ return income_tax(income(pre_price, options)) + cap_tax(all_option(options) * (sale - pre_price))
d9a1be1d6072c92681ca09307714dacd107f5fde
38,156
def _offset_to_boxes(F, center, pred, stride, transform="minmax", **kwargs): """ Change from point offset to bbox. :param center: the initial points center :param pred: the predicted point offsets :param stride: the stride of the offsets :param transform: the transform from points to bbox: "minmax",...
8d0c88ce7f3b5fff13628108babff6c2836b48a9
38,157
def poll_lldp_neighbors(dut, iteration_count=180, delay=1, interface=None): """ Poll for LLDP Neighbours Info Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param iteration_count: :param delay: :param interface: :return: """ i = 1 while True: rv = g...
d1decfd8b4cc6a66cac493a25a646b460526a100
38,158
def GetForegroundControl(): """return Foreground Window""" return ControlFromHandle(Win32API.GetForegroundWindow()) #another implement #focusedControl = GetFocusedControl() #parentControl = focusedControl #controlList = [] #while parentControl: #controlList.insert(0, parentControl) ...
b74832c235a11f53a032ff0c5a095d54d25a91ad
38,159
import torch def _set_device(disable_cuda=False): """Set device to CPU or GPU. Parameters ---------- disable_cuda : bool (default=False) Whether to use CPU instead of GPU. Returns ------- device : torch.device object Device to use (CPU or GPU). """ # XXX we might ...
1d7d448dd4e4a844201b73c8da4939009e70eb5f
38,160
def adaptive_thres(img, FIL1=10, R1=100): """adaptive thresholding for picking objects with different brightness. """ bw = adaptive_thresh(img, R=R1, FILTERINGSIZE=FIL1) return label(bw)
a4903a150512f38fb2cce1ad7e430c6791fecad1
38,161
def two_way_skar_bounds(dist, rvs, crvs, rv_mode=None): """ Iteratively compute tighter bounds on the two way secret key agreement rate. Parameters ----------- dist : Distribution The distribution of interest. rvs : iterable The indices to consider as X (Alice) and Y (Bob). ...
eff69eb2c14e6479bd858914e126ae6c4270ba17
38,162
from pathlib import Path import yaml import json def print_results_from_evaluation_dirs(work_dir_path: Path, run_numbers: list, print_results_only: bool = False) -> None: """Print the aggregated results from multiple evaluation runs.""" def float_representer(dumper, val...
4be2d893da5f321390c4b49cd4283c0b6f98b4d5
38,163
def clear_crontab(owner: Owner) -> Result[Unset]: """ Clear the owning user's crontab, if one exists on the current server. """ if not get_crontab(owner): return Result(State.unchanged) command(["/usr/bin/crontab", "-u", owner_name(owner), "-r"]) return Result(State.success)
df8d46c7a8af3d482403209c3e99c3ac1fd27660
38,164
from datetime import datetime def get_stats_by_month(session, datetime_column, months, autofill=True): """获取月统计数据 :param session: db.sessoin :param datetime_column: ORM Column :param months: int, 用负数表示过去的月数 :param autofill: bool, 是否自动填充没有的数据 """ first_day, last_day = get_first_day_and_las...
8c5dacc56f5987860097bab35990a5893a13a170
38,165
import asyncio async def start_game(game_params: GameParams): """ Method used to create game instance with given parameters :param game_params: GameParams object with integer how_many_cards and list of strings with players_names :return: integer value of game_id """ game_state = game.GameState...
49422ae7892b060d96622af28a4fe7fb591aa528
38,166
def infer_Tmap_from_clonal_info_alone( adata_orig, method="naive", clonal_time_points=None, later_time_point=None, selected_fates=None, ): """ Compute transition map using only the lineage information. As in :func:`.infer_Tmap_from_multitime_clones`, we provide two modes of inference: ...
06509556bb82ddd80c8bf83bbc2e77013b69bb3d
38,167
import os def safe_quote_string(text): """ safe_quote_string(text) returns the text in quotes, with escapes for any quotes in the text itself text - input text to quote returns: text in quotes with escapes """ if os.sep != '\\': text2 = text.replace('\\', '\\\\') text3 = text2.replace('"', '\\"') el...
bcbf74e8b27ab9a76564c82fbb64110c400f5493
38,168
def evaluate(input_data, predicted_output): """The function computes the accuracy for each of the datapoints that are part of the information extraction problem. Args: input_data (list): The input is a list of dictionary values from the isda json file predicted_output (list): This is a list...
9975e355a519c802773a39753b2bb36562590325
38,169
def blockInhalfSpace(conds): """ Returns a block in a halfspace model based on the inputs""" M, freqs, rx_loc, elev = getInputs() # Model ccM = M.gridCC # conds = [1e-2] groundInd = ccM[:, 2] < elev sig = simpeg.Utils.ModelBuilder.defineBlock( M.gridCC, np.array([-1000, -1000, -1500...
cc9194f7fda5246c934665514282cfce44714e4b
38,170
def build_generator(input_shape=(256, 256, 3), ngf=64, kernel_size=4, strides=2): """U-Net Generator""" image_input = Input(shape=input_shape) n_channels = input_shape[-1] # encoding blocks e1 = Conv2D(ngf, kernel_size=kernel_size, strides=2, padding='same')( image_inpu...
0a01b6a9bd0e1fb7c1391e9cf59974c39384274d
38,171
import random def randomize(img, noise_level=.03): """ given an array, randomizes the values in that array noise_level [0,1] controls the overall likelihood of a bit being flipped. This overall level is then multiplied by the levels variable, which modifies the noise level for the various...
1741413566f05c2759ff9dc7fa83fee56a59c138
38,172
def load_time_dependent_dataset(filename, cache=False, record_zero_counts=True): """ Load time-dependent (time-stamped) data as a DataSet. Parameters ---------- filename : string The name of the file cache : bool, optional Reserved to perform caching similar to `load_dataset`. ...
e3c2804ca7dc4f0c8951c3ec2d642e862263617d
38,173
def Log_SetTraceMask(*args, **kwargs): """Log_SetTraceMask(TraceMask ulMask)""" return _misc_.Log_SetTraceMask(*args, **kwargs)
3ae4c102ffab43d9e5122840decbf8f00dba1885
38,174
def find_max_burst(burst_list: list, offset_start, offset_end): """[summary] Args: burst_list (list): [description] offset_start ([type]): [description] offset_end ([type]): [description] Returns: [type]: [description] """ burst_levels = set() burst_lev...
75a15acf96324cafc806a1664e89054f6ade74d2
38,175
def center_text(baseline, text): """Return a string with the centered text over a baseline""" gap = len(baseline) - (len(text) + 2) a1 = int(gap / 2) a2 = gap - a1 return '{} {} {}'.format(baseline[:a1], text, baseline[-a2:])
c5683198cf1f28a38d307555943253bd71fe76de
38,176
def _find_executable_linenos(filename): """ A re-implementation of trace.find_executable_linenos working around compile's problems with missing EOLS """ try: prog = open(filename, "rU").read() except IOError, err: print >> sys.stderr, ("Not printing coverage data for %r: %s" ...
1a52a7511147ab3c1c5acd2295c846d8b874309e
38,177
def dict_allocations(dojo): """ input: dojo returns a dict of allocations """ rooms = list(dojo.office) + list(dojo.livingspace) # makes a dictionary, allocation with key-> roomname: -> value(occupants) allocations = {room.name: people_inroom(dojo, room.name) for room in rooms} return al...
7455f4bfa3686e0aed3d2ba2f75ac813e18c5f69
38,178
from functools import reduce def variance(lA): """ compute the variance elementwise of this list of arrays """ n = len(lA) sX = reduce(np.add, lA) sX2 = reduce(np.add, [A*A for A in lA]) s2 = (sX2 - sX*sX / n) / (n-1) return s2
2c94444f690459817e763cbbbf65af415ac2fdf0
38,179
def single_rvs(n0, psi, size=1): """Generate random deviates from the single division model, still is not working properly possibily needs to be checked""" cdf = single_cdf(1,n0,2,psi) xvals = [0] * size for i in range(size): rand_float = uniform(0,1) temp_cdf = list(cdf + [rand_floa...
72ae915d11de54e632edc7214709424dc212051a
38,180
def get_BRISK_descriptions(image, keyPoints, **kwargs): """ Computes BRISK descriptions for given keypoints. input: image (that was returned with the keypoints!) keyPoints - detected keypoints **kwargs = detection arguments output: list of descriptions for given keypoints ""...
b60395607df1af8337af12311338fdaa4058edb6
38,181
def make_mask(index): """ Create observation selection vector using major and minor labels, for converting to wide format. """ N, K = index.levshape selector = index.labels[1] + K * index.labels[0] mask = np.zeros(N * K, dtype=bool) mask.put(selector, True) return mask
41e4ad2257d8bce9c02ce479514c82a1bf14eeaf
38,182
def verify_request(func): """ verify user request """ def wrapper(request): uid = request.POST.get('uid', '') if not uid: return HttpResponseForbidden() else: try: if is_visit_today(uid): pass else: ...
cbe0fc5782918fec58088d740170265c3f385151
38,183
import itertools def LTL_world(W, var_prefix="obs", center_loc=None, restrict_radius=1): """Convert world matrix W into an LTL formula describing transitions. Syntax is that of gr1c; in particular, "next" variables are primed. For example, x' refers to the variable x at the next time ...
093e2af003c83408e6fb7605e0eb2b0b2181fb48
38,184
def feat_net(img_shape): """Returns a keras Model for feature extract Args: img_shape: tuple (h,w) Returns: model: Keras model """ IMAGE_H, IMAGE_W = img_shape input_image = Input(shape=(IMAGE_H, IMAGE_W, 3)) base_model = keras.applications.resnet50.ResNet50(include_top=False, ...
e1bf0540928563d74757fe9a5828bec4baad0950
38,185
def siconc_cubes(): """Sample cube.""" time_coord = iris.coords.DimCoord([0.0], standard_name='time', var_name='time', units='days since 6543-2-1') lat_coord = iris.coords.DimCoord([-30.0], standard_name='latitude', ...
87fcf145654ed9474ea3e3f4b3105ebd1e809d69
38,186
def criterion_1b(psych, n_trials, perf_easy, rt): """ Returns bool indicating whether criterion for trained_1b is met. """ criterion = (abs(psych[0]) < 10 and psych[1] < 20 and psych[2] < 0.1 and psych[3] < 0.1 and np.all(n_trials > 400) and np.all(perf_easy > 0.9) and rt < 2) retur...
ab89402ea58f032603306c754ed8a31d59df6e1c
38,187
def get_midpoints(z, midpoint_div_1, midpoint_div_2): """ Gets this midpoints in Z space between a batch of images """ # reshape z shape_z = shape(z) z = tf.reshape(z, [shape_z[0], np.prod(shape_z[1:])]) hidden_size = np.prod(shape_z[1:]) batch_size = shape(z)[0] # get the first half of ...
0b10f61e08a60cf2814df8a6d56d779f8e78a627
38,188
def check_neighbors_completeness( adata: AnnData, conn_key="connectivities", dist_key="distances", result_prefix="", check_nonzero_row=True, check_nonzero_col=False, ) -> bool: """Check if neighbor graph in adata is valid. Parameters ---------- adata : AnnData conn_k...
1cd7898038ae7dfa5047d0202398327f7f96e0e1
38,189
def get_measure(axis, qr, cr): """ For X, Y, Z axes, construct a QuantumCircuit that measures a single QuantumRegister :param axis: Axes to be measured, can be multiple. e.g. 'X' , 'XYZ' -- one for each qubit :param qr: QuantumRegister to measure :param cr: ClassicalRegister to measure into :re...
cac5a218db4fd7aac4bf97b09ffd2d94141f069f
38,190
def tbn_pyramid_level(sizes, ai, fdm, a, b): """ Downsize an image to appropriate sizes. A discrete interpolation method is used for images with discrete vs continuous values. """ result = [] result.append(downsize(ai, sizes[0])) if fdm is not None: result.append(downsize(fdm, ...
98723311ceb3359f72525cdcd332e3d7172da20c
38,191
def apply_density(rho: np.ndarray, op: np.ndarray) -> np.ndarray: """Applies a operator O to a density matrix ρ. .. math:: ρ' = O ρ O^† Parameters ---------- rho : (N) np.ndarray The input density matrix ρ. op : (N, N) np.ndarray The operator O to apply on the density m...
a4b7c5fda45e4cee2f45ba3b8d01ff9fadb906fb
38,192
from typing import List def _direct_read(array: tables.CArray, patch_reads: List[PatchRowRW], mask_reads: List[PatchMaskRowRW], npatches: int, patchwidth: int ) -> np.ma.MaskedArray: """Build patches from a data source given the ...
f0e3687171beb838a39d3e9d73d0c14cc492237a
38,193
def cover_get(title): """ Retrieve the cover image of the give movie :param title: the title of the movie :return: a json representing the title and the path toward the cover image """ return jsonify({ 'title': title, 'path': get_cover_path(title) })
abb4f285ebff9e4440153a51ca6f8adfa5367830
38,194
def DateTime_GetCountry(*args): """DateTime_GetCountry() -> int""" return _misc_.DateTime_GetCountry(*args)
fb4015ecef6250d2fa100ca5f82a1e2b77e552bc
38,195
def update_code_location(code, newfile, newlineno): """Take a code object and lie shamelessly about where it comes from. Why do we want to do this? It's for really shallow reasons involving hiding the hypothesis_temporary_module code from test runners like py.test's verbose mode. This is a vastly dispr...
ff3b90c2830f0fb9386bfde3306489e24896e18b
38,196
import scipy def xcorr(a,b,lags,medfilt=0) : """ Cross correlation function between two arrays, calculated at lags Args: a, b : input 1D arrays lags : array (1D) of x-corrlation lags medfilt : size of median filter for arrays (default=0) Returns : ...
e2f2b75823d2090650159144bfa52a886f79c111
38,197
def gist_earth(range, **traits): """ Generator for the 'gist_earth' colormap from GIST. """ _data = dict( red = [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0, 0.0), (0.0084033617749810219, 0.0, 0.0), (0.012605042196810246, 0.0, 0.0), (0.016806723549962...
87e30233c147b9dbdfb3c164a84984a822046197
38,198
def exponentially_distribute(exponent, dist_max, dist_min, num_exp_distributed_values): """ :param exponent: An exponent of 0 results in a linear distribution, otherwise the exp distribution is sampled from e^(exponent)*2e - e^(exponent)*e :param dist_max: Maximum of newly exponential distribution :...
368b106cad16458c879f27686e9a6331e6c32faf
38,199