content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def list_steps(df, step_type=None): """ Function that finds and lists the step number(s) corresponding to a step type. Or lists them if you specify nothing as second argument ARGS : - df [PANDAS.DATAFRAME] : your global rheology data - step_type * [STRING], has to be one of : 'amplitude...
2bcb60c6adb5e757f51a9f7d3fee2b1a03506b8c
3,603,269
def read_mh_z19(): """ Read the CO2 PPM concenration from a MH-Z19 sensor""" result = read_mh_z19_with_temperature() if result is None: return None ppm, temp, s = result return ppm, temp, s
ca746b879f28eac9677c4420c4fb4a5c30873fca
3,603,270
from typing import Optional def get_cluster(cluster_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult: """ Cluster details. Latest API Version: 2020-10-01. :param str cluste...
b78644aa140cb03b4b37aac3a1adeb9794faf919
3,603,271
def ignore(*exceptions, retval=None): """Execute function ignoring any one of the given exceptions if raised.""" def wrapper(func): @wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: if not ...
8e5729e4ec7f9a5a9d5c974c021bfca6151a391a
3,603,272
def remove_recorders(osi): """Removes all recorders""" return osi.to_process('remove', ['recorders'])
c63f23a031a5c957fd8667fc5be87fbd96b26a1e
3,603,273
def removeCutsFromFootprint(footprint): """ Find all graphical items in the footprint, remove them and return them as a list """ edges = [] for edge in footprint.GraphicalItems(): if edge.GetLayerName() != "Edge.Cuts": continue footprint.Remove(edge) edges.app...
ddb047e00f98d73037abb5d9dc0a2e00de457f56
3,603,274
def addPhoto(link, fullPath,object): """ add new photo perm: link = the link to the photo perm: object = the object this photo Belongs to as Model object return the new photo object if added or false if failed""" try: photo = Photos(link=link, full_path=fullPath ,object=object) db.session.add(photo) db.s...
b6606a1c6c264c08c4c7e6f569783c3fc156050a
3,603,275
from typing import OrderedDict def to_options(split_single_char_options=True, **kwargs): """Transform keyword arguments into a list of cmdline options Imported from GitPython. Original copyright: Copyright (C) 2008, 2009 Michael Trier and contributors Original license: BSD 3-Clause "...
b5835d8d9f52fed1ba34799c319be06e9913a1e3
3,603,276
def main_ctx(): """Return a reference to the global Z3 context. >>> x = Real('x') >>> x.ctx == main_ctx() True >>> c = Context() >>> c == main_ctx() False >>> x2 = Real('x', c) >>> x2.ctx == c True >>> eq(x, x2) False """ global _main_ctx if _main_ctx is None...
b4a85d6badbbdb239dde158f5406fc48209ccf3b
3,603,277
def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues, axis_font_size=12): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=Tru...
7c6bdf68cf0f82826b947ba7572e8449254525ed
3,603,278
def make_primitive_smoothed(cas_coords, smoothing_level=2): """ Generates smoothed primitive from a list of coordinates. Parameters ---------- cas_coords : list(numpy.array or float or tuple) Each element of the list must have length 3. smoothing_level : int, optional Number of time...
bcb94241eb9a82482b523a07bb276f48b9ca91db
3,603,279
def manager(): """Retrieves the default top-level manager""" global _defaultManager return _defaultManager
0b917f263010553565d45f527531f3f6bcb7c631
3,603,280
import inspect def getclasses(): """return a list of classes defined in `__all__`""" classes = [] for name, member in getmembers(): if inspect.isclass(member): classes.append(member) return classes
ab734ac5578ba4b8fed342d2c9d41a294937b5e7
3,603,281
def load_lang_data(corpus_name, topk=10000): """ Load {topk} sentences from the corpus named by {corpus_name}. """ fpath = corpus_name + '.' + tokenizer_name tokens = [] with open(fpath) as f: for i, line in enumerate(f): tokens.append(list(map(int, line.split(' ')))) ...
af26319304d364f18d40fca645f7e28cc382bf10
3,603,282
from typing import Match def gen_ruby_html(match: Match) -> str: """Convert matched ruby tex code into plain text for bbs usage \ruby{A}{B} -> <ruby><rb>A</rb><rp>(</rp><rt>B</rt><rp>)</rp></ruby> Also support | split ruby \ruby{椎名|真昼}{しいな|まひる} -> <ruby><rb>椎名</rb><rp>(</rp><rt>しいな</rt><rp>)</rp>...
bd603b67a61812152f7714f3a13f48cac41db277
3,603,284
import numpy def FingerprintMol(mol): """ generates the EState fingerprints for the molecule Concept from the paper: Hall and Kier JCICS _35_ 1039-1045 (1995) two numeric arrays are returned: The first (of ints) contains the number of times each possible atom type is hit The second (of floats) contain...
034b78422c4add407457fdf88c3178d529229b16
3,603,285
import time def _generate_request_id(): """ 生成一个请求 id,暂时用 (时间戳 % 60 分钟) :return: """ return int(time.time() * 1000 % (60 * 60 * 1000))
b334265d41b68fc3455297bbc21065e7cb064920
3,603,286
def SkipIf(should_skip): """Decorator which allows skipping individual test cases.""" if should_skip: return lambda func: None return lambda func: func
135486c94640231328089115d61ba2d1eb87e46a
3,603,287
def generic_image_dataset_summary(): """ Return a short HTML summary of a DatasetJob """ job = job_from_request() return flask.render_template('datasets/images/generic/summary.html', dataset=job)
26919ae503d0a6decb0d13143aeb7dcd617d5fdf
3,603,288
def Choice(*choices): """ note that the class of the choices becomes a base class, e.g. issubclass(Choice(1,2,3), int) == True """ if not len(choices): raise ValueError(f"cannot define Choice without any choices") if any(type(c) is not type(choices[0]) for c in choices): raise ValueError(f"a...
dcbb638d2e062562e7692572d60c13f80acce033
3,603,289
from typing import List import torch def add_sine_features( data_list: List[Data], n_jobs: int = 1, only_physical_cores: bool = False, verbose: bool = False, ) -> List[Data]: """Add the Sine matrix for the given data of a homogeneous graph. Args: data_list (list of :class:`torch_geomet...
7571ac175d79dc41405d380ad130100b760b30be
3,603,290
def cache_execute(fn, cache, pass_kwargs=False, return_tuple=True, expand_fn=None): """Decorator that adds caching to a function that executes multiple tapes on a device. This decorator makes use of :attr:`.QuantumTape.hash` to identify unique tapes. - If a tape does not match a hash in the cache,...
51e8ea9f8cf6596df88e219268627b11bd42ee68
3,603,291
def get_hmslincs_annotations(cell_lines): """ Returns metadata annotations for cell lines available on LINCS DB Parameters ---------- cell_lines: list of str Name of cell lines Return ------ dfs: pandas dataframe dataframe of cell line annotations from HMS LINCS DB for g...
80ff21797e429a6dcdc5b44bae284caec68cb9dd
3,603,292
def plot_trajectory_2color (data, movie_ID): """Separately plot two channel trajectories of a given movie side by side. Args: data (pandas dataframe): dataframe containing parsed data. At the very least, must contain the columns 'color', 'movie_ID', and 'parsed'. movie_ID (str): uni...
56eba8559e3fd2a6bd126b6ef5502924c5e13cb6
3,603,293
def yaml_cloudformation_constructor(loader, node): """ Implements the yaml tag !Cloudformation The tag takes a dict {stack: $stack_name, output: output_key} as node (argument). Example: VpcId: !Cloudformation {stack: ${vpc_stack}, output: VPC} VpcId: !Cloudformation {stack: ${vpc_stack}, r...
5375081cdeaf1fa5a125c08c5cbbc71605439984
3,603,294
from datetime import datetime def convert_row(column_name_type, row): """ Make cell data more user friendly. Args: column_name_type (List[(str, str)]): A list of pairs of column names and types row (dict): The row data as a dict Returns: A list containing row data transformed...
2d5d29ea57f0fe22dd8c3c74b38a34ed16bf637d
3,603,296
def norm(x, train_stats): """ Normalize the data. """ return (x - train_stats['mean']) / train_stats['std']
c7791c39b64a5041e537bb7554c0c4a7267d180c
3,603,298
import random import string def randomstring(size=20): """Create a random string. Args: None Returns: result """ # Return result = ''.join( random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(size)) return result
64ecd935130f6308367d02a5d699ea05c906cbb2
3,603,299
def get_avg_temp(data): """this function gets the average temperatures for each point in the fetched data""" temp_history = [] for point in data: this_point_temp = [] for year_reading in point: this_point_temp.append(int(year_reading['weather'][0]['avgtempC'])) temp_histo...
fe5774ca79e417f75cea2f79832ad8338824e3bf
3,603,301
import torchvision def _transform_block(init_block): """Transform the resnet block to Vega block.""" if isinstance(init_block, torchvision.models.resnet.Bottleneck): inplanes = init_block.conv1.in_channels planes = init_block.bn1.num_features stride = init_block.stride downsamp...
4fe764d71a31f1159eb0988d0787439d7b30c7be
3,603,302
def getAction(num, distance, bird_height, hole_height): """ Gets the action from a network by feeding forward the inputs. """ if strategy == 0: global population distance = distance / 450 - 0.5 # distance = distance / 450 bird_height = min(bird_height, SCREENHEIGHT) / SCR...
139202aa18cdc248db60636c5a47321357bd9582
3,603,303
def reported_br_add(path1, path2=None): """Return expected lines for addition of a (sub)branch. Params are (SUBBRANCH_RPATH) or (OUTER_BRANCH_FULLPATH, SUBBRANCH_RPATH). """ subbranch_rpath, subbranch_fullpath = reported_br_params(path1, path2) return [reported_element_add_line(subbranch_rpath, r' \(branc...
b2cc6427f062e3f116fe922f2e41c1bb49f001f9
3,603,304
def span_accuracy(predictions, positions, n_way=5): """ Exact span match. :param predictions: [batch_size, 2] :param positions: [batch_size, 5, 2] :return: [batch_size] """ predictions = tf.stack(n_way * [predictions], axis=1) _equal = tf.cast(math_ops.equal(predictions, positions), tf.i...
a80e0fb2a71ecac05309df550c74c85d591b2c44
3,603,305
def ldns_is_rrset(*args): """LDNS buffer.""" return _ldns.ldns_is_rrset(*args)
208b08cc99db1dfc41b1ede2629f7b7846b16204
3,603,306
def socketio_service(request): """ The view that will launch the socketio listener """ socketio_manage(request.environ, namespaces=nsmap, request=request) return {}
fb8acf76e82b59b492cd9194499b8e96536b7a55
3,603,307
import psutil def pid(): """Find the PID of the qemu usermode binary which we are talking to. """ # Find all inodes in our process which are connections. targets = set(c.raddr for c in psutil.Process().connections()) # No targets? :( if not targets: return 0 for process in ps...
30f19e80eab375e82499b0d2654ffdde9ded19bd
3,603,309
def has_seven(k): """Returns True if at least one of the digits of k is a 7, False otherwise. >>> has_seven(3) False >>> has_seven(7) True >>> has_seven(2734) True >>> has_seven(2634) False >>> has_seven(734) True >>> has_seven(7777) True """ if k % 10 == 7: ...
8c0b7b02e36247b3685a6a0142ebd81dd63e220c
3,603,310
from datetime import datetime def attempt_auto_login(view): """Attempt to login an unauthenticated user using the SSO server. This decorator does several things: 1. Attempt to log in a locally unauthenticated user using the SSO server. If this succeeds we are redirected back to the original page due...
930c9a036f3fce6f3b2dfe7d894cf5db3eae58f7
3,603,312
import torch def train_or_val(args, loader, simclr, model, criterion, optimizer=None, scheduler=None, train=False): """ Train Linear model """ loss_epoch = 0 accuracy_epoch = 0 simclr.eval() if train: model.train() else: model.eval() model.zero_grad() for s...
da4e8b3aa1dc5f8fa47af55e3b2cc291a4f6c1ea
3,603,313
from typing import Callable def _make_cpp_orderbook( instrument: Instrument, exchange_name: str = "", callback: Callable = lambda x: print(x), ) -> OrderBookCpp: """helper method to ensure all arguments are setup""" return OrderBookCpp(instrument, exchange_name or ExchangeType(""), callback)
0dd28d83defffb1668af919d4b6a5ae733683bdf
3,603,314
import string import re def installed_package_device(ctx): """ :param: ctx :return: device_type with rsp version ie asr900rsp2 """ cmd = 'show version running | include File:' # File: bootflash:/Image/asr900rsp2-rpbase.03.13.03.S.154-3.S3-ext.pkg, on: RP0 # File: bootflash:/Image/asr900rsp...
3e05051f8974aee274bcf28b248b8c1758c9993f
3,603,315
def datetime_from_woql(dt_str, woql_type): """Convert woql datetime objects (str format) to datetime object. Raise ValueError if cannot be converted.""" if woql_type == "xsd:duration" or "P" in dt_str: if dt_str[0] == "-": pidx = 1 # is_negative else: pidx = 0 ...
2e4e58602486728ab032b15e46d71a74f0125ea3
3,603,316
def bd09togcj02(bd_lon, bd_lat): """ Convert coordinates from BD09 to GCJ02 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Lat...
dd2c74f37cc0f7635e0be0f7519470fc38eabb92
3,603,317
def bilinear_additive_upsampling(layer_input, scale_factor, channel_out=None, data_format='channels_last'): """ This function defines a bilinear additive upsampling operation, proposed in following paper: Wojna, Z., Ferrari, V., Guadarrama, S., Silberman, N., Chen, L.-C., Fathi, A., & Uijlings, J. (2017). ...
ace1ff54467e48878291e53d73986b9391d20b34
3,603,318
def reflection_padding(net: tf.Tensor, padding_size: int) -> tf.Tensor: """ Create reflation padding. :param net: layer inputs. :param padding_size: padding size. :return: padded inputs. """ padding_shape = [ [0, 0], [padding_size, padding_size], [padding_size, paddi...
3a2137b90408f17c84db8854ba7e01d1f6877034
3,603,319
import torch def diffusion_coeff(t, sigma, device='cuda'): """Compute the diffusion coefficient of our SDE. Args: t: A vector of time steps. sigma: The $\sigma$ in our SDE. Returns: The vector of diffusion coefficients. """ return torch.tensor(sigma ** t, device=device)
fb57ef3af98e7ad2d6a41a298ec7541f70f9556c
3,603,320
def get_subreport(binary_list, least_most_common_bit, bit_position): """Gets the report subset that has the least/most common bit within the specified bit position. Args: binary_list (): least_most_common_bit (): bit_position (): Returns: subreport (list): Subset that fulfil...
ca69762a416ead2dd3ba177150dc6a7ae6a6f494
3,603,321
def r2(net, distribution, y, *args, n_samples=16, batch_size=32, **kwargs): """ R2 """ y_hat = distribution.mean.detach().cpu().reshape(-1, 1) return _r2(y, y_hat)
420664059af70570780c4f3dc31c2237f20c426d
3,603,322
from typing import Type from typing import Tuple from typing import List import numpy def pytype_to_myiatype(pytype, instance=None): """Convert a Python type into a Myia type. Arguments: pytype: The Python type to convert. instance: Optionally, an instance of the Python type to use ...
02e0d56a4cd25523978de8eb8cec4f0b519267ef
3,603,323
def GetAnglesPolyline(polyline,closed=False): """ see: http://stackoverflow.com/questions/3486172/angle-between-3-points ported to numpy returns n-2 signed angles """ points = polyline[:,0] if closed: a = np.roll(points,1,axis=0) b = points c = np.roll(points,-1,axi...
04bd72d74b42438b17ec0802f0371b1554d02ed5
3,603,325
def get_settings() -> "RobotServerSettings": """Get the settings""" load_dotenv(get_dotenv_path()) return RobotServerSettings()
ee92591a0819b6a3d82b092206c9545599be08f0
3,603,326
import torch def train_epoch(Z, W, net, opt, criterion, batch_size=500): """ :param Z: predictors :param W: labels :param net: nn :param opt: torch.optim :param criterion: BCEloss :param batch_size: batch size :return: losses """ Z = torch.tensor(Z, dtype=torch.float) W = t...
468e9a1ab43b803b2e60394d5e3eedca80820557
3,603,327
import torch def fft_zero_low_magnitudes(input, high, low=0, onesided=True, is_next_power2=True): """ :param input: the input image :param high: the highest value to be zeroed out (up to) :param low: the lowest value to be zeroed out (down to) :param val: the value (to ...
cfe83900c7f862a05ba02092190ffbfa2139021d
3,603,328
def extract_core_mesh(xyzlim, mesh, mesh_type="tensor"): """ Extracts Core Mesh from Global mesh Parameters ---------- xyzlim: numpy.ndarray 2D array [ndim x 2] mesh: BaseMesh The mesh mesh_type : str, optional Unused currently Returns ------- tuple ...
a504e6d46b0ef62a87281cb5f038f58af6f958cf
3,603,329
import itertools def value_iteration(P, nS, nA, gamma=0.9, max_iteration=20, tol=1e-3): """ Learn value function and policy by using value iteration method for a given gamma and environment. Parameters: ---------- P: dictionary It is from gym.core.Environment P[state][action] ...
346691dd9f2ac3dc7bc44ad2ae49fce99e69203d
3,603,330
import array def ofdm_tx(x, nfft, nsc, cp_length): """ OFDM Transmit signal generation """ nfft = float(nfft) nsc = float(nsc) cp_length = float(cp_length) ofdm_tx_signal = array([]) for i in xrange(0, shape(x)[1]): symbols = x[:,i] ofdm_sym_freq = zeros(nfft, dtype=complex) ...
a7ce729fc2b3e886e1e9855689fcab6b83ec9a97
3,603,331
def synthetic_item_response_theory(): """One-parameter logistic item-response theory (IRT) model. This uses a dataset sampled from the prior. This dataset is a simulation of 400 students each answering a subset of 100 unique questions, with a total of 30012 questions answered. Returns: target: StanModel...
4748723e5e42961b0299f7e94de0a13898d4a214
3,603,332
def parse_argument(stream: TokenStream) -> AstNode: """Parse argument.""" spec = get_stream_spec(stream) scope = get_stream_scope(stream) tree = spec.tree.get(scope) if tree and tree.parser: with stream.provide(properties=tree.properties or {}): return delegate(f"command:argume...
e11e6e2c979ec0e2fedbb07e5fe068210abab2fe
3,603,333
from typing import List def ordered_list( children: List[List[BlockToken]], loose: bool = False ) -> block_token.List: """Create a List token with ordered items.""" return list_token(children, ordered=True, loose=loose)
bda0922a619b94fbe828d46b0263e11c0625c6d3
3,603,334
def get_grid_size(grid): """Return grid edge size.""" if not grid: return 0 pos = grid.find('\n') if pos < 0: return 1 return pos
9ff60184bb0eed7e197d015d8b330dcf615b4008
3,603,335
def count_terms_abundance_corrected_KEGG(ui, assoc_dict): """ #!!! modify to use protein groups --> handled in Userinput.py or not? produce abundance corrected counts of GO-terms of background frequency round floats to nearest integer Userinput-object includes ANs of sample, and background as well a...
87ec2757bc40081dd670011019dca6777e1176d9
3,603,336
def randomExchange(pos): """ Randomly shuffle exchange parameters for rnadom labeling """ arraytoShuffle = pos[2, :] _np.random.shuffle(arraytoShuffle) newpos = _np.array([pos[0, :], pos[1, :], arraytoShuffle, pos[3, :]]) return newpos
89b86d851785e165b21db9cb59d46b6aafa0ae95
3,603,337
def value(s, V, full_state_to_index, nA, P, gamma = 1, theta=0.05): """Helper function that calculates value for all actions for a given state. Parameters: s: state index V: Value full_state_to_index: dictionary of state to index Values nA: number of actions (3) P: transi...
6e0feaa932bb22a40c60bbfb042509d314a3e4b4
3,603,338
from typing import Tuple import torch import tqdm def compute_predictions_34(model:nn.Module, device:str, dataloader:DataLoader, srl_vocab:SemanticRolesVocabulary) -> Tuple[list, list]: """ Computes and returns all the true and predicted labels of a model on t...
8e62510e1c801b420b4dbec4beeba07e824ee51a
3,603,339
from typing import List from typing import Optional from typing import Dict def topic_model( text_docs: List[str], model_type: str = "LDA", num_topics: Optional[int] = None, min_topics: int = 2, max_topics: int = 10, no_below: int = 10, no_above: float = 0.2, tfidf: bool = True, mo...
15632e6a575bce4fd8197bcae05289b334d7f61c
3,603,340
def ts_code(code: str) -> str: """ 转换证券代码为 tushare 标准格式 :param code: :return: """ if len(code) != 9: raise Exception('无效的证券代码: 长度不符') stock_code = code.upper() if stock_code.endswith('.SZ') or stock_code.endswith('.SH'): return stock_code elif stock_code.startswith('S...
86f568553955ab66bcea7f86ecc341329f8931e3
3,603,341
import _warnings def array(sequence=None, typecode=None, copy=True, savespace=False, type=None, shape=None, dtype=None): """Attempt to convert SEQUENCE to an array of specified TYPE and SHAPE. SEQUENCE: Data sequence. Can be None, an object with an __array__ method, a NumArray, a buffe...
c38e419e20d7f3956732cadba7df5fadeb25d422
3,603,342
import importlib import inspect def export_models(mods, main_color, bg_color, export_file, export_format, view, peewee_module, display, display_modules_name): """ Export peewee models to JPG, PDF, etc. :param str,list mods: modules, named as imported :param str main_color: main colo...
37c09d193b754e89da27197eb1e01081bfee5784
3,603,343
def find_names_from_num_syms(num_syms): """Have kallsyms_num_syms, find kallsyms_names""" if num_syms is None: return None names = num_syms.add(4) while True: if getByte(names) != 0: break names = names.next() assert num_syms == find_num_syms_from_names(names), "C...
f73d795e7c65996abdb3c759ded61f9d6d4e42df
3,603,344
def no_cache(func): """ Decorator made to modify http-response to make it no_cache """ def disable_caching(request_handler, *args, **kwargs): request_handler.set_header('Cache-Control', 'no-cache, no-store, must-revalidate') request_handler.set_header('Pragma', 'no-cache') reques...
f5f5b9c8e78a883395ad6cbf263c1c82b1aafdc9
3,603,345
def index() -> str: """ Static string home page """ return "Hello, Python!!!"
7bf6b684e8404d0b2d52bb7578e1f44e37bdf565
3,603,346
def efs_energy_vector( name, efs_energy_kernel, x, hyps, cutoffs=None, hyps_mask=None, n_cpus=1, n_sample=100, ): """ Returns covariances between the local eneregy, force components, and partial stresses of a test environment and the total energy labels in the training se...
1337a360d060fe0680dfe6bcd66a51ce2cceb946
3,603,347
def get_unique_coords(df, lat_field, lon_field): """ Takes in a dataframe and extract unique fields for plotting. Uses dataframe group by to reduce the number of rows that need to be plotted, returns the lat and lon fields """ unique = df.groupby([lat_field, lon_field]).size().reset_index() ...
3914e59a9263e07a18833135b0d30a3e5b1d4ce6
3,603,348
def adv_loss(x_train, x_test, y_train, y_test, kernel_fn, loss='mse', t=None, targeted=False, diag_reg=1e-4): """ :param x_train: input tensor (training data). :param x_test: input tensor (test data; used for evaluation). :param y_train: Tensor with one-hot true labels of training data. :param y_tes...
cf941ca3e5a4750b04d69d52dca3e9994ab09c0f
3,603,349
import collections def update(d, u): """Function to update a dictionary with values from another. Arguments: d {dict} -- Base dictionary. u {dict} -- Update dictionary. Returns: dict -- Updated dictionary. """ for k, v in u.items(): if isinstance(v, colle...
58ef1268e84d193f1550c5a482b8fbdd5910a6a0
3,603,351
from typing import Optional def infer_sex( mt: hl.MatrixTable, tmp_bucket: str, out_ht_path: Optional[str] = None, overwrite: bool = False, target_regions: Optional[hl.Table] = None, ) -> hl.Table: """ Runs gnomad.sample_qc.annotate_sex() to infer sex :param mt: input MatrixTable :...
2d818160068291f2dd599a8de40d3b71b6a3c36c
3,603,352
def jets(event, R = 1.0, p = -1, minpt=20): """Returns a list of jets given an event. If the argument `n_hadrones`, `R`, `p` and `minpt` arent't passed in, the default values are used. Parameters ---------- event : Serie Hadrons of the event R : int Size of the radius f...
de1afaf5301d426e7efeed57f96444c6bc25afc9
3,603,354
async def get_vpc_peering_connection(cidr_block=None,filters=None,id=None,owner_id=None,peer_cidr_block=None,peer_owner_id=None,peer_region=None,peer_vpc_id=None,region=None,status=None,tags=None,vpc_id=None,opts=None): """ The VPC Peering Connection data source provides details about a specific VPC peering...
73463aa6e5e10a9faed8cf441c89f7e05a24b73e
3,603,355
def get_subclasses(model, include_abstract=False): """ Returns a list of unique models that inherit from the specified model. If include_abstract is True, abstract inheriting models will also be returned. """ return list(set([klass for klass in _get_subclasses(model) \ if hasattr(klass, '_me...
3440930591e3ed347f640896adffef501c449124
3,603,356
def _filter_optouts_from_recipients(to_list, course_id): """ Filters a recipient list based on student opt-outs for a given course. Returns the filtered recipient list, as well as the number of optouts removed from the list. """ optouts = Optout.objects.filter( course_id=course_id, ...
275d0fba66d41b6c2ca7f5df3dcb557af1d4cf72
3,603,357
def listify(obj): """Return a flat list out of the argument.""" if not obj: obj = list() elif is_iter(obj): obj = list(flatten(obj)) else: obj = [obj] return deepcopy(obj)
c7c6d5b26337f51129e3d8468fa55ae77066d1d2
3,603,360
def load_dataset_A(path=None,train=True,norm=False,selected_chans = None,sfreq = 128,fmin=4,fmax=36,tmin=0,tmax=3,start_id=1,end_id=3): """dataset A is in voltage foramt""" # process Dataset A (S1, S2) # get train target data if path is None: path = '/Users/wduong/mne_data/MNE-beetlmileaderboard...
2bef2119f8e15ec81b25ec21ac38f392dab64481
3,603,361
def get(): """ Returns global API instance. Returns: API instance """ return INSTANCE
797e6958c0cbdd0c4ca3decb49de47fa8e4ec072
3,603,362
def get_context_pairs(graphs, num_time_steps): """ Load/generate context pairs for each snapshot through random walk sampling.""" # load_path = "data/{}/train_pairs_n2v_{}.pkl".format(FLAGS.dataset, str(num_time_steps - 2)) # try: # context_pairs_train = dill.load(open(load_path, 'rb')) # pr...
de72ed953d94a74881a183393311c7b64ecc9e8c
3,603,363
import cmd def rpcDeleteAll(): """ deletes all objects """ res = cmd.delete('all') if res is not None: return res else: return ''
68ea34814417f5fd060a378e7be6cc482cce396d
3,603,366
def getdevices(name): """ Return the devices associated with the given names. Args: name: The name of the profile being accessed. """ cursor = db.find({"_id":name}) for result_object in cursor: if result_object['devices'] == [u'None']: return "None" else: ...
fc30af16b3c919fe741ee3147674eebc41ee2efe
3,603,367
import json def retrieve_transaction_index_template(): """This function is used for test configuration""" with open(str(FILES["template"])) as f: mapping_dict = json.load(f) template = json.dumps(mapping_dict) return template
7a489079bf8a1e8f7b1c95463621a1a914087051
3,603,368
def unhex(value): """Converts a string representation of a hexadecimal number to its equivalent integer value.""" return int(value, 16)
0a8c297a93f484c8a1143511ef8511521c887a78
3,603,369
import heapq from typing import Counter def k_nn_q( k: int, dist: DistanceFunc, training_data: TrainingList, unknown: AnySample ) -> str: """ Use heapq to maintain a list of the neighbors, in order, avoiding a sort after all computations are completed. 1. For each item: 1. Compute the di...
62f2cdf42042166d7c311687f5f3902fa5a09b9c
3,603,370
def make_00a6(sucess): """キャラクター削除結果""" return ("\x00" if sucess else "\x9c")
2c89d1ba457a3d550742721ddfa9c6f6e7f391c7
3,603,371
def _get_all_filters(): """ Find all Filter classes in modules specified in FILTER_PLUGINS. Returns ------- filters: list The filter classes """ filters = list() for module_name in FILTER_PLUGINS: logger.info(f"[green bold]Importing filters from [yellow]{module_name}[/] ...
663a0692aaa556e1f2948dfa22b697746620c5e8
3,603,372
def puzzles(): """ Import a list of Sudoku puzzles from text file and return it as a list Puzzles credit: http://norvig.com/top95.txt http://norvig.com/hardest.txt """ with open('sudoku_puzzles.txt') as file: data = file.readlines() #remove all end ...
e4f876c52b21756a9a97c6f1bc3a0cd2c00fca61
3,603,373
def getXy_insulation(f_ins_pos, f_ins_neg, f_readcts, f_span, outpath, ctonly=False): """ :param f_ins_pos: downstream data from wigvals_from_cutsite() :param f_ins_neg: upstream data from wigvals_from_cutsite() :param f_readcts: read_counts() data (i.e. from mre11) """ data_pos = m.load_nparray...
175bda9b199775dc47d10d14af54a7f8e25dbfe9
3,603,375
def hernquist_profile(mtot,a,r,nfw=0): """Defines a herqnuist profile with mass mtot and scale radius a. has the option of being nfw instead using a flag.""" return a*mtot/(2*np.pi)*(r*(a+r)**(3-nfw))**-1.
e68dabad1bd51399db5c510700c692b91036d565
3,603,376
import json def groups_delete_user_callback(request): """A callback to mock the `/groups/{group_id}/delete_user.json` endpoint.""" resp_body = { 'request': TEST_REQUEST_ID } headers = {'X-Request-Id': TEST_REQUEST_ID} req_body = getattr(request, 'body', None) qs = parse_qs(req_body) ...
6eefedec6f306a2706efb03d35150a30638c61ae
3,603,377
def ew(node): """ Return a dictionary of the nodes and pipes that are connected to node """ cY = {} gM = node.dependent(b.INPUTS | b.HIDDEN_INPUTS) for p in gM: cY[p] = [] for c in range(p.inputs()): if p.input(c) == node: cY[p].append(c) return c...
5012e9dadfe3fd77d9fe1027ddfe51efc60088df
3,603,378
def get_similar_fork(fork_list, fork1): """ Args: fork_list fork1 Return: A list contains the similar forks with fork1 (Top 5) """ if (fork_list is None) or (fork1 is None): return None sort_list = {} param_list = {} for fork2 ...
3100ed7a1585496b3cd71e1e81629a919a34b9df
3,603,380
from typing import Optional from typing import List from datetime import datetime def make_ciphertext_ballot( object_id: str, style_id: str, manifest_hash: ElementModQ, code_seed: Optional[ElementModQ], contests: List[CiphertextBallotContest], nonce: Optional[ElementModQ] = None, timestamp...
7d20ae35cb9b433163a27658c27ef3e507cd0274
3,603,381
import io def discretize_stationary_from_disk(parameter_file): """Generates stationary discretization only based on system relevant data given as .mat files on the hard disc. The path and further specifications to these objects are given in an '.ini' parameter file (see example below). Suitable for discre...
68196452bf1ae00fb4bb26a46abc919f3489884a
3,603,382
from typing import Callable def load_json_file_with_name(module_path: str) -> Callable[[str], dict]: """ Return a function that can load a json from a filename and return a dict, but also the filename """ def _json_loader(filename: str): return _load_json_file_with_name(module_path, filename) retu...
cd01c04d85e294abaa1c6547a5ef96d091b5d94e
3,603,383