content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import copy import scipy def hexdensity(x, y, bounds=None, bins='log', scale='log', cmap=None, vmin=None, vmax=None, ax=None, cax=None, unit='TPM', entity='genes', gridsize=175, fontsize=12, show_corr=True, clip_on=True, rasterized=False): """Wrapper for hexbin""" ...
9e94e00368103d02a67f9077ed3fbe02d30cc53d
67,257
def add_lags_to_sequences(X, lags): """ Given input sequences X adds its lagged versions as extra dimensions, where non-integer lagged versions are computed via linear interpolation. # Input :X: an array of sequences of shape (..., num_examples, len_examples, num_features) :lags: a ...
8d4af80bce97d640080ac9f15945e0371504d5f3
67,258
def reinforce_score(reward: tf.Tensor, baseline: tf.Tensor, decoded: tf.Tensor, logits: tf.Tensor) -> tf.Tensor: """Cost function whose derivative is the REINFORCE equation. This implements the primitive function to the central equation of the REI...
f9ceb3f6bae1be453136fbd29a48f0378ac281e1
67,259
def set_exposure(): """ JSON requirements: - device-type - exposure-time """ data = request.get_json() # Ensure body data if "exposure-time" not in data.keys(): abort(400, "Missing 'exposure-time' object.") try: # Set exposure time CaptureImage.set_ex...
98e1e0db0aa559c66a30b57df6b1eb8f6ebbe5cd
67,260
from re import T def build_cost_functional(lambda_val, h, y_sh, Thetas): """ build_cost_functional (with regularization) J=J_y(Theta,b) # J\equiv J_y(\Theta,b), but now with X,y being represented as theano symbolic variables first, before the actual numerical data values are given INPUT/PARAMETERS =============...
ed670bd7e8d0174d4d9beb9c1902f625792ef119
67,261
def estimatefwhm(objects,verbose=False): """ Estimate FWHM using objects.""" print = getprintfunc() # Get print function to be used locally, allows for easy logging # Check that we have all of the columns that we need for f in ['mag_auto','magerr_auto','flags','fwhm']: if f not in objec...
bf8ed2612529c41ab1756de0d23cda8554c8fbd5
67,262
def sigmoid(x): """Compute softmax values for each sets of scores in x.""" return 1.0 / (1+ np.exp(-x))
67a4db30250aa5c9d03769bf83678f89898bc821
67,263
def create_objects(texture_map, list_of_meshes): """ Create an object for each mesh. For each object, we set the diffuse reflectance as the corresponding texture. Parameters: texture_map (dict[str -> pyreder.Texture): List of textures to apply to diffuse reflectance. ...
719cd34cb2ca28ab205771711ce90132aeef4da0
67,264
def check_uk_postal_code(code, start, end): """Check postal code for uk, split the code by regex. Example postal codes: BH20 2BC (UK), IM16 7HF (Isle of Man). """ pattern = r"^([A-Z]{1,2})([0-9]+)([A-Z]?) ?([0-9][A-Z]{2})$" code, start, end = group_values(pattern, code, start, end) # replace ...
ba7afb6f4c5ff8e6ae593d18c5d18f0a0ea83ac8
67,265
def is_auth(username, password): """ Userテーブルに存在するか否かを返す """ users = db.session.query(User.username, User.password) db.session.close() for user in users: if user.username == username and user.password == password: return True return False
ceadd075ebbb28f3fbff8df4cb2c3ac8a26eee4f
67,266
from functools import reduce import operator def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left', separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x): """Indents a table by column. - rows: A sequence of sequences of items, one sequence per row. - hasH...
4359e9d7908d08dbbc9cee4ef5b52514cc6b9d2d
67,267
def dCOV(x, y, rowvar=1, uv=False, all_est=True): """Estimate dCov measure(s) between x and y. Allows uni- or multi-variate estimations Name dCOV was chosen to match implementation in R energy toolbox: http://cran.r-project.org/web/packages/energy/index.html Parameters ---------- rowvar : int...
6d9c2d7cff26b1e00e8bab68867513a0de75c2bf
67,268
import PIL import io def img_bin_to_img_arr(img_bin_bytes, use_grayscale=False): """Convert image binary data to numpy array. Args: img_bin_bytes: binary image data bytes. use_grayscale: convert to grayscale. Returns: numpy array: (height, width, chs). """ pil_img = PIL.Image.open(io.BytesIO(i...
38b9ba17eb288e0b69172b6ec48a535cbb5df54d
67,269
from websauna.system.model.meta import Base def create_test_dbsession(request, registry: Registry, transaction_manager=transaction.manager) -> Session: """Create a test database session and setup database. Create and drop all tables when called. Add teardown function py.test to drop all tables during teardow...
7a0d8323566d5d098b8e0df230246ac0612947dc
67,270
def rgb_blend(col1, col2, fraction=0.5): """ Calculates colour between two colors. Definition ---------- def rgb_blend(col1, col2, fraction=0.5): Input ----- col1 1st rgb colour tuple col2 2nd rgb colour tuple Optional Input -------------- fractio...
b7526edb6983c618cd01cd78b259b12479602a3e
67,271
def normalize(x): """Normalization helper function.""" return x / np.linalg.norm(x)
4bf3c21f1a7cfa8e8929671d24f545f1208206a2
67,272
import torch def plot_meshes(meshes: Meshes, *, in_subplots: bool = False, ncols: int = 1, **kwargs): """ Takes a Meshes object and generates a plotly figure. If there is more than one mesh in the batch and in_subplots=True, each mesh will be visualized in an individual subplot with ncols number of su...
cd7b6cbe2cfa7b191034c52cf358d6124972e3f4
67,273
def my_simple_str(x): """Seems to be useless, but "no signature found for builtin type <class 'str'>" is raised otherwise""" return str(x)
bbe332fa413a093d634b1ea9010f6b17212594a2
67,274
def convect(sigma, interps): """Convect interps based on density (sigma). Ignores variations in cell depths and convects vertically :arg interps: dictionary of 3D numpy arrays. Key represents the variable name. :type interps: dictionary :arg sigma: sigma-t, density, 3D array ...
0538cd97dd09a808071fee28f5097ea1a4298eb2
67,275
def notqdm(iterable, *args, **kwargs): """ silent replacement for `tqdm` """ return iterable
f37a5f84cf02987e4ada0ba8c0ee324c7a676903
67,276
def getUserUTXO(user: int, UTXO: list = None): """ Get a list containing the amount of each UTXO for a given user user: user ID of the user whose UTXO you want to get UTXO: array of UTXO to use instead of default one: c.BC_UTXO """ if UTXO is None: UTXO = c.BC_UTXO amounts = [] ...
5a6eea0507b4ff892a2b7937adb63d494eecf3df
67,277
def make_surv_array(t,f,breaks): """Transforms censored survival data into vector format Arguments t: Array of failure/censoring times. f: Censoring indicator. 1 if failed, 0 if censored. breaks: Locations of breaks between time intervals for discrete-time survival model (always ...
87275a603f5d63e358f7b2e69086167d37eaaf79
67,278
def get_dc_environment_by_search(search=dict()): """Return a list of dc environments by dict.""" try: environments = DivisaoDc.objects.filter() env_map = build_query_to_datatable_v3(environments, search) except FieldError as e: raise ValidationAPIException(str(e)) except Excepti...
b5d036795d7ac5ddfcb21f37c2764c76c5490ac3
67,279
def load_task(task_type): """Preload organisation data.""" task_type = TaskType[task_type] record_model = getattr(models, task_type.name.title().replace('_', '') + "Record") form = FileUploadForm(extensions=["csv", "tsv", "json", "yaml", "yml"]) if form.validate_on_submit(): try: ...
3d5c8b768aae3ac320810a954f61c4acb55fc68b
67,280
from typing import Tuple def belief_sim_from( gridverse_inner_env: InnerEnv, ) -> belief_types.Simulator: """Transforms ``gridverse_inner_env`` into a sim usable for the belief :param gridverse_inner_env: a domain from ``gym_gridverse`` :return: a simulator suitable for ``pomdp_belief_tracking`` ...
b6abb4767a5340aa4babd763cb8c9e2495481290
67,281
import scipy def convert_continuos_f0(f0): """CONVERT F0 TO CONTINUOUS F0 Reference: https://github.com/bigpon/vcc20_baseline_cyclevae/blob/master/baseline/src/bin/feature_extract.py Args: f0 (ndarray): original f0 sequence with the shape (T) Return: (ndarray): continuous f0 with the shape (T) ...
38cacad911faf3c4240f6737aa0915cd5f78896e
67,283
import six from typing import OrderedDict def getHistory(symbols, startDate, typ='daily', session=None): """ Returns history for ONE (or SEVERAL) symbol(s) """ try: startDate = startDate.dt.strftime(TIMESTAMP_NOSEP_FMT) except: pass if isinstance(symbols, six.string_types): ...
4697019941c69887056a1ff87eee1442eec5c232
67,284
def resnet50_earlyexit(pretrained=False, **kwargs): """Constructs a ResNet-50 model. """ model = ResNetEarlyExit(Bottleneck, [3, 4, 6, 3], **kwargs) return model
865f7ff36a0079b870498bbfba7d5cf5fa95aa6a
67,285
def _aux_epoch_indicators(epoch): """ """ all_accuracy, all_loss = [], [] for row in epoch: aux = ' '.join(row) if 'accuracy:' in aux: # / remove '\x08' / separate num / remove space acc = row[-1].replace('\x08', '').split(':')[-1].strip() ...
a4ecfc9ac23a5a56cec5f89bf4cf79643fbc1e3b
67,286
def convertFrom1D(list): """ Convert from a list to a matrix with the appropriate dimensions """ return [[x] for x in list]
c3bd41be26a20c6895c6ecc30d7e28005a17a44e
67,287
def get_verification_url(user=None): """ Returns the verification url. """ verf_link = "" if user: try: prev_token = UserToken.objects.get(email = user.email, token_type = 0, status = False) if prev_token: prev_token.status = True ...
6fe4f7665a862aa4b7591c18ba32b6c7d14502d4
67,288
import asyncio async def maybe_async(func, *args, **kwargs): """异步调用一个函数,该函数可能是同步函数,也可能是异步函数""" result = func(*args, **kwargs) if asyncio.iscoroutine(result): result = await result return result
ac1d507c8f83b573ef5c3416e2285f3df752d4aa
67,290
from datetime import datetime def get_tail_nature_date(nature_year: str): """ 根据传入自然年的年份获取该自然年最后自然周最后一天的日期 @日期: 2021/05/07 @作者: 徐嘉辉 Args: nature_year: 自然年字符串,形如2020 Returns: yyyymmdd格式的自然年最后自然周最后一天的日期 """ """ 判断本年度12月31日属于哪个自然年,若属于本年度则判断12.31的自然周,得到本年度最后一个自然周的...
968309bd7518f603cbcddcf377bf90ecf04e87cb
67,292
import pprint from datetime import datetime def _JSONtoCSV1_1(data, domains_metadata, columns_to_add): """Rework the top-level JSON results to a CSV file with the added metadata from the domains file""" logger.info("Structure of this file is API 1.1") header = '' body = [] pp = pprint.PrettyPri...
9d821286fe4c184dd307747d48fc60edb464793e
67,293
def tracking_error(r_a, r_b): """ Returns the Tracking Error between the two return series """ return np.sqrt(((r_a - r_b)**2).sum())
8fb180568fc838458cf3754380869714f7b3fd80
67,295
def get_current_price(symbol): """Get current price by symbol.""" if len(symbol) > 5: return "symbol exceeded length", status.HTTP_400_BAD_REQUEST sanitized_symbol = alpha_string(symbol) data = Robinhood.get_current_price(sanitized_symbol) return data
8cb1c853b8a20c072705c784ebaf3789b556e237
67,296
def _format_decode_code_level(message, signal_names, variable_lines): """Format one decode level in a signal tree. """ body_lines = [] conversion_lines = [] muxes_lines = [] for signal_name in signal_names: if isinstance(sign...
8b31e6224616f2cb16077a42d0f1e31372a3e073
67,297
def url_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Role for linking to url articles. :url:`https://google.com` -> link: https://google.com text: https://google.com :url:`Google <https://google.com>` -> link: https://google.com text: Google :ur...
3a25cf711b69e7092fe429b2a2e0fefc07aefb09
67,298
from typing import List from typing import Dict def build_label_relationship_dict(df: pd.DataFrame, names_to_ignore: List[str]=["UNKNOWN, BENIGN"] ) -> Dict[str, str]: """Builds a dictionary which contains as key malware family name and as value m...
5400ad7a96dfdae8d46c258d66ecdc690d1d0b24
67,299
def get_role(): """Get the role of the current process""" return CUR_ROLE
dc4908bd5287952bd6ecd6a58f84e5e3007464e2
67,300
def generos(): """ Muestra las configuraciones para los generos """ grid = webgrid.WebGrid(crud) grid.datasource = db(db.generos).select() grid.pagesize = 20 #grid.fields = ['db.catmod.id', 'db.catmod.nombre', 'db.catmod.posicion'] #grid.filters = ['db.catmod.catmod', 'db.catmod.nombre']...
880ec4d7b5f9f7f848cc8d33c1a97a30adf72e99
67,301
def searcher(nlp: Language) -> TokenSearcher: """It returns a token searcher.""" return TokenSearcher(vocab=nlp.vocab)
26ec606d6eb2792be668f2fc0eb0ae09629591fc
67,302
def replace_value(data, value=0): """Replace specific values in array with NaN :param data: Array where values should be replaced :type data: NumPy.Array :param value: value inside array to be replaced with NaN, defaults to 0 :type value: int, optional :return: array with new values :rtype:...
501f7daca3942a9d28ebf95fb3285af77a4230d0
67,303
def random_csr(shape, density, sorted_): """ Generate a random qutip CSR matrix with the given shape, nnz density, and with indices that are either sorted or unsorted. The nnz elements will always be at least one (use data.csr.zeros otherwise). """ return qutip.core.data.CSR(random_scipy_csr(sh...
effe8ceb67e45ab08ff258f071c8109bc49dd853
67,304
import pickle def getScores(imgURLs, captionTexts, sep='\n'): """ The function """ modelpath = 'models/xgbr_1.pkl' model = pickle.load(open(modelpath, 'rb')) imgURLs = imgURLs.replace('\r','') captionTexts = captionTexts.replace('\r','') imgURLs = imgURLs.split(sep) captionTexts ...
5dd97f8c036cffbe31d1d954a12026e340c2126b
67,305
import socket def _get_vault_path(device_uuid, config): """Generate full vault path for a given block device UUID :param: device_uuid: String of the device UUID :param: config: configparser object of vaultlocker config :returns: str: Path to vault resource for device """ return '{}/{}/{}'.for...
d6b1aab6036f348560b8549584a4e0f4b51cb4bd
67,306
def prompt_timestamp(msg: str) -> NychthemeronTime: """Prompts the user to enter a timestamp to get a NychthemeronTime.""" while True: # Enter input loop. timestamp = input(msg) try: nt = parse_timestamp(timestamp) break # Exit the input loop if successful. exce...
161b93336fd97ea1f756de193a679716d5c26ea0
67,307
def slice2limits(slices): """ Create a tuple of min,max limits from a set of slices Parameters: * slices: list of slices Returns: Tuple of minimum and maximum indices """ mins = [s.start for s in slices] maxs = [s.stop-1 for s in slices] return mins,maxs
1196e67fea135fb3c363def9d5fe53a0ada9b0af
67,308
def get_element(traj_frag_molid, frame_idx, index): """ Parse atom label and return element Parameters ---------- traj_frag_molid: int Denotes trajectory id in VMD frame_idx: int Frame of simulation in trajectory fragment index: string VMD atom index Returns ...
90a73dab6a3c28d6d3338ebd61f742eab61fba2d
67,309
def init_correlation_wf(name="correlation_wf"): """ This workflow calculates betaseries correlations using a parcellation from an atlas. .. workflow:: :graph2use: orig :simple_form: yes from nibetaseries.workflows.analysis import init_correlation_wf wf = init_correlatio...
c35345fc0621a4bd3aa15c757f718d21b09f9e99
67,310
def solution(array, n_rotations): """ Returns the Cyclic Rotation of array with n_rotations positions to the right. """ n = len(array) n_rotations = n_rotations % n if n > 0 else 0 return array[n - n_rotations:] + array[:n - n_rotations]
6f5edc0c8ec3d0e58830466e61577e80a725a624
67,311
def lin_fall(x, max): """f(0)=1. Linear fall off. Hits 0 at max.""" return clip01((max - x) / x)
1f231f733551a61f34b7f94bcc3c09150a5e76f4
67,312
import uuid def get_promotion_lock(replica_set): """ Take a promotion lock Args: replica_set - The replica set to take the lock against Returns: A unique identifer for the lock """ lock_identifier = str(uuid.uuid4()) log.info('Promotion lock identifier is ' '{lock_identi...
e454a75ce7f85d28c1dcd42867bbc28ae967c121
67,313
import re def check_question(msg): """ 提问 :param msg: :return: """ return re.search('\?', msg) or re.search('?', msg) or re.search('吗?', msg)
3ac884d153a32586d5dfe197b597f6e125bed8eb
67,314
def count_all_problems_for_admin(): """Returns the number of all problems. Returns: The count. """ return _db.problems.find({}).count()
f80e032989735a75111dc3ab8c1db660ad72b2f7
67,315
def search_optimal_strike( table, v_cue=1, dt=0.02, dang=0.5, return_once_find=False, event_based=False, ): """Search optimal strike.""" simulate_func = simulate_event_based if event_based else simulate simulate_args = ({'return_once_pocket': True} if event_based...
8b04087c2470c0c5fd9f1f32cdd11c82b56de20f
67,316
def check_color(board: list, num=9) -> bool: """ Function check if in each color of board are unique elements. It there are function return True. False otherwise. >>> check_horizontal(["**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 12 *...
3a6e8418b227e8101f9a8d1338c79193da285bff
67,318
import yaml import json def load_data(file_path, use_yaml=True): """Load data from a given YAML file into a Python dictionary. :param file_path: path to your YAML file. :param use_yaml: use yaml or json :return: contents of the file as Python dict. """ with open(file_path, "r") as f: ...
b136e16cd614cfdb3ca791a6d64d513cf52dbf7c
67,319
import gettext def update(id): """Change user settings. --- post: summary: Change user settings description: > Update a role to change its display name, or to define a new login password. Users can only update roles they have write access to, i.e. their own. param...
8a084ac0a58a421e92447a51997ed3815df34a24
67,320
def load_n_z(block, sample='wl_number_density'): """ Load the n(z) profile in each bin as a 2d array """ num_den = sample n_z = [] N_zbins = block[num_den, 'nbin'] for i in range(1, N_zbins + 1): n_z += [block.get_double_array_1d(num_den, 'bin_%d' % i)] n_z = np.array(n_z) z = bloc...
a2a2db598f31bd3f931042e5bb5dfee1f356f322
67,321
import time def retry_on_exception_exponential_backoff(exceptions, initial_delay=0.1, total_delay=15, exponential_factor=2): """ Retries with exponential backoff. :param exceptions: The exceptions that we will catch and retry on. :type exceptions: list[Exception] :param initial_delay: num seconds...
c642c383e1f9ef6b82bb01761abd1b1efda1ce4f
67,322
def parallax_to_scale(p_meas, p_err, snr_lim=4.): """ Convert parallax flux density scalefactor `s ~ p**2`. Parameters ---------- p_meas : float Measured parallax. p_std : float Measured parallax error. snr_lim : float, optional The signal-to-noise ratio limit used...
64aa4290e5166787ac8f2f1de96e421fc9e183c4
67,323
def levenshtein_distance(s1: str, s2: str) -> int: """Returns the levenshtein distance between two strings""" # https://stackoverflow.com/a/32558749 if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2 + 1] for i1...
1b70d6e2b6241e8b0296c3698aae322bb081fe8c
67,325
from typing import Iterable def validate_multiple_choice_param( params: RequestParams, key: str, choices: Iterable ) -> RequestParams: """Verify that a multiple-choice request parameter contains valid value(s); if not, raise an error. **Used for endpoint-specific params.** Returns: Parame...
5986b2fbed3756137d11462a9c9551418342f926
67,326
def mqtt_client(axis_device) -> MqttClient: """Returns the mqtt_client mock object.""" return MqttClient(axis_device.vapix.request)
00568fe250132b5ec5fbcef87b3515780ed85cbf
67,327
from typing import Dict def loads(text: str) -> Dict: """ Parses a text in Gura format :param text: Text to be parsed :raise: ParseError if the syntax of text is invalid :return: Dict with all the parsed values """ return GuraParser().loads(text)
b7c9dc4d6a1c4fadba47b562c0a026d68e46acd3
67,329
def allocate_lan_networks(root, service, username, logger): """ Main logic for allocating lan networks for remote sites""" lan_pool = service.lan_pool # 10.16.0.0/16 pool_name = get_lan_pool_name(service) prefix = lan_pool.split('/')[0] # 10.16.0.0 prefix_len = lan_pool.split('/')[1] # 16 v...
8a973c8f78f4685311df643c813e3af2bbea464a
67,330
import math def flinn(stream, noise_thres=0): """ Computes the azimuth, incidence, rectilinearity and planarity after the eigenstructure decomposition method of [Flinn1965b]_. :param stream: ZNE sorted trace data :type stream: List of ZNE sorted numpy arrays :param noise_tresh: Variance of th...
63b6895ff3945be93494b2e4db801dc6d356dd3c
67,331
def _to_bool(value): """Simplified version of the bool filter. Avoids having a dependency on Ansible in unit tests. """ if value == 'yes': return True if value == 'no': return False return bool(value)
6e0da8b211ce638e19764a966c417841fafe2a5b
67,332
import click from datetime import datetime def upload(conf): """ Upload to remote and wipe out the local data. """ click.secho('UPLOAD SYNC IN PROGRESS - PLEASE DO NOT INTERRUPT - %s' % datetime.now(), fg='yellow') outcome = _clone(True, confDir = conf.confDir, confFiles = conf.confFiles, verbose = conf.v...
b3faf09469ad294071d09aaaa55b39653b88687f
67,333
def get_mel(filename): """Process loaded audio to mel-spectrogram.""" audio, _ = load_wav_to_array(filename) audio_norm = audio / config.au_max_wav_value audio_norm = np.expand_dims(audio_norm, 0) melspec = _stft.mel_spectrogram(audio_norm) melspec = np.squeeze(melspec, 0) return melspec
f621821d61696d5f97a6ad203e9d31cd737fec70
67,335
import math def tan(x): """tan(x) Return the tangent of x.""" x = complex(x, 0) sr = math.sin(x.real) cr = math.cos(x.real) shi = math.sinh(x.imag) chi = math.cosh(x.imag) rs = sr * chi is_ = cr * shi rc = cr * chi ic = -sr * shi d = rc*rc + ic * ic real = (rs*rc ...
f2aedcff8f7fbce85169dab263163aa461367a53
67,336
from typing import Union from typing import Optional from typing import List from typing import Dict from pathlib import Path import json def compose_config( config_path: Union[str, PathLike], config_name: str, job_name: str, serialization_dir: Optional[Union[str, PathLike]] = None, config_overrid...
0284e10e9ef78e0c5a1c21b9619a95bb30c18440
67,337
def melted_power_ratio(index_df:PandasDf, power_df:PandasDf, freqs:list, selected_categories:list): """ Get power ratio and melt dataframe for seaborn plotting. Parameters ---------- index_df : PandasDf, experiment index power_df : PandasDf, contains pmat and frequency vectors for every row of ...
f427c2b5cab256f1101634d9f06e8bca6e3a9c46
67,338
def CreateInstanceDrbd8(nodes, fail=False): """Creates an instance using disk template 'drbd' on the given nodes. @type nodes: list of nodes @param nodes: nodes to be used by the instance @return: the created instance """ assert len(nodes) > 1 return _CreateInstanceByDiskTemplateRaw( ":".join(n.prim...
14205ca5d1a871247a3fd17ab946b3e6d8f8d037
67,339
def get_fn_at_x(xgrid, fn, at_x): """ Returns function at x Args: xgrid np.array(n_grid): Grid where function was evaluated fn np.array((n_samples,n_grid)): Multiple function evaluations at xgrid at_x float: Value closest to the desired function evaluation Returns: ...
5d70e4d720340c156a2c3987f2506523cb1c514e
67,340
def getNet(chrom, loops, genes, pdis=2000, gap=1): """ Get the enhancer/promoter network for one chromosome. """ #step 1 get merged anchors anchors = stichAnchors(chrom, loops, margin=gap) #step 2 annotate anchors nanchors = {} ts = np.array([[tss] for tss in genes.keys()]) tree = ...
ce367e200c0156302db7fd5e4f56e14f7c220be8
67,341
import requests def get_day_prices(date, rate=None): """ Get PVPC prices for specific date. Args: date: Datetime obj of date to recover information for. rate: Optional string. If None all available rates will be added to the answer. If one is selected just that will be return. ...
556431f368d14b24af7df1290b37359d08109d25
67,342
import random def get_best_move(board, scores): """ Function that computes the best move for the machine given the actual board state """ max_score = max(scores[row][col] for row, col in board.get_empty_squares()) candidates = [(row, col) for row, col in board.get_empty_squares() ...
afabd281ad1547b118cab10ccc912bdf4956f9c4
67,343
def kalman_filter(protein_at_observations,model_parameters,measurement_variance,derivative=True): """ Perform Kalman-Bucy filter based on observation of protein copy numbers. This implements the filter described by Calderazzo et al., Bioinformatics (2018). Parameters ---------- protein_at_obse...
68c0ee11edea65ddea3d6596887f0d0d5d8297b8
67,344
import requests def get_data(coin, currency, exchange): """ Fetch all time data from cryptocompare API :param coin: crypto coin (BTC, XRP...) :param currency: fiat (CAD, USD, EUR...) :param exchange: name of the exchange :return list[dict]: returns the all time data from the coin/currency prov...
5b6d48399974b2872e22b8e98b92c779799b1955
67,345
def recognize_speech_from_mic(recognizer, microphone,language): """Transcribe speech from recorded from `microphone`. Returns a dictionary with three keys: "success": a boolean indicating whether or not the API request was successful "error": `None` if no error occured, otherwise a str...
05156544e1c69fee866e17508e19b10dbee27faf
67,346
from typing import Dict def handle_response(res: Response) -> Dict[str, object]: """ Returns the sdk JSON response :param res: A string url endpoint. :type: str :return: Dict[str, object] """ try: json = res.json() except ValueError as e: handle_parse_error(e) if ...
2d326d81926ba2fbb44612bb76f56bc7406c6bba
67,347
def encode_tag_ref_str(self, node, parent=None, attr_index=None): """This function is the same as encode_string, except that when a halo reference string has zero length, the string doesnt actually exist. It's not just a delimiter character, the string isn't stored at all. To make it work, we instead re...
e6a3acc3691f122e3325fa70eb9ab427456e0edb
67,348
def vapour_pressure_deficit(es, ea): """ VPD - Vapour Pressure Deficit :param es: :param ea: calculated by vp_from_rhmin_rhmax() :return: """ return es - ea
cb1d22a236081b3de3f080f8f2e2acb64543620f
67,349
def get_pca_mean_and_pre_whitener_epochs(epochs, picks, decim, pre_whitener): """Aux method based on ica._fit_epochs from mne v0.15""" if picks is None: picks = _pick_data_channels(epochs.info, exclude='bads', with_ref_meg=False) # filter out all the channels the raw wouldn't have initialized ...
ed27c41fb68b83d2897dcd9ca7c3a6044ec454eb
67,350
def _run_vagrant_command(node_id, args=[], creds={}): """ args: A tuple of arguments to a vagrant command line. e.g. ['up', 'my_vm_name', '--no-provision'] """ cd = 'cd "{}/{}"'.format(HOST_NODES_DIR, node_id) command = ['vagrant'] + [arg for arg in args if arg is not None] return _host_ssh...
91822162ba28a4c6b9bbe9ba4328a2d956223696
67,351
async def _deleteIEXCloudAsync( url, token="", version="stable", filter="", format="json" ): """for iex cloud""" return await _deleteIEXCloudBaseAsync( base_url=_URL_PREFIX_CLOUD, url=url, token=token, version=version, format=format )
85bb12c86dbf2537cd8a129b31aad2644e79ddf2
67,352
def evolve_lindblad_discrete(evolution_time, initial_densities, system_eval_count, controls=None, cost_eval_step=1, costs=list(), hamiltonian=None, ...
f52b9bd15c6fd137f1f9b504f78c32577f2db198
67,353
import asyncio def get_next_valid_seq_number(address: str, client: SyncClient) -> int: """ Query the ledger for the next available sequence number for an account. Args: address: the account to query. client: the network client used to make network calls. Returns: The next val...
c3dd4d0427a39ba8e612a5689a1648567fd4276b
67,354
from pathlib import Path import logging def readMad_hdf5 (filename, paramstr): #timelims=None """@author: Michael Hirsch / Anna Stuhlmacher madrigal h5 read in function for the python implementation of GeoData for Madrigal Sondrestrom data Input: filename path to hdf5 file list of parameters to lo...
ed22f485e1cd9a7f155c03fa353250843534d1d7
67,355
from operator import concat def gumbel_sigmoid(logits, temperature, dtype=tf.float32, seed=0): """Gumbel Sigmoid Layer.""" logits = concat([logits, tf.zeros_like(logits)], 1) prob = gumbel_softmax(logits, temperature, dtype=dtype, seed=seed) return prob[:, 0]
57871305349c8582e67f156f497c2cf9f4370f22
67,356
def rfft(data, **kargs): """ rfft wrapper """ interface = fft_interface_select() return fft_interface_format(interface.rfft, data, **kargs)
e8a0bfa89e02a956a07c5701386a3b9b1455ec93
67,357
def purefa_argument_spec(): """Return standard base dictionary used for the argument_spec argument in AnsibleModule""" return dict( fa_url=dict(), api_token=dict(no_log=True), )
bc8302564bb397b523fde20a986465f3ecb496dd
67,358
def get_release_id(request): """Get the environment ID to release, from request. :param request: The falcon request object. :type request: :obj:`falcon.request` :return: The ID of the environment to release. :rtype: str """ return request.get_param("release")
c6d9aa4907ea0f150ac86930560fca59b7388484
67,359
def get_submission_relations(doc_id, submission_id): """ Get suggested mentions for a document. """ relations = [] for row in db.select(""" SELECT subject, relation, object, provenances, confidence FROM submission_relation WHERE doc_id = %(doc_id)s A...
0b3b3c8fa8766690d9abf4c942ccbe2eb85b63cf
67,360
def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos))
5f06ba50a29d680e992fcffc813d374eb6da4867
67,361
def train_GMM(data, cluster_num): """ 训练混合高斯模型 """ model = GaussianMixture(n_components=cluster_num, covariance_type='full') model.fit(data) return model
e58325939fbe8e3394b19528eb783cb87eb8938e
67,362
def pf_rcc(): """ pf(failed test t) is determined by the root cause param in the change where t fails root cause is localized through manual inspection """ freq = {} failures, misconfs = parsing_utils.failure_map() for img in failures: for t, rootcauses in failures[img][C_EFFECTIVE]...
e7cbf6b64b5c0d677be7bce0c3826c87f1c78c73
67,363
import logging def get_markers(img, mode): """Get initial labels for segmentation.""" assert img.ndim == 4 markers = np.zeros(img.shape[0:3], dtype=np.int16) if mode == 'DWI': # Based on absolute value thresholds (non-scaled image). bg, fg1, fg2 = np.percentile(img, 50), 1400, 1600 ...
eb31fa5a2549eba2bf03b3a3b86689c0808558e9
67,364