content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import unittest def _as_path_test(ctx): """Unit tests for maprule_testing.as_path.""" env = unittest.begin(ctx) asserts.equals( env, "Foo\\Bar\\Baz\\Qux", maprule_testing.cmd_strategy.as_path("Foo/Bar/Baz\\Qux"), msg = "assertion #1", ) asserts.equals( env, ...
a3a21effafe0a9209a43c3e917745890c2679e1a
30,298
def alpha_optimisation (problem, alpha_range=np.arange(0.0, 1.1, 0.1)): """ This method is used to optimise the alpha parameter. Alpha parameter is used in the calculation of edges savings: saving = distance_saving * (1 - alpha) + revenue * alpha The higher is alpha the bigger is the importanc...
6c2e8450ac72b89661a48c1a14971f49afc37dfb
30,299
from typing import Dict def _codify_quantitative_input_by_abs_val( df: pd.DataFrame, threshold: float, p_value: float, ) -> Dict[str, int]: """Codify nodes with | logFC | if they pass threshold, otherwise score is 0.""" # Codify nodes with | logFC | if they pass threshold df.loc[(df[LOG_FC]).a...
0baaf3a58539f5be2a34d41e553b356e0b4df883
30,300
from typing import Optional def labor_day(date: dt.date) -> Optional[str]: """First Monday in September""" if not is_nth_day(date, 0, 0, 9): return None return "Happy Memorial Day. You can wear white again"
f03746c741ba60c18fa6d9254b1a8d80a7aa3437
30,301
def vgg16(reparametrized=False, **kwargs): """VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = VGG(make_layers(cfg['D'], reparametrized=reparametrized), **kwargs) return model
b1c7e4b98fdb25bce70e33865405232b25e17118
30,302
def logout(request): """ :param request: :return: """ auth_logout(request) return redirect('/')
d5d85ff49c36e81557bee83403046e5ec22f78ee
30,303
def vec3d_rand_corners(corner1, corner2): """ Sample one R3 point from the AABB defined by 'corner1' and 'corner2' """ span = np.subtract(corner2, corner1) sample = vec_random(3) return [corner1[0]+span[0]*sample[0], corner1[1]+span[1]*sample[1], corner1[2]+span[2]*sample...
b8e87a869545476d8fce25bfd74c4d29138c93d8
30,304
def meta_body(): """Ugoira page data.""" return '{"error":false,"message":"","body":{"src":"https:\/\/i.pximg.net\/img-zip-ugoira\/img\/2019\/04\/29\/16\/09\/38\/74442143_ugoira600x600.zip","originalSrc":"https:\/\/i.pximg.net\/img-zip-ugoira\/img\/2019\/04\/29\/16\/09\/38\/74442143_ugoira1920x1080.zip","mime_...
abf9e01371938467b12721373a0e5fc8fb926016
30,307
def anatomical_traverse_bids(bids_layout, modalities='anat', subjects=None, sessions=None, extension=('nii', 'nii.gz', 'json'), param_files_required=False, ...
cb48c4af0a4cf2969cbb291daf980d0556989e85
30,308
def get_email_subscriptions(email): """Verifies which email subsciptions exist for the provided email Parameters ---------- email : str The email to the check subscriptions for Returns ------- list(tuple(str, str, query_hash)) """ user_queries = db.get_subscribed_queries(em...
84961b40512005a73b78d28feefcc424385bef8f
30,309
import re def format_comments(text="default", line_size=90): """ Takes a string of text and formats it based on rule 1 (see docs). """ # rules to detect fancy comments, if not text regex1 = r"^ *?####*$" # rules to detect fancy comments, if text regex2 = r"^ *?####*([^#\n\r]+)#*" # if ...
6eba4539aa7128d5654ddab7fe08a2e9df6dc738
30,310
def get_kernel_versions_async(loop=None): """ Execute dpkg commands asynchronously. Args: loop: asyncio event loop (optional) Returns: [DpkgCommandResult]: stats from the executed dpkg commands """ return subprocess_workflow.exec_and_parse_subprocesses_async( [DpkgComma...
425eac2d2ef7e00512b04ed41f3269e094762557
30,311
import math def autoencoder( input_shape, encoding_dim=512, n_base_filters=16, batchnorm=True, batch_size=None, name="autoencoder", ): """Instantiate Autoencoder Architecture. Parameters ---------- input_shape: list or tuple of four ints, the shape of the input data. Should be...
dbb1983cb3b6adfcde823e6a2013e5517b57044f
30,312
import numpy def SHAPER(B, D, LA): """ """ LB = B.size LD = D.size A = numpy.zeros(LA) LC = LB + LA - 1 LCD = LC + LD - 1 C = numpy.zeros(LCD) INDEX = 0 ERRORS = numpy.zeros(LCD) SPACE = numpy.zeros(3 * LA) (A, LC, C, INDEX, ERRORS, S) = ER.SHAPER(LB, B, LD, D, LA, A, ...
cbe86b69c073c36e0f5d97616c9de59f2b4c2652
30,313
from typing import Tuple def _get_efron_values_single( X: pd.DataFrame, T: pd.Series, E: pd.Series, weights: pd.Series, entries: None, beta: np.ndarray ) -> Tuple[np.ndarray, np.ndarray, float]: """ Calculates the first and second order vector differentials, with respect to beta. N...
2d6a049e6894f3be6e002d22cc1c2b7d4705a66f
30,314
import re def get_battery_information(): """Return device's battery level.""" output = adb.run_adb_shell_command(['dumpsys', 'battery']) # Get battery level. m_battery_level = re.match(r'.*level: (\d+).*', output, re.DOTALL) if not m_battery_level: logs.log_error('Error occurred while getting battery s...
dba773386e88728b3a1cf752c6b3bfa74b38963d
30,317
def _tensor_setitem_by_tuple_with_tuple(data, tuple_index, value): """ Tensor assignment. Note: Syntax support: A[B, C, D] = U. Restraint condition: 1) A is a Tensor, and B, C, D are index Tensors. 2) A B and C could be broadcast. 3)...
d00d08cb1391c96938bf5390c5e7f58bac6724a5
30,318
def templates_global_context(request): """ Return context for use in all templates. """ global_context = { 'constant_ddd': constants.DDD, 'constant_estado': constants.ESTADO, 'constant_municipio': constants.MUNICIPIO, 'constant_cep': constants.CEP, 'constant_pais': constants.PAIS, 'constant_current_year...
500ce9eaf26631fdeaa48c4d9001847e713262f5
30,319
import warnings from typing import Concatenate def doubleunet(num_classes, input_shape=(224, 224, 3), model_weights=None, num_blocks=5, encoder_one_type='Default', encoder_one_weights=None, encoder_one_freeze=False, ...
cf50030dfe2ace708b7ee192aa7e4631af2a5e2c
30,320
def get_lldp_neighbors(dut, interface=None): """ Get LLDP Neighbours Info Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param interface: localport :return: """ command = "show lldp neighbors" if interface: command = "show lldp neighbors {}".format(interfac...
2fadb9f1c61a3b289b8d66e3e3cb0566c336bd03
30,322
def encode_onehot(batch_inputs, max_len=None): """One-hot encode a string input.""" if max_len is None: max_len = get_max_input_len() def encode_str(s): tokens = CTABLE.encode(s) unpadded_len = len(tokens) if unpadded_len > max_len: raise ValueError(f'Sequence too long ({len(tokens)}>{max_...
2cecbfd553cde1184720c3b0a5c666f5762b174d
30,323
def plot_confusion_matrix(cm, normalize=True, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. plt.show() must be run to view th...
2dc9f5917d97278844c90eb851a45bc246f22c7c
30,324
def detect_id_type(sid): """Method that tries to infer the type of abstract ID. Parameters ---------- sid : str The ID of an abstract on Scopus. Raises ------ ValueError If the ID type cannot be inferred. Notes ----- PII usually has 17 chars, but in Scopus ther...
b9c6f1442f6824e990ac1275296bb50fdad682cd
30,326
def config_to_dict(plato_config): """ Convert the plato config (can be nested one) instance to the dict. """ # convert the whole to dict - OrderedDict plato_config_dict = plato_config._asdict() def to_dict(elem): for key, value in elem.items(): try: value = value._a...
9e68c2859dc33370554f8015f96bd501f827c1b2
30,327
def analyze_single_user_info(result=load_data()): """ :param result: :return: examp: {user_id: 1, meal_info: {breakfast:{food_name:菜名,times:次数}}, {early_dinner:{...}}, {supper:{...}}} """ result = pd.DataFrame(result, columns=['user_id', 'user_name', 'food_code', 'food_name', 'meal_type', '...
04b8084efce6e5f5707f61d114cdc3a98037c1c1
30,328
def mergeSort(data): """ Implementation of the merge sort algorithm in ascending order """ n = len(data) if n == 1: return data else: midIndex = (int)(n/2) leftHalf = mergeSort(data[0:midIndex]) rightHalf = mergeSort(data[midIndex:n]) return mergeHalves(leftHalf,...
68e693fdcaaf0127372ad3477df64473e989a2e2
30,329
def compute_gradient_logistic(y, tx, w): """Function to compute gradient of loss of logistic regression for given w. Args: y (numpy array): Matrix output of size N x 1. tx (numpy array): Matrix input of size N x D. w (numpy array): Matrix weight (parameters of the model) of size D x 1....
db525602a5d64dda8e64592770210315da29e64f
30,330
import re def parse_py(fname): """Look for links in a .py file.""" with open(fname) as f: lines = f.readlines() urls = set() for i, line in enumerate(lines): for url in find_urls(line): # comment block if line.lstrip().startswith('# '): subidx = ...
c95f6f326a74bfc3e123df4ac09171e0a44d4486
30,331
def lwp_cookie_str(cookie): """Return string representation of Cookie in an the LWP cookie file format. Actually, the format is extended a bit -- see module docstring. """ h = [(cookie.name, cookie.value), ("path", cookie.path), ("domain", cookie.domain)] if cookie.port is not No...
5d7735397fdb23e629ed4db844cbbd44bc386674
30,332
def fiscalyear(): """Retrieve Fiscal Years and display for selection by user.""" cascs = db.session.query(casc).order_by(casc.name).all() cascs_and_fys = {} class F(FyForm): pass list_fy = [] for curr_casc in cascs: cascs_and_fys[curr_casc.name] = {} cascs_and_fys[curr_...
9656aafc00083097417eae8b6633ea99ac9bb9e4
30,333
def forbidden(error) -> str: """ Forbidden resource """ return jsonify({"error": error.description}), 403
6c9fb0c1ad696b9337a2345a82613f2359a00778
30,334
def get_parameter(model, name): """ Finds the named parameter within the given model. """ for n, p in model.named_parameters(): if n == name: return p raise LookupError(name)
ba35b743d9189c94da0dcce27630bba311ea8a46
30,335
def _update_method(oldmeth, newmeth): """Update a method object.""" # XXX What if im_func is not a function? _update(oldmeth.im_func, newmeth.im_func) return oldmeth
1c05204067610acb4f540839e647466f07952323
30,336
def get_stats_asmmemmgr(space): """Returns the raw memory currently used by the JIT backend, as a pair (total_memory_allocated, memory_in_use).""" m1 = jit_hooks.stats_asmmemmgr_allocated(None) m2 = jit_hooks.stats_asmmemmgr_used(None) return space.newtuple([space.newint(m1), space.newint(m2)])
16aa01635d08ea39ab9051c15e60b11c3bc027a5
30,338
def parse_function(filename): """ Parse a filename and load the corresponding image. Used for faces. Parameters ---------- filename : str Path to the faces image. Returns ------- image : tensorflow.Tensor Image object. Raises ------ None No...
878d00c1f9c7dc37041e79a96e030b249e2ca350
30,339
def calc_final_speed(v_i, a, d): """ Computes the final speed given an initial speed, distance travelled, and a constant acceleration. :param: v_i: initial speed (m/s) a: acceleration (m/s^2) d: distance to be travelled (m) :return: v_f: the final speed (m/s) """ ...
14dbf3f6e7391b0fd0c1796f77c5966875b689b8
30,340
def write_table(fh, data, samples=None, tree=None, rankdic=None, namedic=None, name_as_id=False): """Write a profile to a tab-delimited file. Parameters ---------- fh : file handle Output file. data : dict Profile data. samples : list, optional Ordered sa...
40698102a0a000e3ec2ba7fff6cff35e6cf2b598
30,342
def data_context_notification_context_notif_subscriptionuuid_notificationnotification_uuid_changed_attributesvalue_name_get(uuid, notification_uuid, value_name): # noqa: E501 """data_context_notification_context_notif_subscriptionuuid_notificationnotification_uuid_changed_attributesvalue_name_get returns tapi...
7171e1dab60d838d0a321e1d339b07511674a4f6
30,343
def angular_misalignment_loss_db(n, w, theta, lambda0): """ Calculate the loss due to angular fiber misalignment. See Ghatak eqn 8.75 Args: n: index between fiber ends [-] w: mode field radius [m] theta: angular misalignment [radians] lambda0...
4233dad15b3840dda95a762d32eec657a423d28d
30,344
def replace_number(token): """Replaces a number and returns a list of one or multiple tokens.""" if number_match_re.match(token): return number_split_re.sub(r' @\1@ ', token) return token
c5954c447142581efd80aedf0215e66240ef89ae
30,345
import timeit from typing import DefaultDict def dnscl_rpz( ip_address: str, filename: str = FILENAME, tail_num: int = 0, quiet_mode: bool = False, ) -> int: """Return rpz names queried by a client IP address.""" start_time = timeit.default_timer() rpz_dict: DefaultDict = defaultdict(int) ...
951d40f56a7b12a454499524da36e39b1f91b2bd
30,346
def sweep_centroids(nrays, rscale, nbins, elangle): """Construct sweep centroids native coordinates. Parameters ---------- nrays : int number of rays rscale : float length [m] of a range bin nbins : int number of range bins elangle : float elevation angle [ra...
0d5d39589a6b6945618d4cd122c88a9a8f711f57
30,347
import time def toc(): """ 对应MATLAB中的toc :return: """ t = time.clock() - globals()['tt'] print('\nElapsed time: %.8f seconds\n' % t) return t
ce7d5898972fa751178ab35a41736fd136f85d24
30,348
def read_images_binary(path_to_model_file): """ see: src/base/reconstruction.cc void Reconstruction::ReadImagesBinary(const std::string& path) void Reconstruction::WriteImagesBinary(const std::string& path) """ images = {} with open(path_to_model_file, "rb") as fid: num_reg_i...
e1baf9988b74a8e0108d84bca48d2cf2f10f7358
30,350
def __no_conflicts(items): """Return True if each possible pair, from a list of items, has no conflicts.""" return all(__no_conflict(combo[0], combo[1]) for combo in it.combinations(items, 2))
761641bd59162e4714ce4ab04274307353f0aefa
30,352
def valid_tetrodes(tetrode_ids, tetrode_units): """ Only keep valid tetrodes with neuron units so that there is corresponding spike train data. :param tetrode_ids: (list) of tetrode ids in the order of LFP data :param tetrode_units: (dict) number of neuron units on each tetrode :return: (list) of t...
c887f5e5c29d841da63fe0cd56c41eda5ddde891
30,354
from datetime import datetime def get_us_week(date): """Determine US (North American) week number""" # Each date belongs to some week. Each week has a Saturday. The week_sat_offset is number of # days between the Saturday and the date: week_sat_offset = (12 - date.weekday()) % 7 week_sat = date + ...
30e7f7179d732cdf08c0dcdeff627c889af6c340
30,356
def is_street_name(elem): """This function takes an element and returns whether it contains an attrib key 'addr:street'. This is an modification from https://classroom.udacity.com/nanodegrees/nd002/parts/0021345404/modules/316820862075461/lessons/5436095827/concepts/54446302850923""" return (elem.attr...
2b753fab69959200cc79895f382767af76295420
30,357
def read_youtube_urls(): """ Required format that the txt file containing the youtube urls must have: url_1 url_2 . . . url_n :param filepath: :return: """ yt_urls = [] file_to_read = askopenfile(mode="r", filetypes=[("Text file", "*.txt")]) ...
5a8d505fe39d35c117ceaef33cc878f5ed7f5a1c
30,359
def _get_search_direction(state): """Computes the search direction to follow at the current state. On the `k`-th iteration of the main L-BFGS algorithm, the state has collected the most recent `m` correction pairs in position_deltas and gradient_deltas, where `k = state.num_iterations` and `m = min(k, num_corr...
5659dd49c9dcf67b65c3952a839df6c9b099ed76
30,360
def basevectors_sm(time, dipole=None): """ Computes the unit base vectors of the SM coordinate system with respect to the standard geographic coordinate system (GEO). Parameters ---------- time : float or ndarray, shape (...) Time given as modified Julian date, i.e. with respect to the ...
434d2ad867aaefb483f8ec212943fc1af1f4949b
30,362
def rewrite_metadata(content, dic): """From content, which is the old text with the metadata and dic which has the new data, return new_txt which has data replaced by dic content, with relevant headers added """ #Splitting into headers and body. Technically, body is a list of paragraphs where first one is the ...
14f7da66f19c24d073f1fdee4b56d49d28320e71
30,363
def rotate_points(points, axis, angle, origin=None): """Rotates points around an arbitrary axis in 3D (radians). Parameters: points (sequence of sequence of float): XYZ coordinates of the points. axis (sequence of float): The rotation axis. angle (float): the angle of rotation in radian...
a2eb1857dac96d46f7319e638423164ae6951ebe
30,364
def resolve_translation(instance, info, language_code): """Get translation object from instance based on language code.""" loader = TYPE_TO_TRANSLATION_LOADER_MAP.get(type(instance)) if loader: return loader(info.context).load((instance.pk, language_code)) raise TypeError(f"No dataloader found ...
50ada7fd7d681a5ca8def13a5f07c9fe73f4461a
30,365
def reverse_dict_old(dikt): """ takes a dict and return a new dict with old values as key and old keys as values (in a list) example _reverse_dict({'AB04a':'b', 'AB04b': 'b', 'AB04c':'b', 'CC04x': 'c'}) will return {'b': ['AB04a', 'AB04b', 'AB04c'], 'c': 'CC04x'} """ new_dikt = {...
50155858fbbe52dc8daae66e6a94c8885b80ba05
30,366
def get_active_user(request): """ Endpoint for getting the active user through the authtoken """ return Response(UserSerializer(request.user, context={'is_public_view': False}).data, status=status.HTTP_200_OK)
b86214eee8c34c53ed66992420f13f64cc2bda30
30,367
def upsert_website(admin_id, root, data, force_insert=False): """Method to update and insert new website to live streaming. Args: admin_id (str): Admin privileges flag. root (str): Root privileges activation flag. data (dict): ...
bc118cf7c42a375cc458b92713d4e4f802239d3c
30,369
def rest_query_object_by_id(bc_app, url, obj_id, json_obj_name, object_type, para_query_mode=False): """ query object by id :param bc_app: used to attach app sign :param url: do NOT contain params at the end :param obj_id: object id :param json_obj_name: like 'plan' for plan query :param obj...
2ed5390fba651c5874cfc51e472629ba9ad4369b
30,370
import re import unicodedata def bert_clean_text(text): """Performs invalid character removal and whitespace cleanup on text.""" text = re.sub('[_—.]{4,}', '__', text) text = unicodedata.normalize("NFKC", text) output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xFFF...
e31930f7eb04cfc24f5dc2dd031de40d58643027
30,371
import random def get_successors(curr_seq): """ Function to generate a list of 100 random successor sequences by swapping any cities. Please note that the first and last city should remain unchanged since the traveller starts and ends in the same city. Parameters ---------- curr_seq : [li...
db928f0baed2c46211f9633c2e2223e39c177dbe
30,373
def Q(lambda_0, lambda_, eps_c, Delta, norm_zeta2, nu): """ Quadratic upper bound of the duality gap function initialized at lambda_0 """ lmd = lambda_ / lambda_0 Q_lambda = (lmd * eps_c + Delta * (1. - lmd) + 0.5 * nu * norm_zeta2 * (1. - lmd) ** 2) return Q_lambda
e7c624d822713efd9a63e92d40ecb9c13d5ee8d6
30,374
def solve(equation): """ Solves equation using shunting-yard algorithm :param equation: string equation to be solved :return: float result of equation """ postfix = rpn(equation) result = shunting_yard(postfix) return result
c57dc10b4c41f048a5690548a7155550b52d8d1c
30,375
def get_project_url(): # pragma no cover """Open .git/config file and git the url from it.""" project_info = {} try: with open('./.git/config', 'r') as git_config: for line in git_config: if "url = git@" in line: dont_need, need = line.split(' = ') ...
d296a23372c22adfd35e4c0ea463db2fbac557b1
30,376
from datetime import datetime def sign_out(entry, time_out=None, forgot=False): """Sign out of an existing entry in the timesheet. If the user forgot to sign out, flag the entry. :param entry: `models.Entry` object. The entry to sign out. :param time_out: (optional) `datetime.time` object. Specify th...
c94ce2231dda115a53ea41a12dd04cbcd728088f
30,377
def get_button_write(deck_id: str, page: int, button: int) -> str: """Returns the text to be produced when the specified button is pressed""" return _button_state(deck_id, page, button).get("write", "")
34cec488aa5245a620953319ce5dab8a0b7032e0
30,378
def opensafety_a(data: bytes) -> int: """ Compute a CRC-16 checksum of data with the opensafety_a algorithm. :param bytes data: The data to be computed :return: The checksum :rtype: int :raises TypeError: if the data is not a bytes-like object """ _ensure_bytes(data) return _crc_16_...
be2a432874c50e7edd6af0555ed4cd2a7fb4c4b2
30,379
def EM_frac(pdf, iters=30, EPS=1E-12, verbose=True): """ EM-algorithm for unknown integrated class fractions Args: pdf : (n x K) density (pdf) values for n measurements, K classes iter : Number of iterations Returns: frac : Integrated class fractions """ n = pdf.shape[0] K = pdf.shape[1] P = np.z...
7944e75b955b27cc0c7479a5eb7b3e6a6d656ede
30,380
def gaussian_loss(y_true, y_pred, interval, eta): """ non zero mean absolute loss for one batch This function parameterizes a loss of the form Loss = - exp(- x ^ 2 / 2*sigma ^ 2) where x = y_true - y_pred and sigma = eta * y_true and eta is a constant, generally much less than 1 Args: ...
a39e4caa12304f43512f843034c143711797e5f8
30,382
import copy def create_registration_data(legal_type, identifier='FM1234567', tax_id=None): """Test data for registration.""" person_json = { 'officer': { 'id': 2, 'firstName': 'Peter', 'lastName': 'Griffin', 'middleName': '', 'partyType': 'pe...
d0be4516f8f67a5aaa05365ab47c0258b1e174d1
30,385
def proctored_exam_results_csv(entry_id, xmodule_instance_args): """ Compute proctored exam results report for a course and upload the CSV for download. """ action_name = 'generating_proctored_exam_results_report' task_fn = partial(upload_proctored_exam_results_report, xmodule_instance_args) ...
e49927963c17c0c7582f4614dbb570760c84fd34
30,386
def get_twiter_position(twit, market): """ Get's Vicki's position on the appropriate stock :param twit: Twitter API Object :param market: The market pair which to observe :type twit: twitter :type market: str :return: String contining Vicki's position on the relavant market :rtype : st...
fb5cf927de81ae39ba913da27e61916315664f4c
30,387
def build_new_devices_list(module): """ Build List of new devices to register in CV. Structure output: >>> configlets_get_from_facts(cvp_device) { [ { "name": "veos01", "configlets": [ "cv_device_test01", "S...
915ca10ee20c4da5bf1ff4f504ecba1b0f217411
30,388
from typing import Tuple def preprocess(input_path: str, image_size: int) -> Tuple[pd.Series, np.ndarray]: """ Preprocss imager data into a depth, image tuple. Image is resized to a given width. Additionally, to avoid floating point difficulties, depth measurements are converted to centimeters an...
7116555c07fdbb7277d1c9da84b51e83b399dd74
30,389
def _scale_pot(pot, scale_coeff, numtors): """ Scale the potential """ print('scale_coeff test 0:', scale_coeff, numtors) scale_factor = scale_coeff**(2.0/numtors) print('scale_coeff test:', scale_coeff, numtors, scale_factor) new_pot = {} for idx, val in pot.items(): new_pot[i...
0e634b7766a5822d3b2e80fffa0b56dccee125ab
30,391
import pkg_resources def get_substation_file(): """Return the default substation file for the CONUS.""" return pkg_resources.resource_filename('cerf', 'data/hifld_substations_conus_albers.zip')
7628c7981dd9f82b4210a451ad62fffa72222fe8
30,392
def configure_assignment_caller(context, pyramid_request, parsed_params=None): """ Call BasicLTILaunchViews.configure_assignment(). Set up the appropriate conditions and then call BasicLTILaunchViews.configure_assignment(), and return whatever BasicLTILaunchViews.configure_assignment() returns. ...
dc607bf0e82a2956a1e435bfd480442cd9b6b920
30,393
import types import pandas import numpy def hpat_pandas_series_isna(self): """ Pandas Series method :meth:`pandas.Series.isna` and :meth:`pandas.Series.isnull` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_isna1 Test: python...
5a541da044e83e8248446c8b2a0d883213bddd17
30,394
from typing import Optional def _filter_stmts(base_node: nodes.NodeNG, stmts, frame, offset): """Filter the given list of statements to remove ignorable statements. If base_node is not a frame itself and the name is found in the inner frame locals, statements will be filtered to remove ignorable stat...
744710684fd6f8b3e90e01d93e6533d1fa87c117
30,395
def lcp_coordinate_conversion(start_coords,end_coords,crs,transform): """ Simple Example: network = lcp.create_raster_network(array) Parameters: - 'start_coords' is a list of tuples (lon,lat) - 'end_coords' is a list of lists of tuples. Each list of end points corresponds to a...
936a1e4df8147786923dea6e87d487ea61af4408
30,396
def create_large_map(sharing_model): """ Create larger map with 7 BS that are arranged in a typical hexagonal structure. :returns: Tuple(map, bs_list) """ map = Map(width=230, height=260) bs_list = [ # center Basestation('A', Point(115, 130), get_sharing_for_bs(sharing_model, 0)...
4348bc97177ec18dcaaf7f72f5d439a17a100956
30,397
def np_scatter_add(input,axis,index,src): """ numpy wrapper for scatter_add """ th_input = th.as_tensor(input,device="cpu") th_index = th.as_tensor(index,device="cpu") th_src = th.as_tensor(src,device="cpu") dim = axis th_output = th.scatter_add(th_input,dim,th_index,th_src) output = th_output.numpy() return o...
4575d0d65ae93e403511b4ba6e5b920616c8bb37
30,398
def netmiko_connect(device_name, device): """ Successful connection returns: (True, connect_obj) Failed authentication returns: (False, None) """ hostname = device["host"] port = device.get("port", 22) msg = "" try: net_connect = ConnectHandler(**device) msg = f"Netmiko...
f273149ccde031512cd159ca61296ef09bc11d2d
30,399
def get_tracer(request): """ Utility function to retrieve the tracer from the given ``request``. It is meant to be used only for testing purposes. """ return request['__datadog_request_span']._tracer
facd1ff0922dcc7743814cfd738d022316ba5d6d
30,400
def local_self_attention_layer(hparams, prefix): """Create self-attention layer based on hyperparameters.""" return transformer_layers.LocalSelfAttention( num_heads=hparams.get(prefix + "num_heads"), num_memory_heads=hparams.get(prefix + "num_memory_heads"), radius=hparams.local_attention_radius, ...
0b49b116cacdec203f531dfb28b389748a84b9b6
30,402
import pickle def hwtrain(X_csv: str, y_csv: str, model: str = 'lm') -> str: """ Read the feature matrix and label vector from training data and fit a machine learning model. The model is saved in pickle format. Parameters ---------- X_csv The path to the feature ...
fde68a010249859a95264552bfe767f9c4636d7c
30,403
def convert_ban_to_quan(str_ban): """半角转全角""" str_quan = "" for uchar in str_ban: inside_code = ord(uchar) if inside_code == 32: #半角空格直接转化 inside_code = 12288 elif inside_code >= 32 and inside_code <= 126: #半角字符(除空格...
b8e7417c0680dcf113377d32dbb2c43738c0af6c
30,404
import requests def update_user_permissions(userid, profile="grafana", **kwargs): """ Update a user password. userid Id of the user. isGrafanaAdmin Whether user is a Grafana admin. profile Configuration profile used to connect to the Grafana instance. Default is ...
4f5b2ed94896dcb0f7d76b066ed7767700ada682
30,405
def to_xepsilon(_): """ :param _: :return: """ return xepsilon()
69e4e478f3e4d7978cb2a5f76aaf12053458c64a
30,406
def build_permissions_response(): """ Build a response containing only speech """ output = "I'm sorry, I was not able to lookup your home town. "\ "With your permission, I can provide you with this information. "\ "Please check your companion app for details" return { 'outp...
4b01a0fa32958127f7c373b0cedf5d518074e29e
30,407
def simple_tokenizer(text): """ Example for returning a list of terms from text. 1. Normalizes text by casting to lowercase. 2. Removes punctuation from tokens. 3. Returns tokens as indicated by whitespace. """ text = text.lower() # Remove punctuation from file if isinstance(te...
5b26c2dfdb5cc794fd5238e5a2ecdacb18ae1e19
30,408
def progress(*args, **kwargs): """ The HTML <progress> Element is used to view the completion progress of a task. While the specifics of how it's displayed is left up to the browser developer, it's typically displayed as a progress bar. Javascript can be used to manipulate the value of progress ...
f2c41b3b3562485d21c2f1f990f2fa368627c7e7
30,409
def openssl_error(): """Return the OpenSSL error type for use in exception clauses""" return _OpenSSLError
f1782d0cdce002b2214ead438f153631afdf51ab
30,410
def load_path(path, visitor=TokenVisitor): """ Args: path (str): Path to file to deserialize visitor (type(TokenVisitor)): Visitor to use Returns: (list): Deserialized documents """ with open(path) as fh: return deserialized(Scanner(fh), visitor)
e938f08c45737ec60f5258f96ea9d5f08053f99e
30,411
def get_card_names(cards): """ :param cards: List of card JSONs :return: List of card names (str) """ names = [] for card in cards: name = card.get("name") names.append(name) return names
a30ad1ef7d8beaab0451d6f498254b0b5df3cf6d
30,412
import platform def pyversion(ref=None): """Determine the Python version and optionally compare to a reference.""" ver = platform.python_version() if ref: return [ int(x) for x in ver.split(".")[:2] ] >= [ int(x) for x in ref.split(".")[:2] ] else: retur...
2e31c7710b171ad67e56f9dbc1181685e0f32de1
30,413
import tqdm def opt_tqdm(iterable): """ Optional tqdm progress bars """ try: except: return iterable else: return tqdm.tqdm(iterable)
5bcdde21f706f1eb3907beafc9ddeebf6891e0ec
30,414
def get_dataset_config(): """Gets the config for dataset.""" config = config_dict.ConfigDict() # The path to the specification of grid evaluator. # If not specified, normal evaluator will be used. config.grid_evaluator_spec = '' # The directory of saved mgcdb84 dataset. config.dataset_directory = '' # T...
52a026e7c67d09cff9eab3045508f5fb17363db6
30,415
import pathlib import tests import json import yaml def stub_multiservo_yaml(tmp_path: pathlib.Path) -> pathlib.Path: """Return the path to a servo config file set up for multi-servo execution.""" config_path: pathlib.Path = tmp_path / "servo.yaml" settings = tests.helpers.BaseConfiguration() measure_...
572d438f406bb1a1d8ced68be6612dced7cdca9b
30,416
import collections def rename_internal_nodes(tree, pg_dict): """Rename internal nodes (add phylogroups to the name). """ numbers = collections.defaultdict(lambda: 0) for node in tree.traverse("postorder"): if node.is_leaf(): continue pgs = node_to_pg(node, pg_dict) ...
ed77d3d4df42164919a3394fcebc8d49f5bd80eb
30,418
import math import torch import tqdm def assign_by_euclidian_at_k(X, T, k): """ X : [nb_samples x nb_features], e.g. 100 x 64 (embeddings) k : for each sample, assign target labels of k nearest points """ # distances = sklearn.metrics.pairwise.pairwise_distances(X) chunk_size = 1000 ...
31033b8ddf3a2427ec98fdacecb253f6381d38d4
30,419