content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def solution_math( A: np.array, B: np.array, threshold: int = 1_000_000_000, scale: int = 1_000_000 ) -> int: """Math based method. See tutorial/examples in docs for more details.add() Parameters ---------- A : np.array integer part of the decimal numbers B : np.array decimal pa...
d87c860846968e49705ac8390aa5caded1381f84
54,800
def tag_list(context, addon, tags=[]): """Display list of tags, with delete buttons.""" c = dict(context.items()) c.update({'addon': addon, 'tags': tags}) return c
0b59aa158137eecd5210c631f053ae137762b690
54,801
def make_range_partition(min_val, max_val): """ Returns a new partitioning function that partitions keys in the range *[min_val:max_val]* into equal sized partitions. The number of partitions is defined by the *partitions* parameter """ r = max_val - min_val f = ("lambda k_n_p: int(round(fl...
6b9c15f93312a913dff432f0954e409b69f97572
54,802
import torch def sparse_mx_to_torch_sparse_tensor(sparse_mx): """Convert a scipy sparse matrix to a torch sparse tensor.""" sparse_mx = sparse_mx.tocoo().astype(np.float32) indices = torch.from_numpy(np.vstack((sparse_mx.row,sparse_mx.col)).astype(np.int64)) values = torch.from_numpy(sparse_mx.data) ...
cdf10274d87997fbe93085d48e738e3bad92edf9
54,803
def split_outside(a, sep, start="([{", end=")]}"): """Split string a at occurences of separator sep, except when it occurs inside matching groups of start and end characters.""" segments = split_by_group(a, start, end) res = [""] for seg in segments: if len(seg) == 0: continue if seg[0] in start: res[-1] +=...
efd84168831cac6af8ac1b88bdface450c0aea14
54,804
def gen_unique_image_path(standard_image_path, image_num): """ Generates a unique image path based on the standard_image_path by adding the IMAGE_IDENTIFIER_SEQUENCE followed by a number """ # Index where extension sequence starts (.jpg, .jpeg, or .png) extension_start = standard_image_path.lowe...
a42148e671d9d551099108b989cec0d9ec627c96
54,805
from typing import Optional from typing import Any def try_wrapper( func: callable, *args, ret_: Optional[Any] = None, msg_: str = "", verbose_: bool = True, **kwargs, ) -> Any: """Wrap ``func(*args, **kwargs)`` with ``try`` and ``except`` blocks. Args: func (callable) ...
3514663751028e8bcb9979f952045c053a325ff1
54,806
from typing import Dict from typing import Any from typing import List def _CreateSamples(results: Dict[str, Any], number_of_messages: int, message_size: int, cloud: str) -> List[sample.Sample]: """Handles sample creation from benchmark_scenario results.""" samples = [] common_metadata = { ...
a60652e74bd041dc183837746202dd3d3ed24ae5
54,807
def merge(df_list,merge_param_list): """ method to merge the list of data frames based on list of column identifiers. This returns intersection of values :param df_list: :param merge_param_list: :return merged data frame: """ merged = funs.reduce(lambda left, right: pd.merge(left, right,how...
b41a26f8c8b0ff69aa80e1d4d328b67a141d68ec
54,808
def yices_check_context(ctx, params): """Checks whether all the assertions stored in the context ctx are satisfiable. - params is an optional structure that stores heuristic parameters. - if params is NULL, default parameter settings are used. It's better to keep params=NULL unless you encounter perfo...
191f9776a2dd50ee5f56b515571c5a4cfe055b4c
54,809
import torch def collate_fn_v2_(data_batch): """ used for trained on the original complex dataset and tested on the ligand-only and protein-only datasets :param data_batch: :return: """ graphs, graphs3, Ys, Nodes = map(list, zip(*data_batch)) bg = dgl.batch(graphs) bg3 = dg...
18778a2da4986b8e4c42f5d902bc1be752fcca3f
54,810
def standardvariables_get(username=None, label=None, page=None, per_page=None): # noqa: E501 """List all instances of StandardVariable Gets a list of all instances of StandardVariable (more information in https://w3id.org/okn/o/sd#StandardVariable) # noqa: E501 :param username: Name of the user graph to ...
b04df9f32330541c316a7e8d67217c6bcbb0ab71
54,811
from re import S from re import T def construct_scale(root_note, scale_signature, scale_length=None): """Construct a musical scale from a root note Arguments: root_note -- A root note object from class Note scale_signature -- array of frequency ratios between consecutive notes on the scale scale_...
555099024c4e9fc8d2b487ddc7e57138084e494f
54,812
def get_env_logname(name): """ get_env_logname """ modname = name.split('.')[0].upper() envname = f"{modname}_LOGLEVEL" # print(envname) return envname
6fa8032ee77d94695363d976ea06a4e58f69c7f7
54,813
def horizontal_flip(image_array: ndarray): """ horizontal flip doesn't need skimage, it's easy as flipping the image array of pixels ! """ return image_array[:, ::-1]
a56b12889dad254e8618326d1a85d220827652d9
54,814
def lookup(a, idx, dim=0): """ Lookup the values of input array based on index. Parameters ---------- a : af.Array. Multi dimensional array. idx : is lookup indices dim : optional: int. default: 0. Specifies the dimension for indexing Returns ------- out : af....
9084d196de4f84bfdf568ea67b3fc34f357cc88c
54,815
from typing import VT from typing import Optional from typing import Callable from typing import List from typing import Set def match_connected_hboxes(g: BaseGraph[VT,ET], edgef: Optional[Callable[[ET],bool]] = None ) -> List[ET]: """Matches Hadamard-edges that are connected to H-boxes, as these ...
d26dd13ed41ff46d5d46a8df0e4704271570ea92
54,816
import os def _exist_(url): """ 判断所给的路径是否存在,如果所给的是相对路径(在判断文件夹不存在后)转换为绝对路径 :param url: 用户给定文件夹的路径 :return: """ s = url; if not os.path.exists(url): s = os.path.abspath(url) if os.path.exists(s) and os.path.isdir(s): return True else: print(url + " don't exist...
0e3285499caee64d650a6adf51aa9118c7056d0d
54,817
def make_user(d): """Get or create a user. Arguments: d A Dict with keys: name A human readable full name, required. The unique username will be inferred through lowersnake(name). email A valid email, optional. phone A phone number, optional. role A role description, optional. ...
0502b31d80fe20ebc1162fc4d0098a765c38527f
54,818
def n2N(n): """ Calculate the square matrix rank N for a packed storage size n Parameters ---------- n : int The packed length. Returns ------- N : np.uint64 The matrix rank. """ N = np.uint64((np.sqrt(8*n+1)-1)/2) return N
93f73c36a52a1fb4200c07a678b0f5527439092c
54,819
import shlex import subprocess def run(cmd): """ Run a given process. Returns the PID and returned code from execution. param cmd: str The command to be executed """ logger.info("Running process %s", cmd) command = shlex.split(cmd) proc = subprocess.Popen(command) proc.wait() ...
bcde97f08e48a274201912b810a9017f42f7d6a8
54,820
from typing import Union from typing import List from typing import Tuple from typing import Dict import requests def scrape_url(url: str, python_objects: Union[bool, List, Tuple] = False, nonstandard_attrs: bool = False, migrate_old_schema: bool = True, user_agent_str: st...
7edb4a94361bd72999a546a4ae53233b31222140
54,821
import time def ecs_container_instance(request, ecs_cluster, ec2_client, ecs_client, ecs_instance_type, ecs_ami): """ Fixture to handle spin up and tear down of ECS container instance :param request: pytest request object :param ecs_cluster: ecs cluster fixture :param ec2_client: boto3 ec2 client...
9bdf9bc4c16ab1a1c0219ce7c4910e1fa8472227
54,822
from typing import Dict def sound_mode_rev_map_factory(instance: DenonAVRFoundation) -> Dict[str, str]: """ Construct the sound_mode_rev_map. Reverse the key value structure. The sound_mode_rev_map is bigger, but allows for direct matching using a dictionary key access. The sound_mode_map is uses...
c93d33501d8c54c3e38fb7221f7515acdcc2f1c7
54,823
def get_objhash_from_object_desc(gitobjcontent): """returns object hash without control characters""" return gitobjcontent.split(" ")[1][:40]
662357569cb22bf77d6236e7c53a71f19f29823a
54,824
def wgs84_to_lv03(latitude, longitude, altitude=None): """Convert WGS84 to LV03. :param float latitude: latitude in degrees :param float longitude: longitude in degrees :param float altitude: altitude :rtype: (float, float, float) """ lat_sex = dms_to_sex(*dd_to_dms(dd=latitude)) lon_se...
eb7d4c91ce0d8e0d3eeb4b40c556920457b38f14
54,825
def decrypt(signature: str, js: str): """ Main function for decrypting the signature cipher. :param signature: original signature, encrypted :param js: base.js contents :return: the decrypted signature """ functions = get_dict_functions(js) signature = [char for char in signature] ...
d630449ac6e3221a23e3a349026a06ea22558447
54,826
def ffactory(type, data=None): """Devuelve el valor filtrado por la función indicada en type Metodo factory, llama a la función type de filtrado. Parameters ---------- type: str data: any Returns ------- any Depende de la función llamada Raises ------ Convert...
8d1f10582bc5b42799b2dab27436e59c92dfa437
54,827
def get_path(origin, dest): """ MapBox APIを用いてルート探索を行う Arguments: origin {list} -- 出発地の緯度経度 dest {list} -- 到着地の緯度経度 Returns: list -- ルート探索結果 """ api = mapbox.Directions() res = api.directions([{ 'type': 'Feature', 'geometry': { 'type': 'P...
76160f50c12f27ac8db92233cb2bd71863ae6991
54,828
import collections def update_dict(to_update, updates): """ Recursively updates a nested dict `to_update` from a nested dict `updates` """ for key, val in updates.items(): if isinstance(val, collections.Mapping): to_update[key] = update_dict(to_update.get(key, {}), val) else: ...
7697d2beb42d45e60e8fdfb1386842c168bffbcc
54,829
from typing import Optional def sin(duration: int, amp: complex, freq: float = None, phase: float = 0, name: Optional[str] = None) -> SamplePulse: """Generates sine wave `SamplePulse`. Args: duration: Duration of pulse. Must be greater than zero. amp: Pulse amplitude. freq: Pu...
5f5e1f0c00991158a80d530669fc82d433fb11e4
54,830
from typing import List def list_resources() -> List[str]: """ Lists all available resources by name. :returns: A list of resources by name. """ return _get_resources(_get_resources_json()["resources"]).keys()
dad3e4920d353d9de7f7f354d5cc49ab8f5e1449
54,831
import logging def get_impulse(f, tf, dt, T): """ Calculates the impulse response, given a single-sided transfer function. f should be non-negative and increasing. See https://www.overleaf.com/read/mxxtgdvkmkvt """ # calculate number of time points in impulse response n_req = round(T/dt) log...
f80c8ff9d2f09e943cdfcc84a49ad4c39e891a90
54,832
from typing import List from typing import Dict import re from typing import Tuple from typing import Optional def extract_all_content( content: str, author: str, created_at: str, attachments: List[Dict[str, str]], ) -> List[dict]: """ Extract all information for content, allowing for multiple...
7e16c3c45b7d42f2afedea28d45a5e0baa49a3c7
54,833
import torch def computeMaskIntersection(gt, gtMask, pred, predMask): """ Compute intersection between GT instance and prediction. Increase efficiency by computing elementwise product between masks only inside the tight bounding box of the union of the prediction and target masks. """ if g...
69dbe02148f23f7f3925aebab0a1fc8afa6544fa
54,834
from typing import Tuple from typing import Union from typing import Dict def handle_merge_duplicate_facilities( facilities: DataFrame, ) -> Tuple[DataFrame, Union[Dict[str, str], None]]: """Drops duplicate facilities by name and some other logic. Returns facility DataFrame without duplicate facilities an...
e7e1cf96aa6bf541d55865361a52b476c897980e
54,835
import os import io import csv def load_csv_file(csv_file): """ load csv file and check file content format Args: csv_file (str): csv file path, csv file content is like below: Returns: list: list of parameters, each parameter is in dict format Examples: >>> cat csv_file ...
515e025bf8943a55b738e2466394cf517dfffeb9
54,836
def get_applicant(form): """ Gets applicant info, or adds if necessary """ applicant_result = Applicant.query.filter_by(email=form.get("email")).first() if applicant_result: applicant_id = applicant_result.applicant_id else: applicant_id = add_applicant(form) return applicant_i...
8072ee16e20939eeceacda7dc80729f108c9b3ec
54,837
import os import json from datetime import datetime def check_function_task(self, file_path, user_id, q_id, function_name, args, answers, timeout): """task that will check a submission""" # this needs refactoring ! results = [] total = len(args) status = 'Unsucessful' sub_result = False t...
09053e192a5f82dfd094e09cc16ebd24f1d01f75
54,838
def graphing(dataframe_after_LDA, title, color_list, labels): """ Function that given a dataframe after the LDA, returns a graph where each point corresponds to a frame, and each cluster correspond to a different location of the mouse during the experiment (HOME, CORRIDOR, FARCHAMBER) :param dataframe...
409f040951b2215a7ae7434d8d683827bfdc9bf1
54,839
def make_sentences(diff): """Create human-readable sentences out of the diff dict.""" info = [] for t in sorted(diff.keys()): if "old" in diff[t]: old_range = make_range(diff[t]["old"]["min"], diff[t]["old"]["max"]) new_range = make_range(diff[t]["new"]["min"], diff[t]["new"]...
a18865be04cab94c36278e70c048c1d3ec550447
54,840
import os import fcntl import time import signal import threading def acquire_lock(lock_file, sock_file, block, heartbeat): """ Acquire a lock on the passed file, block if needed :param lock_file: :param sock_file: :param block: :return: """ # get dir lock first to check lock file exi...
cd3aed15cd6ceb8faead1757599ea8a5034ccbfa
54,841
def swsl_resnext101_32x16d(pretrained=True, **kwargs): """Constructs a semi-weakly supervised ResNeXt-101 32x16 model pre-trained on 1B weakly supervised image dataset and finetuned on ImageNet. `"Billion-scale Semi-Supervised Learning for Image Classification" <https://arxiv.org/abs/1905.00546>`_ ...
33c1a73fd00da4a64b77fc0408cb09ad66fbdbc1
54,842
def completeTreeNames(tree, useBS = False ) : """ Takes: - tree (ete3.Tree) - useBS (bool) [default = False] : uses bootstrap to name nodes Returns: (ete3.Tree) : the tree, but where the nodes without a name now have one that correspond to their post-order OR the...
07077fce3ea18ba40af578cd1b0768a71e7b16c8
54,843
from typing import Sequence import string def password(characters: Sequence[chr] = string.printable, length: int = 8, unique: bool = False) -> str: """ :param characters: The character pool that will be used when generating the password :param length: The total length of the pass...
949b6df79021cea6654c26bf4e3aeaacc80eab82
54,844
import json def build(kernel_desc, attrs=None, poly=True, use_repo=True): """ build kernel with compute description in json format Args: kernel_desc : str or dict of compute description attrs : dict of build attributes Returns: Module. """ if isinstance(kernel_desc, str...
d2c0926f9a14e465449687bd3bdafc1387211627
54,845
def bitsize(a): """ Compute the bitsize of an element of Z (not counting the sign). """ val = abs(a) res = 0 while val: res += 1 val >>= 1 return res
18755ee3bfe2a122702f3161135288f8fae2dc8b
54,846
def InjectDll(proc, name, entry = None): """Inject a dll with CreateRemoteThread in the remote process""" kernel32 = _GetModuleHandleA(b'kernel32') if not kernel32: raise Win32Exception() LoadLibraryEx = _GetProcAddress(kernel32, b'LoadLibraryA') if not LoadLibraryEx: raise Win32Exce...
28e635ecfba55bfb68585a233942ce8971698c4b
54,847
def find_module_corner2(mask, mode=0): """ mode == 0: detect corners of the convex of module mode == 1: detect corners of the approximated convex of module mode == 2: detect corners of the approximated contour of the module mode == 3: detect corners of the blurred mask of the module """ blur...
d69d76190c166be9ed6835ee7885463e166e37da
54,848
import random def gen_rand_lists(): """ Generate two lists with random numbers in [0,5], output them and compare their mean and tell who is greater """ def gen_list(): ll = [] for i in range(5): ll.append(random.randint(0, 5)) return ll def calc_avera...
03195edb47f43ce17933188523235f87472667d1
54,849
import time import zipfile def get_image_zip(project_id, project_name, json_data, filters=None): """ Create a zip file in memory containing the project's images and a descriptive JSON file. """ all_data = ProjectImageData.query.filter_by(project_id=project_id).all() date_time = time.localtime(...
eea6da48a5f6922f3584b03e9f39d8aa092df56f
54,850
def degre(poly): """Renvoie le degré du polynôme _poly_""" poly = clear_poly(poly) return len(poly)-1
cb8413dbde586e0a8383978ae646bee8f36d6a05
54,851
def store_forecast_values(forecast_id, forecast_df): """Store Forecast data Parameters ---------- forecast_id: string UUID of the associated forecast. forecast_df: DataFrame Dataframe with DatetimeIndex and value column. Returns ------- string The UUID of the as...
7315d566a0cbd6e4ac94347c61d369cfcd37c5f4
54,852
def gather_link_defn_lines(file_lines): """Returns all link def lines occuring after main content. Should be called with set of lines starting with first non-main-content line.""" ld_lines = [] for mdfl in file_lines: if is_ld_block_begin_line(mdfl): continue # ignore the b...
bd5b6a3d3fdb7153b2bbaae14745ca705ca7606e
54,853
def _hdf5_yt_attr(fh, attr, unit_registry=None): """ Read an hdf5 attribute. If there exists another attribute named <attr>_units, use that to assign units and return as either a unyt_array or unyt_quantity. """ val = fh.attrs[attr] units = "" ufield = "%s_units" % attr if ufield in...
a751fe3997af75f4bc4539873c65d0a32580c13c
54,854
import numpy def raster_rpn_calculator_op(*args_list): """Calculate RPN expression. Args: args_list (list): a length list of N+4 long where: - the first N elements are array followed by nodata - the N+1th element is the target nodata - the N+2nd element is an RPN ...
8742cd6087d9c5aa283b33cc29c5847658a32f73
54,855
import random def get_boundary_mutation_function(minimum, maximum): """ Returns a function that pushes a value to either the minimum or maximum allowed value for a gene; see :ref:`mutation-functions` :Valid For: ``"int"``, ``"[int]"``, ``"float"``, and ``"[float]"`` gene types :param minimum...
0f3e2b6b4d69e758fb1d439d2785306da7f537e8
54,856
def nan_to_num(X: np.ndarray, value: float = 0.0): """Sets all NaN values in X to the given value. :type X: np.ndarray :type value: float, optional """ return np.nan_to_num(X, value)
3b5dd81670bf072521e865f55bcafb71f6e78611
54,857
import argparse import pathlib def parse_args(): """Parse the command line arguments""" parser = argparse.ArgumentParser(parents=[kcs_parser], conflict_handler='resolve') parser.add_argument('percentiles', help="Input CSV file with CMIP distribution percentiles") p...
8a39b840d3139e5a4469e90a0e61db1d2a6df348
54,858
def preimage(target, aut): """Return predecessor states of `target`, conjoining player actions.""" action = sym.conj_actions_of(aut.players, aut) vrs = aut.vars_of_all_players qvars = aut.prime_vars(vrs) # \E x', y', i' primed_target = aut.replace_with_primed(vrs, target) u = action & primed...
6aed568f6cadba69c7964b5d0696fdc211db106f
54,859
import binascii def int_to_base64(number): """Convert int -> base64.""" number_bytes = int_to_bytes(number) return binascii.b2a_base64(number_bytes)[:-1].decode('utf-8')
6c420e26551022e55ec3e12caec53df05294c1bd
54,860
def fit_frap(bkgnd_corr_int, frame_interval=1.0, bleach_n_frames=1): """Normalize and fit each fluorescence trace to a standard FRAP curve. Args: bkgnd_corr_int (list): List of numpy arrays (one for each track in track_intensities) storing background-subtracted track intensities ...
2c1f55183ea1199ec530f5df5980d27e6ded3e0e
54,861
def read_raw_parse(path): """ Read GamParse's forum output into a list. :param path: path to a file containing GamParse output :return: a list containing the lines of the input file """ with open(path, 'r') as input_handle: return input_handle.read().splitlines()
26926ca6a164c29681a0cf45a4114ffc5cff0fa9
54,862
from typing import Optional def get_network_region(network_region: str) -> Optional[str]: """ Trim the numbers off the end of nem regions """ if ( network_region and type(network_region) is str and len(network_region) > 1 ): if is_number(network_region[-1:]): ...
59668cae05bae5138d0b71166be59b197b4aaa27
54,863
def aes_cbc_no_padding_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long ...
7e21631a0cbd7a6c555f3f156a656a71f592d985
54,864
import math def position_check(inlat, inlon): """ Simple check to make sure that the latitude and longitude are within the bounds specified by the ICOADS documentation. Latitude is between -90 and 90. Longitude is between -180 and 360 :param inlat: latitude :param inlon: longitude :type ...
7f9e6d92667cd81ad02b034fcba231fd4763f966
54,865
import re import os def extract_dark_fp_threshold_one_aneurysm(subdir, aneur_path, bids_dir): """This function computes the intensity ratio of one aneurysm Args: subdir (str): parent directory to aneurysm nifti file aneur_path (str): filename of aneurysm nifti file bids_dir (str): path...
697753f236c3d8573b88f06fcce69f26d1a48b1c
54,866
from typing import Dict from typing import Any import json def _get_node_provider(provider_config: Dict[str, Any], cluster_name: str, use_cache: bool = True) -> Any: """Get the instantiated node provider for a given provider config. Note that this may be used by ...
2ab2c7d61d9976f447954fe1b24e60287a436359
54,867
def eval_poly_model(theta, obj_dict): """ Routine to evaluate a star spectrum model as a true model spectrum times a polynomial. Parameters ---------- theta : array shape (ntheta,) Array containing the polynomial coefficients obj_dict : dict Dictionary containing additional argum...
28d1e543107c9c0cab568f92057a4876f37d01ec
54,868
import itertools def compute_rank_wr(wr): """ Compute intervals for each ranks in order to plot them. Parameter: wr -- list of Decimal Return: rank_wr -- list of tuples """ # Transform Decimal into float getcontext().prec = 8 wr = [float(w) for w in wr] # Sort by w wr = sorted(wr) rank, wr = find...
a0d7ff4eb7b474015ab408a28ec289f709574a89
54,869
def normalize_email(email): """ Email Address Normalization. 1. Remove leading and trailing spaces. 2. Convert all ASCII characters to lowercase. 3. In gmail.com email addresses, remove the following characters from the username part of the email address: 1) The period (. (ASCII code 46)). ...
e128952a38cd699dffa55de0e486ee6bb245697a
54,870
def make_perfect_cd(wcs): """ Create a perfect (square, orthogonal, undistorted) CD matrix from the input WCS. """ def_scale = (wcs.pscale) / 3600. def_orientat = np.deg2rad(wcs.orientat) perfect_cd = def_scale * np.array( [[-np.cos(def_orientat),np.sin(def_orientat)], [np.s...
68e5c5a55e43aff78485798a4be5a2f5a92e262f
54,871
def urljoin(url, suffix=""): """ Will join url and its suffix Example: "https://google.com/", "/" => "https://google.com/" "https://google.com", "/" => "https://google.com/" "https://google.com", "api" => "https://google.com/api" "https://google.com", "/api" =...
cd8a81d7b427678330d1258fa5644f9d4cf631a0
54,872
import os import json def read_credentials(): """Return a json data containing user's credentials Read user's credentials from a json file """ script_dir = os.path.dirname(__file__) rel_path = "credentials.json" abs_file_path = os.path.join(script_dir, rel_path) with open(abs_file_path) a...
52c64e487f123a07f30b87509aec07655d766526
54,873
import collections def _get_variable_nodes_from_graph_def(graph_def): """Get the list of Variable nodes from `graph_def`. Args: graph_def: An instance of `GraphDef`. This GraphDef *must* have already been optimized by Grappler. In particular, function inlining must have already happened. Ret...
59a7c8b6b0ab6b3ae8d93526127252ed5866329c
54,874
def deprecated(filename, msg=''): """Decorator which will print a warning message on the first call. Use it like this:: @deprecated('myfile', 'do something different...') def fn_name(...) ... And it will print:: WARNING myfile.fn_name deprecated. do something different... ...
75b2774d019665a27aec4432c695163a8e535f2c
54,875
def construct_dataset(df, past_lags, future_intervals): """Construct demand dataset""" # Total NEM demand for a given week df_t = df.sum(axis=1).rename('total_demand') # Add an interval ID df_t = df_t.reset_index().rename_axis('interval').set_index(['year', 'week'], append=True) # Get lags ...
ada01368eb23b01ea9c13f11042088818d6dab81
54,876
import tempfile import os import sys import shutil def with_rw_repo(working_tree_ref): """ Same as with_bare_repo, but clones the rorepo as non-bare repository, checking out the working tree at the given working_tree_ref. This repository type is more costly due to the working copy checkout. To make working ...
3fe6d73374c9a3acb5d8dabcf4e30816d7b6d198
54,877
import subprocess import re def vagrant_status(): """ Run `vagrant status` and parse the current vm state """ node_state = {} output = subprocess.check_output(['vagrant', 'status']) for i, line in enumerate(output.splitlines()): if i < 2: continue parts = re.split('\s+', l...
4fc2a12bd71430327aed851d9312a9656b09e39f
54,878
def lists( stype="spotify", sort="followers", country="US", limit=100, offset=0, indie=False, ): """ Get the list of playlists, given the streaming platform. https://api.chartmetric.com/api/playlist/:streamingType/lists **Parameters** - `stype`: string streaming plat...
b506a22fd70f69be582484fdb1dabbdfc58ae22a
54,879
def convert_edu_categories_to_years(categories,age_finished_education): """ Converts education categories to years based ob the dictionary 'CamCan2eduyrs'. inputs: categories: list of categories separated with semicolon age_finished_education: age finished full-time education. outp...
88e7ad2502919a6f61aab6f3e7dfba325af76aed
54,880
import struct def ReadUint64(fileBytesIO:BytesIO): """ Reads an unsigned long (uint32) from the current position. """ format = ">Q" rawbytes = ReadRawBytes(fileBytesIO, struct.calcsize(format)) val, = struct.unpack(format, rawbytes) return val
180f4188bf7f7bd4b8f272666340ad9acdc69961
54,881
import argparse def parse_args(): """Parse command line arguments""" parser = argparse.ArgumentParser(prog='Metasploit RPC Library') parser.add_argument('command', choices=['config', 'command', 'console']) return parser.parse_args()
ff4807507300b31159bf92560b02904765a83bdc
54,882
import logging import requests def fetch_exchange_forecast( zone_key1="JP-TH", zone_key2="JP-TK", session=None, target_datetime=None, logger=logging.getLogger(__name__), ) -> dict: """Gets exchange forecast between two specified zones.""" if not session: session = requests.session(...
a8d1e824d5a254b34f15ead03c100671f69ef017
54,883
def get_dx_dims(fname, dataset): """ Read array size of a specific group of Data Exchange file. Parameters ---------- fname : str String defining the path of file or file name. dataset : str Path to the dataset inside hdf5 file where data is located. Returns ------- ...
38c32b6ae65670e84296186ea33a2ce54ea7ea77
54,884
def adaptive_pixel_signals_from( pixels: int, pixel_weights: np.ndarray, signal_scale: float, pix_indexes_for_sub_slim_index: np.ndarray, pix_size_for_sub_slim_index: np.ndarray, slim_index_for_sub_slim_index: np.ndarray, hyper_image: np.ndarray, ) -> np.ndarray: """ Returns the (hyp...
a5af9249ffa8a9a2665a31b1bfba405c0c9e7247
54,885
import sys import subprocess def run_executable(cmd, env): """Runs an executable within Xvfb on Linux or normally on other platforms. Returns the exit code of the specified commandline, or 1 on failure. """ if sys.platform == 'linux2': if env.get('_CHROMIUM_INSIDE_XVFB') == '1': openbox_proc = None...
331dd188fac5d0da165b4b7c683578feab6ccbb6
54,886
def gpg_decrypt(cfg, gpg_config=None): """Decrypt GPG objects in configuration. Args: cfg (dict): configuration dictionary gpg_config (optional[dict]): gpg configuration dict of arguments for gpg including: homedir, binary, and keyring example: ...
9f128eb621799393783f750bb43941db8e5976f3
54,887
import yaml def get_info(dirs, parallel, resources=None): """Retrieve cluster or local filesystem resources from pre-retrieved information. """ # Allow custom specification of cores/memory in resources if resources and isinstance(resources, dict) and "machine" in resources: minfo = resources["...
cc805fe6406a1a803c60825c086c9dc0fb156e5a
54,888
def poly_gcd(a, b): """ Finds the greatest common divisor of two polynomials :math:`a(x)` and :math:`b(x)` over :math:`\\mathrm{GF}(q)`. This implementation uses the Extended Euclidean Algorithm. Parameters ---------- a : galois.Poly A polynomial :math:`a(x)` over :math:`\\mathrm{G...
1e0160426698747a959e38d3ca30906e22e6dd9f
54,889
def keyphrase_label_from(candidate_span, element, generic_label=True): """Receive candidate_span and element from dataset and return keyphrase label""" label = "NON-KEYPHRASE" if "keyphrases" in element and\ "keyphrase-id" in candidate_span and \ candidate_span["keyphrase-id"] in ele...
d9f6e4a0697c441f6b597eaf0695cbdc1cc81d61
54,890
def _calc_fracture_step_sizes(start_yx, ang): """ Calculate the sizes of steps dx and dy to be used when "drawing" the fracture onto the grid. Parameters ---------- start_yx : tuple of int Starting grid coordinates ang : float Fracture angle relative to horizontal (radians) ...
deb7a6c9c13b72005ff986ba0271044450af1c6c
54,891
def delete_user(email): """Delete an existing user. :param email: email of the user :return: True if user could be deleted or False if the user doesn't exist. """ db.connect() try: user = User.get(User.email == email) user.delete() return True except User.DoesNotExis...
cd586b930b47d8b0721300bd895eb863039c366c
54,892
import re def stripper(song: str, artist: str) -> str: """ Generate the url path given the song and artist to format the Genius URL with. Strips the song and artist of special characters and unresolved text such as 'feat.' or text within braces. Then concatenates both with hyphens replacing the blank spaces. Eg....
dc680085d61de798bf45c632106730a0b690ee29
54,893
def _generate_synthetic_gaps( mean: np.ndarray, covariance: np.ndarray, size: int, offset: int, threshold: int, seed: int ) -> np.ndarray: """Return numpy array with the coordinates of gaps in matrix mask. Parameters ------------------ mean: np.ndarray, Mean of biologica...
25872d2de9169f010ab40cdb49cce5eb6764969b
54,894
def getDistantAuthUrl(): """ """ auth_mode = config.AUTH_MODE log_.debug("getDistantAuthUrl / auth_mode : %s", auth_mode ) if auth_mode != 'internal' : auth_url_root_modes = { "default" : config.AUTH_URL_ROOT_LOCAL, "dev" : config.AUTH_URL_ROOT_LOCAL, "local" : config.AUTH_URL_ROOT_...
7a40f01fc07f99b1bad89e3a6275ea155c7d5c56
54,895
def build_tree(package_store, mkbootstrap, tree_variants): """Build packages and bootstrap tarballs for one or all tree variants. Returns a dict mapping tree variants to bootstrap IDs. If tree_variant is None, builds all available tree variants. """ # TODO(cmaloney): Add support for circular depe...
6afcb90c04bf873aa14e8a8a3f91b2f4b17f2041
54,896
def score_string(lm, s, k, c): """k: UID exponent; c: string cost""" return lm.score_string_UID(s, k) + c * len(s)
35533d52ec7f1c65f9b49c38b51d52c9fe8c0ef0
54,897
import random def formula_49(r, log, eps=1.e-7): """ Generate shifts from group translation. """ tx0, ty0, tz0 = 0, 0, 0 if(r.tx>eps): tx0 = random.normalvariate(0,r.tx) if(r.ty>eps): ty0 = random.normalvariate(0,r.ty) if(r.tz>eps): tz0 = random.normalvariate(0,r.tz) d_r_V = matrix.col((tx0,ty0,tz0)) ...
a5dc0039aec751738b117cfd263fe6d4f1161e18
54,898
def get_promising_zeros(mtx, R=3): """ Runs over the matrix and finds all indices of zeros that are neighboring a one. The same rule as in the greedy algorithm is used to determine if a position is promising. Result: positionList """ N = 2*R + 1 k = np.ones((N, N)) k[R, R] = 0 mt...
fe876072864d5adfadd47d6d32cc2b4c0d4be948
54,899