content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List import copy import logging def connect_circuit(components: List[SimulatedComponent], net_count: int) -> SimulatedComponent: """ Connects the s-matrices of a photonic circuit given its Netlist and returns a single 'SimulatedComponent' object containing the frequency array, the a...
9caf51a1455f4630f40e7492b28da446240fc07c
3,603,300
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
from typing import Optional from typing import Union import os import fsspec def xgetsize(path, use_auth_token: Optional[Union[str, bool]] = None) -> int: """Extend `os.path.getsize` function to support remote files. Args: path (:obj:`str`): URL path. Returns: :obj:`int`, optional ""...
83dc21b3f165cc9b3c62222d81d7a873c0feb1a0
3,603,308
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
import json import os def ParseConfigFile(filename): """Parses a .config file. Args: config_filename: A Config filename. Returns: A Config object. """ with open(filename, 'r') as fp: config_data = json.load(fp) directory = os.path.dirname(os.path.abspath(filename)) config = Config() con...
0420cfe4faeac933ab977ef2bb098f7ed8f95b7d
3,603,311
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
import sys def get_conflicting_pkgs(package): """Returns list of packages that contain some files that are also found in 'package'. These packages should be listed as dependencies. """ if package in ["collection-basic"]: conflicting_pkgs = [] elif package in ["collection-latex"]: ...
c191a32aa0b0a35fa59c193223467a4430dc6888
3,603,324
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
def process_checkin(): """Process periodic checkins from servers.""" app.logger.debug("Saw request %s", request.form) version = request.form['Version'] periodic_queue.put([version, request.remote_addr or '', munge(request.form, 'Number-Of-Servers'), munge(...
cc7be412e7a6098a0332080f6badf693b29a0221
3,603,350
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
import get_coverage_tests as gct import os import sys def standardMain(argv,convert): """ For most scripts, this should be the desired behavior of the 'if __name__=="__main__"' block of a converstion script. It covers getting the filename list, checking files exist, creating backups, converting, prettifying...
8516ff9f60bd8079d150094f5baa98f8c1984d85
3,603,353
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
from xbbg.core import trials def bdib(ticker: str, dt, session='allday', typ='TRADE', **kwargs) -> pd.DataFrame: """ Bloomberg intraday bar data Args: ticker: ticker name dt: date to download session: [allday, day, am, pm, pre, post] typ: [TRADE, BID, ASK, BID_BEST, ASK_BE...
49ddb7aa0b51b70a8d8558f3b53ef5a71c134542
3,603,358
import sys def closestServers(client, all=False): """Determine the 5 closest speedtest.net servers based on geographic distance""" global netpoc_error urls = [ '://www.speedtest.net/speedtest-servers-static.php', '://c.speedtest.net/speedtest-servers-static.php', '://www.speedtest...
8eb8ac21f2918fb812ce98992021a964f4941c31
3,603,359
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
def match_structure_sequence(orig_seq, new_seq, match='X', fill_with='X', ignore_excess=False): """Correct a sequence to match inserted X's in a structure sequence This is useful for mapping a sequence obtained from structural tools like MSMS or DSSP to the sequence obtained by the get_structure_seqs m...
f5e7fdc1a9626e00c9f5efa3fdd5841eb367453d
3,603,364
import os def scanForFiles(folder_name, extensions=('.frm', '.bas', '.cls', '.vb')): """Return all suitable VB files in a folder and subfolders""" filenames = [] for subdir, dirs, files in os.walk(folder_name): for filename in files: filepath = os.path.join(subdir, filename) ...
685043454a105adeabe2768973d0a728f29fd6e4
3,603,365
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
import os def enf_rastlist(filelist): """ Ensures a list of inputs filepaths contains only valid raster types :param filelist: a list of filepaths that contains some raster filetypes :return new_filelist: a list of filepaths with all non-raster files removed """ # first place the in...
92caa032d45757151f927de1e9cc3ba2f1464f2f
3,603,374
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
import threading import os def concurrency_safe_write(object_to_write, filename, write_func): """Writes an object into a unique file in a concurrency-safe way.""" thread_id = id(threading.current_thread()) temporary_filename = '{}.thread-{}-pid-{}'.format( filename, thread_id, os.getpid()) wri...
a2ef6dc6cb69523bc7fd487c2d1298a1c59d5323
3,603,379
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
def feedback_reply(): """ 反馈回复 """ if request.method == "GET": feedback_id = request.args.get("feedback_id") page = request.args.get("page") if feedback_id: feedback = None try: feedback = FeedBack.query.get(feedback_id) except...
aab76ef9191066cd546a8e9e7fab62f1331aea6c
3,603,384
from typing import Optional def subcommand( name: Optional[str] = None, description: Optional[str] = None ) -> SlashSubCommandConstructor: """Build a subcommand for within a group.""" return SlashSubCommandConstructor( parent=None, name=name, description=description, )
a5defe20061533e00b7c0b87c82f43e5777bf030
3,603,385
import random def genRandomStructure(): """ Generates a random neural network structure. """ s = [] # Input layer has either 2 or three nodes. if random.uniform(0, 1) > 0.5: s.append(3) else: s.append(2) p = 1.0 while p > 0.5: # Add a new layer of random si...
efd1ea11e27cdea9222052ac7f12dbed89f5ac44
3,603,386
def pix(cm_value, dpi=600): """Function to convert figure sizes in cm to pixels based on a dpi requirement""" return int(np.round((cm_value/2.54)*dpi))
27ac1059441438b4c68497f3968ca602fbff1c74
3,603,387
import logging def distribution_plot(data, title="Distribution", fig_size=(5, 5), c="red", save_as=None, logger=None): """ Build, save, and return a heat map plot. :param pandas.DataFrame data: A pandas DataFrame containing data for the plot :param str title: O...
3db1d1bc1c126e54c5ee48e12a6124594fd144ed
3,603,388
from pathlib import Path def get_lon_lat_path(ax, transform, lon_lat): """ Draw a curve, taking into account discontinuities. Parameters ---------- ax : ~matplotlib.axes.Axes The axes in which to plot the grid transform : transformation class The transformation between the wor...
c9d48b36e1d5bdee955fc93befdabc39c3424935
3,603,389
def get_keck_osiris_filt(name): """ Define keck osiris filters as pysynphot object """ try: t = Table.read('{0}/keck_osiris/{1}.txt'.format(filters_dir, name), format='ascii') except: raise ValueError('Could not find keck_osiris filter {0} in {1}/keck_osiris'.format(name, filters_dir...
4d918a21fb40d4e39843653a95e6367b5a935be4
3,603,390
from datetime import datetime def parse_time_from_schedule(str_time, parsed_time_is_future): """ Given a string time in the format of SCHEDULE_TIME_FORMAT = '%H:%M' and a boolean value stating if that time is in the future or not, convert that string into a datetime object. Some examples, assuming...
665e8e31785c05c0536ad643afc22f7895c550e8
3,603,391
def validate_boxes(boxes, image_size=None, min_area=None, box_format='corner', normalized=False): """ Checks if the given boxes are valid. :param boxes: array of boxes with shape (#boxes, 4) :param image_size: If set check for each box if it is in the image :param min_area: if set check for each box...
6658fed8b2cba457968220142e86e64492353716
3,603,392
def get_short_long_labels_from_qval_dict(qval_dict, geometry="saxs"): """Y.G. 2016, Dec 26 Get short/long labels from a qval_dict Parameters ---------- qval_dict, dict, with key as roi number, format as {1: [qr1, qz1], 2: [qr2,qz2] ...} for gi-saxs format as {...
883ed4fdbd9ccbd367830a73502d99b816be1306
3,603,393
def get_number_of_hangars_to_visit() -> int: """ Function loads the number of stops/hangars to visit """ nr_of_hangars_to_visit = input().rstrip() while not is_number_of_stops_ok(nr_of_hangars_to_visit): print('Incorrect value!') nr_of_hangars_to_visit = input().rstrip() return...
48ffb96ee3978b67b1da049271d7a2309b8d0b3a
3,603,394
def filter_errors(seq, errors): """Helper for filter_keys. Return singleton list of error term if only errors are in sequence; else return all non-error items in sequence. Args seq: list of strings errors: dict representing error values Returns List of filtered items. """...
93f44cd933e48974c393da253b7f37057ea7de19
3,603,395
def state_to_df(statefile): """Transform state file into pandas dataframe """ return pd.read_csv(statefile, compression='gzip', sep=' ', skiprows=[1,2] )
995bb5a3695c4bc25a54d629dadbcae78f5c80e7
3,603,396
import torch def train_torch_model(network, config, data_iterator, new_weights=False): """Main function to run the optimization. Parameters ---------- network : class A pytorch network class. config : yaml The configuration file. data_iterator : dict A data iterator wi...
8ac02cb370ccee07909ced8c321795eb4ba3e05d
3,603,397
def _offset(x, y, xoffset=0, yoffset=0): """Return x + xoffset, y + yoffset.""" return x + xoffset, y + yoffset
a6c88b2ee3172e52f7a538d42247c0fdc16352f8
3,603,398
import psutil def net_stat_recv(x, interface=None): """ Get the number of bytes received. """ if not interface: interface = get_netiface() if interface: return psutil.net_io_counters(pernic=True)[interface].bytes_recv else: return 0
4d829d3ef493d0437bdfae479778f4f7d2587ce9
3,603,399