content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def clamp(value, low, high): """Clamp the given value in the given range.""" return max(low, min(high, value))
48303b27d78f8d532b1e74db052457ae19b9f10d
64,200
def simulate2(atomList, *XYZs, **kwargs): """ Simulation of a two-component diffraction pattern """ magnification = kwargs.pop('mag', 0.7) beamSize = kwargs.pop('beamsize', 250e-6) DetectionParameters = fed.Detector(imageSizeX, imageSizeY, cenX, cenY, detDist, pixelSize, magnification) rota...
3a452a1f86764edcc590a95350c7eb6d07c27cb9
64,201
def fmt_n(large_number): """ Formats a large number with thousands separator, for printing and logging. Param large_number (int) like 1_000_000_000 Returns (str) like '1,000,000,000' """ return f"{large_number:,.0f}"
7b23e902a1c9600f1421b45b27623abaa1930f05
64,202
import logging def open_sat_data( zarr_path: str, consolidated: bool, logger: logging.Logger, sample_period_minutes: int = 15 ) -> xr.DataArray: """Lazily opens the Zarr store. Adds 1 minute to the 'time' coordinates, so the timestamps are at 00, 05, ..., 55 past the hour. Args: zarr_path:...
6a9b2632f3d91c764f1bc21f640217be71c9e686
64,203
import time def send_and_receive(random_pool, storage, progress, size): """Sends a random file and gets it back. # TODO(maruel): Add a batching argument of value [1, 500] to batch requests. Returns (delay, size) """ # Create a file out of the pool. start = time.time() batch = 1 items = [ isola...
262f910b7295bb8b766c1117cd5de142bd7a68af
64,204
import os def make_fake_catalog(SN=20): """ Make a fake photometric catalog """ data_path = test_filters.test_data_path() os.chdir(data_path) #### Generate data res = filters.FilterFile('filters/FILTER.RES.latest') templ = test_templates.test_read_template_ascii() ##...
14e04bae7f6ef98c8bff6e397f16e9aa289d7060
64,205
def make_cuda_consistent(refobj, *args): """ Attempt to make the cuda states of args consistent with that of ``refobj``. If any element of args is a Variable and the cuda state of the element is inconsistent with ``refobj``, raise ValueError, since changing the cuda state of a Variable involves rewr...
aefcebef6d0637921d757c7ef03189c5ce2c6682
64,206
def forward_backward_prop(X, labels, params, dimensions): """ Forward and backward propagation for a two-layer sigmoidal network Compute the forward propagation and for the cross entropy cost, the backward propagation for the gradients for all parameters. Notice the gradients computed here are dif...
3b232a6c265b3d87b0a941f15eb22ae9deb2a9f0
64,207
def api_symbols_by_name(): """ /api/v1/resources/symbols?symbol_id=1223 >>> """ current_app.logger.info("[trace]") dat = clib.read_db(path_to_db) if "symbol_id" in request.args: symbol_id = str(request.args["symbol_id"]) else: return "Error: No symbol_id field provided. P...
be185d7461f941cdf421a1471b7875010ffc9007
64,208
def nested_submit(fn, combos, kwds, executor=None): """Recursively submit jobs directly to an executor pool. Parameters ---------- fn : callable Function to submit jobs to. combos : tuple mapping individual fn arguments to sequence of values Mapping of each argument and all its poss...
c128c151d576158967b865b5cafbb0c64dfa43bd
64,209
def euclidean_distance(source, destiny): """ Calculates the euclidean distance between two points in the space. Where each argument is a list = [SSID, signal, channel] """ ret = 0 x_1 = source[0] y_1 = source[1] z_1 = source[2] x_2 = destiny[0] y_2 = destiny[1] z_2 = destin...
0c13bdf81aad184b4c427539a370e8ce53e7c043
64,210
def index(request): """ 前台首页 :param request: 请求 :return: """ news_art = NewsArticle.objects.order_by('-publish_time')[:10] print(len(news_art)) news_list = encapsulation_data(news_art) hot_art = NewsArticle.objects.order_by('-read_total')[:10] hot_list = encapsulation_data(hot_ar...
f4816fc4bbe7042fa82d40caebd3169b817445db
64,211
def convertGeoJsonGeometry(data): """ Convert JSON features into shapely geometry and then convert entire json data object into geopandas dataframe. Accepts a JSON data object. Returns a geopandas geodataframe or an error. """ try: # convert features to shapes so...
40fcee738da4b9d5c97d8abbd21c861c051801ac
64,212
from time import strftime import os def construct_path(pathv, project_path, folder_path, ext, **kwargs): """ THINGS TO ADD: 1. CHECK PROJECT_PATH, FOLDER_PATH IF EXISTS 2. CHECK IF FULL PATH ALREADY EXISTS """ filename = "\\" for i,arg in enumerate(pathv): if i == (len(pathv) - 1): filename += pathv[i...
5322a6cbee9001ff9205a4fff16d4ea8b21031f6
64,213
def forecast_svr(X_test_tract1_array, days ,model_svr, lag, scaler): """ multi-step future forecast. for each ticker, forescast Args: X_test_tract1_array, days ,model_svr, lag, scaler return """ last_test_sample = X_test_tract1_array[-1] X_last_test_sample = np.reshape(last_test_sam...
fc4dbb44d071ae9120ec8c55b9d1c9fac727b0db
64,214
import copy async def fetch_html(url: str, session: ClientSession, **kwargs) -> str: """GET request wrapper to fetch page HTML. kwargs are passed to `session.request()`. """ kwargs2 = copy.deepcopy(kwargs) kwargs2.pop('crawler') resp = await session.request(method="GET", url=url, **kwargs2) ...
25e4951e52fc1655e238a0157ce3d2a6106b9959
64,215
import logging from typing import Iterable def track(params_file, directions="det", max_angle=30., sphere=None, seed_mask=None, seed_threshold=0, n_seeds=1, random_seeds=False, rng_seed=None, stop_mask=None, stop_threshold=0, step_size=0.5, min_length=10, max_length=1000, odf_model="DTI"...
309ebac8558bc8a4bf26267b971300f45a2826ef
64,216
def inner_product(L1, L2): """ Take the inner product of the frequency maps. """ result = 0. for word1, count1 in L1: for word2, count2 in L2: if word1 == word2: result += count1 * count2 return result
65ede8eddcf86d75a1b130a76381416c2a272f61
64,217
def aggregate(assignments, exprlist): """aggregates are a assignments with special attribute None > list of subtuple""" lexprs = len(exprlist) if lexprs<1: raise ValueError, "aggregate on no expressions?" lassns = len(assignments) pairs = list(exprlist) for i in xrange(lexprs): ...
f2a685d28afaf8dc6dfd79610666288662a11d4c
64,218
import json def compute_metrics(ent_lst, rel_lst, _2_r_lst, _2_ht_lst, _n_r_lst, _n_ht_lst, _n_a_lst, _n_v_lst, eval_result_file): """ Combine the ranks from batches into final metrics. """ all_ent_ranks = np.array(ent_lst).ravel() all_rel_ranks = np.array(rel_lst).ravel() ...
193476f00dc9866c697dddedf2b49b39bd5f3ebe
64,219
def nb_count_prob(n, rate, r_inv, sim_time): """ Negative binomial count probability. The mean is given by :math:`r \cdot \Delta t` like in the Poisson case. """ g = rate*sim_time if g == 0: return (n == 0).astype(float) r = 1./r_inv log_terms = sps.loggamma(r+n) - sps.logg...
9f90340acd917137386b7a41bbdffa7d2c39176c
64,220
def resnet50(pretrained=False, last_stride=1, use_non_local=False, model_path='', **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return ...
319f8c55c4541e660fc11f4f56e93ff8de65ae6d
64,221
def img_to_slices(img): """ From 3D image to slices list """ res = [] for i, slice_img in enumerate(img): res.append(slice_img) return res
7776eed3c9abaf3267eb304421b58a6af190a63f
64,222
def x_point_wgt_av(df_agg, x_var): """ Set the x_point to be the weighted average of x_var within the bucket, weighted by stat_wgt. """ if not (x_var + '_wgt_av') in df_agg.columns: raise ValueError( "\n\tx_point_wgt_av: This method can only be used when" "\n\tthe wei...
15d8515efceb67e1dc9062d7fd79250c5935b549
64,223
import sys import textwrap def __get_docstr(text, indent=0): """ Format a docstring. Take the first sentence (. followed by a space) and use it for the brief. Then put the rest of the text after a blank line if there is text there """ # string handling is handled differently in Python 3+ ...
f210adf64e59eae236f42e2ee5b3bf898229d73c
64,224
def numba_find_phys_grid(xv, yv, bdyx, bdyy, inside): """ Computes whether the points spanned by xv, yv are inside of the polygon defined by the x-coordinates bdyx and the y-coordinates bdyy The polgon is assumed not to be closed (the last point is not replicated) """ if inside: result =...
31a82d1faaee6c6558a887ffb2e2bc26a31874a0
64,225
import hashlib def generate_hash(bytes_, hash_algorithm=hashlib.sha256) -> str: """ Return string with hash containing only hexadecimal digits """ return hash_algorithm(bytes_).hexdigest()
2f4bbc9d47d9cf22f005434aea7b2749ae8594bd
64,226
def BRepOffset_Tool_Deboucle3D(*args): """ * Remove the non valid part of an offsetshape 1 - Remove all the free boundary and the faces connex to such edges. 2 - Remove all the shapes not valid in the result (according to the side of offseting) in this verion only the first point is implemented. :param S: ...
aa94002643068ccaa09abb70185215d13ce34bb9
64,227
from typing import Tuple import subprocess from bs4 import BeautifulSoup def get_pdf_dim(pdf_file: str, page: int = 1) -> Tuple[int, int]: """Get the dimension of a pdf. :param pdf_file: path to the pdf file :param page: page number (starting from 1) to get a dimension for :return: width, height ...
b432c41c417a90474f61846d422d7f6e9c7c22d0
64,228
def GetFixupTgtSel(ea): """ Get fixup target selector @param ea: address to get information about @return: -1 - no fixup at the specified address otherwise returns fixup target selector """ fd = idaapi.get_fixup(ea) if not fd: return -1 return fd.sel
16bbaa668ecd98eda8fc0e064140e644178a3ec8
64,229
def ic_to_gamma(water_level): """ Return the expression needed to compute "gamma_predict" """ below_water = (1.0 - col("depth")) < water_level ti = col("type_index") return ( pl.when(ti > 3.22) .then(11.0) .when((ti <= 3.22) & (ti > 2.76)) .then(16.0) .whe...
dde11a76aee749e6f25969c5a38f41d546219df6
64,230
def set_path(*args): """ set_path(pt, path) Set the file path @param pt: file path type Types of the file pathes (C++: path_type_t) @param path: new file path, use NULL or empty string to clear the file path (C++: const char *) """ return _ida_loader.set_path(*args)
8f5aa01a9459d14a42c090f78a13becfaf17fe6b
64,231
def get_max_trajectory(l_curr, v_curr, acceleration, dt, n_begin=0, n_end=0, upsampling_factor=10): """ returns max braking deceleration bound for a given trajectory point """ dt = dt / upsampling_factor n_end = n_end * upsampling_factor # the returned trajectory includes current position and t...
3c60ab2418b66676bc4f28c7ea07e316fc386a62
64,232
import socket def get_host_by_ipaddr(ipaddr): """ returns a reverse DNS name if available """ try: socket.inet_aton(ipaddr) return socket.gethostbyaddr(ipaddr)[0] except socket.herror: return 'no reverse DNS found' except (socket.error, TypeError): return 'illegal IP a...
36767a2d105318cddb33e400d73ba7c2eee98add
64,233
def simplify_specifiers(spec): """Try to simplify a SpecifierSet by combining redundant specifiers.""" def key(s): return (s.version, 1 if s.operator in ['>=', '<'] else 2) def in_bounds(v, lo, hi): if lo and v not in lo: return False if hi and v not in hi: ...
da2a62caa0b26f646060c2aa15543c829c61f9e1
64,234
from typing import Mapping from typing import Dict from typing import Optional def get_injector_for_testing( providers: Mapping, additional_settings: Dict = None, overrides_registry: Optional[OverridesRegistryBase] = None ) -> Injector: """ Return an :class:`Injector` using a fake craw...
352b189ad5f2af550da801576b6e6654b138fc11
64,235
from re import T def conv1d_md(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True): """ using multiple dot products """ if border_mode not in ('valid', 0, (0,)): raise RuntimeError("Unsupported border_mode for conv1d_md: " ...
f8f84cb739723ff8ed41b4686f9f13d667dd0c70
64,236
from typing import Mapping from typing import Optional def _rename_nodes_on_tree( node: dict, name_map: Mapping[str, str], save_key: Optional[str] = None, ) -> dict: """Given a tree, a mapping of identifiers to their replacements, rename the nodes on the tree. If `save_key` is provided, then the ...
b8d3df2f2247b27c614b767b28eda7b91e380524
64,237
def create_exchange_graph(exchange: ccxt.Exchange): """ Returns a simple graph representing exchange. Each edge represents a market. exchange.load_markets() must have been called. Will throw a ccxt error if it has not. """ graph = nx.Graph() for market_name in exchange.symbols: try: ...
f3412c4d34042e34962d743af5f328c210ba34d3
64,238
def Galactocentric_to_rotated(): """Transformation matrix from GC Cartesian to rotated coordinates.""" return GALACTOCENTRIC_ROT_MATRIX
3e68f468e3a4cc6c0f6b8237b1e3960690518e22
64,239
import functools def sgmcmc_sampler(build_sampler_fn): """ Decorator that turns a kernel factory into a sampler factory """ @functools.wraps(build_sampler_fn) def wrapper(*args, **kwargs): compiled = kwargs.pop('compiled', True) pbar = kwargs.pop('pbar', True) init_fn, my_k...
ba0b5c5dbb410194abe984f30050491c25c91239
64,240
def asynchronously(func): """Decorator to execute a function asynchronously.""" @catch_exceptions def wrapper(*args, **kwargs): Thread(target=func, args=args, kwargs=kwargs).start() return wrapper
237bb96d632c26b62ba13cadc82527c1abd23246
64,241
import os def apply(func, path, proc=1, only=None): """Apply a function to each entry in the data base. Parameters ---------- func : callable Function to apply. path : str Path to data base, proc : int Number of processes to run application in. Default is 1. If les...
d64b4cfdcebc6b916a78412d620f25070b4e6bd1
64,242
def get_bonded_tunnels_for_physical_tunnel( self, ne_pk: str, physical_tunnel_id: str, state: str = None, ) -> dict: """Get bonded tunnels associated with a particular physical tunnel .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint ...
852e07aa20005ff06819876e2546627aa86e8f5f
64,243
def RGL(elements, p=None, q=None, a=None, xi=None, r0=None, cutoff=1.73, delta=0.15, debug=False): """ Calculator based on the RGL/Gupta semi empirical tight-binding potential. Parameters ---------- elements: List of the elements that will be supported. The parameters can be given here...
74394431e3b9f444300c4ac4bf09bc1dedcf1efe
64,244
import torch def nll_gaussian_variablesigma(preds, target, sigma, epoch, temperature, total_epochs, add_const=True): """ Loss function for the case of variable sigma, with isotropic gaussian :param preds: prediction values from NN of size [batch, particles, timesteps, (x,y,v_x,v_y)] :param ...
8f497e1669f451dcd14a93b4a7914ff4fc19bca3
64,245
def replace_secret_of_hub_uri(uri_path: str, txt: str = '<secret>') -> str: """Replace the secret of the Jina Hub URI. :param uri_path: the uri of Jina Hub URI :param txt: text to replace :return: the new URI """ try: secret = parse_hub_uri(uri_path)[-1] if secret: ...
611e708bdce176799bf329a263c0e7d4e5a033cd
64,246
def construct_cv_grads(vbobj, lam, eps, elbo_gsamps=None, method="hessian"): """ main method to construct reduced variance reparameterization gradients using a variety of methods. Methods: - "mc" : full monte carlo estimator - "hes...
b5db7f8aafed23f138abe39fae207d2ed252d032
64,247
def add_edges(t, countDict, G, last_k): """ :param t: Tree of the sequnces available as states :param countDict: dicionary counting the occurence for each sequence :param G: the graph containing the states (each one is a sequence) :param last_k: the number of recent item considered :return: the ...
9016808d44230503521ba098aef4a5ac157fdf1d
64,248
import os def _get_stripped_path(bin_path): """Finds the stripped version of |bin_path| in the build output directory. returns |bin_path| if no stripped path is found. """ stripped_path = bin_path.replace('lib.unstripped/', 'lib/').replace('exe.unstripped/', '')...
616cf9b66d9002792ab51489a25e0bbc49096f6b
64,249
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up MFP as config entry.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = config_entry.data.get(CONF_USERNAME) password = config_entr...
132b605a4b90a74e681ffa41b624eff1a1ca73ff
64,250
def build_graph(mode, config, sequence_example_file_paths=None): """Builds the TensorFlow graph. Args: mode: 'train', 'eval', or 'generate'. Only mode related ops are added to the graph. config: An EventSequenceRnnConfig containing the encoder/decoder and HParams to use. sequence_exampl...
fc3a1929c92db40e6c888eafb15d650fd4a6e221
64,251
def ignore(name): """ Files to ignore when diffing These are packages that we're already diffing elsewhere, or files that we expect to be different for every build, or known problems. """ # We're looking at the files that make the images, so no need to search them if name in ['IMAGES']: return Tru...
d5f64616480fa14c03b420165d2c89040a8cc768
64,252
def create_image(module, ecs, snapshot_id, image_name, image_version, description, instance_id, disk_mapping, client_token, wait, wait_timeout): """ Create a user-defined image with snapshots. :param module: Ansible module object :param ecs: authenticated ecs connection object :para...
96a1bb2adc53fb167ed974053450dedbcd054e8e
64,253
def add_active_handler(parent, **kwargs): """ deprecated function """ return internal_dpg.add_item_active_handler(parent, **kwargs)
ec39b3228b6e754cf4866e3c384eff81b24b165e
64,254
def get_school_class_by_level_id(): """ { "level_id": 2 }, """ domain = request.args.to_dict() return school_class_service.get_school_class_by_level_id(domain)
f22ab9abdf72a084bbb76302bae373589a82bafc
64,255
from typing import Any async def recover_password( email: str, db_session: AsyncSession = Depends(dependencies.get_db_session) ) -> Any: """ Send a password recovery email to the provided email address. """ user = await crud.user.get_by_email(db_session, email=email) if not user: awa...
caca8da49229e16d724539e5ccad3b4a0b5d57b5
64,256
from typing import Type from typing import Callable def multimethod(*types: Type) -> Callable: """ Function decorator for supporting method overloading. Based on an article written by Guido van Rossum (see https://www.artima.com/weblogs/viewpost.jsp?thread=101605). Best way to see its usage is by...
0320507d0cec5cee38e2b8aadb9b000db650874a
64,257
def ADS_matrix(log, T): """Return a matrix that represents whether events in the log actually always (A), never (N), or sometimes (S) followed each other. """ case_cnt = len(log.cases) T = transit_matrix(log, T) activities = log.activities ADS = dict() for v1 in list(activities) + ...
37ff65701e3611a9b6c4faba684adc4ec0e123de
64,258
def power(work, time): """ Power is the rate at which the work is done. Calculates the amountof work done divided by the time it takes to do the work Parameters ---------- work : float time : float Returns ------- float """ ...
48eb476658fa19a6002b428993bfa58c81634638
64,259
import io def calculateSubStacks(source, z = all, x = all, y = all, **args): """Calculates the chunksize and other info for parallel processing and returns a list of sub-stack objects The sub-stack information is described in :ref:`SubStack` Arguments: source (str): image source ...
b20d7aff2b45969d01460ed60f9daef0689c2562
64,260
def setup(app): """Sphinx extension entry point.""" app.require_sphinx('1.8') # For "config-inited" event app.connect('html-page-context', _html_page_context) app.connect('config-inited', _config_inited) return { 'version': __version__, 'parallel_read_safe': True, }
73dfa069fcb6e44edd96b45b73fcb0d63d8b1eb5
64,261
def trainingdb_show_email(request, item_container, data, item): """ zeigt die Daten der Online-Anmeldung """ class DmsItemForm(forms.Form): """ Elemente des Anmeldeformulars """ vorname = forms.CharField(required=False, widget=forms.HiddenInput(attrs={'value': data['vorname']}) ) nachname = fo...
ad0c25b70fe7995477799caee0a62469924368be
64,262
def reconstruct_from_estimator(input_examples, predict_results): """ the predict_results contains the prediction entity of the splited examples. We need to reconstruct the complete entitys for each example in input_examples. and return the results as dictionary. input_examples: each should contains (sta...
907edb81e26811b975f520a1685677e267e2afeb
64,263
def new_iface(ifname, device): """ Create Interface """ iface = Interface(ifname) if "mtu" in device: iface.config.mtu = device["mtu"] if "mac-address" in device: iface.ethernet.config.mac_address = device["mac-address"] return iface
216d4333424a3a240becb7e16fa33a81b47a3a00
64,264
import requests def make_request( method, resource, token=None, vault_url=None, namespace=None, get_token_url=False, retry=False, **args ): """ Make a request to Vault """ if "vault_token" in __context__: connection = __context__["vault_token"] else: ...
c3b5daef66c779e37827f91aae363f877ac8f38d
64,265
def send_email(receivers, subject, content_text, content_html=None): """This method sends an email""" #Create the message if content_html: msg = MIMEMultipart('alternative') msg.set_charset("utf-8") part1 = MIMEText(content_text, 'plain', "utf-8") part2 = MI...
64333f9c81b97c348c235a68b0b1ad1097369884
64,266
def find(*patterns): """Decorate a function to be called for each time a pattern is found in a line. :param str patterns: one or more regular expression(s) Each argument is a regular expression which will trigger the function:: @find('hello', 'here') # will trigger once on "hello you"...
884005008791baba3a9949e9d2c02aee0f985552
64,267
import pyvex import simuvex import claripy def find_ioctls(p, dispatch_addr): """ Returns a list of potential IOCTL codes by symbolically executing starting at the provided function address """ s = p.factory.blank_state(addr=dispatch_addr) pg = p.factory.path_group(s) generic_reg_vals = set() val_addr = {} ...
d9c1a1b5aa6870f5bfd6ca81cba4a7a4c6f77f9d
64,268
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload HALO Home config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
cf8d8777937ea94efef45f600d3532a2bbaefcf1
64,269
def LineGrouper(num, constructor=strip, ignore=is_empty): """Returns num lines at a time, stripping and ignoring blanks. Default constructor is string.strip, but can supply another constructor to transform lines and/or coerce into correct type. If constructor is None, passes along the lines without alt...
6ecf7d5dea2afea32f646afe200f07f3a7a7cdf4
64,270
import subprocess def get_installed_reqs(site_packages_dir): """ Return the installed pip requirements as text found in `site_packages_dir` as a text. """ # Also include these packages in the output with --all: wheel, distribute, setuptools, pip args = ['pip', 'freeze', '--exclude-editable', '--al...
6201718f42b22e60ba3a1088e80be8767958feb3
64,271
def _basis2name(basis): """ converts the 'basis' into the proper name. """ component_name = ( 'DC' if basis == 'diffmap' else 'tSNE' if basis == 'tsne' else 'UMAP' if basis == 'umap' else 'PC' if basis == 'pca' else basis.replace('...
d359fc8a1fe91ccf954a5e0a1dbf69077d444a44
64,272
import concurrent def extract_frames_from_video(video_file, times, use_multithreading=False, blackbar_threshold=32, max_perc_to_trim=.20): """ Extracts multiple things from the video and even handles black bars :param video_file: what we are loading :param times: timestamps to use :param use_mult...
cdcf6dd5c9e3d1dfb18cbb29a6ccd89c25bc35e4
64,273
from datetime import datetime def get_reddit_comments_url(year, month): """Url for reddit comment data download.""" target_date = datetime.date(year, month, 1) url = _get_reddit_comments_path(target_date, _REDDIT_COMMENT_BASE_URL) return url
2863ead940cabf8e4734e8dc5d4148fe68aa4b12
64,274
from typing import List import ast from typing import cast def get_funcs(module) -> List[ast.FunctionDef]: """ get function list """ return [ cast(ast.FunctionDef, stm) for stm in ast.walk(module) if isinstance( stm, ast.FunctionDef)]
98d62ee1e13461cc13226037fa1233431533ca08
64,275
def remove_folders(bookmarks, folders): """Function to remove top level folders from bookmarks.""" for i, item in enumerate(bookmarks['Data Science']): if type(item) is dict: folder_name = list(item.keys())[0] if folder_name in folders: del bookmarks['Data Sc...
b2f6a85e9a518f475985124820ba931a442d3c38
64,276
def calfunc(obs_spectra, std_spectra, ext_spectra, airmass, exptime, error=False): """Given an observe spectra, calculate the calibration curve for the spectra. All data is interpolated to the binning of the obs_spectra. The calibrated spectra is then calculated from: C = ...
7a5eab40edfd87214cde49789c2d048c961496a0
64,277
def get_release_group_image_front(releasegroupid, size=None): """Download the front cover art for a release group. The `size` argument and the possible error conditions are the same as for :meth:`get_image`. """ return get_image(releasegroupid, "front", size=size, entitytype="re...
b519ec7632cf8a89a3c08e57c0b573c3d2c0c73f
64,278
def SUM(strArg, composList, atomDict): """ *Calculator Method* calculates the sum of a descriptor across a composition **Arguments** - strArg: the arguments in string form - compos: the composition vector - atomDict: the atomic dictionary **Returns** a float """ accum =...
1531318eb8db455ee99e2944a4518d4e61a1239f
64,279
def validate_report(reportname, print_files=False, write_file=False): """Validate cached.filelist for the given report""" try: result = models.Results.objects.get(resultsName=reportname) except ObjectDoesNotExist: print("No result object was found for '%s'" % reportname) return None ...
844e7b72887f07bab1be4d99894950aabc69815e
64,280
def get_xyz_bm16(logobj, specobj, fit_elastic=False): """function to get 3 arrays representing the RIXS plane .. note: this scheme is currently used at FAME-UHD beamline (ESRF/BM16) and requires a SPEC file and log file Parameters ---------- logobj : numpy.ndarray or str 2lD c...
bf1ccd4f140c54c3ff289ceaaf2100cb7a070299
64,281
import pathlib import hashlib import os def GetDirectoryChecksum(abspath: pathlib.Path) -> str: """Compute a checksum to determine the contents and status of the directory. The checksum is computed Params: abspath: :return: """ hash = hashlib.md5() paths = [os.path.join(abspath, filename) for file...
55cf50c9ba228192806278c283ebc335b96ad905
64,282
def lof_text(pwd, src): """creates a .txt file in pwd (LAStools bin) containing a list of .las/.laz filenames from src directory""" filename = pwd + 'file_list.txt' f = open(filename, 'w+') if type(src) == str: for i in las_files(src): f.write('%s\n' % i) else: # this i...
a28a632cc42063784c046efc89a2c4e1bcdac8d8
64,283
import os def __guess_dataset_by_filename(filename): """Return a guessed dataset by filename""" try: fields = os.path.split(filename) if fields: if fields[-1].startswith('dataset_') and fields[-1].endswith('.dat'): # dataset_%d.dat return Dataset.get(int(fields[-1]...
afabda32089bbdc9bbe3a313e84032174e2a4dc8
64,284
def host_is_locked(host): """ Returns true if the host is locked """ if HOST_ADMIN_STATE.LOCKED == host['administrative']: return True, "host is locked" return False, "host is not locked"
e73a0bad5229df8b81d597068714cb7ad646cdfe
64,285
import re def validate_container_name(name): """Make sure a container name accordings to the naming convention https://docs.openstack.org/developer/swift/api/object_api_v1_overview.html https://lists.launchpad.net/openstack/msg06956.html > Length of container names / Maximum value 256 bytes / Cannot c...
5bef8b304c004dc3169b6984b49a0d669fc9b7b3
64,286
def class_instances_from_soap_enveloped_saml_thingies(text, modules): """Parses a SOAP enveloped header and body SAML thing and returns the thing as a dictionary class instance. :param text: The SOAP object as XML :param modules: modules representing xsd schemas :return: The body and headers as cla...
9e92066769d904f76f948837ac16db55431efed4
64,287
def function(values): """A simple fitness function, evaluating the sum of squared parameters.""" return sum([x ** 2 for x in values])
ee96b0948e43eec1e86ffeeca681567d2a0afa53
64,288
def _parse_end(end): """Helper for `from_string`. Determines if an endpoint is INF, NEG_INF, int, or float. """ if end == 'inf': return INF if end == '-inf': return NEG_INF if end.isdigit(): return int(end) return float(end)
e3ee23adc8b78a8323868d21c1e066e940b2b595
64,289
def normalize(array): """ Normalize an array's value domain to [0, 1] Note: the original normalize function is at dnnbrain/utils/util.py but 'from dnnbrain.dnn.core import Mask' in the file causes import conflicts. Fix the conflicts in future. Parameter: --------- array[ndarray]...
c01bcc5de5e21a95efb4aad708352f7763772bc5
64,290
from pathlib import Path def write_metadata( metadata: MediaMetadata, media_filepath: Path, output_filepath: Path, overwrite: bool = False, quiet: bool = True, ) -> Path: """Apply some given metadata to some given media content. Args: metadata (MediaMetadata): The meta...
7c304faa8b44ca48e758430d82b9c6a77fe997ce
64,291
def preprocess_notice_xml(notice_xml): """Unfortunately, the notice xml is often inaccurate. This function attempts to fix some of those (general) flaws. For specific issues, we tend to instead use the files in settings.LOCAL_XML_PATHS""" notice_xml = deepcopy(notice_xml) # We will be destructive ...
61fb6c2e17a6a8bd11bdcd6750a48a8feef6b85b
64,292
import math import sys def _find_optimal_smooth_sensitivity_parameters( votes, baseline, num_teachers, threshold, sigma1, sigma2, delta, ind_step1, ind_step2, order): """Optimizes smooth sensitivity parameters by minimizing a cost function. The cost function is exact_eps + cost of GNSS + two stds...
e054e4a45c33df572e15942cbd5e8e29fa2d771c
64,293
import random def get_minibatches_indices(n, minibatch_size, shuffle=True, shuffleBatches=True, allow_smaller_final_batch=False): """ Inputs: n - An integer corresponding to the total number of data points Returns: minibatches - a list of li...
41945f0d985ccc173ebe4686139b8df0a9c0a35b
64,294
def create_redis_compose_node(name): """ Args: name(str): Name of the redis node Returns: dict: The service configuration for the redis node """ return { "container_name": name, "image": "redis:3.2.8", "command": "redis-server --appendonly yes", "deplo...
e6d01acc8b0c5c324ad3e0f6e5f527e2a6433705
64,295
def getInfo(request): """ 1건의 현금영수증 상태/요약 정보를 확인합니다. - https://docs.popbill.com/cashbill/python/api#GetInfo """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 현금영수증 문서번호 MgtKey = "20211227-001" cashbillInfo = cashbillService.getInfo(CorpNum, MgtKey) ...
fc9778db50ac9c2a704ad9b38e63f6d2d695de7a
64,296
def join_germanic(iterable, capitalize=True, quoteChars="\"", concat="'"): """Like "".join(iterable) but with special handling, making it easier to just concatenate a list of words. Tries to join an interable as if it was a sequence of words of a generic western germanic language. Inserts a space between each ...
94b4117994b4d83ce47cfed7cd461741bb1c131c
64,297
import re def strip_between(a, b, string): """ Removes anything between (and including) string a and b inside the given string. """ p = "%s.*?%s" % (a, b) p = re.compile(p, re.DOTALL | re.I) return re.sub(p, "", string)
ef440f952b04273040eb847704f4bc6c897ad8c9
64,298
def dft(y, spect='ampl', **kwargs): """ Discrete Fourier transform. Parameters ---------- y : list Signal to transform. dt : float Time interval [s]. spectrum : str Type of spectrum to return: 'ampl'/'power'/'phase'. Default: 'ampl'. Returns ------- Y : list Ampl...
30b3de0a3fa5bf49b798ffd88bd131422e01f55a
64,299