content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def rsa_obj(key_n, key_e, key_d=None, key_p=None, key_q=None): """ Wrapper for the RSAObj constructor The main reason for its existance is to compute the prime factors if the private exponent d is being set. In testing, the construct method threw exceptions because it wasn't able t...
1ad6d0b4c6f96170b2452b87ea049f63df350b8f
25,200
from operator import ge import logging def create_surface_and_gap(surf_data, radius_mode=False, prev_medium=None, wvl=550.0, **kwargs): """ create a surface and gap where surf_data is a list that contains: [curvature, thickness, refractive_index, v-number] """ s = surface.Su...
187cad25433db2f64aeb482bc5313c97b31a834e
25,201
def deprecate_build(id): """Mark a build as deprecated. **Authorization** User must be authenticated and have ``deprecate_build`` permissions. **Example request** .. code-block:: http DELETE /builds/1 HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate Authorization:...
3002a8c46e4aa27a03d8b4fdb16fa94d4a7a8698
25,202
from re import A def project_task_list_layout(list_id, item_id, resource, rfields, record, icon="tasks"): """ Default dataList item renderer for Tasks on Profile pages Args: list_id: the HTML ID of the list item_id: the HTML ID of the item ...
7e9ee4d7e808921a430ee7cf7792038513ddff34
25,203
def subtractNums(x, y): """ subtract two numbers and return result """ return y - x
2b16636e74a2d1a15e79e4669699c96adcd3833b
25,204
def getTraceback(error=None): """Get formatted exception""" try: return traceback.format_exc( 10 ) except Exception, err: return str(error)
62da3e5b13860c2ecefa1da202aa63531c4fbc19
25,205
import os import shutil def _copy_and_rename_file(file_path: str, dest_dir: str, new_file_name): """ Copies the specified file to the dest_dir (creating the directory if necessary) and renames it to the new_file_name :param file_path: file path of the file to copy :param dest_dir: directory to copy th...
b53ce9d5e968e257919c8f2eb7749a171eddb59d
25,206
from datetime import datetime def confirm_email(token): """ Verify email confirmation token and activate the user account.""" # Verify token user_manager = current_app.user_manager db_adapter = user_manager.db_adapter is_valid, has_expired, object_id = user_manager.verify_token( token,...
83015e9fc74b88eeb57b1ef39decd37b7adf662d
25,207
from typing import List from pathlib import Path import logging def get_vector_paths_4_sample_set(set_name: str, base_path: str) -> List[PosixPath]: """ Gets the files for a given directory containing sample set :param set_name: Str indicating the name of the directory for a given set of samples :para...
60e75b96b3b8f685e034ae414e8af4983d105d12
25,208
def _GetInstanceField(instance, field): """Get the value of a field of an instance. @type instance: string @param instance: Instance name @type field: string @param field: Name of the field @rtype: string """ return _GetInstanceFields(instance, [field])[0]
fdf8eebf1dbd9cb443da21530058c6c7b30d8204
25,209
def infectious_rate_tweets(t, p0=0.001, r0=0.424, phi0=0.125, taum=2., t0=0, tm=24, bounds=None): """ Alternative form of i...
939ddde24301badaf1c43731027d40167b5ab414
25,210
def fetch_user(username): """ This method 'fetch_user' fetches an instances of an user if any """ return User.objects.get(username=username)
9861fc648c40312dea62450bd152d511867fcfe5
25,211
def get_script_name(key_combo, key): """ (e.g. ctrl-shift, a -> CtrlShiftA, a -> A """ if key_combo != 'key': return get_capitalized_key_combo_pattern(key_combo) + key.capitalize() return key.capitalize()
a550c4b3852bf7ee3c30c4cecd497ae48a4d4a9d
25,212
def layer(name, features): """Make a vector_tile.Tile.Layer from GeoJSON features.""" pbl = vector_tile_pb2.tile.layer() pbl.name = name pbl.version = 1 pb_keys = [] pb_vals = [] pb_features = [] for j, f in enumerate( chain.from_iterable(singles(ob) for ob in features)): ...
a08e4dea809a938e1a451d34673f2845dd353a21
25,213
def serialize(formula, threshold=None): """Provides a string representing the formula. :param formula: The target formula :type formula: FNode :param threshold: Specify the threshold :type formula: Integer :returns: A string representing the formula :rtype: string """ return get_e...
872b4d5e135a6b1b9c5964ca353edccd0a6d8a40
25,214
import collections def find_single_network_cost(region, option, costs, global_parameters, country_parameters, core_lut): """ Calculates the annual total cost using capex and opex. Parameters ---------- region : dict The region being assessed and all associated parameters. option :...
9602d13a85ee5d4273d6bb82d28a525f42714890
25,215
def get_headings(bulletin): """"function to get the headings from text file takes a single argument 1.takes single argument list of bulletin files""" with open("../input/cityofla/CityofLA/Job Bulletins/"+bulletins[bulletin]) as f: ##reading text files data=f.read().r...
4b84928f8f4f13692c1236277aba6c6d4eb6c5ba
25,216
def phi_text_page_parse(pageAnalyse_str, phi_main_url): """ params: pageAnalyse_str, str. return: phi_page_dict, dict. It takes the precedent functions and maps their information to a dictionary. """ # phi_page_dict = {} phi_page_dict["phi_text_id_no"] = phi_text_id(pageAnalyse_str,...
e11a8b14726c2a65fb721f7a1f8c2f4148d18fea
25,217
def fdfilt_lagr(tau, Lf, fs): """ Parameters ---------- tau : delay / s Lf : length of the filter / sample fs : sampling rate / Hz Returns ------- h : (Lf) nonzero filter coefficients ni : time index of the first element of h n0 : time index of the center of h ...
3a80d3682eb255b7190cc5cd6ddf44a9abbd58bc
25,218
import tqdm def hit_n_run(A_mat, b_vec, n_samples=200, hr_timeout=ALG_TIMEOUT_MULT): """ Hit and Run Sampler: 1. Sample current point x 2. Generate a random direction r 3. Define gamma_i = ( b - a_i'x ) / ( r'a_i ) 4. Calculate max(gamma < 0) gamma_i and min(gamma > 0) gamma_i ...
e867c66ec97b9bbb91ad373b93fb9772e2d519cb
25,219
def construct_simulation_hydra_paths(base_config_path: str) -> HydraConfigPaths: """ Specifies relative paths to simulation configs to pass to hydra to declutter tutorial. :param base_config_path: Base config path. :return Hydra config path. """ common_dir = "file://" + join(base_config_path, 'c...
3353f910f9de708bbf0e5d46dc64b1d833230043
25,220
def delete_from_limits_by_id(id, connection, cursor): """ Delete row with a certain ID from limits table :param id: ID to delete :param connection: connection instance :param cursor: cursor instance :return: """ check_for_existence = get_limit_by_id(id, cursor) if check_for_existence...
7e035550c2d9d22be1af48434d0e36cd6424ecb7
25,221
def article_search(request): """Пошук статті і використанням вектору пошуку (за полями заголовку і тексту з ваговими коефіцієнтами 1 та 0.4 відповідно. Пошуковий набір проходить стемінг. При пошуку враховується близькість шуканих слів одне до одного""" query = '' results = [] if 'query' in reque...
423fd3cc4be6cdcef8fd4ab47bc7aa70f52e32bf
25,222
def get_campaign_data(api, campaign_id): """Return campaign metadata for the given campaign ID.""" campaign = dict() # Pulls the campaign data as dict from GoPhish. rawCampaign: dict = api.campaigns.get(campaign_id).as_dict() campaign["id"] = rawCampaign["name"] campaign["start_time"] = rawCa...
6dc344079e73245ef280d770df3b07f62543d856
25,223
def create_small_map(sharing_model): """ Create small map and 2 BS :returns: tuple (map, bs_list) """ map = Map(width=150, height=100) bs1 = Basestation('A', Point(50, 50), get_sharing_for_bs(sharing_model, 0)) bs2 = Basestation('B', Point(100, 50), get_sharing_for_bs(sharing_model, 1)) ...
ecc56eb95f7d2d8188d7caa7353f5bc95793f46e
25,224
def save_dataz(file_name, obj, **kwargs): """Save compressed structured data to files. The arguments will be passed to ``numpy.save()``.""" return np.savez(file_name, obj, **kwargs)
2ea4ecff522409d79fbecd779710a27a9026dbe4
25,225
def step(x): """Heaviside step function.""" step = np.ones_like(x, dtype='float') step[x<0] = 0 step[x==0] = 0.5 return step
2e11c87668b04acef33b7c7499ad10373b33ed76
25,226
def createRaviartThomas0VectorSpace(context, grid, segment=None, putDofsOnBoundaries=False, requireEdgeOnSegment=True, requireElementOnSegment=False): """ Create and return a space of lowest order Raviart...
100242b50f9aac6e55e6e02bb02c07f3b85c4195
25,227
def edus_toks2ids(edu_toks_list, word2ids): """ 将训练cbos的论元句子们转换成ids序列, 将训练cdtb论元关系的论元对转成对应的论元对的tuple ids 列表并返回 """ tok_list_ids = [] for line in edu_toks_list: line_ids = get_line_ids(toks=line, word2ids=word2ids) tok_list_ids.append(line_ids) # 数据存储 return tok_list_ids
b3b87bfb0ae90c78cff3b02e04f316d917834e2b
25,228
def pd_log_with_neg(ser: pd.Series) -> pd.Series: """log transform series with negative values by adding constant""" return np.log(ser + ser.min() + 1)
cf67df4173df27c7b97d320f04cd607c0ee8b866
25,229
def filter_X_dilutions(df, concentration): """Select only one dilution ('high', 'low', or some number).""" assert concentration in ['high','low'] or type(concentration) is int df = df.sort_index(level=['CID','Dilution']) df = df.fillna(999) # Pandas doesn't select correctly on NaNs if concentration...
b886c87c1c5b96e6efc951ef197d3a0fb13707c1
25,230
def update_params(base_param: dict, additional: dict): """overwrite base parameter dictionary Parameters ---------- base_param : dict base param dictionary additional : dict additional param dictionary Returns ------- dict updated parameter dictionary """ ...
e73581cb0b8d264343ead56da52c6dc12fe49dd7
25,231
import torch def lanczos_generalized( operator, metric_operator=None, metric_inv_operator=None, num_eigenthings=10, which="LM", max_steps=20, tol=1e-6, num_lanczos_vectors=None, init_vec=None, use_gpu=False, ): """ Use the scipy.sparse.linalg.eigsh hook to the ARPACK la...
2a3c236817524f2656f9b1631801293b1acf5278
25,232
import urllib import json def get_articles_news(name): """ Function that gets the json response to our url request """ get_news_url = 'https://newsapi.org/v2/top-headlines?sources={}&apiKey=988fb23113204cfcb2cf79eb7ad99b76'.format(name) with urllib.request.urlopen(get_news_url) as url: ge...
3394112b15903671ec5522c128e9035a404f2650
25,233
import os def execute( name, params=None, constraints=None, data_folder=None, tag=None, time_to_expire_secs=None, suffix=None, app_metrics=None, app_params=None, metadata=None, ): """ Create an instance of a workflow :param name: name of the workflow to create the i...
21fcf6dcd9f9910c3ec9769cf15b98c79bc8e4eb
25,234
def coordConv(fromP, fromV, fromSys, fromDate, toSys, toDate, obsData=None, refCo=None): """Converts a position from one coordinate system to another. Inputs: - fromP(3) cartesian position (au) - fromV(3) cartesian velocity (au/year); ignored if fromSys is Geocentr...
29ef79ff896806171a9819fc5ad8bf071bd48969
25,235
def sample_recipe(user, **params): """create recipe""" defaults = { 'title': 'paneer tikka', 'time_minute': 10, 'price': 5.00 } defaults.update(**params) return Recipe.objects.create(user=user, **defaults)
50b53622c68e6385c20296206759bc54f24afa3c
25,236
def briconToScaleOffset(brightness, contrast, drange): """Used by the :func:`briconToDisplayRange` and the :func:`applyBricon` functions. Calculates a scale and offset which can be used to transform a display range of the given size so that the given brightness/contrast settings are applied. :...
b75ce49f4e79f7fef34a855f2897cfa6b4bd7cc7
25,237
def HostNameRequestHeader(payload_size): """ Construct a ``MessageHeader`` for a HostNameRequest command. Sends local host name to virtual circuit peer. This name will affect access rights. Sent over TCP. Parameters ---------- payload_size : integer Length of host name string....
2371dba58d974408be28390462b5e7eb943edd88
25,238
import os import numpy def california_quadtree_region(magnitudes=None, name="california-quadtree"): """ Returns object of QuadtreeGrid2D representing quadtree grid for California RELM testing region. The grid is already generated at zoom-level = 12 and it is loaded through classmethod: QuadtreeGrid2D.from...
e6096c174c2e5f139f4e4a4338b2611ec62b27cd
25,239
def cinema_trip(persons, day, premium_seating, treat): """ The total cost of going to the cinema Parameters: ---------- persons: int number of people who need a ticket day: int day of the week to book (1 = Monday, 7 = Sunday) preimum_seating: bool ...
8a2c4418124251ae16dddee6c1a134e3b883b1b8
25,240
import pathlib def check_path(path: pathlib.Path) -> bool: """Check path.""" return path.exists() and path.is_file()
2279dde6912ae6f6eb51d90ed5e71e0b3892fea9
25,241
def omega2kwave(omega, depth, grav=9.81): """ Solve the linear dispersion relation close to machine precision:: omega**2 = kwave * grav * tanh(kwave*depth) Parameters ---------- omega : float Wave oscillation frequency [rad/s] depth : float Constant water depth. [m] (<0...
c448780d0edc3eb59ea79b4025182501875bb82f
25,242
def is_true(a: Bool) -> bool: """Returns whether the provided bool can be simplified to true. :param a: :return: """ return z3.is_true(a.raw)
e579a9793700132f38526d5cb737f3540d550821
25,243
from typing import Counter def traverse_caves_recursive(cave: str, cave_system: dict, current_path: list[str]): """Recursively traverse through all paths in the cave.""" if cave != "START": # build the current path traversed current_path = current_path[:] current_path.append(cave) ...
e78680ce8e1c3e7675d8fed980c4c706c87c1758
25,244
from sys import path def check_dummybots(): """ Checks the availablity of dummybots and set the global flag. Runs once per test session. """ global DUMMYBOTS if not DUMMYBOTS['tested']: DUMMYBOTS['tested'] = True # Load bot configuration fp = open(path.join(TEST_CONFIG...
2d122c1a5aa5f6381424bcb3700a111bec7d1dae
25,245
def count(A,target): """invoke recursive function to return number of times target appears in A.""" def rcount(lo, hi, target): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return 1 if A[lo] == target else 0 mid = (lo+hi)//2 left = rcount(lo...
79d9be64d332a11993f65f3c0deba8b4de39ebda
25,246
def asset_get_current_log(asset_id): """ """ db = current.db s3db = current.s3db table = s3db.asset_log query = ( table.asset_id == asset_id ) & \ ( table.cancel == False ) & \ ( table.deleted == False ) # Get the log with the maximum time asset_log = db(query)....
38bbdaade290e0f60a2dd7faa628b2c72dd48a8c
25,247
def _filter_to_k_shot(dataset, num_classes, k): """Filters k-shot subset from a dataset.""" # !!! IMPORTANT: the dataset should *not* be shuffled. !!! # Make sure that `shuffle_buffer_size=1` in the call to # `dloader.get_tf_data`. # Indices of included examples in the k-shot balanced dataset. keep_example...
d61f064dbbdc00b68fffc580baf7e658610e44eb
25,248
def _create_tf_example(entry): """ Creates a tf.train.Example to be saved in the TFRecord file. Args: entry: string containing the path to a image and its label. Return: tf_example: tf.train.Example containing the info stored in feature """ image_path, label = _get_i...
c50c2ff02eccc286319db6263841472d7c2b9fe3
25,249
def _gen_parameters_section(names, parameters, allowed_periods=None): """Generate the "parameters" section of the indicator docstring. Parameters ---------- names : Sequence[str] Names of the input parameters, in order. Usually `Ind._parameters`. parameters : Mapping[str, Any] Parameter...
9bc249ca67dcc1c0f7ff8538b8078bfcd5c231a1
25,250
import os def unload_agent(): """returns zero in case of success or if the plist does not exist""" plist_path = installed_plist_path() ret = 0 if os.path.exists(plist_path): ret = sync_task([LAUNCHCTL_PATH, "unload", "-w", "-S", "Aqua", plist_path]) else: log_message("nothing ...
4814df3a60eb4294899edb830882d557fce2f88b
25,251
def bins(df): """Segrega os dados de notas de 10 em 10 pontos para construção de gráficos. Parameters ---------- df : type Pandas DataFrame DataFrame de início. Returns ------- type Pandas DataFrame DataFrame final. """ df_bins = pd.DataFrame(df['ALUNO'].rename('Co...
7c4570866fcb5795dc9052222479e23574fbf64b
25,252
import os import logging def _GetBrowserSharedRelroConfig(): """Returns a string corresponding to the Linker's configuration of shared RELRO sections in the browser process. This parses the Java linker source file to get the appropriate information. Return: None in case of error (e.g. could not lo...
913d35acfdde7b4044cddeb841b2dbe514f709b5
25,253
from datetime import datetime def insert_video(ID): """ The function gets a valid YouTube ID, checks for its existence in database, if not found calls YouTube API and inserts into the MongoDB database. """ client = MongoClient('localhost:27017') db = client['PreCog'] collection = db['YoutubeRaw'] check...
9c4f453db72739973384ea1890614463855fcca2
25,254
def get_neighbor_v6_by_search(search=None): """Return a list of NeighborV6's by dict.""" try: objects = NeighborV6.objects.filter() search_dict = search if search else dict() object_map = build_query_to_datatable_v3(objects, search_dict) except FieldError as e: raise api_res...
3ed22479c140b7f71cd02d03be6c0fc82b0e81ca
25,255
import functools def validate_customer(fn): """ Validates that credit cards are between 1 and 5 and that each is 16 chars long """ @functools.wraps(fn) def wrapped(*args, **kwargs): # Validate credit card length cc_list = kwargs.get("credit_cards") trimmed_cc = [remove_non...
ecd5b63ed5f1ae8ecf94a27ba3f353f371dabe39
25,256
from typing import Any from typing import Sequence from typing import Mapping def format_field(value: Any) -> str: """ Function that formats a single field for output on a table or CSV output, in order to deal with nested arrays or objects in the JSON outputs of the API. :param value: the value to for...
5eef5c433924807b195c574c568d0e0a0a433eb7
25,257
def count_honeypot_events(): """ Get total number of honeypot events Returns: JSON/Dict number of honeypot events """ date = fix_date( get_value_from_request("date") ) if date: try: return jsonify( { "count_honeypot_eve...
22a0fd932098ec9e846daaa097c01a9f62763cc6
25,258
def k_i_grid(gridsize, boxsize): """k_i_grid(gridsize, boxlen)""" halfgrid = gridsize // 2 boxsize = egp.utils.boxsize_tuple(boxsize) dk = 2 * np.pi / boxsize kmax = gridsize * dk _ = np.newaxis k1, k2, k3 = dk[:, _, _, _] * np.mgrid[0:gridsize, 0:gridsize, 0:halfgrid + 1] k1 -= kmax[0] ...
29ffb72367672b8dd3f2e0a37923af565fb26306
25,259
def is_bool_type(typ): """ Check if the given type is a bool. """ if hasattr(typ, '__supertype__'): typ = typ.__supertype__ return isinstance(typ, type) and issubclass(typ, bool)
3d8dfae184be330c8cbd7c0e7382311fef31ede5
25,260
def gaussians_entropy(covars, ns=nt.NumpyLinalg): """ Calculates entropy of an array Gaussian distributions :param covar: [N*D*D] covariance matrices :return: total entropy """ N = covar.shape[0] D = covar.shape[-1] return 0.5 * N * D * (1 + log(2*ns.pi)) + 0.5 * ns.sum(ns.det(covar))
fe858d891cb4243b0aaf8b73fc7f38e542c5130d
25,261
def genBetaModel(matshape, cen, betaparam): """ Generate beta model with given parameters inputs ====== matshape: tuple or list Shape of the matrix cen: tuple or list Location of the center pixel betaparam: dict Parameters of the beta function { "A": float, ...
cabe4ff2d217bf918af291ad1fe875a66de2ca2a
25,262
def folders_to_create(search_path, dirs, base_path=""): """ Recursively traverse through folder paths looking for the longest existing subpath. Return the dir info of the longest subpath and the directories that need to be created. """ # Allow user to pass in a string, but use a list in the rec...
91750afa8a4756a09b71cc397a5991b106fd8909
25,263
def profile_line(image, src, dst, linewidth=1, order=1, mode='constant', cval=0.0): """Return the intensity profile of an image measured along a scan line. Parameters ---------- image : numeric array, shape (M, N[, C]) The image, either grayscale (2D array) or multichannel ...
29a020f77448c394d96be3fbd0b382b4657d401e
25,264
def set_out(pin, state): """ Set simple digital (high/low) output :param pin: pun number or logical name :param state: state: 1/0 = True/False :return: verdict """ __digital_out_init(pin).value(state) return {'pin': pin, 'state': state}
c76fb07d52fce9e0c66a6b63b5518b6575589807
25,265
import requests def get_session(): """Define a re-usable Session object""" session = requests.Session() session.auth = auth session.verify = False return session
3539e4a7433ffb58aa726c7fef87af080b011f64
25,266
import os def main(): """Main function.""" options = get_options() LOG.debug("Options are %s", options) entry_point = get_entrypoint() plugin = get_plugin(entry_point) inventory = plugin.get_dynamic_inventory() if options.list: dumps(inventory) elif options.host in inventory...
4b8edf05088ce45aff455ebbbd2dea6852870156
25,267
def create_test_action(context, **kw): """Create and return a test action object. Create a action in the DB and return a Action object with appropriate attributes. """ action = get_test_action(context, **kw) action.create() return action
8093d8f9b73ad0871ee422e2ba977f34907a3ae1
25,268
def parse(header_array, is_paper=False): """ Decides which version of the headers to use.""" if not is_paper: version = clean_entry(header_array[2]) if old_eheaders_re.match(version): headers_list = old_eheaders elif new_eheaders_re.match(version): ...
91f692b20300f96fac5d67e40950f7af17552ecb
25,269
def _GetIssueIDsFromLocalIdsCond(cnxn, cond, project_ids, services): """Returns global IDs from the local IDs provided in the cond.""" # Get {project_name: project} for all projects in project_ids. ids_to_projects = services.project.GetProjects(cnxn, project_ids) ref_projects = {pb.project_name: pb for pb in id...
26c41523adef27ae28b576707eb1c9f24961d8a0
25,270
import json def lookup_plex_media(hass, content_type, content_id): """Look up Plex media for other integrations using media_player.play_media service payloads.""" content = json.loads(content_id) if isinstance(content, int): content = {"plex_key": content} content_type = DOMAIN plex_...
060b5cded7bbb8d149a7bf2b94d5a5352114d671
25,271
import os def get_file_paths(directory, file=None): """ Collects the file paths from the given directory if the file is not given, otherwise creates a path joining the given directory and file. :param directory: The directory where the file(s) can be found :param file: A file in the directory ...
62e79a52682e046b83f9ad89df18d4dece7bf37a
25,272
def dsym_test(func): """Decorate the item as a dsym test.""" if isinstance(func, type) and issubclass(func, unittest2.TestCase): raise Exception("@dsym_test can only be used to decorate a test method") @wraps(func) def wrapper(self, *args, **kwargs): try: if lldb.dont_do_dsym...
d31c5bd87311b2582b9668fb25c1d4648663d1b8
25,273
from datetime import datetime def count_meetings(signups=None, left: datetime=None, right: datetime=None) -> int: """ Returns the number of meetings the user has been to, between two date ranges. Left bound is chosen as an arbitrary date guaranteed to be after any 8th periods from the past year, but befor...
8cb5290111db947b3daa01248452cfd36c80ec46
25,274
def fake_surroundings(len_poem, size_surroundings=5): """ Retourne une liste d'indices tirée au sort :param len_poem: nombre de vers dans le poème :param size_surroundings: distance du vers de référence du vers (default 5) :return: liste """ # bornes inférieures lower_bounds_w_neg = np.a...
91bbdefedd3ed2aa4d63db1ef7281129adb20036
25,275
import numpy def interpolate_missing(sparse_list): """Use linear interpolation to estimate values for missing samples.""" dense_list = list(sparse_list) x_vals, y_vals, x_blanks = [], [], [] for x, y in enumerate(sparse_list): if y is not None: x_vals.append(x) y_vals.a...
a2983a08f00b4de2921c93cc14d3518bc8bd393d
25,276
import os def auto_format_rtf(file_path, debug=False): """ Input complete filepath to .rtf file replaces all instances of "\\line" to "\\par". writes new data to new file with "MODFIED" appended. Prints debug messages to console if debug=True. """ # Separates file name and extensio...
e5b0ba32b0299b4ede115a6378e6ac3c4de59baf
25,277
def classifier_uncertainty(classifier: BaseEstimator, X: modALinput, **predict_proba_kwargs) -> np.ndarray: """ Classification uncertainty of the classifier for the provided samples. Args: classifier: The classifier for which the uncertainty is to be measured. X: The samples for which the u...
419da65825fff7de53ab30f4be31f2be0cf4bbbd
25,278
from typing import Optional import os from typing import Union def fetch_nature_scene_similarity(data_home: Optional[os.PathLike] = None, download_if_missing: bool = True, shuffle: bool = True, random_state: Optional[np.random.RandomState] = None, re...
f34d4700887df5ef00956ce8dfade1250a0814b8
25,279
def test_preserve_scalars(): """ test the preserve_scalars decorator """ class Test(): @misc.preserve_scalars def meth(self, arr): return arr + 1 t = Test() assert t.meth(1) == 2 np.testing.assert_equal(t.meth(np.ones(2)), np.full(2, 2))
ae48d49e5dd6781a304f75abd9b43e67faa09ee1
25,280
def from_string(zma_str, one_indexed=True, angstrom=True, degree=True): """ read a z-matrix from a string """ syms, key_mat, name_mat, val_dct = ar.zmatrix.read(zma_str) val_mat = tuple(tuple(val_dct[name] if name is not None else None for name in name_mat_row) ...
cf3817268cab7e79bf924f9d52cb70d01188ea48
25,281
def search(raw_query, query_type='/fast/all'): """ Hit the FAST API for names. """ out = [] unique_fast_ids = [] query = text.normalize(raw_query, PY3).replace('the university of', 'university of').strip() query_type_meta = [i for i in refine_to_fast if i['id'] == query_type] if query_ty...
0b543f662d0b26f89abc9ebcfb540c4ce925852e
25,282
def get_jmp_addr(bb): """ @param bb List of PseudoInstructions of one basic block @return Address of jump instruction in this basic block """ for inst in bb: if inst.inst_type == 'jmp_T': return inst.addr return None
13e69032bc7d6ed5413b5efbb42729e11661eab1
25,283
import os def mock_publish_from_s3_to_redis_err( work_dict): """mock_publish_from_s3_to_redis_err :param work_dict: dictionary for driving the task """ env_key = 'TEST_S3_CONTENTS' redis_key = work_dict.get( 'redis_key', env_key) str_dict = ae_consts.ev( env_k...
04cbc9dd5f29970fc46acc561dbf9f95ca141cab
25,284
import sqlite3 def open_db_conn(db_file=r'/home/openwpm/Desktop/crawl-data.sqlite'): """" open connection to sqlite database """ try: conn = sqlite3.connect(db_file) return conn except Exception as e: print(e) return None
28338f3ff3679c83a1e9040aa9b6e4f5026e4606
25,285
def totals_per_time_frame(data_points, time_frame): """For a set of data points from a single CSV file, calculate the average percent restransmissions per time frame Args: data_points (List[List[int,int,float]]): A list of data points. Each data...
9e71ac2fe7deabd36d7df8ae099575b191260c5d
25,286
import os def extract_lesional_clus(label, input_scan, scan, options): """ find cluster components in the prediction corresponding to the true label cluster """ t_bin = options['t_bin'] # t_bin = 0 l_min = options['l_min'] output_scan = np.zeros_like(input_scan) # threshold input ...
4502b7e1ac3bfcfe21781f04dea2ff12f3955ea9
25,287
def add_port_fwd( zone, src, dest, proto="tcp", dstaddr="", permanent=True, force_masquerade=False ): """ Add port forwarding. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.add_port_fwd public 80 443 tcp force_masquerade when a zone is c...
15c3cc5cbfb3e2921232df0508ea18d727d7861c
25,288
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...
0a952caf700216e67c7dd81958dd62d7734bb0fe
25,289
import struct def read_int(handle): """ Helper function to parse int from file handle Args: handle (file): File handle Returns: numpy.int32 """ return struct.unpack("<i", handle.read(4))[0]
cd175251fed79c8d79ea4a73d713457c06cbda6b
25,290
def prem_to_av(t): """Premium portion put in account value The amount of premiums net of loadings, which is put in the accoutn value. .. seealso:: * :func:`load_prem_rate` * :func:`premium_pp` * :func:`pols_if_at` """ return prem_to_av_pp(t) * pols_if_at(t, "BEF_DECR")
7d72e7e2e0b10ffb3958383817ddb7cc5f72a06a
25,291
from scipy.spatial import cKDTree def remove_close(points, radius): """ Given an nxd set of points where d=2or3 return a list of points where no point is closer than radius :param points: a nxd list of points :param radius: :return: author: revised by weiwei date: 20201202 """ tree...
42f8727488018e7f27802e81dbecfd300b38f45a
25,292
import torch def pose_mof2mat_v1(mof, rotation_mode='euler'): """ ### Out-of-Memory Issue ### Convert 6DoF parameters to transformation matrix. Args: mof: 6DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [B, 6, H, W] Returns: A transformation matrix -- [B, 3, 4, H, W] ...
78d42b36e64c0b6ba0eab46b6c19a96d44ed29fb
25,293
import os def kmercountexact(forward_in, reverse_in='NA', returncmd=False, **kwargs): """ Wrapper for kmer count exact. :param forward_in: Forward input reads. :param reverse_in: Reverse input reads. Found automatically for certain conventions. :param returncmd: If set to true, function will retur...
fb7166388002a1ad037fc7751f660f79be31cb27
25,294
def update(isamAppliance, local, remote_address, remote_port, remote_facility, check_mode=False, force=False): """ Updates logging configuration """ json_data = { "local": local, "remote_address": remote_address, "remote_port": remote_port, "remote_facility": remote_facil...
ed8af5d9d1b2f59726622ca6ebdfb4a20b88982f
25,295
from typing import Tuple def get_model_and_tokenizer( model_name_or_path: str, tokenizer_name_or_path: str, auto_model_type: _BaseAutoModelClass, max_length: int = constants.DEFAULT_MAX_LENGTH, auto_model_config: AutoConfig = None, ) -> Tuple[AutoModelForSequenceClassification, AutoTokenizer]: ...
b65cc9cb6e32c65b4d91becb51358146651fddb8
25,296
def get_forecast_by_coordinates( x: float, y: float, language: str = "en" ) -> str: """ Get the weather forecast for the site closest to the coordinates (x, y). Uses the scipy kd-tree nearest-neighbor algorithm to find the closest site. Parameters ---------- x : float L...
061007f152328929f2ed1c70f5a8b1401f3268f7
25,297
def get_calculated_energies(stem, data=None): """Return the energies from the calculation""" if data is None: data = {} stem = stem.find('calculation') for key, path in VASP_CALCULATED_ENERGIES.items(): text = get_text_from_section(stem, path, key) data[key] = float(text.split()[...
d2c0fcf9023874e6890b34e6950dc81e8d2073ce
25,298
from sys import argv import pip def main(): """Be the top-level entrypoint. Return a shell status code.""" commands = {'hash': peep_hash, 'install': peep_install, 'port': peep_port} try: if len(argv) >= 2 and argv[1] in commands: return commands[argv[1]]...
55c72e23657e546c9ef371ebcf84cd010f8212cb
25,299