content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def onehot_to_smiles(array, indices_token: dict, start_char: str, end_char: str): """ Convert one-hot encoded array of SMILES back to a SMILES string Args: array: (np.array) one-hot encoded numpy array with shape (mol_length, vocab_length) indices_token: (dict) the location of each token in the...
1cda48a4c7c5a08610c5152e0e3879a8b681d23a
78,316
def find_basic_blocks(pp_lst, start_addr, jmp_addrs): """ @brief Determines which parts are basic blocks @param pp_lst List of PseudoInstructions push/pop represtentation @param start_addr Start address of obfuscated function @param jmp_addrs List of Tuples:(jump address, address of jump instruction...
977b20bf057347cf70f083a7fd3a5c28c84df92e
78,317
def get_clean_old_parties(): """Gets and cleans data about political majorities as of August 2020.""" op = get_old_parties() op["clean_name"] = op["Authority"].apply(clean_names) op["old_majority"] = [string.upper() for string in op["Control"]] op = op.drop(columns=["Authority", "Control"]).reset_in...
882d6bbe748fe0420229e5444e96e1c7e1872fc7
78,318
import itertools def get_graphviz(saf): """ Create a pygraphviz graph from the SAF dependencies """ g = AGraph(directed=True, strict=False) nodeset = set(itertools.chain.from_iterable((t['child'], t['parent']) for t in saf.saf['dependencies'])) for n in so...
24d962d3d3ca91369ff586e5945ce0f445cb6448
78,320
def simlex_analysis(word_vectors): """ This method computes the Spearman's rho correlation (with p-value) of the supplied word vectors. The method also prints the gold standard SimLex-999 ranking to results/simlex_ranking.txt, and the ranking produced using the counter-fitted vectors to results/counter_ranking.tx...
879e22305997434b0d4eddfa504c8daa2e29016d
78,321
from typing import Literal def make_altr_graph (uri,links,tokens,labels,content_type): """ make a serialisation of the altR model for W3C list_profiles using content type requested """ gr = Graph() nsgr = NamespaceManager(gr) nsgr.bind("altr", ALTRNS) nsgr.bind("dct", DCT) id = URIRef(uri) ...
aa96b4738168f4a5a5d768e4d49d082bdce53fb5
78,322
def compute_climate_statistics(gdir, tmin='1985', tmax='2015', lapse_rate=0.0065): """Computes monthly average temperature and precipitation during the climate period defined by tmin and tmax. Temperatures are reduced to the terminus elevation assuming a constant lapse rate. Parameters ...
9e71c8b96712a7235969cb9cc44d677c58337367
78,323
def check_grid(grid): """Determines if any rows or columns violate the sudoku condition. This checks for strings (letters) in the layout, because those represent the symbols. A grid with just numbers is valid because those integers represent shape placement, not symbols, so it can't be falsy. A...
53a9a7f502900a48ff1c340262e5f8ef62367c05
78,324
def load_data(database_filepath): """ load sqlite datasets and seperate the features and targets. Input: filepath name Output: X: fetures used to be learned contain message. Y: targets to be classfied. contain all categories of messages. """ engine = create_engine('sqlite:///' + databas...
a5a4e805196d53cf2e4d37fbc725877b7fb12ea0
78,325
def latestFileUri(): """ This will only work if you've just taken a picture. The state will include the attribute latestFileUri. You need this to transfer the file from the camera to your computer or phone. """ try: state_data = state()["state"] except: return False lat...
a6b41a8037a3e78e3246162e55298ae61514fb72
78,326
from operator import rshift def bounding_tile(*bbox, **kwds): """Get the smallest tile containing a geographic bounding box NB: when the bbox spans lines of lng 0 or lat 0, the bounding tile will be Tile(x=0, y=0, z=0). Parameters ---------- bbox : sequence of float west, south, east...
a5e9f2b4e492b35d60d0679408da6cfaebd62386
78,327
from typing import List def linspace(start: float, stop: float, n: int) -> List[float]: """Returns a List of linearly spaced numbers.""" if n <= 0: return [] elif n == 1: return [start] else: step = (stop - start)/(n - 1) return [start + step*i for i in range(n)]
0ba6eb029f96cb662c48c8c8b997a73e2f5a9bc9
78,328
def volcoords_from_polar_irregular(sitecoords, elevs, azimuths, ranges, proj=None): """Create Cartesian coordinates for polar volumes with irregular \ sweep specifications Parameters ---------- sitecoords : tuple sequence of three floats indicating the radar position (longitude in d...
1578f7d1b3f8acc3f7a4601b1bdaf77a84dec8c2
78,329
def build_model(arch, hidden_units): """ Builds a neural network from a pretrained architecture with a variable number of hidden_units Parameters arch - a shorhand string for an architecture hidden_units - the number of hidden units to include in the classifier Returns model - a nn.Mo...
6526fe83ebe71bf16220575f9b13dfa740995843
78,330
def ntail(l, u): """ % samples a column vector of length=length(l)=length(u) % from the standard multivariate normal distribution, % truncated over the region [l,u], where l>0 and % l and u are column vectors; % uses acceptance-rejection from Rayleigh distr. % similar to Marsaglia (1964); ...
4f7442993e8142b1b157343ff2b60a6add287c83
78,331
def insert_into_statement(db_name, table_name, query_text, column_names=None): """ Create a vanilla INSERT statement for the given query. Optionally derive the column names from the query directly. >>> print(insert_into_statement( ... "my_db", ... "my_table ' uea$3}", ... "SELEC...
e8b8a389e830bec99a9a1754dd02436b26c5dc28
78,332
from operator import concat def prototypical_clustering_learn_layer(nclasses, x_train, y_train, x_test, phi, num_clust...
1616f1442b5f4cdd07a96842700f0cc218a79ff6
78,333
import torch def _grad_spherical_harmonics_l0(xyz): """Compute the nabla of l=0 Spherical Harmonics Args: xyz : array (Nbatch,Nelec,Nrbf,Ndim) x,y,z, of (Point - Center) Returns \nabla * Y00 = 0 """ return torch.zeros_like(xyz)
1afdec897c80ff75e0d30b98f2187616102e5ab8
78,334
def get_critic_network(train_env, fc_layer_params=(256, 256)): """Critic network to give estimates of Q(s, a).""" observation_spec, action_spec, time_step_spec = ( spec_utils.get_tensor_specs(train_env)) # Input: state and action # Output: Q value return critic_network.CriticNetwork( ...
bd4eb56c8eb7595474e64b901a6137b6f31083d1
78,335
def aut(results, metric=None): """Compute the AUT with respect to the given metric. Note that for results spanning a _single_ time period, AUT = 0 as this is not considered a time-aware evaluation. Args: results: The set of time-aware results to operate over. metric: The metric to oper...
14d2b2f59cc3d67aa16e72fb4785f71ec0c2b8d8
78,336
def frequency_analysis(text, m, p = None): """ Calcola la frequenza(occorrenze) delle lettere o serie di lettere in una stringa :param text: stringa di testo :param m: parametro per divisione stringa in m_grams :param p: se p = 'plot' stampo il diagramma :return: un dizionario con le keys = m_grams , values = freq...
79e777da374fe538a285b79c19d60a38dcc67873
78,337
def crossmatch_distance(pos, match): """Returns distance in arcsec between two sets of coordinates.""" c1 = SkyCoord(pos[0]*u.deg, pos[1]*u.deg, frame='icrs') c2 = SkyCoord(match[0]*u.deg, match[1]*u.deg, frame='icrs') return c1.separation(c2).to(u.arcsec)
bf51099585c1e56b5c0f708660d973cf940abdbe
78,338
def define_period(): """Define the default periods for the fake data functions Parameters ---------- None Returns ------- period : dict Dictionary of periods to use in test instruments """ period = {'lt': 5820, # 97 minutes 'lon': 6240, # 104 minutes ...
974fc41760e68a0d4ef553d82f212f8b3449f552
78,340
def correlation_with_indices(*, index_filename, pc_df): """Correlate principal component with SV of magnetic index read from file. SV of indices AE, Dst, PC, Em must be precalculated and written to file. Index files are only read here, not calculated. The SV for the magnetic indices should be the same ...
5fdf50cf55a44ba6749b44479e35b14dcd5e5179
78,341
def ibm_cos_resource_to_json(ibm_cos_resource: IBMCOSResource): """ The function converts an object of IBMCOSResource to a json string. :param ibm_cos_resource: A IBMCOSResource object. :type ibm_cos_resource: ibmpairs.external.ibm.IBMCOSResource :rtype: ...
290fa58e8aac96bb45fe370ebd4ea956e5b36099
78,342
from unittest.mock import Mock from click.testing import CliRunner import click def runner(mock_fancy_print: Mock, mock_requests_get: Mock) -> CliRunner: """Fixture for running command-line interface.""" return click.testing.CliRunner().invoke( console.main, "--iterations 1 --time_to_sleep 0" )
54eae3c364570d1af52c1b953a47b0899d6e4a13
78,343
def _parse_example(serialized, parse_function): """Decode the given feature.""" ds = tf.data.Dataset.from_tensors(serialized) ds = ds.map(parse_function) if tf.executing_eagerly(): return next(iter(ds)) else: return tf.compat.v1.data.make_one_shot_iterator(ds).get_next()
68b85145b0bdf6e40fad481eaefff5f972b750ec
78,344
def ftvhunter_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]: """Read the html for ftvhunter.com""" # Parses the html of the site soup = soupify(driver) image_list = soup.find("ul", class_="list-justified2").find_all("a") images = [image.get("href") for image in image_list] num_f...
b7fa854ea1e57f814c5d526f4eca1e04a15e10b6
78,345
def run(request, run_id): """Details of single run page""" run = ModelRun.objects.get(pk=run_id) redis_conn = django_rq.get_connection() job = Job.fetch(run.job_id, redis_conn) run.job_metadata = job.meta metrics = run.metrics.order_by("name").values("name").distinct() return render(requ...
a6985ae21c66e2eddaa018ed7a584dbbfd0c4ce2
78,347
def count_substring_regex(array, pattern, *, ignore_case=False): """ Count the non-overlapping matches of regex *pattern* in each value of a string array. Parameters ---------- array : pyarrow.Array or pyarrow.ChunkedArray pattern : str pattern to search for exact matches ignore...
8cd0fb3c29250f158853631fbac0dd07b4b38302
78,348
from htk.utils.emails import find_company_emails_for_name import re def findemail(event, **kwargs): """Find email event handler for Slack webhook events """ text = kwargs.get('text') command = kwargs.get('command') args = kwargs.get('args') if command == 'findemail': if args: ...
bf5decb0251100a280d4375a7fb11dd227df3110
78,350
def getABsC(_quad, _edge, _vertex, regularPoints): """ :param:_quad: Quad :param:_edge: Edge :param:_vertex: Vertex :param:regularPoints: numpy.ndarray :return: A, B1, B2, C :rtype: numpy.ndarray([int, int, int, int]) """ assert isinstance(regularPoints, np.ndarray) assert isin...
ced424cb247600d77a958bdecf7b207d4cb0d6d2
78,351
import torch def compute_m(z: torch.sparse, c: torch.sparse, max_K: int): """ This function computes the m_i = sum{n_ij}. :param z: the sparse matrix recoding z_ij. node_number X node_number. Each node has at least one edge required. :param c: the sparse matrix recoding c_ij. node_number X node_numbe...
36bdd0e7c9ff062508c79244f0a44fb2694d6853
78,352
import functools def randomize(table, ntrials=100): """ Parameters ---------- table : :class:`pandas.DataFrame` Table of coupling strengths ntrials : int, optional Number of trials for eigenvalues Returns ------- Array of eigenvalues """ _, Ntime = table.s...
f4ac751979f688b74cdf85ed6d78ab4e23aa08ff
78,353
from re import A from re import T def site(): """ RESTful CRUD controller """ # Load the Models s3mgr.load("event_event") # Parse the Request r = s3mgr.parse_request() link = request.vars.get("link", None) # Pre-Process if r.id and link: # Go back to the facility list of th...
1c0ec0307f8c40f6a7444c3a5201e1ad82d69017
78,354
def nemeth_smoother(particles, log_weights, statistics, additive_statistic_func, kernel, lambduh = 0.95, **kwargs): """ Algorithm 2 of Nemeth et al. (2015) Calculate E[SUM[h(x_t, x_{t+1})] | Y] Args: particles (ndarray): N by n, latent states (x_t) log_weights (ndarray): N,...
7ff0714c121a38b5b1c2f919727ad3162a7dcdd5
78,355
def _find_curv_local_minima(curv, peak_curv_value, filtered_maxima, start, dir, rel_thre = 0.45, minima_dir_thre = -0.25): """ Find a negative curvature value that is a local minima or a filtered local maxima with respect to density value. dir represents the direction of search, choosing from '+' or '-'. ...
7912854e417cf7534ac064e5f8765e73bcec9661
78,356
def obtain_header_fields(first_line, sep='\t'): """ Obtain a dictionary: "field_name" => "position" """ fields_dict = {} header_fields = first_line.strip().split(sep) for x in xrange(0, len(header_fields)): fields_dict[header_fields[x].lower()] = x return fields_dict
8b399918ff56e784eba549fe2f83db1cbaf728b4
78,357
from typing import Iterable def generate_bias_volts(bias, steps=None, polarity=1, check_monotonic=True): """ Create and return a np.array of bias voltages. If step is None and bias is a number, np.linspace is used and creates *bias* voltages. If *bias* is already an iterable of voltages, checks are pe...
603f5f3fa56c21418642de20b0cc8a22c0dd12c2
78,358
import warnings def _set_arrayorder(obj, arrayorder='C', sep=None): """ Set the memory order of all np.ndarrays in a tofu object """ msg = "Arg arrayorder must be in ['C','F']" assert arrayorder in ['C','F'], msg d = obj.to_dict(strip=-1, sep=sep) account = {'Success':[], 'Failed':[]} for k, ...
a6eb9e61600a93c376c84aee7565bb40b85587f9
78,359
import typing def GetOptPasses( cflags: typing.Optional[typing.List[str]] = None, language: typing.Optional[str] = "c", stubfile: typing.Optional[str] = "int main() {}", ) -> typing.List[OptPassRunInvocation]: """Get the list of passes run by opt. Args: cflags: The cflags passed to clang. Defaults to -...
bd9a419a7915fd20e198b5ae7f54ebcfd5ea8b8b
78,360
def traj_passes_pt(traj, pt, threshold=1e-10): """ Returns true if trajectory crosses a point within radius 1e-10. """ return np.amin(np.abs(traj- pt)) < threshold
df28a7832c5c81560ba2919ab09257873e86cf41
78,362
import warnings def pmap(function, *arguments, **kwargs): """ Parallelized version of map. It calls function on arguments using numprocesses threads. Also try the numexpr package or numba, which are easy to use and may give you better performance. Parameters ---------- function : functio...
035af858a0b2cbd400c1b0ffe73d4a4a1ed3934a
78,363
def ellipsis_after(text, length): """ Truncates text and adds ellipses at the end. Does not truncate words in the middle. """ if not text or len(text) <= length: return text else: return text[:length].rsplit(' ', 1)[0]+u"\u2026"
9b15c5e8f63caec0a7327ae1ce872bac932208ab
78,365
def popcount(arr): """ Provides a population count implementation. The population count is the number of one bits. Based on GCC's __builtin_popcount(). The implementation is written in C. Parameters ========== arr : numpy array Must have dtype of uint8, uint16, uint32 o...
bd0ecbf1c95b51a400d6d86f66d7f8d296994620
78,366
def order_columns(dataset, col_names, feature_to_predict): """ Method is responsible of putting the 'feature_to_predict' name as the first column of the dataset and sorts the other columns names. Parameters ---------- dataset col_names = column names to be sorted feature_to_predict = fea...
05cb77502defa2648c6cc9279cf130d07ffd9bb7
78,367
import re def _pathname_to_category(pathName): """This match the path name againt the set of regular expressions defining broad categories of files: Sockets, libraries, temporary files... These categories are not technical but based on application best practices, rules of thumbs etc...""" for rgxT...
8423d8ccdd30053f0fbddddf07150a65f5f06f94
78,368
import csv def read_csv(inp, header=True): """ Reads a csv file. :param inp: input file :param header: inp contains a header :return: :titles: titles of the columns :xs: x-values (1- or 2-dim np.array) :ys: y-values (1- or 2-dim np.array, matches x) """ titles = No...
a4137246f228478014252d0dd73fe1185ea509d4
78,369
def precision_at_k(data, k): """Returns a float. Input format for data is list of tuples (article_id, prediction, label). The P@k for given prediction scores for an article is the percentage fake sentences among the top-k. This function returns the mean P@k of the given articles. """ ...
653c9e5d257b14859125e036b76e8139b8b24f83
78,370
import math def modify_hough_results(hough_results: list, img_size: tuple) -> list: """ cv2.HoughLinesの結果を整形する. :param hough_results: ハフ変換結果のリスト :param img_size: ライン検出に使った画像のサイズ(height, width) :return: 各線の情報を整形したリスト """ n_lines, _, _ = hough_results.shape height, width = img_size l...
0b01f287da014a275646d707fb8ef674e5ea8da1
78,372
def fake_stereo_geometry(gra, ntries=5, max_dist_err=0.5): """ generate a fake stereo geometry """ return _fake_stereo_geometry( gra, ntries=ntries, max_dist_err=max_dist_err)
f55e0ca4222a6a58d18b861febef13c1271acfac
78,373
def memoize_dropdown(func): """Checks if the dropdown list has already been created. If it did, it returns the cached list. otherwise, it creates one. """ dropdown_cache = [] def wrapper(): if not dropdown_cache: for city in func(): dropdown_cache.append((city, ...
728e105d4e45c9504790bd68253c0d37f122cff5
78,374
def load_data(data_dir, train_img_ids, val_img_ids, test_img_ids, context_size, batch_size, num_workers=4, max_bg_boxes=-1): """ Args: data_dir: directory which contains x.png Image and corresponding x.pkl BBox coordinates file train_img_ids: list of img_names to consider in train split ...
92825f23e8878cc876f9b8f00ef896b5cf004b38
78,375
def data_summary(df): """ Return summary sof the dataframe e.g. Missing values, unique values, first and last values of the dataset :param df: pandas dataframe :return: summary: dataframe that contains summary of df """ print(f"Dataset Shape: {df.shape}") summary = pd.DataF...
871793791c05efdd289e5e0108bfed74b64f28ed
78,376
def plist_url_path(plist): """Returns a constructed URL.""" result = None result = '{}/{}/{}'.format(config.AUDIOCONTENT_URL, config.LP10_MS3_CONTENT, plist) return result
f3d772618ebbde1b6e7ef75ce0381f5fbcfc532e
78,377
def modulo(x, y): """Divides the first parameter by the second and returns the remainder. Note that this function preserves the JavaScript-style behavior for modulo. For mathematical modulo see mathMod""" return x % y
efea1409596564a393cae7b46afe17141326552b
78,378
def transform_by_pose(point: np.ndarray, pose: np.ndarray) -> np.ndarray: """Transforms a list of 3D points by a pose. Args: point: array containing (x, y, z) coords or numpy array of shape (3, N). pose: pose for the transformation. Returns: array containing (x, y, z) points of shape (3, N). """ ...
907dff888153df4cf9a0b4ef51849143bd8722f7
78,379
def render_sidemenu(menu_id, active_item=None, **kwargs): """Render a sidemenu with sections/items. :param menu_id: The identifier of the menu. :param active_item: The name of the currently-active menu item. :param kwargs: Additional arguments passed to the menu signals. """ items = build_menu_...
8098d496a55deff0f0a3adb8bbfa97aebd3c6770
78,380
import socket def get_host_name(): """Returns the name of the host.""" return socket.gethostname()
feddd2a5bf674ff956b280d02649f5872b61991b
78,381
def get_prng(seed=None): """Turn seed into a PRNG instance Parameters ---------- seed : {None, int, object} If seed is None, return a randomly seeded instance of SHA256. If seed is an int, return a new SHA256 instance seeded with seed. If seed is already a PRNG instance, return ...
97b7dffbb704354f56868964199eedd4eac0a158
78,382
def sortArrayByParity2(A): """ :type A: List[int] :rtype: List[int] """ i, j = 0, len(A) - 1 while i < j: if A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i] if A[i] % 2 == 0: i+=1 if A[j] % 2 == 1: j-=1 return A
048786203eab589fa74a78ddfc2bc05a104a8f4e
78,383
import pickle def predict_which_user(user1_handle, user2_handle, tweet_text, cache=None): """ Determines which user is more likely to tweet a given phrase. Parameters ---------- user1_handle : str First user's Twitter handle. user2_handle : str Second user's Twitter handle...
b9acebeae0e1fac7c7a7357ad1099703ffe44480
78,384
import typing def merge_reports(reports: typing.Iterable[dict]) -> dict: """Merge the size reports in reports. :param reports: The reports to merge. :return: the merged report. """ final_report = dict() for report in reports: for k, v in report.items(): final_report[k] = f...
7045d0e7f8047678a5bdb90c885717bc917cb46a
78,385
def uncover_dash(guess, answer, dashed_word): """ :param guess: str, the character that user type and has been converted to upper case :param answer: str, the answer word :param dashed_word: str, the present dashed_word :return: str, the new_dashed_word with all correct guess been shown in dashed_wo...
30e2134e607ef24071cbb50e43723ae0d5fc88a9
78,386
def rotation2quaternion(rot): """ Calculate quaternion when rotation matrix is provided Reference: https://gist.github.com/shubh-agrawal/76754b9bfb0f4143819dbd146d15d4c8 Reference: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ :param rot: numpy matrix with sh...
0b0c6ce7b1fd4dd5da506fbc68e38a4443f0a64e
78,387
def get_meter_value(poll): """Return the actual value for the meter element.""" users_voted = float(get_users_voted(poll)) voters_group = float(get_voters_per_group(poll)) try: val = (users_voted/voters_group)*100 return int(val) except ZeroDivisionError: return 0
69b275fb1c8cc24e2d67273a5a000a909c4d7775
78,388
def filter_bandstop( trace: Trace, sampling_frequency: int, low: int, high: int ) -> Trace: """ Apply a bandstop digital filter (Butterworth) to `trace`, given `sampling_frequency`, with the stopband from `low` to `high`. :param trace: :param sampling_frequency: :param low: :param high: ...
77f64a994d248cf920de3a36707b4e81e57f64c9
78,389
def make_password_message(model, password): """Creates email message for password.""" return NEW_PASSWORD_MESSAGE.format( name=model.full_name, password=password )
8e3dab8be2e1a4013387a884fd27c9a15ab83e37
78,390
import math def angle_3p(p0, p1, p2): """get the angle between three 3D points, p0 is the intersection point""" u, v = p1-p0, p2-p0 costheta = u.dot(v) / math.sqrt(u.dot(u) * v.dot(v)) return math.degrees(math.acos(costheta))
3a5ac0c4d0cfa8ae97e979175292fe416cc683b8
78,391
def create_uNet(args, num_output_final): """Create network in barrista. Create a network in barrista similar to a combination of U-Net and the one in the learning data-driven reflectance priors paper. """ print("Using u-net") layers = [] filler = design.PROTODETAIL.FillerParameter() fi...
64d952eb8b88710d3a795e278831ddde16bd72f0
78,392
import socket import logging def get_ip(): """ Request to the external host sending. Returns an external IP-address of a current host. """ sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(TIMEOUT) try: # Any arbitrary existing host and opened # for TCP-requests port of t...
309145e80685a96277864f9ef360ecbaace1acf1
78,393
def strictly_increasing(L): """严格单调递增""" # None as 0 return all(x < y for x, y in zip(L[:-1], L[1:]))
0e3d8a8f8032f0ea97b2097280b7960bbd0e43a0
78,394
import hmac import hashlib def mailgun_signature(timestamp, token, webhook_signing_key): """Generates a Mailgun webhook signature""" # https://documentation.mailgun.com/en/latest/user_manual.html#securing-webhooks return hmac.new( key=webhook_signing_key.encode('ascii'), msg='{timestamp}{t...
64d549e53a7c8f6842d176caa501335a0bc1ca61
78,395
import copy def create_annotation_data(save_data): """Returns the final annotation JSON which is a cleane dup version of the save JSON""" #annotation_data = save_data annotation_data = {} annotation_data["image"] = copy.deepcopy(save_data["image"]) annotation_data["grid_cells"] = copy.deepcopy(sav...
ee8ceb51cac98b7ac795c9bfefd525d23168d6d1
78,396
def _x_like(prototype, dtype, shape, constructor, fill_value=None): """ Returns a tensor with the same shape and type as prototype, using constructor. """ _ = _check_input_for_asarray(prototype) dtype_out = dtype shape_out = shape if not dtype_out: dtype_out = _get_dtype(prototyp...
2e0eb07b02012ab4d9694a7b4485a7eee7ac3226
78,397
def pad_ranges(inranges,padding,chr_ranges=None): """Add the specfied amount onto the edges the transcripts :param inranges: List of genomic ranges in Bed o GenomicRange format. :param padding: how much to add on :param chr_ranges: looks like the list of ranges within which to pad :type inranges: GenomicRang...
7733bf975e7d4aaa4d548f231fd81cad37ca2229
78,398
def get_interface_ip(interface): """ Get an interface IP address """ print() task_start(f"Finding IP address of {interface} using ifconfig") ip_address = run_command_shell( f'ifconfig {interface} | grep \'inet\' | awk \'$1 == "inet" {{ print $2 }}\'').rstrip() if ip_address: ...
0dc02bcc8eb7d74d56625cf3eca847f57842b7af
78,399
def _parse_data_row(row, columns, counters, **options): """Parse table data row. If a cell has multiple tags within it then each will be seperated by `sep` character. Parameters ---------- row : BeautifulSoup Tag object A <tr> tag from the html, with data in at least one cell. ...
500c9634b8110575d3c7800a0a1f2616fa08ac03
78,400
def cal_det_fpfn(data, categories, iou_thr=0.5, score_thr=-1, category_to_show=None): """Calculate fp and fn for detection. Args: data (dict): Annotation of current image. categories (list): Categories of whole dataset. ...
d9b37acc29dd0d2714ee2c65eb42e409c2636aa2
78,401
import aiohttp import ssl import certifi def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: """ Creates TCP connector with resonable defaults. For details about available parameters refer to `aiohttp.TCPConnector <https://docs.aiohttp.org/en/stable/client_reference.html#tcpconnector>`_...
7ad31deb002487bbc40ce561fd9dd2d0060cace5
78,402
def _random_helper(random, sampler, params, shape, dtype, ctx, out, kwargs): """Helper function for random generators.""" if isinstance(params[0], NDArray): for i in params[1:]: assert isinstance(i, NDArray), \ "Distribution parameters must all have the same type, but got " \...
205bf061768de0b3c000f178a63cf675e1844283
78,403
def get_brain(data_store, project_id, brain_id): """Get cached brain or read brain from data_store. Args: data_store: data_store.DataStore to read from if the brain is not cached. project_id: Project ID associated with the requested brain. brain_id: Brain ID associated with the requested brain. Retu...
06cc32691a381e90d2ef0de4dc3342ed826a42c0
78,404
def get_sample_answers(exploration_id, exploration_version, state_name): """Fetches a list of sample answers that were submitted to the specified exploration state (at the given version of the exploration). Args: exploration_id: str. The exploration ID. exploration_version: int. The version...
6806561150bd86a42dd9191badc7234aa751e22d
78,405
def clear_all_messages(request): """ Clears all message from the cache """ clear_outbox() return JsonResponse({"status": "success"})
04712124426ea17145cba606f96ca6808d55eff6
78,406
def generate_triggers() -> list: """Generate triggers list.""" result = [] for s in WEATHER_STATES_CONVERSION.keys(): for d in [True, False]: result.append(map_state(src=s, is_day=d, mapping=WEATHER_STATES_CONVERSION)) return list(set(result))
b646155cdab880d626b9eb4ef7e90cbd069a329b
78,407
def encode(request_data): """ with tempfile.NamedTemporaryFile(mode="wb", suffix=".jpg") as f: #f.write(request_data) #img = cv2.imread(f.name) #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) """ img = np.array(Image.open(BytesIO(request_data))) images = [img] molded_imag...
a9dcd96c94935c6994838c6615a76becef5fd5fb
78,408
def _format_message(key, *args): """ Format the specified message key with the specified arguments. :param key: the message key :return: the formatted text message """ return ExceptionHelper.getMessage(key, list(args))
7e32e6b09298b6bae8669915ea333b5fce7879fe
78,409
def generate_wpe_labels(labels): """ :param probs: [batch, seq_len, n_words] :param labels: [batch, seq_len] :return: out: labels with ignored position being padding_idx. [batch, 1, seq_len] """ # [batch, 1, seq_len] out = labels.unsqueeze(1) return out
6a32a0bd29ca20b543a1b052c0284a6e0d3127f0
78,410
def get_input_month(model_year_dti: pd.DatetimeIndex) -> np.ndarray(int): """Determine month of each day :param pd.DatetimeIndex model_year_dti: a DatetimeIndex encompassing the model year. :return: (*np.ndarray*) -- stores the month the day is in for each day of the year. """ return model_year_dti...
6553e6fc2b3905ce967283970691623890bdf666
78,411
def make_conv_fatality_rate(infection_fatality_rate, total_days): """Computes the probability of death on day `i` given infection on day `j`.""" p_fatal_all_countries = daily_fatality_probability( infection_fatality_rate, total_days) # Use the probability of death d days after infection in each count...
502e442964ba2767fc4ef48bef067fc338ed2474
78,412
def find_parser(path_or_stream, forced_type=None, is_path_=False): """ Find out config parser object appropriate to load from a file of given path or file/file-like object. :param path_or_stream: Configuration file path or file / file-like object :param forced_type: Forced configuration parser type...
8e639929c04eddc33389f98ffb4cd20d4402fb1d
78,413
from typing import Optional async def get_last_update_time(region: Region, config: Config) -> Optional[Arrow]: """Get time the price data was updated last. :returns None: If file not found. :returns arrow.Arrow: Last update time. """ file_dir = config.paths.price_data_dir file_name = defaults...
85b03399352b5196901ae071f69865c0ce0be27a
78,414
async def test_execute_autoruns(mocker): """ Test execute_autoruns function """ state = { 'queue': [] } def get_autoruns(self, file_type): # pylint: disable=unused-argument return [ ('1', '1', None), ('2', '2', None), ('3', '3', None), ...
7f6569eb2d5dc96b45f55c0ff0e75e9d5dbe43e4
78,415
import random def select(dataset, size, digits_to_keep, stratified_sampling=False): """Select randomly specific elements given by digits_to_keep.""" len_dataset = len(dataset) indices = list(range(len_dataset)) random_select_indices = [] random.shuffle(indices) if stratified_sampling: ...
9b69f09bbb5ba717d3600a097a40dbef5255770a
78,416
from typing import Union from typing import Sequence def launch(args:'Union[Sequence[str], str]', **kwargs)->Popen: """launch process""" if isinstance(args, str): proc = Popen(args, stdout=PIPE, shell=True, **kwargs) else: proc = Popen(list(args), stdout=PIPE, shell=False, **kw...
c0f634558459036424b32a0ac4de578a2784c010
78,417
def generic_tabs(context, object_list=[], tab_id='tab', title_key='title', content_key='content', *args, **kwargs): """ Crea un componente <Tabs> con el QuerySet en object_list El `title` pasa a ser el título del tab, y el `content` es el contenido """ _object_list = [] for obj in ob...
32060dbea81713bb737edc19d5780db90ba1f655
78,419
def cci(df, high, low, close, cci, n, c=0.015): """ The CCI is designed to detect beginning and ending market trends. The range of 100 to -100 is the normal trading range. CCI values outside of this range indicate overbought or oversold conditions. You can also look for price divergence in the CCI. ...
d564a4f22106702ac39d5d5de9ed17eb96623237
78,420
def _spreadsheet_by_url(url, api): """[summary] Args: url ([type]): [description] api (obj): gspread object Returns: [type]: [description] """ return api.open_by_url(url)
c7c5ab72c7d88cc7ff8d13a50e6838da6a6fbdeb
78,421
def condicion_del_producto(): """ se pide la condicion enviada por parametro junto el request""" c = request.args.get('condicion') """ se filtra segun la condicion """ productos = op.filtrar_por_condicion(db, c) """ se obtienen el resto de los datos necesarios para renderizar """ categorias = ...
09938a0ed7b1d1ec14203a517e93ecdffa73223a
78,423
def FL(f): """get fully-parenthesized string representation of formula""" return '(' + f.to_str('spot', full_parens=True) + ')'
5d35b96ed7089294d85ca31ed24c8824a243e7ee
78,424