content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def convert_country_codes(source_codes: List[str], source_format: str, target_format: str, throw_error: bool = False) -> List[str]: """ Convert country codes, e.g., from ISO_2 to full name. Parameters ---------- source_codes: List[str] Lis...
7589dec9ccec5edc7bf5ea356b40fac3898c7c77
3,643,200
def get_simple_lca_length(std_tree, test_gold_dict, node1, node2): """ get the corresponding node of node1 and node2 on std tree. calculate the lca distance between them Exception: Exception("[Error: ] std has not been lca initialized yet") std tree need to be initialized before running ...
8433259814fe656bdbdd6997ca613b30c458f8b8
3,643,201
def edit_catagory(catagory_id): """edit catagory""" name = request.form.get('name') guest_id = session['guest_id'] exists = db.session.query(Catalogs).filter_by(name=name, guest_id=guest_id).scalar() if exists: return abort(404) if name...
a0d342490881968f39cf4636fb424176c6608e4a
3,643,202
def match_patterns(name, name_w_pattern, patterns): """March patterns to filename. Given a SPICE kernel name, a SPICE Kernel name with patterns, and the possible patterns, provide a dictionary with the patterns as keys and the patterns values as value after matching it between the SPICE Kernel name...
a54b7f1fcda67b5649f92a21f4711874dd226ee9
3,643,203
def _generate_good_delivery_token_email(request, good_delivery, msg=''): """ Send an email to user with good_delivery activation URL and return the token :type request: HttpRequest :type good_delivery: GoodDelivery :type msg: String :param structure_slug: current HttpRequest :param str...
4567c3d0ad3f2d65c850ed5291e602cb552b11cb
3,643,204
def get_flavor(disk=None, min_disk=None, min_ram=None, name=None, ram=None, region=None, rx_tx_factor=None, swap=None, vcpus=None): """ Use this data source to get the ID of an available OpenStack flavor. """ __args__ = dict() __args__['disk'] = disk __args__['minDisk'] = min_disk __args__[...
f6689712d4bde04ae43bb4c999b04df34b1db089
3,643,205
from typing import Tuple def deal_hands(deck: Deck) -> Tuple[Deck, Deck, Deck, Deck]: """Deal the cards in the deck into four hands""" return (deck[0::4], deck[1::4], deck[2::4], deck[3::4])
151def07061a23df6c80f2be6d9015e3efbd515e
3,643,206
import select def add_new_publication_group(project): """ Create a new publication_group POST data MUST be in JSON format POST data SHOULD contain the following: name: name for the group published: publication status for the group, 0 meaning unpublished """ request_data = request.get...
0890b71f972149bd860768dfeb5a377bd4fd28b0
3,643,207
def test_gmres_against_graph_scipy(n, tensor_type, dtype, error, preconditioner, solve_method): """ Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation: the result match scipy in graph """ if not _is_valid_platform(tensor_type): return # Input CSRTensor of...
47fde403d403138dd1746cab532f7c7cf9b2f5a3
3,643,208
def wtime() -> float: """ :return: the current time as a floating point number. """ return MPI.Wtime()
862b18fc688fd5e34ccfc7a2f986bdb2ceb98ed4
3,643,209
def survival_df(data, t_col="t", e_col="e", label_col="Y", exclude_col=[]): """ Transform original DataFrame to survival dataframe that would be used in model training or predicting. Parameters ---------- data: DataFrame Survival data to be transformed. t_col: str Column na...
8d35c27a75340d5c6535727e0e419fc0548d6094
3,643,210
from datetime import datetime def get_date_today(): """Get date today in str format such as 20201119. """ return datetime.today().strftime('%Y%m%d')
d5e69607dbf4b8c829cfe30ea0335f46c7d2512a
3,643,211
def check_model_in_dict(name, model_dict): """ Check whether the new model, name, exists in all previously considered models, held in model_lists. [previously in construct_models] If name has not been previously considered, False is returned. """ # Return true indicates it has not been c...
9c3cf9be0c973872ab63e8de57f6b5a26ea53838
3,643,212
import json def generate_api_key(request): """Handles AJAX requests for a new API key.""" new_key = ApiUser.objects.get_unique_key() return HttpResponse(json.dumps({'token' : new_key}), content_type="application/javascript")
9e29a82c3a967d7a98537ec680a0a2bfe068a88c
3,643,213
def input_output_details(interpreter): """ input_output_details: Used to get the details from the interperter """ input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() return input_details, output_details
3024f2a6c91a533c3aff858ee3a1db11d360bb25
3,643,214
def charge_drone_battery(drone): """Handle the drone battery charging operation.""" battery_level = drone["State"]["Battery"] if float(battery_level) < 95: # Increase battery level drone["State"]["Battery"] = float(battery_level) + 5 else: # If battery >= 95 set battery level to ...
2f7d955a44310215883ac5bed57fb27463a66315
3,643,215
def expirations(self, symbol, useDatetime=True, block: bool = True): """Gets list of available expiration dates for a symbol. Calls the 'market/options/expirations.json' endpoint to get list of all exp_dates available for some given equity. Args: symbol: Specify the stock symbol against wh...
24a33bdac8da42be9433400b32c16fa4fb860766
3,643,216
from re import T def track(name, x, direction=None): """ An identity function that registers hooks to track the value and gradient of the specified tensor. Here is an example of how to track an intermediate output :: input = ... conv1 = nnt.track('op', nnt.Conv2d(shape, 4, 3), 'all')...
81ae80bc8b77c16d493befdb209fe648e9a07c96
3,643,217
from pathlib import Path from typing import Callable from datetime import datetime def expected_l1_ls8_folder( l1_ls8_folder: Path, offset: Callable[[Path, str], str] = relative_offset, organisation="usgs.gov", collection="1", l1_collection="1", lineage=None, ): """ :param collection: ...
16b934d3ea6c4a3daee3bde2a37bd5a7a48856b9
3,643,218
def fetchPackageNames(graphJson): """Parses serialized graph and returns all package names it uses :param graphJson: Serialized graph :type graphJson: dict :rtyoe: list(str) """ packages = set() def worker(graphData): for node in graphData["nodes"]: packages.add(node["p...
ccac1cfa1305d5d318cf3e2e3ed85d00fff7e56b
3,643,219
def get_nc_BGrid_POP(grdfile, name='POP_NEP', \ xrange=(170,270), yrange=(240, 350)): """ grd = get_nc_BGrid_POP(grdfile) Load Bgrid object for POP from netCDF file """ nc = pycnal.io.Dataset(grdfile) lon_t = nc.variables['TLONG'][:] lat_t = nc.variables['TLAT'][:...
3ce9eec34f3332d21fce1ceaca2862faa69443d1
3,643,220
def types_and_shorthands(): """a mapping from type names in the json doc to their one letter short hands in the output of 'attr' """ return { 'int': 'i', 'uint': 'u', 'bool': 'b', 'decimal': 'd', 'color': 'c', 'string': 's', 'regex': 'r', '...
39f364677a8e2ee1d459599ba2574a8a4f4cd49e
3,643,221
def _make_event_from_message(message): """Turn a raw message from the wire into an event.Event object """ if 'oslo.message' in message: # Unpack the RPC call body and discard the envelope message = rpc_common.deserialize_msg(message) tenant_id = _get_tenant_id_for_message(message) cr...
daaba3567fbb4e95d311a12f58852bb0b81c6f05
3,643,222
def to_region(obj): """Convert `obj` to instance of Region.""" if obj is not None and not isinstance(obj, Region): return Region(*obj) else: return obj
da5412adcc182c97950465e3c4e3248be00f242b
3,643,223
import PIL def create_textures(): """ Create a list of images for sprites based on the global colors. !!! SHOULD be able to add custom images in here instead of the general colors.""" texture_list = [] for color in colors: image = PIL.Image.new('RGB', (WIDTH, HEIGHT), color) texture_l...
2652812d96157fc6f7d502e6ca39f4c4eee32dea
3,643,224
import psutil def check_if_process_is_running(process_name): """" Check if there is any running process that contains the given name process_name. """ # Iterate over the all the running process for process in psutil.process_iter(): try: # Check if process name contains the give...
372cd2183b7250ce738157c986adb9a3abfdca84
3,643,225
import cProfile import pstats import io from pstats import SortKey # type: ignore import optparse def exec_main_with_profiler(options: "optparse.Values") -> int: """Enable profiler.""" profile = cProfile.Profile() profile.enable() ret = exec_main(options) profile.disable() string_io = io.Str...
8eefc801319d94081364218fc80500b710610f31
3,643,226
def put_text(image, text, point, scale, color, thickness): """Draws text in image. # Arguments image: Numpy array. text: String. Text to be drawn. point: Tuple of coordinates indicating the top corner of the text. scale: Float. Scale of text. color: Tuple of integers. RG...
aeab690da16577e7eff27b515cf9b682110716e9
3,643,227
from typing import List from pathlib import Path def squash_dimensions( dimensions: List[Dimension], check_path_changes=True ) -> Dimension: """Squash a list of nested Dimensions into a single one. Args: dimensions: The Dimensions to squash, from slowest to fastest moving check_path_chang...
301304cf32115d103bb53a209df85880f27fcf53
3,643,228
def CreateRootRelativePath(self, path): """ Generate a path relative from the root """ result_path = self.engine_node.make_node(path) return result_path.abspath()
79053bb1bcb724e8ddf9bfc4b5b13b67be9227f0
3,643,229
import os def resolve_font(name): """Sloppy way to turn font names into absolute filenames This isn't intended to be a proper font lookup tool but rather a dirty tool to not have to specify the absolute filename every time. For example:: >>> path = resolve_font('IndUni-H-Bold') ...
b5716cb4390ebdf3ce8103efb33cd6b197e171a3
3,643,230
import json from typing import Mapping def to_shape(shape_ser): """ Deserializes a shape into a Shapely object - can handle WKT, GeoJSON, Python dictionaries and Shapely types. """ if isinstance(shape_ser, str): try: # Redirecting stdout because there's a low level exception th...
d9a0975696ee48d816d5b61e7cc57c0547ff5033
3,643,231
import inspect def _from_module(module, object): """ Return true if the given object is defined in the given module. """ if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif inspect.isfunction(object): ...
564157a4eb10b887b6b56c82d17d74557c233104
3,643,232
def _escape_pgpass(txt): """ Escape a fragment of a PostgreSQL .pgpass file. """ return txt.replace('\\', '\\\\').replace(':', '\\:')
3926f683a2715ff1d41d8433b525793e8214f7a9
3,643,233
import re import os def harvest_dirs(path): """Return a list of versioned directories under working copy directory PATH, inclusive.""" # 'svn status' output line matcher, taken from the Subversion test suite rm = re.compile('^([!MACDRUG_ ][MACDRUG_ ])([L ])([+ ])([S ])([KOBT ]) ' \ ...
8c48558e29952513b521685bee013679a52902ce
3,643,234
from typing import Dict from typing import Set from typing import List import math def gen_index(doc_term_map: Dict[PT.Word, Set[PT.IndexNum]], dependency_map: Dict[PT.IndexNum, Count], i: PT.IndexNum, words: List[PT.Word] ) -> PT.PkgIndex: """Generate packa...
4d82498309019f9bdc55fec8b6917576b2b0ff22
3,643,235
from typing import OrderedDict def arr_to_dict(arr, ref_dict): """ Transform an array of data into a dictionary keyed by the same keys in ref_dict, with data divided into chunks of the same length as in ref_dict. Requires that the length of the array is the sum of the lengths of the arrays in each...
55339447226cdd2adafe714fa12e144c6b38faa2
3,643,236
def test_makecpt_truncated_zlow_zhigh(position): """ Use static color palette table that is truncated to z-low and z-high. """ fig = Figure() makecpt(cmap="rainbow", truncate=[0.15, 0.85], series=[0, 1000]) fig.colorbar(cmap=True, frame=True, position=position) return fig
f615d425d6433a6e4bc6dc0d8d5e18f2a0aa60c7
3,643,237
import os def extract_boar_teloFISH_as_list(path): """ FUNCTION FOR PULLING KELLY'S TELOFISH DATA FOR 40 BOARS into a LIST.. TO BE MADE INTO A DATAFRAME & JOINED W/ MAIN DATAFRAME if possible These excel files take forever to load.. the objective here is to synthesize all the excel files for te...
a431282679f916a71cab7cc002dce26a39de147e
3,643,238
def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") """ return captured_output("stdout")
9226c23c13ad86cc09f2c08ce1ffb44f324a1044
3,643,239
def login(): """ Handles user authentication. The hash of the password the user entered is compared to the hash in the database. Also saves the user_id in the user's session. """ form = SignInForm() banned = None reason = None if form.validate_on_submit(): user_id = form.user...
d2cea08572c7b1461cda490f063009bc139c7c3a
3,643,240
def create_ipu_strategy(num_ipus, fp_exceptions=False, enable_recomputation=True, min_remote_tensor_size=50000, max_cross_replica_sum_buffer_size=10*1024*1024): """ Creates an IPU config and returns an IPU strategy r...
2aaa76de946e43305cdb7e50b673e39a08e19a50
3,643,241
def run_pipeline(context, func, ast, func_signature, pipeline=None, **kwargs): """ Run a bunch of AST transformers and visitors on the AST. """ # print __import__('ast').dump(ast) pipeline = pipeline or context.numba_pipeline(context, func, ast, ...
559d9c44ae143e49ff505fd76df0393bae56f012
3,643,242
from typing import Union from typing import Optional def convert_acc_data_to_g( data: Union[AccDataFrame, ImuDataFrame], inplace: Optional[bool] = False ) -> Optional[Union[AccDataFrame, ImuDataFrame]]: """Convert acceleration data from :math:`m/s^2` to g. Parameters ---------- data : :class:`~bi...
e9c60ebdc143cd8243fa7ec7ebde27f0ad5beceb
3,643,243
def replace_by_one_rule(specific_rule: dict, sentence: str): """ This function replace a sentence with the given specific replacement dict. :param specific_rule: A dict containing the replacement rule, where the keys are the words to use, the values will be replaced by the keys. :param sentence: A s...
31a5bd58ef77d76c968c353dd493ba3357d5b506
3,643,244
def get_os(platform): """ Return the icon-name of the OS. @type platform: C{string} @param platform: A string that represents the platform of the relay. @rtype: C{string} @return: The icon-name version of the OS of the relay. """ if platform: for os in __OS_LIST: ...
1610c373076a8fd9b647dad22c5ff39732d14fa7
3,643,245
def get_loglikelihood_fn(dd_s, f_l=f_l, f_h=f_h, n_f=n_f): """ x: parameter point dd_s: signal system """ fs = jnp.linspace(f_l, f_h, n_f) pad_low, pad_high = get_match_pads(fs) def _ll(x): # Unpack parameters into dark dress ones gamma_s, rho_6T, M_chirp_MSUN, log10_q = x ...
da3843fd069a9c3a4646aa282c854bbd5557d74b
3,643,246
def to_module_name(field): """_to_module_name(self, field: str) -> str Convert module name to match syntax used in https://github.com/brendangregg/FlameGraph Examples: [unknown] -> [unknown]' /usr/bin/firefox -> [firefox] """ if field != '[unknown]': field = '[{}]'.format(fi...
75e3fbb9a45710ea6dacecf5ecc34a5b9409606a
3,643,247
def ApplyMomentum(variable, accumulation, learning_rate, gradient, momentum, use_nesterov=False, gradient_scale=1.0): """apply momentum""" return apply_momentum.apply_momentum(variable, gradient, accumulation, learning_rate, momentum, use_nesterov=use_nesterov, grad_scal...
f86b923e707c7f98d55cbf23a7ac17040bf2929c
3,643,248
def init(): """Return True if the plugin has loaded successfully.""" ok = True if ok: #g.registerHandler('start2',onStart2) g.plugin_signon(__name__) #serve_thread() #g.app.remoteserver = ss = LeoSocketServer() return ok
74cc6395310d648b809b6df965700ca708581b5e
3,643,249
def _fftconvolve_14(in1, in2, int2_fft, mode="same"): """ scipy routine scipy.signal.fftconvolve with kernel already fourier transformed """ in1 = signaltools.asarray(in1) in2 = signaltools.asarray(in2) if in1.ndim == in2.ndim == 0: # scalar inputs return in1 * in2 elif not in1.ndi...
a32d85bb24fe0d1e64b12cdae14391c0c8e9e111
3,643,250
def solve_step(previous_solution_space, phase_space_position, step_num): """ Solves the differential equation across the full spectrum of trajectory angles and neutrino energies :param previous_solution_space: solution to previous step of the differential equation across all angles and energies, include...
6678a9482453f2a43942f04085c892e8484e75cc
3,643,251
def gradientDescentMulti(X, y, theta, alpha, num_iters): """ Performs gradient descent to learn theta theta = gradientDescent(x, y, theta, alpha, num_iters) updates theta by taking num_iters gradient steps with learning rate alpha """ # Initialize some useful values J_history = [] ...
72b5512e115c405216fe262724b85a02df984c6d
3,643,252
def execute(*args, **kw): """Wrapper for ``Cursor#execute()``.""" return _m.connection["default"].cursor().execute(*args, **kw)
8bb11436046e479c580c48eb42d4cb2b37372945
3,643,253
def get_login_client(): """ Returns a LinodeLoginClient configured as per the config module in this example project. """ return LinodeLoginClient(config.client_id, config.client_secret)
786d3d6981f81afa95ed7de62544896982b17c58
3,643,254
import re def detect_ascii_slice(lines): # type: (List[str]) -> slice """ Given a list of strings, this will return the most likely positions of byte positions. They are returned slice which should be able to extract the columns from each line. """ for line in lines: # if the conte...
06cf3b9faa24f46aef37ae94495cbe129851bd7c
3,643,255
import torch def inception_model_pytorch(): """The InceptionBlocks model the WebGME folks provided as a test case for deepforge.""" class InceptionBlocks(nn.Module): def __init__(self): super().__init__() self.asymmetric_pad = nn.ZeroPad2d((0, 1, 0, 1)) self.conv2...
c70e4ea71eb38ae0d81b6985076a0c1588758df2
3,643,256
def get_trained_coefficients(X_train, y_train): """ Create and train a model based on the training_data_file data. Return the model, and the list of coefficients for the 'X_columns' variables in the regression. """ # TODO: create regression model and train. # The following codes are adapte...
bfafbd3370bc48fa64144842fa2400bbe629cf3e
3,643,257
def register(): """Handles the creation of a new user""" form = dds_web.forms.RegistrationForm() # Validate form - validators defined in form class if form.validate_on_submit(): # Create new user row by loading form data into schema try: new_user = user_schemas.NewUserSchema...
ed0c65daf3dfaa7fce315eb510c59c171d9f16d0
3,643,258
def project_in_2D(K, camera_pose, mesh, resolution_px): """ Project all 3D triangle vertices in the mesh into the 2D image of given resolution Parameters ---------- K: ndarray Camera intrinsics matrix, 3x3 camera_pose: ndarray Camera pose (inverse of extrinsics), 4x4 mes...
9615d940fe083853e0bc179b79e1a19b7f9304bf
3,643,259
from typing import Any def forbidden(description: Any) -> APIGatewayProxyResult: """Return a response with FORBIDDEN status code.""" error = ForbiddenError(description) return _build_response(error, HTTPStatus.FORBIDDEN)
7b87e41081f1f7fa8f1e140a2c4d5ee597222193
3,643,260
from datetime import datetime def str_2_datetime(p_str, fmt="%Y-%m-%d %H:%M:%S"): """ 将字符串转换成日期 :param p_str: 原始时间字符串 :param fmt: 时间格式 :rtype: datetime.datetime """ # don't need to transform if isinstance(p_str, datetime.datetime): return p_str if not isinstance(p_str, str): ...
0fa86e0aebcf2c2ff53ceb26ae93ed762175ef03
3,643,261
def traitement(l): """Permet de retirer les cartes blanches inutiles""" while l[-1][1] == 'nan': del l[-1] return l
d21a7d493a35fc53195315da9b824b0ca3c8ba25
3,643,262
import os def save_audio(text: str, filename: str, dir: str): """ Converts text to audio and saves Notes ----- If the .mp3 file extension is missing in the filename, it will be added If a file with the same name exists, it will not save, only notify the user Returns _______ Path ...
a8306dfb56cbb00f99ca3dc658991ba7e42fa021
3,643,263
import os import logging def build_report(test_controller): """Report on the test results.""" options = test_controller.options citest_log_dir = os.path.join(options.log_dir, 'citest_logs') if not os.path.exists(citest_log_dir): logging.warning('%s does not exist -- no citest logs.', citest_log_dir) r...
4cfe128cae57575c35983aad26cd0bf846617c3a
3,643,264
from datetime import datetime import bisect def group_frames_by_track_date(frames): """Classify frames by track and date.""" hits = {} grouped = {} dates = {} footprints = {} metadata = {} for h in frames: if h['_id'] in hits: continue fields = h['fields']['partial'][0] ...
327a6357c5ce8fc9a54d27107e2cb43424dd7630
3,643,265
def generate_violin_figure(dataframe, columns, ytitle, legend_title=None): """ Plot 2 columns of data as violin plot, grouped by block. :param dataframe: Variance of projections. :type dataframe: pandas.DataFrame :param columns: 2 columns for the negative and the positive side of the violins. :type...
23baa052cf835ba55a43ffa496d606cccadb0c5b
3,643,266
def measure_single(state, bit): """ Method one qubit one time :param state: :param bit: :return: """ n = len(state.shape) axis = list(range(n)) axis.remove(n - 1 - bit) probs = np.sum(np.abs(state) ** 2, axis=tuple(axis)) rnd = np.random.rand() # measure single bit i...
ff2c18039e6900febaa731f9a3db9f16b797e18b
3,643,267
def anchor_to_offset(anchors, ground_truth): """Encodes the anchor regression predictions with the ground truth. Args: anchors: A numpy array of shape (N, 6) representing the generated anchors. ground_truth: A numpy array of shape (6,) containing the label boxes in t...
3aced37f0838d2ab4f90ce0e212747111fc87876
3,643,268
def horizontal_flip(img_array): """Flip image horizontally.""" img_array = cv2.flip(img_array, 1) return img_array
7f53442b072127e5c02253aefabcc8e7bd422504
3,643,269
def chunker(file_path): """ Read a block of lines from a file :param file_path: :return: """ words = [] with open(file_path, 'r') as file_object: for word in file_object: word = word.strip() if word: words.append(word) return words
a60b6f3cc7003955ae6acd8ac5e74574cdbd5976
3,643,270
import subprocess def c2c_dist(commande,octree_lvl=0): """ Commande CC cloud2cloud distance """ if octree_lvl==0: commande+=" -C2C_DIST -split_xyz -save_clouds" else: commande+=" -C2C_DIST -split_xyz -octree_level "+str(octree_lvl)+" -save_clouds" subprocess.call(comma...
723082644cb6d8b24cc27b634a3bca2b8caabe4a
3,643,271
def legalize_names(varnames): """returns a dictionary for conversion of variable names to legal parameter names. """ var_map = {} for var in varnames: new_name = var.replace("_", "__").replace("$", "_").replace(".", "_") assert new_name not in var_map var_map[var] = new_name ...
ad8e9ef3394d4ac3cfa80198f488c1834bd227fc
3,643,272
def _IsUidUsed(uid): """Check if there is any process in the system running with the given user-id @type uid: integer @param uid: the user-id to be checked. """ pgrep_command = [constants.PGREP, "-u", uid] result = utils.RunCmd(pgrep_command) if result.exit_code == 0: return True elif result.exit...
8a4e529a98298ec4c2d9df30c6fc28a91c124edd
3,643,273
def mobilenetv3_large(data_channel): """ Constructs a MobileNetV3-Large model """ cfgs = [ # k, t, c, SE, NL, s [3, 16, 16, 0, 0, 1], [3, 64, 24, 0, 0, 2], [3, 72, 24, 0, 0, 1], [5, 72, 40, 1, 0, 2], [5, 120, 40, 1, 0, 1], [5, 120, 40, 1, 0, 1]...
ec14d6628bf9e69f05a79f4207a32e00fbae1b8b
3,643,274
def ravel_lom_dims(tensor, name='ravel_lom_dims'): """Assumes LOM is in the last 3 dims.""" return tf.reshape(tensor, tensor.shape_as_list()[:-3] + [-1], name=name)
f0f56c4f747b4a40e63bddbb7d6dd3452044151f
3,643,275
def run_cv(cfg, df, horiz, freq, cv_start, cv_stride=1, dc_dict=None, metric="smape"): """Run a sliding-window temporal cross-validation (aka backtest) using a given forecasting function (`func`). """ y = df["demand"].values # allow only 1D time-series arrays assert(y.ndim == 1) ...
cb95657aeaa4cb74c6252d46029db88c6be18ddb
3,643,276
import pyarrow as pa def ST_Area(geos): """ Calculate the 2D Cartesian (planar) area of geometry. :type geos: Series(dtype: object) :param geos: Geometries in WKB form. :rtype: Series(dtype: float64) :return: The value that represents the area of geometry. :example: >>> import pan...
ae69ec90c9e5c54c5f6afa468d6cb1212e64eaf4
3,643,277
import subprocess def check_conda_packages(edit_mode=False, packages=None): """Check conda inslalled packages information filtering for packages. It is Python/Conda environment dependent. Returns: dict(str): Dictionary filled with respective information. """ info = {'CONDA PACKAGES': {}...
0a55356b71e692068e85b05902a1f9c2d495fa3f
3,643,278
from operator import matmul def P_from_K_R_t(K, R, t): """Returns the 3x4 projection matrix P = K [R | t].""" K = K.astype(np.float64) R = R.astype(np.float64) t = t.astype(np.float64) return matmul(K, np.column_stack((R, t)))
0304ea513df81a67e653ba1e3516c39ec38f94ad
3,643,279
from typing import List from typing import Union from typing import Callable from typing import Type from typing import OrderedDict from typing import Any def multi_value_precondition(parameter_selector: List[Union[int, str]], predicate: Callable[..., bool], exception_factory: Union[Type[...
97632d8e77858e3d854a8f610fae772a8a6c3c5b
3,643,280
from operator import itemgetter import json def activity_list_retrieve_view(request): # activityListRetrieve """ Retrieve activity so we can populate the news page :param request: :return: """ status = '' activity_list = [] activity_manager = ActivityManager() activity_notice_seed...
4ab7d7e2cd5c0a3c812b6ec1729efda19fb87ced
3,643,281
import argparse from textwrap import dedent def arg_parser() -> argparse.Namespace: """ Reads command line arguments. :returns: Values of accepted command line arguments. """ _parser = argparse.ArgumentParser( description=dedent( """Find all recipes in a directory, bui...
6bf2f99cbab0674fb5b127b58cdb0e28ad87ef0a
3,643,282
import http from typing import Optional def edit_action( request: http.HttpRequest, pk: int, workflow: Optional[models.Workflow] = None, action: Optional[models.Action] = None, ) -> http.HttpResponse: """Invoke the specific edit view. :param request: Request object :param pk: Action PK ...
43f128dfe2abd47c1c6cf78d667343d9086aeb98
3,643,283
from typing import Any from typing import Set from typing import KeysView def to_set(data: Any) -> Set[Any]: """Convert data to a set. A single None value will be converted to the empty set. ```python x = fe.util.to_set(None) # set() x = fe.util.to_set([None]) # {None} x = fe.util.to_set(7) # ...
df2649d0b7c7c2323984edd3eeea76eff0eab4d2
3,643,284
def Pei92(wavelength, Av, z, Rv=-99.0, ext_law="smc", Xcut=False): """ Extinction laws from Pei 1992 article Parameters ---------- wavelength: `array` or `float` wavlength in angstroms Av: `float` amount of extinction in the V band z: `float` redshift Rv: `flo...
9b0b9690f548319ffed7fcc964dc0e651828371f
3,643,285
import warnings def plot_profile_avg_with_bounds( data, ax=None, confint_alpha=0.05, label=None, xs=None, axis=0, bounds: str = "ci", **kwargs, ): """ TODO: Documentation Parameters ---------- data ax confint_alpha label kwargs Returns ----...
cbce13474608bd710031698120b9ab01c78facc4
3,643,286
import mimetypes def get_mimetype(path): """ Get (guess) the mimetype of a file. """ mimetype, _ = mimetypes.guess_type(path) return mimetype
7677259fcdf052f9647fe41e4b4cb71d83ea50cd
3,643,287
import select async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """Get epics from a client_id""" statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) r...
e5af5d2776a941cde83ea341143732bcdb67da2a
3,643,288
def id_number_checksum(gd): """ Calculates a Swedish ID number checksum, using the Luhn algorithm """ n = s = 0 for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']): # Letter? It's an interimspersonnummer and we substitute the letter # with 1. if c.isalpha(): ...
bbf0a9fa7f6ed2c2bfc414173fd2ac9e9c1d8835
3,643,289
def date_loss_l1(pred, target_min, target_max, mask): """L1 loss function for dates.""" pred = jnp.squeeze(pred, 0) loss = 0. loss += jnp.abs(pred - target_min) * jnp.less(pred, target_min).astype( pred.dtype) loss += jnp.abs(pred - target_max) * jnp.g...
12f0d5a1f7efbb8d51501c4d3fe41d192528010d
3,643,290
def new_single_genres(genres, val): """Takes the genres list and returns only one genre back if multiple genres are present Also has the parameter val with values "high" and "low" High picks the genres belonging to the existing genres with the highest examples count Low picks the genres belonging to the...
0cabcb93548007b3cd87dc40740da5d0f4614867
3,643,291
import sys import unittest def run(funcs_to_test=None, tests_to_run=None, verbosity=2): """ run testing routine args: - funcs_to_test: dict: {lang_name <str>: lang_func <callable>} of language processing modules to test ...
116bbbbb5c20b8dd73b5d45af3bde9cf80ae841f
3,643,292
def roparameter(cosphi, hist, s_cosphi=0.25): """ ... Parameters ---------- cosphi : ... hist : ... s_cosphi : ... Returns ------- ... """ perp=(np.abs(cosphi)>1.-...
c9f30db90482600c50a9369139fc75c046d57e40
3,643,293
def execute(model_fn, input_fn, **params): """Execute train or eval and/or inference graph writing. Args: model_fn: An estimator compatible function taking parameters (features, labels, mode, params) that returns a EstimatorSpec. input_fn: An estimator compatible function taking 'params' that...
44b5cc8105ec663642724a4cbba66c12a81e3b98
3,643,294
def polyfill_bbox( min_lng, max_lng, min_lat, max_lat, min_resolution=0, max_resolution=30 ): """Polyfill a planar bounding box with compact s2 cells between resolution levels""" check_valid_polyfill_resolution(min_resolution, max_resolution) rc = s2sphere.RegionCoverer() rc.min_level = min_resolu...
d6c2cb0d3f0d7a9eea05a456beda96a1a646e306
3,643,295
from lvmspec.qa import qalib import copy def qa_skysub(param, frame, skymodel, quick_look=False): """Calculate QA on SkySubtraction Note: Pixels rejected in generating the SkyModel (as above), are not rejected in the stats calculated here. Would need to carry along current_ivar to do so. Args: ...
3b53f99ae4936fa6870dc8020d677ffddcb2d4ef
3,643,296
def _code_to_symbol(code): """ 生成symbol代码标志 """ if code in ct.INDEX_LABELS: return ct.INDEX_LIST[code] else: if len(code) != 6 : return '' else: return 'sh%s'%code if code[:1] in ['5', '6', '9'] else 'sz%s'%code
4b783adad975246c9d6722f6eeeb95a2388d1823
3,643,297
def gesv(a, b): """Solve a linear matrix equation using cusolverDn<t>getr[fs](). Computes the solution to a system of linear equation ``ax = b``. Args: a (cupy.ndarray): The matrix with dimension ``(M, M)``. b (cupy.ndarray): The matrix with dimension ``(M)`` or ``(M, K)``. Returns: ...
333f06bd8f91bdfde5526c80894c284580074bb5
3,643,298
def del_none(d): """ Delete dict keys with None values, and empty lists, recursively. """ for key, value in d.items(): if value is None or (isinstance(value, list) and len(value) == 0): del d[key] elif isinstance(value, dict): del_none(value) return d
46cf9e331c633f5f69b980f3b10c96306d3478c2
3,643,299