content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_application_directory(): """Get the application directory. Returns: str: The application directory. .. versionadded:: 1.7 """ _check() return _ec.get_application_directory()
d87ecdf9542bd92165ebb656d7f1d18db989c52e
67,800
def insert_modification_record(method: str, resource_url: str, session: scoped_session) -> int: """ Insert a modification record into the database. :param method: HTTP method type of related operation. :param resource_url: URL of resource modified. :param session: sqla...
61430d3b40d2fdaaacdf6a734c19659e73584be2
67,801
def _construct_GPL_url(accession): """Example URL: ftp://ftp.ncbi.nlm.nih.gov/geo/platforms/GPLnnn/GPL570/annot/GPL570.annot.gz """ number_digits = len(accession) - 3 # 'GPL' is of length 3. if number_digits < 4: folder = accession[:3] + 'nnn' # e.g. GPLnnn. elif 3 < number_digits < 5: folder = accession[...
36527d413cc005abe5055eab46e4d7fe93f4aa8e
67,802
import struct def load_mbrec(package): """ Load master boot record and compute magic checksum """ data = package.read_and_pad(package['mbrec']['filename'], 512) checksum = file_checksum(data[2:-2], stride=2, magic=0x1234) checksum &= 0xffff struct.pack_into('<H', data, 0, checksum) return data
d2f839f8ed1d4a5fd1805aba875fb479b6a03a0a
67,803
def get_get_upload_details_retry_predicate(resp): """Triggers retry if upload details came back without last status.""" return not resp.last_status
ecadf182751e55c2c3cbd85f2a7343adc34821e5
67,804
def same_day_hour_moving_average( datetime_col, value_col, window_size, start_week, average_count, forecast_creation_time, output_col_prefix="moving_average_lag_", ): """ Creates moving average features by averaging values of the same day of week and same hour of day of previous ...
b50f2c5bdba602040f9695a359e5256bac66c1cf
67,805
def get_setuptools_package_version(setuptools_version: str) -> str: """ Generate the right setuptools command for pip command :param setuptools_version: Setuptools version obtained from :return: A string formatted for pip install command (e.g setuptools==58.0.0) """ setuptools_version = setupto...
99554292253752545d1bbf82edfef92a925b1746
67,806
import struct def replace_pyzzer_entry_point_shebang(all_data, placeholder, new_prefix): """Code adapted from pyzzer. This is meant to deal with entry point exe's created by distlib, which consist of a launcher, then a shebang, then a zip archive of the entry point code to run. We need to change the sheb...
5f9a4ac7b3c09e78cad6706570b9f45a022f0988
67,807
def _m_verify_mg(state, method, multigoal, history): """ _m_verify_g is a method that GTPyhop uses to check whether a multigoal method has achieved the multigoal for which it was used. """ goal_dict = _goals_not_achieved(state,multigoal) if goal_dict: raise Exception(f"depth {len(history...
dbf96a0896f444c44c070559137928700e6a17ba
67,808
def create_filters(fields=None): """ Decorator for extracting filter parameters from the request arguments and optionally verifying their validity according to the provided fields. :param fields: a set of valid filter fields. :return: a Decorator for creating and validating the accepted fields. ...
cb7d2e7b17d28de5a1010b5f4217ea7998bf1466
67,809
def unwrap2D(wraped_phase,type="boundary",noise = True): """ 2D unwarp function. There are several type to use in several different situation. Type: ----------------------------------------------- Simple: The very simple algorithm to unwrap 2D warpped phase just scan the whole matrix to unwrap phase. Very noi...
05e06287781234a3cdea692b7566de5974b553d2
67,810
import glob import json def getRecords(path): """ Method is used to get data for all CSV files in the path. Args: path (string) : The path for the CSV files. Returns: list: A list of dictionaries with file data. """ sales_data_files = [ file_name for file_name in glob.glob(f"...
b3338dbe3ed96c698b4aad8bfba94a797755f87a
67,811
import os import re def base_disk_for_block_device(partition: str) -> str: """ Returns the base disk of a disk partition. :param partition: Path to the partition to get the base disk of :return: Path to base disk of given partition """ # Follow link(s) # partition should now be in forma...
4734d67dbc958637d088be17b25b0ee8e63fa20d
67,812
def composite_conv_layer(inputs, num_filters=16, kernel_size=3, strides=1, activation='relu', batch_normalization=True, conv_first=True, regularization_factor=1e-4, layer_name=''): """ ...
daa43ff2dfa898339441c133017ccf5aad303b2f
67,813
def _generate_trace(distance, start_time): """ 生成轨迹 :param distance: :return: """ # 轨迹删除 trace = [[base_x, base_y, 1, 0]] for index, x in enumerate(tracks_list): trace.append([base_x + x, base_y + y_list[index], 3, timestamp_list[index] - start_time]) return trace[:-1]
d34a9e464327d0d3a2c445be3213c5b2627940c9
67,814
import torch def log1pMSELoss(log_predicted_counts, true_counts): """A MSE loss on the log(x+1) of the inputs. This loss will accept tensors of predicted counts and a vector of true counts and return the MSE on the log of the labels. The squared error is calculated for each position in the tensor and then averag...
ba7d244885303fa6755c4c25f1f991afae6d10ed
67,815
from typing import Optional import os def _maybe_prepend_base_path(base_path: Optional[os.PathLike], path: os.PathLike): """ Prepends the provided path with a base path prefix if: 1) base path is not None; 2) path is a local path """ if base_path is None: return path if _is_relativ...
bf18eab29361352ffcef39e18beb78937eeff6ce
67,816
import os import time import ftplib from StringIO import StringIO # Python 2 from io import StringIO # Python 3 def ftp(source, host=None, user=None, password=None, filetype=None): """ Upload file/data to FTP server `Required` :param str source: data or readable file-like object :param...
df18c1126b62fadb2ea02733e78d3f3c1d523f43
67,817
def prepare_res_align(gc): """ type (GenerateContactsPdbFile) -> dict :param gc: object of GenerateContactsPdbFile class. :return:dict key = residue_id; value = list atoms of triple. [[Atom N, Atom CA, Atom C, Atom O], [Atom N, Atom CA, Atom C, Atom O], [Atom N, Atom CA, Atom C, Atom O]] ...
2bd069a6b4f287c4127b85d3127ee34e6d4d69a7
67,818
import requests import http import json def get_upstream_constitution(): """ Retrieves a copy of the constitution from the master branch of the upstream repository. Returns a string in binary format. """ response = requests.get(UPSTREAM_API_PATH) if response.status_code == http.client.OK: result_dict ...
3bc470bf74e57f782ec8a1a73ff9727a282fb585
67,819
import logging def check_connection(ssh_conn): """ This will check if the connection is still available. Return (bool) : True if it's still alive, False otherwise. """ try: ssh_conn.exec_command("ls", timeout=5) return True except Exception as e: logging.error( ...
f443d6788eb4a79db7011f0ca9dc4ae15cdf6145
67,820
import re def parse_show_ip_bgp_route_map(raw_result): """ Parse the 'show ip bgp route-map' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show ip bgp route-map command in a \ dictionary of the form: :: { ...
48aecdc76da27fbbc991c30405d1efef82bcbfc3
67,821
from tqdm import tqdm from scipy.misc import comb from itertools import combinations from sklearn.metrics.pairwise import pairwise_distances import warnings def compute_distance_matrix(input_df, metric_func, fast=True, is_ones=False) -> pd.DataFrame: """ Compute a matrix that is symmetric down the diagonal. T...
55eb503ba18fa9a21b46fe7c0ca3a16f94d09f4a
67,822
import math def distance(a, b, R_weight=None, metrics='PEARSON', has_null=True): """Calculate distance between two np.arrays. a, b: np.array R_weight: np.array, default None, weighting vector metrics: str, 'PEARSON' or 'MANHATTAN', or 'EUCLIDEAN' has_null: wether input vector may contain NULL""" ...
b4202dcc65c5da096696e6ce98be037367ae1ef5
67,823
def generate_all_combinations(a, n): """ Generate all possible combinations of length n from a list of a numbers """ if n > len(a): return [] return list(combinations(a, n))
878bd5a051ee3a2b00ce05d4fc29bfe02cda07f4
67,824
def getSPP(mol): """ ################################################################# Calculation of submolecular polarity parameter(SPP) ################################################################# """ return round(getQmax(mol)-getQmin(mol), 6)
db7b4dc6f57f3de4267d0631f737cb347733f7a9
67,825
def num_words_on_board(board, words): """ (list of list of str, list of str) -> int Return how many words appear on board. >>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO']) 3 """ count=0 for word in words: if board_contains_word(board,...
fa2b22336d2c6020220fbce4267ef1a62cb44adc
67,826
import logging def _ensure_positive_percs_for_model( model, reactions, verbose, raise_error, update_values, at_equilibrium_default ): """Ensure calculated PERCs for a model are positive. Warnings -------- This method is intended for internal use only. """ if reactions is None: re...
90ae1444e7a6b398bf098a54d048502e2be8bb79
67,827
def delete(request, list_id): """View to delete a post.""" item = TodoList.objects.get(pk=list_id) item.delete() return redirect("home")
f0caa44cd87125d28f82e20a847e07b744a9a538
67,828
def bulk_insert_dynamic(stream, index_name_attribute, message_attribute, bulk_size=1, credentials='es', ssl_trust_all_certificates=False, name=None): """Stores JSON documents in a specified index of an Elasticsearch database. The index name is part of the input stream. Ingests tuples and stores them in Elastic...
9ca1a0dd6a2a24acf432b4886f2938612b87ec4d
67,829
def _resolve_absolute_url(absolute_url, allow_caching): """ Given a string that is an absolute URL, return a tuple consisting of: a :py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of the object. """ splitted = pathsplit(absolute_url) backend = infe...
84b8995b939f65a3e3f87eb6d2558543e8acb5c2
67,830
async def send_email(mail: BaseEmail = None): """Configure and send an email over SSL Args: mail (BaseEmail): The recipient(s), subject and contents of the message.""" # Set up an EmailMessage object if not mail: return None message = EmailMessage() message["From"] = mail.sender ...
c1d2dd605c1d4dcae1aeee69e87854553301eb97
67,831
import torch def sample_image(): """Sample torch image of correct shape.""" return torch.zeros((3, 300, 300))
fc62ae5720fc1237822faad81c8924026f5b42a7
67,832
def softmax(x): """Compute softmax values for each set of scores in x.""" return np.exp(x) / np.sum(np.exp(x), axis=0)
832c9d865fbdb1270f05f0721110b6ec9b8c1784
67,833
def generate_layer(layer_def, query_tokens, extent, empty_zoom): """ If empty_zoom is True, adds an extra sql column with a constant value, otherwise if it is an integer, tests if the geometry of this layer covers the whole tile, and outputs true/false, otherwise no extra column is added """ lay...
6afc16d5d84775f329ceda1334c714e72b341e7a
67,834
def invisible(fn): """A transform to make a quantum function non-recordable or invisible within a QNode or quantum tape context. Args: fn (function): A quantum function that applies quantum operations. Returns: function: The input function transformed, so that it will not be re...
7d779163d533054664903124c1d017bf1428eb1d
67,835
def __create_brightness_temparature_levels(df): """ Args: df (pandas.DataFrame): Returns: dict: a dictionary of DataFrame objects; """ levels = {} levels[1] = df.query("value > 330") levels[2] = df.query("value <= 330 and value > 320") levels[3] = df.query("value <= 320 ...
6d85267219026c978720d0ba4dadc6ac58bb5836
67,836
def compute_distance_on_graph(G, s_id, t_id): """ Computes the sum of the length in the shortest path between <tt>s</tt> and <tt>t</tt>. If the shortest path are more than one the shorter in edge lengths is considered <tt>return</tt> a double value of the length of the shortestpath between <tt>s</tt> and <t...
22ab67a556d78bcb146a731e23af5e1cededc72c
67,837
import logging def parse_md(folder: str, inp: str, proj_name: str): """ Args: folder (str): path of the folder inp (str): the input file for CP2K proj_name (str): the CP2K project name. The prefix used for MD dumps """ logging.info(f"parse md in folde...
06d353a563306a53abc8ed7cdefc3bc2426e6e24
67,838
def arch2abi(arch): """Map arch to abi""" # pylint: disable=too-many-return-statements if "rv32e" in arch: if "d" in arch: return "ilp32ed" if "f" in arch: return "ilp32ef" return "ilp32e" if "rv32i" in arch: if "d" in arch: return "ilp...
a315f04f5c45588953a15cc0fbfda8e3b9621621
67,839
def solve_L(centers_i,centers_r): """ From [1] as an intermediary step to obtain the reorientation of the calibration plate. L is a matrix which when multiplied with the rotation and translation parameters r'1, r'2, r'4, r'5 and T'x returns the vector of the x_r values at each calibration point. Solving it resu...
a1c57d29340a2f2dfc13257669b6ac35242d08a5
67,840
import Part def edgeToSketch(edges, sketch): """ Project the selected edges onto Sketch plane and add them to Sketch domain. (return num_edge, return_edges, num_point, return_points) Return the number of edges transferred in Sketch domain and the corresponding projections and if any the nu...
14577f20289c872ede164e991f40f3516f37cdc4
67,841
def clean_age_column(age) -> str: """Cleans the age column of a dataframe Args: age (Any): An int, str or float representing age Returns: str: a string based on the age passed """ if isinstance(age, str): n = age.replace(" ", "") if 'or' in n: return age...
1c8dedd4f0d3abc19352aa9710f31b84517da74c
67,842
import uuid def create_id(): """ Create ID with specified lenght based on HEX digits """ return uuid.uuid4().hex[:ID_LENGTH].upper()
c40ce9198828d3ff28d3ac36ef8cf029c36a1ab8
67,843
def get_haskell_command_window_view_file_project(view = None): """Returns window, view and file""" if view: return view.window(), view, view.file_name() window = sublime.active_window() view = None if window: view = window.active_view() file_name = None if view: file...
afc3d8fddda99d878e2a4bad5103d444535c5032
67,844
def datasource_table_schema_get_by_name(request, datasource_name, table_name): """Get the schema for a data source table.""" datasource = datasource_get_by_name(request, datasource_name) client = congressclient(request) return client.show_datasource_table_schema(datasource['id'], table_name)
54ee63820bddcfca568c7714c28a279e2c620006
67,845
def parsedir(directory, parsed, files, blocked, errfunc, include_metainfo=True): """Recurses breadth-first starting from the passed 'directory' looking for .torrrent files. THIS IS BLOCKING. Run this in a thread if you don't want it to block the program. Or better yet, use async_...
135dae53cd0e6066f919c6fbb7097c1eadc4c6f4
67,846
def GetBisectFYITryJobEmailReport(job, message): """Gets the contents of the email to send once a bisect FYI job completes.""" results_data = job.results_data subject_dict = { 'bot': job.bot, 'test_name': job.job_name, } report_dict = { 'message': message, 'bot': job.bot, 'job_ur...
e333f4ef4a6cabb4ec41453d7b2667044f445f49
67,847
def validate_integer(s): """digits and negative sign only. will not convert a decimal value!""" if isinstance(s, intTypes): return s if not isinstance(s, basestring): raise ConfigTypeError('integer value may contain only digits and a leading negative sign') negate = s.startswith('-') if ne...
eeba92fc248610ac08d67d04d9e886cb05f72d12
67,848
def _random_crop(image_list, crop_height, crop_width): """Crops the given list of images. The function applies the same crop to each image in the list. This can be effectively applied when there are multiple image inputs of the same dimension such as: image, depths, normals = _random_crop([image, depths, ...
8326355405dad072f544b3a20c7dd35c49897096
67,849
def find_nearest_date(items, pivot): """This function will return the datetime in items which is the closest to the date pivot. See https://stackoverflow.com/questions/32237862/find-the-closest-date-to-a-given-date Parameters ---------- items : list List containing datetimes pivot : dat...
7b719357c92210729857957e5b4ed8aee4a1f466
67,850
def next_coord(snake_coords, apple): """ 计算下一个坐标 :param snake_coords: snake_coords :param apple: apple :return: 下一个坐标 """ # 搜索head到apple的路径 if len(snake_coords) < HALF: path = a_path_search.cal(snake_coords[0], apple, snake_coords[:-1]) # 移动时tail会腾出空间...
cb0e776949f9e4e2bdfaf5d5f16118b837476b58
67,851
def donsker_varadhan_eig(model, design, observation_labels, target_labels, num_samples, num_steps, T, optim, return_history=False, final_design=None, final_num_samples=None): """ Donsker-Varadhan estimate of the expected information gain (EIG). The Donsker-...
4df22857f1ce63aada170b5fbeb888bf174faec1
67,852
import base64 import json def status(request, id): """ This view reports on the status of a running leximancer project. The id is actually the Leximancer URL base64 encoded. """ url = base64.urlsafe_b64decode(id.encode('ascii')) try: result = utils.get_project_status(url) except utils...
1724e5228e67914f8e34c66a1d1fdf190b534c29
67,853
from typing import Sequence from typing import Mapping from typing import List import json from typing import Dict def get_graphql_property_inputs( property_types: Sequence[PropertyDefinition], properties_dict: Mapping[str, PropertyValue], ) -> List[PropertyInput]: """This function gets existing property ...
39387d229c88b463cfe9703e510c3464d82c1903
67,854
def create_coordinate_dataset( foci=1, foci_percentage="100%", fwhm=10, sample_size=30, n_studies=30, n_noise_foci=0, seed=None, space="MNI", ): """Generate coordinate based dataset for meta analysis. .. versionadded:: 0.0.4 Parameters ---------- foci : :obj:`int` o...
080caab742bba4940cf1a524dd65136644a324ac
67,855
def ng_CountVectorizer(X_train, ngram_range=(1, 3)): """ create CountVectorizer to validate in df the use of it. Parameters ---------- X_train ngram_range Returns ------- """ # print('ngram_range=', ngram_range) count_vectorizer = CountVectorizer(stop_words=None, ngram_rang...
3b1fc15fe754d22881c0bb204ec6742552bda8ba
67,856
def parse_interproscan_file(interproscan_file): """ Parses InterProScan TSV files into an assignment cache. :param interproscan_file: A InterProScan file handle object. :return: An assignment cache object. """ signatures_and_basic_match_info = create_match_dataframe(interproscan_file) ident...
f9ad73eb161a7a3d1c3243686d0dcadd693b6ca7
67,857
import time def package_graph_event(data): """ Package the summary graph event. Args: data (Bytes): Graph bytes string. Retruns: Event, event log object. """ graph_event = Event() graph_event.wall_time = time.time() modelp = ModelProto() modelp.ParseFromString(dat...
bded3b99793546d29a1a40385e2ba13cea099841
67,858
def get_time_tied_leading_trailing(event, previous_score, last_goal_time): """ Calculate time of previous score state according to current event time and time of last goal scored. """ if previous_score['home'] == previous_score['road']: return 'tied', event['time'] - last_goal_time elif ...
d53172e0beb9ab3155f02f3feca3680d25e5bcd0
67,859
import logging import re def vcf_to_fasta(full_vcf: str, filtered_vcf: str) -> str: """Creates a sequence out of the VCF file Processes the VCF file and make changes to the reference allele according to the variants discovered in VCF file. Parameters ---------- full_vcf : str VCF fil...
ee47f3a2911e9c6510f507fd52ccd1d1b3b6d9f2
67,860
import os import shutil import subprocess def load_ndarray(filename): """Load a NumPy array from disk into memory, with extension .npy or .7z. If no extension is included in the argument, first assume it's .npy, then .7z. Args: filename (str): Name of the NumPy array (in disk). Returns: ...
72147c95b1e2314a8be67a4db186241f2d441d30
67,861
def grappler_optimize(graph, fetches=None, config_proto=None): """Tries to optimize the provided graph using grappler. Args: graph: A `tf.Graph` instance containing the graph to optimize. fetches: An optional list of `Tensor`s to fetch (i.e. not optimize away). Grappler uses the 'train_op' collection...
783def94de518ea19a2eb8f3382ccf747106c022
67,862
from typing import Optional from typing import List def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool: """Return if the `node` and its previous siblings match types against the provided list of tokens; the provided `node`has its type matched against the last element in th...
242c38542de8897b3392f994f03689ae1c1cd0b7
67,863
def request_uri(prefix=""): """ Current request """ query_string = web.ctx.environ["QUERY_STRING"] path_info = web.ctx.environ["PATH_INFO"] query_string = query_string and ("?" + query_string) return config.base_url + prefix + path_info + query_string
cc9b4e9e676ea575490d3f310c713fe7e8774eb8
67,864
import subprocess def get_git_remote_default_branch(remote_name): """Get the name of the default branch for the given remote It is typically called 'main', but may differ """ cmd = "git remote show {}".format(remote_name).split() try: remote_info = subprocess.check_output(cmd, ...
59048627ba5c5ee23471c7fcde3674a2abbf2c20
67,865
import datasets def evaluate(sess, test_inputs, test_labels, model, report): """Evaluates model against normal test examples and adversarial training examples :param sess: tensorflow session :param test_inputs: placeholder for test inputs :param test_labels: placeholder for test labels :param model: cleve...
e428d870b573c0389bec505c518bc525fab65528
67,866
def getencoding(): """ Returns the default encoding for input strings (usually 'utf-8'). """ return NX_ENCODING
70f3967c8726124d985a4dc8abaa839395dc21de
67,867
from datetime import datetime def isonow_str(): """ Current timestamp in UTC with "Z". """ return datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
6595f37391d81e915c8c78fe5e45e99676b60055
67,868
def transform_time_data(df): """ Return a dataframe with each timestamp in the input dataframe extrapolated into units: timestamp, hour, day, week of year, month, year, day of week """ timestamps = df.ts time_data = [] for index, ts in timestamps.items(): dt = pd.to_datetime(ts...
bdbd9ed8fa8d6adfabfde03813a520245c3eef58
67,869
def update_user_in_cache(uid, user_info): """ 把mysql用户数据更新redis :param: uid, dict :return:bool """ # TODO 存入redis中 return mj_hall_bridge.update_user_in_cache(uid, user_info)
66d6bdc21ff50d4495f3a369e36f19039e63f849
67,870
import os def has_freesurfer(): """Aux function""" return 'FREESURFER_HOME' in os.environ
4cc6137ac5bcf0b6fdc24797967147266851948d
67,871
from typing import Collection from typing import Tuple from typing import Set def find_namespace_orphans( meta_manifests: Collection[MetaManifest] ) -> Tuple[Set[MetaManifest], bool]: """Return all orphaned resources in the `meta_manifest` set. A resource is orphaned iff it lives in a namespace that ...
e46e41269d30aafd69dcdf2da9900102b9695b62
67,872
import numpy def bd_PSNR(rate1, psnr1, rate2, psnr2): """ BJONTEGAARD Bjontegaard metric calculation Bjontegaard's metric allows to compute the average gain in psnr between two rate-distortion curves [1]. rate1,psnr1 - RD points for curve 1 rate2,psnr2 - RD points for curve 2 returns t...
fb981408fc2a35523e1e7c906adf8b67b9b51626
67,873
def linalg_mat_trace(matrix): """ Compute the trace of matrix Parameters: * matrix (matrix): The matrix Return (number): The trace of the matrix """ return np.trace(matrix)
0b16c27c95bbd96b3172e8f53e68a1c03ffd0cb6
67,874
from frappe.event_streaming.doctype.event_consumer.event_consumer import has_consumer_access def get_update_logs_for_consumer(event_consumer, doctypes, last_update): """ Fetches all the UpdateLogs for the consumer It will inject old un-consumed Update Logs if a doc was just found to be accessible to the Consumer ...
a8e8d59bcddd703fbfb0900a1c1b028a44f5bee3
67,875
def strategy_result_update(strategy_result, strategy_result_reason, phase_result, phase_result_reason): """ Update Strategy Stage Result given a strategy phase result """ if STRATEGY_RESULT.WAIT == strategy_result: # Nothing to update return strategy_result, st...
fa5ea5dfe4ad74a121bd90b2177ebfbf199c81ee
67,876
def J_int_yt(yt, membrane_geometry): """ Jacobian using yt = 1. - rt coordination Note that the coordination definition for y is not consist between [1] and [2]. """ J = 1. - yt if (membrane_geometry=='FMM' or membrane_geometry=='FMS'): J = 1. return J
45e8ea2ef74c7bfd2dfa96543a8bfcb47531d6d4
67,877
from datetime import datetime def get_current_utc_time(): """Return string representation of current time in UTC.""" return datetime.datetime.utcnow()
90b32042fe26986f63e8c30a6b29f1690c602c0b
67,878
def df_to_aa_seqs( IDs_df: DataFrame, fasta_dict: dict, n_flanking: int = 7 ): """Takes a specifically structured DataFrame specifying variable site locations and defines all amino acids sequences around those sites in a new column. Args: IDs_df: DataFrame of variable site l...
891bb0e58184ab5571fb0e290725a61f0a603d42
67,879
def get_primer_direction(primer, delimiter='_', left='left', right='right'): """ Check if the primer is on the left or the right side of the amplicon. """ primer = delimiter.join([str(item) for item in primer]) try: if left in primer.lower(): return 'LEFT' elif right in p...
3aed4e1d3397befa2ae713c5cae1a0c018abb5ae
67,880
import numpy def linear(domain_min, domain_max, range_min, range_max): """Return an instance of :class:`toyplot.projection.Piecewise` that performs a linear projection. Parameters ----------- domain_min, domain_max : number Defines a closed interval of domain values that will be mapped to the...
ffdaeddf1d95ae4010277539209d67042e3bc1d0
67,881
def fully_connected_as_corr(ip, filters, bias): """turns a conv ouput to fully connected layer into a correlation by sliding it across the horizontal direction. this only needs to happen in 1D as the nuerons see the same size as the input ip is DxHxW filters is 2D - (DxHxW)x(num_neurons) op is W...
06c168b4f4a6c2056116cb12ab6dce4f4064eea7
67,882
def render(core): """Calls :func:`~megastep.cuda.render`, turns the output into an :ref:`attrdict <dotdicts>`, then converts the :attr:`~megastep.cuda.Render.screen` attribute into the kind of (batch, channel, height, width) tensor expected by PyTorch convolution modules. This is almost always wha...
feaf82ccdc3bed5a7ef767032eb47b496fe6b394
67,883
def Rx(a): """Rotate y and z about x""" R = [[1, 0, 0], [0, +cos(a), -sin(a)], [0, +sin(a), +cos(a)]] return Matrix(R)
706691ef88ac1bf4867ec8f1c37632b636fcdab3
67,884
import gc def detect_mask(image): """Using Mask-RCNN to detect object and generate masks Params ====== image (ndarray): image """ mrcnn_model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # Load weights trained on MS-COCO mrcnn_model.load_weigh...
2287c6f7f51e1b3107a44a51b173cee33ecfbd9f
67,885
def plot_pca_vectors(comp, nstds=2, scale=100.0, transform=None, ax=None, **kwargs): """ Plot vectors corresponding to principal components and their magnitudes. Parameters ------------- comp : :class:`numpy.ndarray` Composition to use. nstds : :class:`int` Multiplier for magnit...
cd9228dacc48e7115d5b1756cb98d3c440b8f731
67,886
import re def get_sentences_list_matches(text, keysentence): """ Check which key-sentences from occurs within a string and return the list of matches. o Term count: The query counts as a “hint” every time that finds a term from our lexicon in the previously selected articles (by the target words ...
0476a25e92d1e8278a0bd093975c73e957b7df03
67,887
def flatten(inputs): """ Flattens a tensor along all non-batch dimensions. This is correctly a NOP if the input is already flat. """ if len(shape(inputs)) == 2: return inputs else: size = inputs.get_shape().as_list()[1:] return tf.reshape(inputs, [-1, size])
5ca09a1f33c53357d0432681c8d1864ae5dcdd99
67,888
def manhatten_distances(size, point): """ Returns a numpy array of size size, with manhatten distances from the given point for every location in the array """ x = np.linspace(0, size[0], size[0]) y = np.linspace(0, size[1], size[1]) distances = abs(x[:, None] - point[0]) + abs(y[None, :] - po...
d01106fb2ea26e806324b325ef156cd5c33b1f35
67,889
import os def exists(name): """Returns whether the given file or folder exists""" return os.path.exists(name)
d3f3ff1971a12b74355623feb5954356d0811735
67,890
def get_ground_clearance(data): """ Extracts the minimum value of for_pos[2] and returns that value and the timestep it happened at. """ structure = data.structure min_clear = np.PINF ts_min_clear = None for ts, tstep in enumerate(structure.timestep_info): try: tstep....
a6cb94100e4419e195f10ab7a7aa3891d6c2dce3
67,891
def is_global_meterdel(ofmsg): """Is a delete of all meters.""" return is_meterdel(ofmsg) and ofmsg.meter_id == ofp.OFPM_ALL
12eef40bb2cd9cce13d90ee0867f4fb5e1a7503b
67,892
def get_endpoints_by_server(server_id, data): """ Liste les endpoints connects au serveur [[id0,latence0],..] :param server_id: :param data: :return: """ n_videos, n_endpoints, n_requests, n_servers, server_space, video_sizes, endpoints, requests = data # Parcourir les endpoints et ajo...
71280d187a2e9027d06d2686979005bb208fe0e9
67,893
import os def is_package(folder): """ Comprueba si una carpeta es un paquete python :param str folder: ruta de la carpeta :return: True si es un paquete, False en otro caso :rtype: bool .. code-block:: python >> is_package('../pydoc') 'True' """ return os.path.isdir...
4cc46b31df07d36d478192294fb8c50c53f716f8
67,894
def solar_alpha_(xDatetime, xLat, xLon): # pragma: no cover """ solar azimuth angle relative to due north # typically, allowed zero at night, ie when sza >9 deg below the horizon :param xDatetime: :param xLat: :param xLon: :return: """ psi = solar_psi_(xDatetime, xLat, xLon) delta ...
f4ffc8b3f52abfc9fa79cb645dd1ae5cec3b35c3
67,895
def sample_from_simplex(rng, dim): """Uniformly samples a probability vector from a simplex of dimension dim.""" alpha = [1] * dim return rng.dirichlet(alpha)
d034c4502634678874f89e17f2fde28eb8c28e0b
67,896
def render_panel(request): """Render the contents of a panel""" toolbar = DebugToolbar.fetch(request.GET['store_id']) if toolbar is None: content = _("Data for this panel isn't available anymore. " "Please reload the page and retry.") content = "<p>%s</p>" % escape(conten...
53240f3d3a404290c5e333b23d21f1aaf01e2fe8
67,897
import concurrent def future_or_callback(future, callback, io_loop, return_value=_DEFAULT): """Compatible way to return a value in all Pythons. PEP 479, raise StopIteration(value) from a coroutine won't work forever, but "return value" doesn't work in Python 2. Instead, Motor methods that return valu...
41866105ef07937b7dd3d8532ee784729491b005
67,898
def get_proto_serializer(): """ Return a proto serializer that serializes the proto, adds the associated version, and then serializes the RedisState proto to a string """ def _serialize_proto(proto, version): serialized_proto = proto.SerializeToString() redis_state = RedisState( ...
c568290dc8f24535997462ff927cf2dcae3446b3
67,899