content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_geometry_origin_mesh(obj): """ Get the mesh which is most suitable for origin of visual mesh. obj: Object(ID) """ # TODO: Use better way than this in finding relative inertial mesh inertia_meshes = [c for c in obj.parent.children if c.phobostype == 'inertial' and 'inertial_' + ...
ab1c447694bdb004bf3d5e16162210f9ef6af7c5
3,632,200
def read_fchk(in_name): """ Read a Gaussian .fchk. Returns the total energy, gradients and ground state energy. Parameters ---------- in_name : str Name of the file to read Returns ------- energy : float Gaussian total calculated energy in Hartree grad : list of...
c2686ca723dc2e874355879a84ec4b57157a70cf
3,632,201
def miles(kilometers=0, meters=0, feet=0, nautical=0): """ Convert distance to miles. """ ret = 0. if nautical: kilometers += nautical / nm(1.) if feet: kilometers += feet / ft(1.) if meters: kilometers += meters / 1000. ret += kilometers / 1.609344 return ret
6ffd67913280a7148a84463b9679a17e004176d6
3,632,202
def LookupScope(scope): """Helper to produce a more readable scope line. Args: scope: String url that reflects the authorized scope of access. Returns: Line of text with more readable explanation of the scope with the scope. """ readable_scope = _SCOPE_MAP.get(scope.rstrip('/')) if readable_scope:...
de7d24b6769830d55e6260d5ee2ac5b4846e854c
3,632,203
def label2binary(y, label): """ Map label val to +1 and the other labels to -1. Paramters: ---------- y : `numpy.ndarray` (nData,) The labels of two classes. val : `int` The label to map to +1. Returns: -------- y : `numpy.ndarray` (nData,) Maps ...
5bce8491e9eef3a8c36b784ee0e252c641b24fdf
3,632,204
from typing import Tuple def detect_corners(R: np.array, threshold: float = 0.1) -> Tuple[np.array, np.array]: """Computes key-points from a Harris response image. Key points are all points where the harris response is significant and greater than its neighbors. Args: R: A float image with the h...
b8cb5ae857a8255b263af2034703a0cf08ce66ca
3,632,205
import os def allocate_transects(mmt, transect_type='Q', checked=False): """Method to load transect data. Changed from Matlab approach by Greg to allow possibility of multi-thread approach. Parameters ---------- mmt: MMT_TRDI Object of MMT_TRDI transect_type: str Type of trans...
af68f72e25f2c8cca6130a0517b3a69e6d44a894
3,632,206
from typing import Union from typing import Iterable def add_file_replica_records( files: Union[Iterable[File], QuerySet], compute_resource: Union[str, ComputeResource], set_as_default=False, ) -> int: """ Adds a new laxy+sftp:// file location to every files in a job, given a ComputeResource. ...
0a703205bd0e972b8c1e829bd850946cc1fe855a
3,632,207
from typing import List import os def generate_config(imgs_dir: str, cursor_sizes: List[Num], hotspots: any) -> str: """ Generate helpers files. hotspots is JSON data for each cursor having xhot & yhot parameters.Provide `None` value set hotspots to middle of cursor. """ helpers.generate_...
d68c4fee25d073321e0c3a015279b6bedd3df4e5
3,632,208
import os import fnmatch def index_returns_directory(): """ Prior to compiling a master, it is useful to get the order of projects by their file name, as the compile.run() function traverses the directory top to bottom to build the master. We can then use this to compare with the order or projects...
c6599d21f0be6d9e0dc7785bdd8461b3b9cde6ce
3,632,209
def in_suit3(list, list0): """ test 2 suits of street numbers if they have crossed numbers For example: "22-27" in "21-24"retruns True :param a: Int of number :param b: String List of number :return: boolean """ text = list.replace("-", "") text0 = list0.replace("-", "") if (...
57409220b93c66ab4b957a05713e5e89b380253a
3,632,210
def mp_wfs_110_nometadata(monkeypatch): """Monkeypatch the call to the remote GetCapabilities request of WFS version 1.1.0, not containing MetadataURLs. Parameters ---------- monkeypatch : pytest.fixture PyTest monkeypatch fixture. """ def read(*args, **kwargs): with open('...
1c3f83f9ae7665a3cf77e5e2fa6217f72b7dc4ea
3,632,211
def extract_power(eeg, D=3, dt=0.2, start=0): """ extract power vaules for image Parameters ---------- seizure : EEG | dict eeg data D : int, optional epoch duration, by default 3 dt : float, optional time step (seconds), by default 0.2 start : int, optional ...
04c3fed38fa2a2d46ba7edee4bb3f04011d9d2a7
3,632,212
import time import tqdm def extract_HOG(generator, category='species', image_size=256, train=True, verbose=True): """ Extract HOG features for specified dataset (train/test). Args: generator (Generator class object): Generator class object. train (bool): Am I working with train or test da...
76cd3a6ed206bbbe258ade6433708dd8df20f990
3,632,213
def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple, range)): values = construct_1d_object_array_from_listlike(values) if getattr(values, "dtype", None) == np.object_: if hasattr(values, "_values"): ...
79790a639ee5946f81c033584904491bfcd9be8b
3,632,214
def build_training_response(mongodb_result, hug_timer, remaining_count): """ For reducing the duplicate lines in the 'get_single_training_movie' function. """ return {'movie_result': list(mongodb_result)[0], 'remaining': remaining_count, 'success': True, 'valid_key': True, 'took': float(hug_timer)}
77d541957ff9abaa51bd3eb7fd06b550f41291e2
3,632,215
def calc_fm_perp_for_fm_loc(k_loc_i, fm_loc): """Calculate perpendicular component of fm to scattering vector.""" k_1, k_2, k_3 = k_loc_i[0], k_loc_i[1], k_loc_i[2] mag_1, mag_2, mag_3 = fm_loc[0], fm_loc[1], fm_loc[2] mag_p_1 = (k_3*mag_1 - k_1*mag_3)*k_3 - (k_1*mag_2 - k_2*mag_1)*k_2 mag_p_2 = (k_...
00ba68c74d781748f39d2a577f227316dc523f0f
3,632,216
def generate( song_name, raw_data_name, base_path=utils.BASE_PATH, chunk_size=100, context_size=7, drop_diffs=[], log=False): """ Generate an SMDataset from SM/wav files. Only creates datasets with no step predictions. """ sm = SMData.SMFile(s...
b61a20cfe1080139d80b3a1ee4ad8e9a7a7c0928
3,632,217
from functools import reduce def cmap_map(function, cmap): """ from scipy cookbook Applies function (which should operate on vectors of shape 3: [r, g, b], on colormap cmap. This routine will break any discontinuous points in a colormap. """ cdict = cmap._segmentdata step_dict = {} # Firt ...
874618f4a685ae46edf896d759beafdd222dedf5
3,632,218
from datetime import datetime from typing import Dict from typing import Any def get_legislation_passed_legislature_within_time_frame( begin_date: datetime, end_date: datetime ) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetLegislationPassedLegislatureWithinTimeFram...
ed851675da641b33665a814f8d50ee936c97af7d
3,632,219
import glob import os def find_output(directory, extension="out", abspath=True): """ Find output file in a directory. Parameters ---------- directory : str Path to folder in which output should be located. extension : str File extension of output file (default: 'out'). abspath...
bb45e97990ea0a6ec98c9212ce9aa1b9effe3040
3,632,220
def trim_mismatches(gRNA): """ trim off 3' mismatches 1. first trim to prevent long alignments past end of normal expressed gRNAs 2. second trim to mismatches close to end of gRNA """ pairing = gRNA['pairing'] # 1. index of right-most mismatch before index -40 # if no MM is...
ab0bed78d29d64e9218201a561bb857fd80ed885
3,632,221
def validateRequest(endpoint, params): """Validate that a valid argument with the correct number of parameters has been supplied.""" if endpoint not in endpoints: helpInfo = ", ".join(endpoints.keys()) print(f"Invalid endpoint. Please use one of the following: {helpInfo}") return False ...
b2037f9ea1706f39c406e3708b445c0fb3474c01
3,632,222
import random def augment_sequence(seq): """ Flip / rotate a sequence with some random variations""" imw, imh = 1024, 570 if random.random()>0.5: for frame in range(len(seq)): for m in [0, 1]: seq[frame][m][0] = imw-seq[frame][m][0] # X flip if random.random()>0.5: ...
1f95c7e183cd696c985f30da335bcbc9337b5255
3,632,223
from mapalign import embed from sklearn import metrics from sklearn.utils.extmath import _deterministic_vector_sign_flip def dme(network, threshold=90, n_components=10, return_result=False, **kwargs): """ Threshold, cosine similarity, and diffusion map embed `network` Parameters ---------- networ...
97a5014fc0cf174ea10dca171fdaea96509ac3ef
3,632,224
def constant_substitution(text, constants_dict=None): """ Substitute some constant in the text. :param text: :param constants_dict: :return: """ if not constants_dict: # No constants, so return the same text return text template = Template(text) return template.safe_...
ea5b6e49818064fc6051740d85b9661ca431d3f7
3,632,225
def zticks(model_name, dat, let): """ Read model name and return the corresponding array of z-coordinates of front side of cells. """ delzarr = delz(model_name, dat, let) arr = np.array([np.sum(delzarr[:i]) for i in range(delzarr.size+1)]) return arr
12c48e5d73c364436aadaaa6a1d468d2e319c75c
3,632,226
import copy def reformat_args(args): """ reformat_args(args) Returns reformatted args for analyses, specifically - Sets stimulus parameters to "none" if they are irrelevant to the stimtype - Changes stimulus parameters from "both" to actual values - Changes grps string...
305999d1e1c252660314d837b7bbce8a8d5e7cc8
3,632,227
def load_xlsx_to_plan_list( filename, sort_by=["sample_num"], rev=[False], retract_when_done=False ): """ run all sample dictionaries stored in the list bar @param bar: a list of sample dictionaries @param sort_by: list of strings determining the sorting of scans strings include ...
dc106e243cf5174c263954a33a968a0ac2a83af1
3,632,228
def WTERMSIG(status): """Return the signal which caused the process to exit.""" return 0
d4f45d41de95308c4a16f374e58c16b4384f8fc0
3,632,229
import io def create_toplevel_function_string(args_out, args_in, pm_or_pf): """ Create a string for a function of the form: def hl_func(x_0, x_1, x_2, ...): outputs = (...) = calc_func(...) header = [...] return DataFrame(data, columns=header) Parameters -...
44d78a9d0a3146b4008868073e5828422b819cc8
3,632,230
def remove_duplicates(df: pd.DataFrame, **kwargs: dict) -> pd.DataFrame: """ Remove duplicates entries Args: df (pd.DataFrame): DataFrame to check Returns: pd.DataFrame: DataFrame with duplicates removed """ return df[~(df.duplicated(**kwargs))]
5d4f290acfda2f51334fc58bad71dd79f7b1a185
3,632,231
import sys import imp def mainfrozen(): """return True if we are a frozen executable. The code supports py2exe (most common, Windows only) and tools/freeze (portable, not much used). """ return ( pycompat.safehasattr(sys, "frozen") # new py2exe or pycompat.safehasattr(sys, "impor...
1e565fab2750127e0e451e53c2e74549f21521b9
3,632,232
from npc_engine.exporters.base_exporter import Exporter import click def test_model(models_path: str, model_id: str): """Send test request to the model and print reply.""" if not validate_local_model(models_path, model_id): click.echo( click.style(f"{(model_id)} is not a valid npc-engine ...
bf05a6147ceb8769c4cbe5bac25ceab906b4fa92
3,632,233
def create_x11_client_listener(loop, display, auth_path): """Create a listener to accept X11 connections forwarded over SSH""" host, dpynum, _ = _parse_display(display) auth_proto, auth_data = yield from lookup_xauth(loop, auth_path, host, dpynum) r...
806230b424f3ce2efa0197d50762b5e7ee497521
3,632,234
def expand_tile(expand_info): """Tile expander""" # get op info. input_desc = expand_info['input_desc'][0] attrs = expand_info['attr'] multiples = None for item in attrs: if 'multiples' in item: multiples = item['multiples'] output_shape, _, _, shape_compatible = _get_ti...
b4550770d82387d7245b142975b1e6d347a5b630
3,632,235
def compare_system_and_attributes_csv(self, file_number): """compare systems and associated attributes""" # get objects analysisstatus_1 = Analysisstatus.objects.get( analysisstatus_name='analysisstatus_1' ) systemstatus_1 = Systemstatus.objects.get(systemstatus_name='systemstatus_1') ...
d438b767af16deaa4d8d435a6ba7d4c6a943d026
3,632,236
def is_live_request(request): """ Helper to differentiate between live requests and scripts. Requires :func:`~.request_is_live_tween_factory`. """ return request.environ.get("LIVE_REQUEST", False)
1e5e64901715131f363d6d343acbd4d631cf6b6f
3,632,237
import requests from bs4 import BeautifulSoup def get_videos(episode): """ Get the list of videos. :return: list """ videos = [] html = requests.get(episode).text mlink = SoupStrainer('p', {'class':'vidLinksContent'}) soup = BeautifulSoup(html, parseOnlyThese=mlink) items = soup.fi...
34f13b9ace698738c62be6ac3794c9937844ab03
3,632,238
from typing import List import logging def validate_documentation_files(documentation_dir: str, files_to_validate: List[str] = None): """Validate documentation files in a directory.""" file_paths = list(filesystem_utils.recursive_list_dir(documentation_dir)) do_smoke_test = bool...
80a4b4b5f3ca42234cf3d2db86669f71c245e313
3,632,239
def _add_reference_resources(data): """Add genome reference information to the item to process. """ aligner = data["config"]["algorithm"].get("aligner", None) align_ref, sam_ref = genome.get_refs(data["genome_build"], aligner, data["dirs"]["galaxy"]) data["align_ref"] = align_ref data["sam_ref"]...
63b4d7f70e6074341f84429d4d4e90cfa56d8fab
3,632,240
def parse_solid_selection(pipeline_def, solid_selection): """Take pipeline definition and a list of solid selection queries (inlcuding names of solid invocations. See syntax examples below) and return a set of the qualified solid names. It currently only supports top-level solids. Query syntax exa...
6a69d79f0bdcf459c213262f05c06f9c0b256854
3,632,241
def _equal(v1, v2): """Same type as well.""" if isinstance(v2, float) and np.isinf(v2): return True if isinstance(v2, str): v2 = th.string(v2) return v1 == v2
0e5803da376019b93b6f3084cfb10fc0c36d873a
3,632,242
def dec_prefix(value, restricted=True): """Get an appropriate decimal prefix for a number. :param value: the number :type value: int or float :param bool restricted: if ``True`` only integer powers of 1000 are used, i.e. *hecto, deca, deci, centi* are skipped :return: de...
ecd78692a2638aa06b44292219f35488eb294667
3,632,243
from datetime import datetime def _download_coaching( loc_id: str, start_date: datetime.datetime, end_date: datetime.datetime = None, collection: str = "CoachingActionEntries", base = "prod", pipeline_name = "sleep_quality"): """Queries the database for given location id, source id and i...
8247446d6358a09b752c45d83d20bda59d3dc296
3,632,244
import random def Make_Random(sents): """ Make random parses (from LG-parser "any"), to use as baseline """ any_dict = Dictionary('any') # Opens dictionary only once po = ParseOptions(min_null_count=0, max_null_count=999) po.linkage_limit = 100 options = 0x00000000 | BIT_STRIP #| BIT_U...
d32d0b17935c7c5951e817f156de6223ee7f0d1d
3,632,245
def get_published_online_date(crossref_data): """ This function pulls the published online date out of the crossref data and returns it as an arrow date object :param doi: the DOI of interest that you want the published online date for :returns: arrow date object for published online date if it exists ...
5d2f506f34ff956b344d1663b78ef1fb72dc3d04
3,632,246
def ingredients_available(menu_item): """Accepts a dictionary of ingedients and checks if the machine has enough to make the drink""" for item in MENU[menu_item]['ingredients']: if resources[item] < MENU[menu_item]['ingredients'][item]: print(f"There is not enough {item} to make your order....
946ad6fe8ceadc2ec7a0889ff2b3a8d48191ea7e
3,632,247
from typing import OrderedDict def pyvcf_calls_to_sample_info_list(calls): """ Given pyvcf.model._Call instances, return a dict mapping each sample name to its per-sample info: sample name -> field -> value """ return OrderedDict( (call.sample, call.data._asdict()) for call in call...
937a748b3a0ff26a28ff4a4db5e1505dbb927ff9
3,632,248
def DesignPatch(Er, h, Freq): """ Returns the patch_config parameters for standard lambda/2 rectangular microstrip patch. Patch length L and width W are calculated and returned together with supplied parameters Er and h. Returned values are in the same format as the global patchr_config variable, so can be...
90b35a7c46f96c977ccd5ce4fed987d0c1beccd6
3,632,249
from typing import Optional def injection_file_name( science_case: str, num_injs_per_redshift_bin: int, task_id: Optional[int] = None ) -> str: """Returns the file name for the raw injection data without path. Args: science_case: Science case. num_injs_per_redshift_bin: Number of injectio...
57b034b6a60c317f0c071c1313d0d99f2802db30
3,632,250
def focal_general_triplet_loss(embs, labels, minibatch_size, alpha=0.2): """ NOTE: In order for this loss to work properly, it is prefered that labels contains several repetitions. In other word: len(np.unique(labels))!=len(labels) """ classes = tf.one_hot(labels,depth=minibatch_size) # Cla...
2dc3d531051a61217d1429c1c10c44f9422cec29
3,632,251
def angle_between(v1, v2): """ Returns the angle in degrees between vectors 'v1' and 'v2'.""" v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.degrees(np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)))
01ccbdd26398b1dbb14e08766c6fee4ec9d8006e
3,632,252
def SUM(A: pd.DataFrame, n) -> pd.DataFrame: """Sum (Time Series) Args: A (pd.DataFrame): factor data with multi-index n: days Returns: pd.DataFrame: sum data with multi-index """ At = pivot_table(A) res = At.rolling(n, min_periods=int(n/2)).sum() res = stack_table(re...
a761d854b516be3dd3d52bcc0060d87e074c9bf9
3,632,253
def load_properties(filepath, sep='=', comment_char='#'): """ Read the file passed as parameter as a properties file. """ props = {} with open(filepath, 'rt') as f: for line in f: l = line.strip() if l and not l.startswith(comment_char): key_value = l....
05769171ffe2e57e1022ff40b9c3ed2b82bb31bc
3,632,254
import posixpath import os def resolveComponents(url): """ >>> resolveComponents('http://www.example.com/foo/bar/../../baz/bux/') 'http://www.example.com/baz/bux/' >>> resolveComponents('http://www.example.com/some/path/../file.ext') 'http://www.example.com/some/file.ext' """ parts = list(...
78048dbcb48a62ad33b8587b23b9d731ed76bfa5
3,632,255
def query_add(session, *objs): """Add `objs` to `session`.""" for obj in objs: session.add(obj) session.commit() return objs
95ffa9e0f5a4a9255f8b0b063c5bd092f0f66039
3,632,256
from re import T from typing import Iterator def scale_streams(s: Stream[T], factor: T) -> Stream[T]: """ scale streams """ def scale_generator(g: Iterator[T]) -> Iterator[T]: """ scale generator """ yield next(iter(g)) * factor yield from scale_generator(g) ...
d6ddfc6c031c4e74ae284e9b92325bd86f6bcead
3,632,257
def sd_title(bs4_object, target=None): """ :param bs4_object: An object of class BeautifulSoup :param target: Target HTML tag. Defaults to class:title-text, a dict. :return: Returns paper title from Science Direct """ if target is None: target = {"class": "title-text"} return bs4_o...
8429fe680fafb86c773a0cd2b3280e893b95fc9a
3,632,258
def generate_word_feat(sentence, word_vocab_index, word_max_size, word_pad): """process words for sentence""" sentence_words = tf.string_split([sentence], delimiter=' ').values sentence_words = tf.concat([sentence_words[:word_max_size], ...
433dc0c79998828a95d87f8dce16f4209a017229
3,632,259
def split_formula(formula, net_names_list): """ Splits the formula into two parts - the structured and unstructured part. Parameters ---------- formula : string The formula to be split, e.g. '~ 1 + bs(x1, df=9) + dm1(x2, df=9)'. net_names_list : list of strings A...
1fce8617cbdaf767c1aebb6d0d685ca63975c820
3,632,260
from sys import intern def joinHostmask(nick, ident, host): """nick, user, host => hostmask Joins the nick, ident, host into a user hostmask.""" assert nick and ident and host return intern('%s!%s@%s' % (nick, ident, host))
e039f6afe37638a24f07a924bd537e6f6b6eb415
3,632,261
from math import ceil from struct import pack def message( command=0, payload_size=0, data_type=0, data_count=0, parameter1=0, parameter2=0, payload=b"", ): """Assemble a Channel Access message datagram for network transmission""" if type(command) == str: command = commands...
babbc4830a147f47819733095e0afe45b77c1b33
3,632,262
def polynomial(x, degree=1, add_bias_coefs=False): """used to calculate the polynomial coefficients of a given array. Args: x (array): the input array to be calculated. degree (int, optional): polynominal degree. Defaults to 1. add_bias_coefs (bool, optional): set True if you wan to add...
fdfc6e8c7e00e56636f07cc115a57f997630b5e2
3,632,263
def plot_energy_group_comparison(df: pd.DataFrame, reverse_axes: bool = False, size: float = 5.0) -> \ sns.axisgrid.FacetGrid: """ Plot energy level recovery for a group of conformation sets. :param df: DataFrame where the columns are Energy, Method, and Discovery. Energy is the energy level (kcal/m...
fbde0758fcb060c419bc1f55f07dcba6b1667111
3,632,264
def get_summary_mapping(inputs_df, oed_hierarchy, is_fm_summary=False): """ Create a DataFrame with linking information between Ktools `OasisFiles` And the Exposure data :param inputs_df: datafame from gul_inputs.get_gul_input_items(..) / il_inputs.get_il_input_items(..) :type inputs_df: pandas.Da...
2000cad2e91009807d9907ae671f97e5038456c1
3,632,265
def reduce_puzzle(values): """Reduce a Sudoku puzzle by repeatedly applying all constraint strategies Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456789', ...} Returns ------- dict or False The values dictionary after continued application o...
389d720231e8395b59adee667e2a23f699e55411
3,632,266
def run_tests(): """Run test suite. """ with virtualenv("benlew.is"): with cd('~/repos/me'): return run("nosetests")
ab56bb53e43f7f204782191130436f944d2dcdcf
3,632,267
from typing import Dict import requests def ls( # pylint: disable=invalid-name url: str, resource_type: str, headers: Dict[str, str] ) -> requests.Response: """ Get a list of all of the resources of a certain type. """ resource_url = generate_resource_url(url, resource_type) return requests.g...
f028a26eb4dc14f70811f175f159b45579869869
3,632,268
def uniform(iterable): """ Returns a random variable that takes each value in `iterable` with equal probability. """ iterable = tuple(iterable) return RandomVariable({val: 1 for val in iterable})
80046c04ba91a4a09287241c9821a192b2f6dfe2
3,632,269
def remove_id3v2_footer( data ): """Remove ID3v2 footer tag if present""" pos = len( data ) - 10 while pos > 0: if data[pos:pos+3] == b'ID3' and data[pos+4] == 0: if data[pos+3] == 2 or data[pos+3] == 3: return data[:pos] + data[pos+decode_synchsafe_int( data[6:10] )+10:] elif data[pos+3] == 4: if da...
ab4014d7b14ac2027ed994cfbaefe7b4e46c2a5b
3,632,270
def get_ilorest_client(oneview_client, server_hardware): """Generate an instance of the iLORest library client. :param oneview_client: an instance of a python-hpOneView :param: server_hardware: a server hardware uuid or uri :returns: an instance of the iLORest client :raises: InvalidParameterValue ...
c1de72a30d3814f7b869d905d9cf2c2584a425b3
3,632,271
def get_metric(metric): """获取使用的评估函数实例. Arguments: metric: str or classicML.metrics.Metric 实例, 评估函数. Raises: AttributeError: 模型编译的参数输入错误. """ if isinstance(metric, str): if metric == 'binary_accuracy': return metrics.BinaryAccuracy() elif met...
34eed6adabe622a975e14936b0b85f86b30cd28f
3,632,272
import numpy def compute_ld(chromosome, position, genotype_name, N=20): """ Returns ordered list of the N neighboring SNPs positions in high LD --- parameters: - name: snp_pk description: pk of the SNP of interest required: true type: string paramType: p...
1b4c0449941876cbc8481d894d03a7178624ceee
3,632,273
def load_user(userid): """ Flask-Login user_loader callback. The user_loader function asks this function to get a User Object or return None based on the userid. The userid was stored in the session environment by Flask-Login. user_loader stores the returned User object in current_user during ev...
0059c0dd65790dee0bca52acd6f9657de8113e96
3,632,274
def flow_read(input_file, format=None): """ Reads optical flow from file Parameters ---------- output_file: {str, pathlib.Path, file} Path of the file to read or file object. format: str, optional Specify in what format the flow is raed, accepted formats: "png" or "flo" ...
590cc6bf5a041a569a3f2b202435940ce3936d57
3,632,275
from itertools import combinations from typing import List from functools import reduce from operator import mul def max_triple_product_bare_bones(nums: List[int]) -> int: """ A bare-bones O(n3) method to determine the largest product of three numbers in a list :param nums: the list of numbers :retur...
8053bc6e35120f6ee8eca2b24e81cbaa7713dfb3
3,632,276
def is_number(s: str): """ Args: s: (str) string to test if it can be converted into float Returns: True or False """ try: # Try the conversion, if it is not possible, error will be raised float(s) return True except ValueError: return False
08b0572e66fafdcd239e9f419fa41b31620de2c5
3,632,277
def getProxyVirtualHostConfig( nodename, proxyname,): """Gets or creates a ProxyVirtualHostConfig object.""" m = "getProxyVirtualHostConfig:" sop(m,"Entry. nodename=%s proxyname=%s" % ( nodename, proxyname, )) proxy_id = AdminConfig.getid( '/Node:%s/Server:%s' % ( nodename, proxyname ) ) sop(m,"pro...
e115985ebbcb6db88814dc49783e3d1b54ef7a43
3,632,278
def relu6(name=None, collect=False): """Computes Rectified Linear 6: `min(max(features, 0), 6)`. Args: name: operation name. collect: whether to collect this metric under the metric collection. """ return built_activation(tf.nn.relu6, name, collect)
b649a5fd646815053f956bc8d1d838330935666a
3,632,279
def announcements(soup): """ ** Announcements Tab** """ try: _div = soup.find('div', {'class':'ex1'}) z= _div.find_all('a') return True,collection(z) except Exception as e: return False,[str(e)]
2c4013e954903f7e275a32e37f70293a086a1201
3,632,280
import requests def analyze_comments_page(username, repo, per_page, page, print_comments, print_stage_results): """ Analyzes one page of GitHub comments. Helping function. Parameters ---------- username : str The GitHub alias of the repository owner repo : str The GitHub repo...
e3d153a0319db0bc723df65cb8a92533f9b37b82
3,632,281
def get_remotes(y, x): """ For a given pair of ``y`` (tech) and ``x`` (location), return ``(y_remote, x_remote)``, a tuple giving the corresponding indices of the remote location a transmission technology is connected to. Example: for ``(y, x) = ('hvdc:region_2', 'region_1')``, returns ``('hvdc...
3c479d818947362349982c77a9bbd87a97a3d4d5
3,632,282
from typing import List def ingrid(x: float, y: float, subgrid: List[int]) -> bool: """Check if position (x, y) is in a subgrid""" i0, i1, j0, j1 = subgrid return (i0 <= x) & (x <= i1 - 1) & (j0 <= y) & (y <= j1 - 1)
d296d8a7abe5eeb3da8d57691755a2bd19dd15b6
3,632,283
from typing import Union from pathlib import Path from typing import Any import json def load_jsonl(path: Union[Path, str]) -> list[dict[str, Any]]: """ Load from jsonl. Args: path: path to the jsonl file """ path = Path(path) return [json.loads(line) for line in path.read_text().splitlines()]
a59d2920bfa491b1d4daa693b5e2e1b4846d6fc6
3,632,284
def getComUser(userId): """ユーザー情報を取得を処理するMapperを呼び出す サービス層のExceptionをキャッチし、処理します。 :param userId: ユーザーデータID """ try: result = __selectUser(userId) return result except OperationalError: abort(500)
90c656e9ac4646b651c40e7147aead20ebe2fe61
3,632,285
def to_rgb_array(image): """Convert a CARLA raw image to a RGB numpy array.""" array = to_bgra_array(image) # Convert BGRA to RGB. #print(array.shape) array = array[:, :, :3] array = array[:, :, ::-1] return array
2feeef439b25692ecc137d3bc4b1d1385b95ee7c
3,632,286
import subprocess import re def git_version(): """ Get the full and python standardized version from Git tags (if possible) """ try: # Full version includes the Git commit hash full_version = subprocess.check_output('git describe --dirty', shell=True).decode("utf-8").strip(" \n") # Py...
12f90dc2dc6cd620acff215aa2b0ad20079a2484
3,632,287
import typing def extract_features(data: typing.Union[list, np.ndarray], attributes: list = None, nvd_attributes: list = None, nltk_feed_attributes: list = None, share_hooks=True, **kwargs): """Extract data by...
3fd8f3b582dad0375b343b7ba6d1f4de225dc4eb
3,632,288
import os import json def load_json(path, api_version=None): """ Loads JSON to the given path, ignoring any C-style comments. """ path = os.path.abspath(path) with open(path, 'r') as fd: content = fd.read() content = minify_json.json_minify(content) d = json.loads(content) i...
0fb433454dd012229b3db748ecd2ba0ffee2dadd
3,632,289
def wrap(get_io_helper_func): """A decorator that takes one argument. The argument should be an instance of the helper class returned by new_helper(). This decorator wraps a method so that is may perform asynchronous IO using the helper instance. The method being wrapped should take a keyword argumen...
f2cdd8009d1722a81d848ab05c3cb6f3acaf5e50
3,632,290
def loads(fn, sdata=None): """ Load compressed pickle """ print " loading", fn fhd = gzip.open(fn, 'rb') print " loading", fn, 'opened' data = cPickle.load( fhd ) print " loading", fn, 'loaded' fhd.close() #print " loading", fn, 'closed', len(data), data.keys() if sdata ...
8d500eebe23a39ceaec90c113175b811f8b6a6c4
3,632,291
from typing import Set import os import shutil def copy_to_build_dir(variables: dict) -> Set[int]: """ Copy files from the source directory and paste them in the destination directory. Args: `variables` dict keys used: workspace_path: The path of the workspace we are working within...
c720d566e464e70fa358194939dc99543c45d9e9
3,632,292
def internal_superset_url(): """The URL under which the Superset instance can be reached by from mara (usually circumventing SSOs etc.)""" return 'http://localhost:8088'
8a66c1d2c0587e9e6a563d08506606d389c2e6be
3,632,293
import tempfile def temp(): """ Create a temporary file Returns ------- str Path of temporary file """ handle, name = tempfile.mkstemp() return name
5955f3ceabd30ba5bb487677d9382253e1fde50a
3,632,294
def ignoreNamePath(path): """ For shutil.copytree func :param path: :return: """ path += ['.idea', '.git', '.pyc'] def ignoref(directory, contents): ig = [f for f in contents if (any([f.endswith(elem) for elem in path]))] return ig return ignoref
9d51d53c8dae8fb2322c3f90ea0f451731395816
3,632,295
def cos_np(data1,data2): """numpy implementation of cosine similarity for matrix""" print("warning: the second matrix will be transposed, so try to put the simpler matrix as the second argument in order to save time.") dotted = np.dot(data1,np.transpose(data2)) norm1 = np.linalg.norm(data1,axis=1) n...
69680cbf1cef58e96ddcd16109dd9408054732e1
3,632,296
import logging def log_scale_dataset(df, add_small_value=1, set_NaNs_to=-10): """ Takes the log10 of a DF + a small value (to prevent -infs), and replaces NaN values with a predetermined value. Adds the new columns to the dataset, and renames the original ones. """ number_columns = get_number...
5dfcefc6e7a3dc5b5d8c7a5a05c8e42fbbf8e2cc
3,632,297
def isoparse(s: str) -> tzdatetime: """ Parses timestamps formatted like 2020-05-01T10:32:02.925961Z """ # TODO could use dateutil? but it's quite slow as far as I remember.. # TODO support non-utc.. somehow? assert s.endswith('Z'), s s = s[:-1] + '+00:00' return fromisoformat(s)
1ffeb44c736d0fd43e1e877181229c768669458a
3,632,298
def ul_model_evaluation(classifier, train_set, test_set, attack_set, beta=20): """ Evaluates performance of supervised and unsupervised learning algorithms """ y_pred_test = classifier.predict(test_set).astype(float) y_pred_outliers = classifier.predict(attack_set).astype(float) n_accurate_test...
d83a23fb0a5f7257fa434bb24d49a324e62659ac
3,632,299