content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from typing import Optional from typing import Tuple from typing import Union def match_format( node: FormatNode, data: str, *, variables: Dict[VarName, VarDecl], values: Optional[Dict[VarName, Dict[Tuple[int, ...], Union[int, float, str]]]] = None, ) -> Dict[VarName, Dict[...
4d7cf10e7238f201c684e74f2f85d82ed9c52db3
70,300
def get_discussions(book_object): """ 获得本书所有的讨论 :param book_object: Book模型实例 :return: 本书所有讨论的列表 """ return book_object.discussions.order_by('-pub_date').all()
842a158a18e1e7a31579f409997d56a452f1cf61
70,301
def bagging_classifier(*args, **kwargs): """ same as in bagging_from_scratch() """ return BaggingClassifier(*args, **kwargs)
ac7965cc456c3a5f0722962ab779a5710dfe2b2c
70,302
def get_tool_path(folder, name, check=True, suffix=None): """Get tool path, returns pathlib.Path""" bin_dir = find_kit_dir('.bin') if not suffix: suffix = 'exe' name_arch = f'{name}{ARCH}' # "Search" tool_path = bin_dir.joinpath(f'{folder}/{name_arch}.{suffix}') if not (tool_path.exists() or name_arc...
37f398dfe0567db1d7b1125f1f7987bc76404db4
70,303
import google def load_tables(dataset, tablespecs): """Construct a dictionary of BigQuery tables given the input tablespec. Args: dataset: bigquery.Dataset tablespecs: list of strings of "NAME:DAYS", e.g. ["day:1"] Returns: client, {name: (bigquery.Table, incremental table name)} ...
9320488a9d0bdd3e15de4311d14c29cd1f295279
70,304
def get_last_shifts(user, count=5): """ Returns the last number of shifts of user :param user: User object :param count: Number of shifts to return. Default is 5 :return: Shift objects or None """ finished_shifts = Shift.objects.filter(employee=user, finished__isnull=False)[ :count ...
703998e841b3cf021219717e06409d01decb2317
70,305
def time_version(propagator, model, prop_kwargs=None, model_kwargs=None): """Measure the runtime of the specified version using the specified model. Args: propagator: The propagator object to use model: The model (such as one from test_scalar) to use Returns: Runtime in seconds ...
ec51e21c9392056352199b9f42db6c2211ff3f0a
70,306
import os import re import time def get_version(package): """ Return package version as listed in `__version__` in `__init__.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() mth = re.search("__version__\s?=\s?['\"]([^'\"]+)['\"]", init_py) if mth: return mth.group(1...
776afb3f41e18f2034bbd914b44018795ca13db3
70,307
def gen_service(cluster, bundle=None, prototype=None) -> models.ClusterObject: """Generate service of specified cluster and prototype""" if not prototype: bundle = bundle or gen_bundle() prototype = gen_prototype(bundle, 'service') return models.ClusterObject.objects.create( cluster=...
5b39a0d169f0a3d49c11d4ce9624212e0ee176b3
70,308
import logging def _get_log_level(log_level_string): """return the logging log leve. Validates log_level_string is a valid value""" log_level = '' if log_level_string == 'DEBUG': log_level = logging.DEBUG elif log_level_string == 'INFO': log_level = logging.INFO elif log_level_...
e834600b0c07f5c48e82c03aa64ee373de65ff4f
70,309
def compute_kepler_orbit( a, e, inc_0, omega, Omega_0, M_0, t, delta_n=0, inc_dot=0, Omega_dot=0, C_uc=0, C_us=0, C_ic=0, C_is=0, C_rc=0, C_rs=0, ref_sys='ECEF', GM=defaults.EARTH_GM(), ome...
51477f90f3c17223f4382aaf2e5b48d8079642fc
70,310
import logging def phoneme_is_ok(path_mono_align_lab, path_mono_score_lab): """ 音素数と音素記号が一致するかチェックする。 """ mono_align_label = up.label.load(path_mono_align_lab) mono_score_label = up.label.load(path_mono_score_lab) # 全音素記号が一致したらTrueを返す for mono_align_phoneme, mono_score_phoneme in zip(mono_...
4a65ef10aa15db9548a24cca2c7bebde57598d5d
70,311
def batchnorm_forward(x, gamma, beta, bn_param): """ Forward pass for batch normalization. During training the sample mean and (uncorrected) sample variance are computed from minibatch statistics and used to normalize the incoming data. During training we also keep an exponentially decaying run...
04a55f6bd07f15927800ac82a97442bb81950d16
70,312
from typing import Type from re import T from typing import Union def try_enum(cls: Type[T], val, default: D = None) -> Union[T, D]: """Attempt to convert a value into their enum value. Parameters ---------- cls: :class:`Enum` The enum to convert to. val: The value to try to conve...
4a5f25dbc2d71655388252aab40f71e332eeebdd
70,313
def SimInspiralNRWaveformGetRotationAnglesFromH5File(h5File,inclination,orb_phase): """ Compute the angles necessary to rotate from the intrinsic NR source frame into the LAL frame. See DCC-T1600045 for details. Implementation copied from https://github.com/lscsoft/lalsuite/blob/d6e071988b46ec4497a...
2551248ee7578cda998e47d4fb0c717b7f1fab5a
70,314
def char_cnn_model(x, y): """Character level convolutional neural network model to predict classes.""" y = tf.one_hot(y, 15, 1, 0) byte_list = tf.reshape(learn.ops.one_hot_matrix(x, 256), [-1, MAX_DOCUMENT_LENGTH, 256, 1]) with tf.variable_scope('CNN_Layer1'): # Apply Convolution fi...
3254a81f4030a4c661ccee40437a7da3f4275e80
70,315
import os def query_all_libraries(repository_root_path, packages): """ Given a list of (BUILD.pom) packages, walks the paths up to find the root library directories, and returns those (without duplicates). """ lib_roots = set() for package in packages: while len(package) > 0 and packag...
382bb5d197ca6cf661a2646bc71c8fa87ee97fd6
70,316
def convert(root: 'TreeNode') -> 'TreeNode': """ 解法1:遍历两次。 """ if not root: return None inorder = [] def dfs(node): if node: dfs(node.left) inorder.append(node) dfs(node.right) dfs(root) for i, n in enumerate(inorder[:-1]): n.r...
a24d29d89459ec6be783fbc8d6f455665df7df68
70,317
import torch def batch_shuffle_ddp(x): # pragma: no-cover """ Batch shuffle, for making use of BatchNorm. *** Only support DistributedDataParallel (DDP) model. *** """ # gather from all gpus batch_size_this = x.shape[0] x_gather = concat_all_gather(x) batch_size_all = x_gather.shape[0...
6e49dbd4532054672d770d1f5825b13ce058a85d
70,318
def hostconfigurator(request, hosts): """Returns a configurator page with graphs on it""" stat, obj = parse() service_list = real_meta(hosts) return configurator(request, stat, obj, graphs=service_list)
272889a5e6cb9f37e0880853d0a13906fc186d9d
70,319
def process_args(*args, **kwargs): """returns a pair (artifact name, arg invocation)""" positional_kwargs = [] named_kwargs = [] for name in kwargs: if name.startswith('_'): positional_kwargs.append(name) else: named_kwargs.append(name) positional_kwargs.sort() named_kwargs.sort(...
a3ee66317b8309c7f49e543ece46bdb4024c5002
70,320
def create_graph(mdl, feature_names=None, cmap=None): """ Display a graph of the decision tree. Args: mdl (obj): Model used for prediction. feature_names (list): Names of the features. cmap (obj): Colormap. Returns: graph (obj): Graphviz graph. Example usage: ...
8e9131a2811e9eb32340fbd06d381df7e3d74f88
70,321
import json import html def build_alerts_elements(images_url_live_alerts, live_alerts, map_style): """ This function is used in the main.py file to create alerts-related elements such as the alert button (banner) or the alert markers on the map. It takes as arguments: - 'images_url_live_alerts':...
666c16029b73839107d0e9280416164a549ca565
70,322
import inspect def list_formatter(cls): """ This returns a function to map a given list of dictionaries to a list of class instances via a _from_dict class method. There is a corner case in which a passed in class might be a primative like a string. This also handles that case by skipping the...
a54f4c37a13343701133780dedc2dc3979cabde2
70,323
def get_edge_to_unique_attr(edgelist, src_col, dst_col): """Get a map from edge indexes to unique attribute indexes. Parameters ---------- edgelist : DataFrame Each row of the dataframe should contain the source, destination, and attributes of an edge. src_col : str Column name for ...
8d9c0a4871b9be6ba3f67eb6efc1cdbd711d18e8
70,324
def make_matrix_horizontal(l): """ Get the matrix with dimension 1*n needed for n*n masks, from an 1D list """ return np.array(l).reshape(1, -1)
345c1e075f6411f987b4edb34eb8bb1a92fe6612
70,325
def update_validator_registry(state: BeaconState, config: Eth2Config) -> BeaconState: """ Update validator registry. """ current_epoch = state.current_epoch(config.SLOTS_PER_EPOCH) # The active validators active_validator_indices = get_active_validator_indices(state.validator_registry, current_e...
934d378f5d299e98bed7a608fb3b1376cdaaf154
70,326
def membership_in_stream(in_stream, out_stream, membership_object): """ Parameters ---------- in_stream: Stream The input stream of the agent. Each element of the input stream is a pair: (function_name, string) where function_name is a string which is one of 'a...
8d145ef195da13f4e2078a661277b71deeecaf23
70,327
def _object_format(o): """ Object arrays containing lists should be printed unambiguously """ if type(o) is list: fmt = 'list({!r})' else: fmt = '{!r}' return fmt.format(o)
c71c0713d5b44c4733bc934d6026431e919db252
70,328
import copy def tensor_matrix_mult(X, V, n=None, Transpose=False, use_gpu=True): """ tensor_matrix_mult: Tensor times matrix. Parameters ---------- X: Tensor with N modes V: 2D array n: mode of tensor X to which to multiply the matrix by Transpose: Should we ro...
22a76d58909cb2b1213a3c2a5bb42d784bf7758a
70,329
import traceback def handle_error(error): """Error handler when a routed function raises unhandled error""" print(traceback.format_exc()) return 'Internal Server Error', 500
d93d3c4bbabb578b28ade961bb46793187a5ee06
70,330
def cifar100_rnn_gate_74(pretrained=False, **kwargs): """SkipNet-74 with Recurrent Gate""" model = ResNetRecurrentGateSP(BasicBlock, [12, 12, 12], num_classes=100, **kwargs) return model
2f4d40f804237972364bcd322ce3a6c6d8261ea0
70,331
def appliance_status_json(): """ Appliance Status JSON call :return: """ return jsonify(verify_appliance_status())
93a117a20f602e05b34bdf8df70e9c0784422708
70,332
import os def plot_recall(out_fold): """ plot barplot recovery complexes for every condition """ csfont = {"fontname": "sans-serif"} fig, ax = plt.subplots(figsize=(6, 6), facecolor="white") repo = os.path.join(out_fold, "ComplexReport.txt") repo = pd.read_csv(repo, sep="\t") repo = re...
964733761fbd476eece59bcad6c7e55acda4df91
70,333
import numpy def equalization(img): """ Função que equaliza o histograma :param img: a imagem a aplicar a equalização :return: O histograma equalizado """ h,r = numpy.histogram(img, bins=256, range=(0, 256)) p = h/float(dim[0] * dim[1]) pa = numpy.cumsum(p) pa_norm = pa*255 equ...
02d55f2dd848848062d340fccb5a8aede4ee6c9f
70,334
from typing import Optional def filter_by_chart( chart_filter_pattern: Optional[FilterPattern], chart_name: str ) -> bool: """ Return True if the schema needs to be filtered, False otherwise Include takes precedence over exclude :param chart_filter_pattern: Model defining chart filtering logic ...
22e24e91eb85bc4cdcc1bdb638eea9c008bcde6e
70,335
def get_agencies_dict(agencies_file): """ Pulls agencies list into a dictionary for use in abbreviations pipeline. Args: agencies: file of the agency documents. currently set to agencies.csv Returns: dictionary of all agencies """ df = pd.read_csv(agencies_file) aliases = {...
eb80f30f570913959b63c0bc8a215d9d7942b19e
70,336
def compute_batch_indices(batch_size, k): """ Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: bat...
d342ced62fc776b78ff940be55c05497639d5897
70,337
def _set_conditions(condition_list): """Returns an argument for config_settings that sets specific options. Args: condition_list: a list of three booleans Returns: a dictionary parameter for config_settings such that ":conditionN" is True iff condition_list[N + 1] is True """ ...
a1d4443a8f638754d8ece8692ab702f80670c09a
70,338
def getAvgEvalScores_ofTrainRuns(nr_runs,X_train,y_train,ID_train,label_dict, scores_list, print_flag): """ Get the average scores of the specified score list from a number of runs. Args: nr_runs (int): number of runs. X_train (dataframe of features, once removed the columns of label an...
6ceeb648463a88cf0cc671c65049ab82196830b1
70,339
import os def pretty_path(input_path): """ return path string replacing '~' for home directory """ home_path = os.path.expanduser('~') cwd_path = os.getcwd() output_path = input_path.replace(home_path, '~').replace(cwd_path, './') return output_path
b10bc85e4fba7ac7c73b53bc2bf5c8a61573e39f
70,340
import colorsys def scale_lightness(rgb, scale_l): """ Scales the lightness of a color. Takes in a color defined in RGB, converts to HLS, lightens by a factor, and then converts back to RGB. """ # converts rgb to hls h, l, s = colorsys.rgb_to_hls(*rgb) # manipulates h, l, s values and retu...
2fee635f26419cfe8abc21edb0092a8c916df6ef
70,341
def get_hw_type_from_client(hw_client) -> HWType: """ Return hardware wallet type (HWType) based on reference to a hw client. """ if hw_client: t = type(hw_client).__name__ if t.lower().find('trezor') >= 0: return HWType.trezor elif t.lower().find('keepkey') >= 0: ...
02946f1284705bc06e89874f240b0dbfb93b5f55
70,342
def kmeans(X, n_features, batch_size, n_iterations, verbose=False): """ Finds kmeans for X. Parameters: X: 2D matrix with shape: (n_samples, dimensions) config: n_features: number of centers (k). NOTE: the final k can be less than n_features since this code ...
29a0c8f378c22f77dc699e3b87ceffa0b4391779
70,343
def fit_linreg_robust(x, y, mask=None, intercept=False, r2=True, est_method='rlm'): """Apply robust linear regression of y w.r.t x. Arguments --------- x: :class:`~numpy.ndarray` or sparse `csr_matrix` A vector of independent variables. y: :class:`~numpy.ndarray` or sparse `csr_matrix` ...
6b6372a2aa0a7239b7e3598c8972f25fea62260b
70,344
def emg_process(emg, sampling_rate=1000, emg_names=None, envelope_freqs=[10, 400], envelope_lfreq=4, activation_treshold="default", activation_n_above=0.25, activation_n_below=1): """ Automated processing of EMG signal. Parameters ---------- emg : list, array or DataFrame EMG signal array....
bd95e1a8708bce5fda3ca7c5274363faa2bcea36
70,345
def peek(src: TextIOBase, n: int = 1) -> str: """Read up to `n` bytes from `src` without advancing the offset""" with peeking(src): return src.read(n)
5975dc8c94c262e700281120c81eb936adf677d6
70,346
def generate_key(**kwargs): """ Generates a new RSA private key. :param size: :param key_gen: :param kwargs: :return: """ key_gen = kwargs.get("key_gen", default_key_gen) return key_gen(**kwargs)
ae8355e4a3dfc62af24c947b3526b0892ea36d03
70,347
import torch def dummy_compute() -> torch.Tensor: """ returns a predefined size random Tensor """ return torch.rand(100, 100)
9b1c05359c9b57573bd2771124e878ccee7eae87
70,348
import typing def validator(*kinds: typing.List[str], collect=True, raise_on_invalid_kind=False) \ -> typing.Callable: """ decorator to generate validator functions. Expects LintError exceptions on invalid configurations. """ def add(f: typing.Callable): @wraps(f) ...
baee56ab9d7ed2aa9f538567e75d11f189d9c708
70,349
def mlp_net_input(h, w, b): """ Return the network input z as a function of h, w, and b. :param h: the input from the previous layer. :param w: the weights for this layer. :param b: the biases for this layer. :return: the linear network activations for this layer. """ result = np.dot(h, ...
21c035ea5c8704d27bd53e22cd253113cd602e61
70,350
import json async def get_schedules_handler( request: Request, ip_address: str, phone_id: str, device_id: str, device_password: str, ) -> HTTPResponse: """Use for handling requests to /switcher/get_schedules. Args: request: ``sanic``'s request object. ip_address: the local ip ...
14e54ec0872689a7730e6c9b26de4bf100423ea4
70,351
def extractPrefix(x, prefix_length, as_string): """ Returns an IPNetwork object of the ipaddress module created using ip address `x` given as string with a prefix length of `prefix_length` x (String): ip address prefix_length (int): number of bits to use as a prefix as_string (boolean) : ...
4fa68867ebebac28b2fd69fd7b33146be81e2fa3
70,352
import os def get_fallback_executable(command_name='vmrun'): """Get a fallback executable for a command line tool.""" if 'PATH' in os.environ: LOGGER.debug("os.environ['PATH']:%s", os.environ['PATH']) for path in os.environ['PATH'].split(os.pathsep): vmrun = os.path.join(path, comm...
c421aa3b1c1e492f42e57dcef05b40182fcfe3d1
70,353
def vel_distance(v1, v2, theta): """ Velocity distance. The Equation (2) of Mould et al. (2000). Parameters ---------- v1 : float The velocity of the first object, units: km/s. v2 : float The velocity of the second object, units: km/s. theta : float The angular dist...
f34354d6f8ef6c731c329524db9fbcefe4bb1ba9
70,354
def for_list_lang(context): """Вывод списка языков""" return settings.LANGUAGES
081a0ee93ce0901827407abeb711f6763dc67eb7
70,355
from typing import Optional from typing import List import logging import itertools def _process_table_identifiers( pdf: DataFrame, dimension_combinations: Optional[List[List[str]]] = None, max_combination_length: int = 5 ) -> List[List[str]]: """ Dask wrapper around extracting identifiers from a single s...
7d7d81723310be77808109f236fc595705b0464c
70,356
def raster2array(rasters,band_no=1): """ Arguments: rast A gdal Raster object band_no band numerical order Example : raster = gdal.Open(rasterfn) raster2array(raster,1) """ bands = rasters.RasterCount if band_no>0 and band_no <=bands: band = rasters.Get...
76bdcffbf22a0936fe24c29eba975f21edd7cd41
70,357
def early_stopping(cost, opt_cost, threshold, patience, count): """ Determines if you should stop gradient descent. Early stopping should occur when the validation cost of the network has not decreased relative to the optimal validation cost by more than the threshold over a specific patience count ...
5baea9f867e8ca8326270f250327494a5c47af46
70,358
def search(): """search for a specific item""" searchword = request.args.get('search', '') json = request.args.get('json', '') if not json: # if the user didn't provide a search word return error message. if not searchword: return render_template("mes.html", error="must prov...
adeff4717d9884a6c903aa7aeb10c0f22e40df06
70,359
def diameter(domain): """ Returns the diameter of a domain. :param domain: a domain :type domain: `escript.Domain` :rtype: ``float`` """ return sqrt(sum( [ v**2 for v in boundingBoxEdgeLengths(domain) ] ))
8fe13ecf19f96ea624f0a2d20f165033593bc3ad
70,360
import asyncio def chain_execution(commands): """ Executes given commands sequential. If one commands fails all other commands fail too. """ result = [] error = False for command in commands: try: cmd = Command( command["method"], uuid=c...
d06be2a3f9395343be5787d248e95e1996b9ec9a
70,361
import os def _wait(): """Replacement for perl wait() call""" global CHILD_ERROR try: (pid, stat) = os.wait() CHILD_ERROR = stat return pid except Exception: return -1
e3b5e41ebea00f8c57827e3455db667118271fe9
70,362
import random import sys def next_positive_random(modulus): """Calculates a positive random number in the range(0, modulus - 1). Parameters ---------- modulus : int Modulus of the operation. Returns ------- int New positive random integer. """ rn = random.randint...
63b0493d5eecb960eea0f2d33f2a17ea7ed0d49b
70,363
import json def export_roast(): """Export a roast log.""" c = mongo.db[app.config['HISTORY_COLLECTION']] roast_id = request.args.get('id') roast_id = paranoid_clean(roast_id) item = c.find_one({'_id': ObjectId(roast_id)}, {'_id': 0}) if not item: return jsonify({'success': False, 'mess...
deb25421561c6e66782c351ccfa4f6b82f94e898
70,364
def tagset_mapping(source, target): """ Retrieve the mapping dictionary between tagsets. >>> tagset_mapping('ru-rnc', 'universal') == {'!': '.', 'A': 'ADJ', 'C': 'CONJ', 'AD': 'ADV',\ 'NN': 'NOUN', 'VG': 'VERB', 'COMP': 'CONJ', 'NC': 'NUM', 'VP': 'VERB', 'P': 'ADP',\ 'IJ': 'X', 'V':...
fc1acd0d33dc201b1d692e84c1469d1899488f53
70,365
def beqs(screen, asof=None, typ='PRIVATE', group='General', **kwargs) -> pd.DataFrame: """ Bloomberg equity screening Args: screen: screen name asof: as of date typ: GLOBAL/B (Bloomberg) or PRIVATE/C (Custom, default) group: group name if screen is organized into groups ...
48db4985943383d62bcabe201206aecf7f2afc88
70,366
def generate_launch_description(): """Run demo nodes via launch.""" return LaunchDescription([ launch_ros.actions.Node( package='pub_sub_tests', executable='talker', output='screen', remappings=[('chatter', 'my_chatter')]), ])
578f9763da52cb8991f07c9e2f6a865069a170c3
70,367
def get_features(contour): """Get the three features that identify a corner marker""" try: return (cv2.contourArea(contour), cv2.arcLength(contour, True), cv2.contourArea(get_bounding_rect(contour))) except ZeroDivisionError: #return 4*[np.inf] return ...
54bfa67d8bc59b145ef93bc3ee29b00665e4c8ce
70,368
from alpa.pipeline_parallel.stage_construction import get_submesh_choices import os import pickle import ray import time def profile_all(device_cluster, cluster_key, max_comm_size_intra_node, max_comm_size_inter_node, max_fail_retry, cache_filename, dot_range=(0, 64)): """Profile c...
c5cc52cbd7c5164762e3f1b776446d17ccd342d3
70,369
import re def _MatchStaticFile(handler, path): """Match a path to a regular expression and return a StaticPage. Args: handler: A handler dictionary with a static_files field. path: The path portion of the url. Returns: A StaticPage object or None. """ pattern = handler['url'] if not pattern....
2dca79df358d0c51710f8d559d7d23139b8a378b
70,370
def apply_non_max_suppression(boxes, scores, iou_thresh=.45, top_k=200): """Apply non maximum suppression. # Arguments boxes: Numpy array, box coordinates of shape (num_boxes, 4) where each columns corresponds to x_min, y_min, x_max, y_max scores: Numpy array, of scores given for ea...
5651577e32a7dbb23400e354ff6527fbdb785a7c
70,371
def get_default_configuration(invocation_id, config_id=None): """ Returns a new Configuration with fields initialized to defaults. Args: invocation_id (str): The id of the invocation for the configuration. config_id (str): The id of the configuration. Returns: A new Configurati...
d5a82349bc5031869e919b2bee859b11a022362b
70,372
def cosh(input, name=None): """Element-wise hyperbolic cosine of a tensor.""" if is_tensor(input, 'tf'): return tf.math.cosh(input, name=name) else: return np.cosh(input)
aec39ba69b6c3836114338564fdde3b149e2b86b
70,373
def blockwise( func, output, output_indices, *arrind_pairs, numblocks=None, concatenate=None, new_axes=None, dependencies=(), **kwargs, ): """Create a Blockwise symbolic mutable mapping This is like the ``make_blockwise_graph`` function, but rather than construct a dict,...
0433678321afbff5d999185a98de6bdfb2a6f59f
70,374
import os def scan_videos_from_txt(file_list_path, extensions=()): """Get existing files from the file list .txt file.""" files = _read_lines(file_list_path) files = [x for x in files if os.path.isfile(x)] if len(extensions) > 0: files = filter_extensions(files, extensions) return files
ae2fc140528e58a7b6e03ce59ea1ede1b0c902fa
70,375
def extract_biofuel_shares_from_IAM( model, fp, IAM_region, years, allocate_all_synfuel=False ): """ This function extracts biofuel shares from a IAM file provided. :param fp: file path to IAM file :type fp: str :param IAM_region: IAM region for which to extract the biofuel shares :type IAM...
372412f6e2355cf8cc9c0c7ab19dac4b234d7668
70,376
import os def check_diagnostics_figure(): """ Simple check if .png figures were created. """ result = True fig = './tests/lakes/results/lakes_test_20190401_20190402/diagnostics_lakes_test.png' if not os.path.isfile(os.path.abspath(fig)): result = False return result
a626103d3d1886862eed5572948f318bb7f9bb57
70,377
def blendLayers( background: Image.Image, foreground: Image.Image, blendType: BlendType | tuple[str, ...], opacity: float = 1.0, ) -> Image.Image: """Blend layers using numpy array. Args: background (Image.Image): background layer foreground (Image.Image): foreground layer (must be same size as background) ...
df352c3d9bff6a7972a98984b8e032408bb5ac22
70,378
import importlib def class_from_class_path(class_path): """ Get a python class instance given the python "class path". EG: # >>> class_from_class_path("decimal.Decimal") # <class 'decimal.Decimal'> Args: class_path - str - dot-delimited python path followed by class name. Returns: class...
5584c827da786dec73b85026289a0580214d022d
70,379
def save_all_animations(): """Save all animation actions in Blender file """ animations = [] if len(bpy.data.armatures) == 0: return animations # get armature, assume single armature armature = bpy.data.armatures[0] try: obj_armature = bpy.data.objects[armature.name] ...
0e1d68459a69e1fe1e40b1aee921abf5c755442c
70,380
def is_if_then(tokens): """:note: we assume single-line if have been transformed in preprocessing step.""" return tokens[0:1+1] == ["if","("]
aa1a946ed94299e689534ca98dcf1d0fa9bdca32
70,381
import multiprocessing import os import subprocess import glob import traceback def multipart_s3_file_transfer(bucket, s3_key_name, tarball, mb_size, use_rr=True): """ file transfer above 5GB to s3 """ cores = multiprocessing.cpu_count() def split_file(in_file, mb_size, split_num=5): prefix = os....
d47902e0bedefa7ebf1640098ac07daf60fc8315
70,382
import os from datetime import datetime def batlogger2guano(fname): """Convert an Elekon BatLogger .WAV with sidecar .XML to GUANO metadata""" xmlfname = os.path.splitext(fname)[0] + '.xml' if not os.path.exists(xmlfname): raise ValueError('Unable to find XML metadata file for %s' % fname) g =...
16b93b1efa4576815c5336920a572d601bd6bfa1
70,383
def get_implline(cursor: Cursor) -> int: """ finds the first line of implementation source code for class method pointed by the cursor parameter. Args: cursor: libclang cursor pointing to the target mock class definition. Returns: an integer, the line number of the first line of the correspondi...
ad1fe32e6dba22a42ee2da0295e95490288e5daf
70,384
def inverse_dissim(X): """ :param X: int or np.array :return: """ X = np.asarray(X) X = zscore(X) X = minmax(X, 0, 10) return 1./(1+X)
87737ba4d425bb91d58060ef4aa535010099d002
70,385
import yaml def yaml_load(file): """ Load single-document YAML and return document """ with open(file, "r") as f: return yaml.safe_load(f)
76402fd742f5aaf1776751f44b3583a62c1f3581
70,386
import time def is_available(workshift_profile, shift): """ Check whether a specified user is able to do a specified workshift. Parameters: workshift_profile is the workshift profile for a user shift is a weekly recurring workshift Returns: True if the user has enough free time...
a847e3d7e91d4272c035a9a8dd609e20a0247b8a
70,387
def BuildEdgeFunction(function_ref, arch, source, function): """Calls Cloudbuild to build Edge Function. Args: function_ref: Edge function resource arch: str, target architecture, should be one of 'x86-64', 'armhf', or 'aarch64' source: str, GCS URI of source provided from command line functi...
f18c90a3db684b847bd3de2289802599e916656f
70,388
def convert_event_data_timestamp(ts): """ Convert the default event_data timestamp format to Pandas and unixtime format. Parameters ---------- ts : str UTC timestamp in custom API event data format. Returns ------- timestamp : datetime Pandas Timestamp object format. ...
99f4604b4a1c5d164dfcf4567c85fcf12e149337
70,389
import tempfile import zipfile def unzip_csar_to_tmp(zip_src): """ Unzip csar package to temp path :param zip_src: :return: """ dirpath = tempfile.mkdtemp() zip_ref = zipfile.ZipFile(zip_src, 'r') zip_ref.extractall(dirpath) return dirpath
b6be57f4e20c208583cc15dc9d0b997f6b41e2f1
70,390
import time from re import L def integrate_verlet(X, V, iparams, blist, sp): """ Verlet integration for Nt steps. Save each thermo-multiple step into xyz_frames. Mass set to 1.0. Input: * X: (N, 3) matrix * V: (N, 3) matrix * iparams: (Nbt, Nbt) matrix with interaction params * blist: ...
e9b60a294e257a87461afe8f745f61083f4a1075
70,391
import torch def seq_collate_fn(batch): """ Returns several tensors. Tensor of lengths should not be sent to CUDA. """ idx2batch = pd.Series(np.arange(len(batch)), index = [b["idx"] for b in batch]) df = pd.concat(b["path"] for b in batch) value_cols = [c.startswith("Value") for c in ...
2a1fcbd3ce386f5cc9b6851359ac7ade0d0e979a
70,392
def adminSummaryHomeView(request, dieName): """ An administrative view that displays a list of images and info about the typed information for each for the given Die. The administrator can see how much data has been entered for each image and click on the image to open a new view showing more detai...
95baa0450e730f85ab51a587c7df40691cc1a6cf
70,393
def get_device_fn(device): """Choose device for different ops.""" OPS_ON_CPU = set(get_cpu_list()) def _device_fn(op): # Startswith "Save" is a hack... if op.type in OPS_ON_CPU or op.name.startswith('save'): return '/cpu:0' else: # Other ops will be placed on...
fe7993d624d38f003311c4a7d1b010af5320c6f8
70,394
def handle_element(elem, args, func=None, func2=None): """ A helper function to handle elements from BeautifulSoup element.find() :param elem: BeautifulSoup Tag (element) :param args: args tuple for find method. String can be used for a single arg, otherwise tuple :param func: ad hoc fun...
7f63b4ec8f762bfdf427328eeec05846504ee8d8
70,395
def add_columns(input_header, input_rows, column_names, fill_with="NULL", in_place=True): """Add new columns filled with the requested value Parameters: input_header (list): List of column headers from input file input_rows (list): List of lists of fields from each i...
12979c354c0031f1ebc5f17d229a09dc59b020d3
70,396
from datetime import datetime def date2datetime(dt): """ date 类型转换问 datetime类型 :param dt: :return: """ return datetime(dt.year, dt.month, dt.day)
53bf2cabe3d8a70791cb92fb12387a78d0beedd7
70,397
import re def splitSentence(content): """ Given block of text, split into sentence Output: list of sentences """ # Multiple space to single space, remove separators like - and _ if pd.notnull(content): content = re.sub('\s*\t\t\t', ' ', content) content = re.sub('--+|==+|__+', ...
85a4eea6928f689b87a60edd2d4fe47b9f6d0a15
70,398
def save_data(outpath, header, row, data): """ Simple shortcut If `feather-format` is available, save data to `.feather` file otherwise `.csv` """ try: return save_data_to_R(outpath, header, row, data) except ImportError as e: return save_data_to_csv(outpath, header, row, data)
17e59bad3e68cab15b40d6e229c09842b62df3fe
70,399