content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
import sys def exception_in_stack(): """Return true if we are currently in the process of handling an exception, ie one has been caught in a try block. https://docs.python.org/3/library/sys.html#sys.exc_info """ return sys.exc_info()[0] is not None
71f2076c956fa3bb92751778c29537df7bceac35
30,305
import os import csv import re def validate_terminology(table, gecko_labels): """Validate an IHCC mapping table.""" basename = os.path.splitext(os.path.basename(table))[0].capitalize() problems = [] problem_count = 0 # label -> locs labels = {} # loc -> parent_term parent_terms = {} ...
5a3bfc7337ad489acd08f0af64a089848149b0e8
30,306
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 os import scipy def Interp_photometry_nosum(grid, wteff, wlogg, wmu, jteff, jlogg, jmu, area, val_mu): """ Simple interpolation of an atmosphere grid having axes (logtemp, logg, mu). Note: As opposed to Interp_photometry, this function does not sum the surface elements. Parameters ---...
96e1d8e2fff960b6d8f528b413da5fee83dbebf4
30,315
import re from datetime import datetime def get_and_save_data(_=None): """Download data from John Hopkins, do some processing, and save as pickles Args: _: Empty variable. Was needed for the Google Cloud Function to work """ tot_deaths_df = load_raw_covid_file(DEATHS_FILE) tot_cases_df =...
9f5533c4843a77d05c0a5a3f8bee5fbf120d37da
30,316
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_calendar_name(request): """ # Checks if the user has a saved calendar name and returns it """ # TODO: Try-except should be replaced try: if request.user.options.calendar_name: # Saved in options return request.user.options.calendar_name except AttributeErr...
0816e1ef0997a74f71f3ce50243d5b6cc2494806
30,321
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 get_capped_cluster(atoms, folder_path, file_name, save_traj, EF_O_index): """ #TODO: check whether capping is necessary Inconsistent capping (remove all caps for now, does not need this cluster to be physical) Possible fix: change mult in neighbor list Extract smaller cluster containing the extra-f...
ecb65d1ac9d64ec61613a1fafabfe2f91c30cdb9
30,325
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
import sys def romanize(string, system): """ Transliterate Burmese text with latin letters. >>> romanize("ကွန်ပျူတာ", IPA) 'kʊ̀ɴpjùtà' >>> romanize("ပဒေသရာဇာ", MLC) 'padezarājā' >>> romanize("ဘင်္ဂလားအော်", BGN_PCGN) 'bin-gala-aw' """ romans = [] for syllable in Phonemi...
7242021137124345656d90ee528a039058bbe82c
30,337
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 build_samples(ctx, version="DEBUG", filter="", delphi_version=DEFAULT_DELPHI_VERSION): """Builds samples""" init_build(version) delphi_projects = get_delphi_projects_to_build('samples', delphi_version) return build_delphi_project_list(ctx, delphi_projects, version, filter, delphi_version)
7584e39ed25e32ad637e11f782b55140e5c04c7c
30,341
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
import logging def dashboard(): """ This function deals with the server side of the flask application :return: render the html page """ logging.info("client accessed either route") deaths, hospital_cases, nat_week_ava = covid_API_request('England', 'Nation') local_average = covid_API_requ...
162ccd3133259188907c7b1e993153bd3eddf5bf
30,349
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
import re import os def Filter_Readouts_by_RNAfold(cand_readout_file='selected_candidates_genome.fasta', rnafold_exe=r'E:\Shared_Apps\ViennaRNA\RNAfold', energy_th =-6.0, readout_folder=_readout_folder, make_plot=False, verb...
0c0c9210fbe48a4527f6490e8b634128f3146af2
30,351
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
import os def _demo_home(options): """For convenience demo home is in the same folder as jar file""" bp, fn = os.path.split(options.jar_file) demo_home = os.path.join(bp, 'demo') assert os.path.isdir(demo_home), 'Folder does not exist: "%s"' % demo_home return demo_home
97cdb9a36e56539719cf3aab1e7a5d0c95d87a1d
30,353
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
def PreviewApply(source, deployment_full_name, stage_bucket, messages, location, ignore_file, source_git_subdir='.', preview_format=_PREVIEW_FORMAT_TEXT, config_controller=None): """...
68a56d5f13f395d59a697cbeb6934f92dca620fa
30,355
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
from typing import List import os def run_fast_scandir(path: str, ext: List[str]) -> (List[str], List[str]): """ From [stack overflow](https://stackoverflow.com/a/59803793/9163028) answer Searches all files with extensions below path """ subfolders, files = [], [] for i in os.scandir(path): ...
df055eaa50c126da3be640693aa05b1358b3144f
30,358
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
import os import json async def get_config(guildid): """ :param guildid: :return: Guild-Config as Json """ path = os.path.join("data", "configs", f"{guildid}.json") with open(path, "r") as f: data = json.load(f) return data
4057569c71ac546a504cabe1ec19d6778f6ab6fa
30,361
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
import joblib import os import inspect import shutil import json import subprocess def subprocessdec(func, jobtype="source", cache_dir="."): """calls function as subprocess (allows for nested multiprocessing)""" @wraps(func) def nfunc(*args, **kwds): # collapse args into kwds to dump to json ...
6932b32dae4ef370a37fa4ff021e5bfc14bb36ef
30,368
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 sys import time import os def _fail_callback(die_lock_file: str, actor_rank: int = 0, fail_iteration: int = 6): """Returns a callback to cause an Xgboost actor to fail training. Args: die_lock_file (str): A file lock used to prevent race conditions ...
4a65c4015d9bc6a5292108f330a48f123ae07141
30,372
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
import os def get_files(extensions, args): """Generates a list of paths whose boilerplate should be verified. If a list of file names has been provided on the command line, it will be treated as the initial set to search. Otherwise, all paths within rootdir will be discovered and used as the initial s...
9262c3586e9370fd4ca42a6f0994898859d547ee
30,381
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 time def create(params): """ Create Neo4j Docker instance :param params: dict :return: Help message for end user """ con_name = params['dbname'] config_dat = Config.info[params['dbtype']] volumes = config_dat['volumes'] for vol in volumes: if vol[0] == 'DBVOL': vol[0...
2a705e2d71319f427e13d91476100c69e9ee96b6
30,383
import logging import argparse def str_to_verbosity(verbosity_str: str) -> int: """ Return a logging level from a string (compared in lower case). - `DEBUG` <=> {`debug`, `d`, `10`} - `INFO` <=> {`info`, `i`, `20`} - `WARNING` <=> {`warning`, `w`, `warn`} - `ERROR` <=> {`error`, `e`, `...
b23fb8828ea06ac4e5f43d6f72c1ebc57459019a
30,384
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
from typing import List import subprocess def import_template_ids() -> List[str]: """Return a list of all the supported template IDs.""" return subprocess.check_output(["meme", "-list-templates"]).decode("utf-8").splitlines()
89914e20965e87e9d9589955000854dc8f8d743b
30,390
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