content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_statement_at_line(source: str, lineno: int, checker): """Get statements at line *lineno* from a source string. :param source: The source to get the statements from. :param lineno: Line number which the statement must include. Counted from 1. :param checker: A function that checks each statement...
d2066f5fafa1c20c4b5276e44d82ae95ffa2f59b
15,300
def ptrace(Q, sel): """ Partial trace of the Qobj with selected components remaining. Parameters ---------- Q : :class:`qutip.Qobj` Composite quantum object. sel : int/list An ``int`` or ``list`` of components to keep after partial trace. Returns ------- oper : :cla...
a98e7bea41cff00b44534cecac7f86958ef47ebb
15,301
from operator import index def createConformations(outputfile, forcefield, smiles, sid): """Generate the conformations for a molecule and save them to disk.""" print(f'Generating {index}: {smiles}') try: mol = Molecule.from_smiles(smiles, allow_undefined_stereo=True) fftop = Topology() ...
fce6cb1c7620b755a500e76822aa3ac27b7a12f4
15,302
import numpy import math def two_angle_circular_correlation_coef(angles1, angles2, mean1, mean2): """ Circular correlation measure. SenGupta 2001 """ centered_a = angles1-mean1 centered_b = angles2-mean2 sin_centered_a = numpy.sin(centered_a) sin_centered_b = numpy.sin(centered_b) sin2...
6a95f8726f45105c68b9c0b4f8f13191a88734e2
15,303
from typing import Union import yaml def format_data(data: Union[dict, list]) -> str: """ :param data: input data :return: pretty formatted yaml representation of a dictionary """ return yaml.dump(data, sort_keys=False, default_flow_style=False)
b4e79a8957995fb8e2eaa549a6a208a48574a598
15,304
import os def fasta2select(fastafilename, is_aligned=False, ref_resids=None, target_resids=None, ref_offset=0, target_offset=0, verbosity=3, alnfilename=None, treefilename=None, clustalw="clustalw2"): """Return selection strings that will select equivalent residu...
b259f15cae11fa3a7678b3d143613996d49c61f3
15,305
def eval_on_dataset( model, state, dataset, pmapped_eval_step): """Evaluates the model on the whole dataset. Args: model: The model to evaluate. state: Current state associated with the model (contains the batch norm MA). dataset: Dataset on which the model should be evaluated. Should already ...
dd2296f80db37687de6fc8a4bcf0046d43cda115
15,306
import os def create_directory(path): """Creates the given directory and returns the path.""" if not os.path.isdir(path): os.makedirs(path) return path
7e1d254276b3f4fd4560e206d7a77b11c6dfdfae
15,307
def factorize(n): """ Prime factorises n """ # Loop upto sqrt(n) and check for factors ret = [] sqRoot = int(n ** 0.5) for f in xrange(2, sqRoot+1): if n % f == 0: e = 0 while n % f == 0: n, e = n / f, e + 1 ret.append((f, e)) if n >...
bc4b4a26010f2f18c9989acd2b7d81615b21f8db
15,308
import random def createSimpleDataSet( numOfAttr, numOfObj ): """ This creates a simple data base with 3 attributes The second one is 2 times the first one with some Gauss noise. The third one is just random noise. """ database = [] for i in range(numOfObj): data = data...
dd4e8005634bd49411a785982fe3112acaf8e544
15,309
import tqdm import warnings def clean_data( data, isz=None, r1=None, dr=None, edge=0, bad_map=None, add_bad=None, apod=True, offx=0, offy=0, sky=True, window=None, darkfile=None, f_kernel=3, verbose=False, *, mask=None, ): """Clean data. Par...
d50cb5b723661925c81f215e3bba903b4f9bb56c
15,310
def select_points(): """ Select points (empty) objects. Parameters: None Returns: list: Empty objects or None. """ selected = bpy.context.selected_objects if selected: return [object for object in selected if object.type == 'EMPTY'] print('***** Point (empty) object...
4134277f427518da188d8bcac4d5023d0b39e55a
15,311
import sys def _get_best_encoding(stream): """Returns the default stream encoding if not found.""" rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding() if _is_ascii_encoding(rv): return 'utf-8' return rv
c27739e48395e32457ad7955dcc70a3c0a9973bb
15,312
def mask_conv1d1(in_channels, out_channels, strides=1, groups=1, use_bias=False, data_format="channels_last", **kwargs): """ Masked 1-dim kernel version of the 1D convolution layer. Parameters: -------...
0c06482e36ef55322ed3b52e68f321750843ef01
15,313
import decimal def decimal_from_tuple(signed, digits, expo): """Build `Decimal` objects from components of decimal tuple. Parameters ---------- signed : bool True for negative values. digits : iterable of ints digits of value each in [0,10). expo : int or {'F', 'n', 'N'} ...
c3b67505440600b5e9f3ce944c9018539b32bbf7
15,314
from typing import Dict def metadata_update( repo_id: str, metadata: Dict, *, repo_type: str = None, overwrite: bool = False, token: str = None, ) -> str: """ Updates the metadata in the README.md of a repository on the Hugging Face Hub. Example: >>> from huggingface_hub impor...
1faf2ae158d598a7538f86ce328ea22b55308507
15,315
def convertStringToArabic(numStr, stripChars=0): """ Convert a string to an arabic number; Always returns numeric! 12-09-2004: Changed default stripChars to 0, because otherwise a roman I was stripped before processing! Need to watch for programs that need to now explicitly set stripChar...
17020a3131b91aeb8cfc63ee5c04d827c8585478
15,316
import logging def set_logging(): """Sets additional logging to file for debug.""" logger_migrator = logging.getLogger('migrator') logger_migrator.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - ' '%(message)s - \n ' ...
8de4def9910d2ffb94631b6505c26e2a2dbcb632
15,317
def system_types(): """ 系统类型(工作空间类型) :return: """ return Workspace.sys_types().values()
968fbf7993d4ad645fe741ac48702440ba01a2e3
15,318
def get_rnd_simplex(dimension, random_state): """ Uniform random point on a simplex, i.e. x_i >= 0 and sum of the coordinates is 1. Donald B. Rubin, The Bayesian bootstrap Ann. Statist. 9, 1981, 130-134. https://cs.stackexchange.com/questions/3227/uniform-sampling-from-a-simplex Parameters ----...
d5e1105655192fe13bcad5e3dd08a7247461d8bf
15,319
def backup_generate_metadata(request, created_at='', secret=''): """ Generates metadata code for the backup. Meant to be called by the local handler only with shared secret (not directly). """ if not secret == settings.GAEBAR_SECRET_KEY: return HttpResponseForbidden() backup = models.GaebarBackup.all...
30ae381be8454a1df6b47fd5fc55af68f10e8b1f
15,320
import torch def contains_conv(module: torch.nn.Module) -> bool: """ Returns `True` if given `torch.nn.Module` contains at least one convolution module/op (based on `deepcv.meta.nn.is_conv` for convolution definition) """ return any(map(module.modules, lambda m: is_conv(m)))
0f9ae25fa1189c9c576089c913a5d7d9e2739c78
15,321
def _construct_cell(empty=False): """Constructs a test cell.""" cell = scheduler.Cell('top') if empty: return cell rack1 = scheduler.Bucket('rack:rack1', traits=0, level='rack') rack2 = scheduler.Bucket('rack:rack2', traits=0, level='rack') cell.add_node(rack1) cell.add_node(rack2)...
c1b8016b8ff048ab0ecad8c69f960ce3d099bd8c
15,322
def gaussian_kernel(F: np.ndarray) -> np.ndarray: """Compute dissimilarity matrix based on a Gaussian kernel.""" D = squared_dists(F) return np.exp(-D/np.mean(D))
62f97009c791213255d8bdb4efc0fcfa60c20bb0
15,323
def _parse_yearweek(yearweek): """Utility function to convert internal string representations of calender weeks into datetime objects. Uses strings of format `<year>-KW<week>`. Weeks are 1-based.""" year, week = yearweek_regex.search(yearweek).groups() # datetime.combine(isoweek.Week(int(year), int(week)).w...
319166595c506a73d125ed53a11433976aa4f106
15,324
def get_subpixel_indices(galtable, hpix=[], border=0.0, nside=0): """ Routine to get subpixel indices from a galaxy table. Parameters ---------- galtable: `redmapper.Catalog` A redmapper galaxy table master catalog hpix: `list`, optional Healpix number (ring format) of sub-region....
5a2d18f79ef8cc478752ef8059c71a512efced9f
15,325
def is_common_secret_key(key_name: str) -> bool: """Return true if the key_name value matches a known secret name or pattern.""" if key_name in COMMON_SECRET_KEYS: return True return any( [ key_name.lower().endswith(key_suffix) for key_suffix in COMMON_SECRET_KEY_SUFF...
b0250f28638a0ad58a3a45dd8e333610fea378d5
15,326
from sys import path def check_md5(func): """ A decorator that checks if a file has been changed. """ @wraps(func) def wrapper(*args, **kwargs): ret = func(*args, **kwargs) assert _check_md5(path, original_path), 'The file has been changed after {}().'.format(func.__name__) return ...
bb7dcae110be816af1796cdd66c7b9d74e7c265d
15,327
def showgraphwidth(context, mapping): """Integer. The width of the graph drawn by 'log --graph' or zero.""" # just hosts documentation; should be overridden by template mapping return 0
6e2fad8c80264a1030e5a113d66233c3adc28af8
15,328
def diff_last_filter(trail, key=lambda x: x['pid']): """ Filter out trails with last two key different """ return trail if key(trail[-1]) != key(trail[-2]) else None
82e67a98a1b09e11f2f1ebd76f470969b2dd1a51
15,329
def cpu_times(): """Return a named tuple representing the following system-wide CPU times: (user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]) Last 3 fields may not be available on all Linux kernel versions. """ procfs_path = get_procfs_path() set_scputimes_n...
70dd518296bc873add8a7164446e908d80e74174
15,330
def calc_centeroid(x, network: DTClustering, n_clusters: int): """クラスタ中心を計算します. Notes: Input x: [batch, sequence, feature, 1] Output: [n_clusters, hidden sequence, hidden feature, 1] """ code = network.encode(x) feature = code.view(code.shape[0], -1) # [batch, sequence * feature] ...
cf0a158d86105e34ad476dbfb7bc6ff911a65e52
15,331
def start_run(): """ Starts at test run.. TODO all of it. """ uuid = request.form.get('uuid', default='none', type=str) print('Starting a run: %s' % uuid) return "ok"
49b304801cb1ff9875f16c9f66253ff282087692
15,332
def softXrayMono1(eV, k, m, c, rb_mm, bounce, inOff_deg, outOff_deg, verbose): """ # calculate premirror and grating angles for NSLS-II soft xray monos # eV: energy # k: central line density in mm-1 # m: diffraction order # c: cff 0 < cff < infinity # bounce = 'up' or 'down' # inOff_deg ...
3309b8ec7e3f5433025c4c676bf2966281df4d02
15,333
def createHelmholtz3dExteriorCalderonProjector( context, hminusSpace, hplusSpace, waveNumber, label=None, useInterpolation=False, interpPtsPerWavelength=5000): """ Create and return the exterior Calderon projector for the Helmholtz equation in 3D. *Parameters:* - context (Context) ...
bfb6c139787355d07cb8c82475f34dcc349c55f3
15,334
def prepare_xrf_map(data, chunk_pixels=5000, n_chunks_min=4): """ Convert XRF map from it's initial representation to properly chunked Dask array. Parameters ---------- data: da.core.Array, np.ndarray or RawHDF5Dataset (this is a custom type) Raw XRF map represented as Dask array, numpy ar...
a8c4b442f367759237f77571c51e98bd1cc9d53a
15,335
def colorbar_factory(cax, mappable, **kwargs): """ Create a colorbar on the given axes for the given mappable. .. note:: This is a low-level function to turn an existing axes into a colorbar axes. Typically, you'll want to use `~.Figure.colorbar` instead, which automatically handle...
37b0198ea77db887d92ee4fd45e6df73d49f4223
15,336
import time def fourth_measurer_I_R(uniquePairsDf): """ fourth_measurer_I_R: computes the measure I_R that is based on the minimal number of tuples that should be removed from the database for the constraints to hold. The measure is computed via an ILP and the Gurobi optimizer is used to solve the ILP...
a8e29e0a70dfd2e2a4c151ca25b2f7fd528e25f3
15,337
def is_sublist_equal(list_one, list_two): """ Compare the values of two lists of equal length. :param list_one: list - A list :param list_two: list - A different list :return EQUAL or UNEQUAL - If all values match, or not. >>> is_sublist_equal([0], [0]) EQUAL >>> is_sublist_equal([1],...
717b4287e212498ef85719fbf4d8e5437f16db48
15,338
def black_box_function(x, y): """Function with unknown internals we wish to maximize. This is just serving as an example, for all intents and purposes think of the internals of this function, i.e.: the process which generates its output values, as unknown. """ return -x ** 2 - (y - 1) ** 2 + 1
962c0dd5638ac71ee375f4bb1ba07b2bd241a6e8
15,339
def file_extension(path): """Lower case file extension.""" return audeer.file_extension(path).lower()
264f8afd0a2328d342693b2ec893706760b5c7ae
15,340
import os def locate(verbose): """Print location of the current workspace. :param verbose: Unused. """ if not os.path.islink(ws_file): print('no current workspace found, see "ros-get ws-create --help" how to create one') return 1 else: print(os.path.realpath(ws_file))
75e9d90cba4c8394fdbc18e505fe19120bd1c5dd
15,341
import math def motion(x, u, dt): """ motion model """ x[2] += u[1] * dt x[0] += u[0] * math.cos(x[2]) * dt x[1] += u[0] * math.sin(x[2]) * dt x[3] = u[0] x[4] = u[1] return x
e33adae2a6c5934dc7e0662570c42292eacbfd89
15,342
from typing import Union from typing import Callable def sweep( sweep: Union[dict, Callable], entity: str = None, project: str = None, ) -> str: """Initialize a hyperparameter sweep. To generate hyperparameter suggestions from the sweep and use them to train a model, call `wandb.agent` with the sweep...
50ba0d79a8fca5d5eba08b4e739845b797c0c839
15,343
def connection_end_point (id, node_uuid, nep_uuid, cep_uuid): """Retrieve NodeEdgePoint by ID :param topo_uuid: ID of Topology :type uuid: str :param node_uuid: ID of Node :type node_uuid: str :param nep_uuid: ID of NodeEdgePoint :type nep_uuid: str :param cep_uuid: ID of ConnectionEndP...
76dc345732d3209730b6022ba12cb2ca191e4a40
15,344
def remove_melt_from_perplex(perplex,melt_percent=-1): """ Extrapolate high temperature values to remove melt content using sub-solidus values. The assumption is that alpha and beta are constant and temperature-independent at high temperature.""" Tref = 273 Pref = 0 rho = perplex.rho.re...
6d2473d7147cdecdcd64cbb7e3beafd3b5df5c6a
15,345
def similarity_score(text_small, text_large, min_small = 10, min_large = 50): """ complexity: len(small) * len(large) @param text_small: the smaller text (in this case the text which's validity is being checked) @param text_large: the larger text (in this case the scientific stud...
8449b5273909382225f9de43d8fb936424d1a43e
15,346
def abline(a_coords, b_coords, ax=None, **kwargs): """Draw a line connecting a point `a_coords` with a point `b_coords`. Parameters ---------- a_coords : array-like, shape (2,) xy coordinates of the start of the line. b_coords : array-like, shape(2,) xy coordiantes of the end of th...
e262b689046ac5dd75152b8472a841c7a1e5db29
15,347
def get_extensions(): """ Returns supported extensions of the DCC :return: list(str) """ return ['.hip', '.hiplc', '.hipnc', '.hip*']
414391db5cd4f8989967100bae347e741ca4b46c
15,348
from datetime import datetime import os def precheck_data_format(idir, hlsp_name): """ Generates parameter file for check_metadata_format based on file endings. :param idir: The directory containing HLSP files to check. :type idir: str :param hlsp_name: The name of the HLSP. :type hlsp_nam...
4e8c99fa83bee879ebba73c3ef0229ffd32acd40
15,349
def calc_spatially_diffusion_factors( regions, fuel_disagg, real_values, low_congruence_crit, speed_con_max, p_outlier ): """ Calculate spatial diffusion values Arguments --------- regions : dict Regions fuel_disagg : dict Disa...
95361bb3f8ba5d3d47cd1a4ad065ec857e291f7b
15,350
def get_set(path): """Returns a matrix of data given the path to the CSV file. The heading row and NaN values are excluded.""" df = pd.read_csv(path, sep=';', encoding='latin') return df.dropna(subset=['PMID1', 'PMID2', 'Authorship'], how='any').values
aa701f440a9535d534826a50e8803fa0095bda25
15,351
from typing import Callable from typing import Any import os import logging def _client_get(client_create_fn: Callable[..., Any], params: ClientGetParams) -> Any: """ :param client_create_fn: the `boto3.client` or `boto3.resource` function """ which_service = params.boto3_client_name endpoint_url ...
19f3ff3238768a3bea4884a7b5be21e69a749ebc
15,352
import os from datetime import datetime def parse_metadata_from_sensorcommunity_csv_filename(filename): """Parse sensor id, sensor type and date from a raw luftdaten.info AQ .csv filename. Parameters: filename (path): the file to parse. Format of the file is expected to be the one use...
3b16a945930311fdbb0094956c8a58fa5f4b5a70
15,353
def gaussian_target(img_shape, t, MAX_X=0.85, MIN_X=-0.85, MAX_Y=0.85, MIN_Y=-0.85, sigma2=10): """ Create a gaussian bivariate tensor for target or robot position. :param t: (th.Tensor) Target position (or robot position) """ X_range = img_shape[1] Y_range = img_shape[2] XY_range = np.arang...
47fbb46e2e46b1a4cc2cec3906e9c0dfb5282c0e
15,354
def XMLToPython (pattern): """Convert the given pattern to the format required for Python regular expressions. @param pattern: A Unicode string defining a pattern consistent with U{XML regular expressions<http://www.w3.org/TR/xmlschema-2/index.html#regexs>}. @return: A Unicode string specifyin...
14072879e11ea0425903be314fdba6fb8bfd2538
15,355
import fcntl import termios import struct def __termios(fd): """Try to discover terminal width with fcntl, struct and termios.""" #noinspection PyBroadException try: cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except Exception: retur...
78f3450d65a453cfd22c575bbddb77fcfbef1496
15,356
def encode(numbers, GCE=GCE): """ do extended encoding on a list of numbers for the google chart api >>> encode([1690, 90,1000]) 'chd=e:aaBaPo' """ encoded = [] for number in numbers: if number > 4095: raise ValueError('too large') first, second = divmod(number, len(GCE)) ...
9a15134e0266a0dfc60b654b9da8d2a6169bee7f
15,357
def compute_f_mat(mat_rat,user_count,movie_count): """ compute the f matrix :param mat_rat: user`s rating matrix([user number,movie number]) where 1 means user likes the index movie. :param user_count: statistics of moive numbers that user have watch. :param movie_count: statistics of user numbers t...
ff13544c28dde9025630878aed0844f56453e08e
15,358
import json def metadata(path="xdress/metadata.json"): """Build a metadata file.""" md = {} md.update(INFO) # FIXME: Add the contents of CMakeCache.txt to the metadata dictionary # write the metadata file with open(path, 'w') as f: json.dump(md, f, indent=2) return md
cbc1981ecd9c7146f082321a1b05c094cfdd0cc6
15,359
import logging import tqdm def query_assemblies(organism, output, quiet=False): """from a taxid or a organism name, download all refseq assemblies """ logger = logging.getLogger(__name__) assemblies = [] genomes = Entrez.read(Entrez.esearch( "assembly", term=f"{organism}[Organism...
48b4f4946f4368865b2934f1ac30ce650a00b5d0
15,360
def main(params): """Loads the file containing the collation results from Wdiff. Then, identifies various kinds of differences that can be observed. Assembles this information for each difference between the two texts.""" print("\n== coleto: running text_analyze. ==") difftext = get_difftext(params[...
425aa27fb7ba1ee0b1aa23c2489e8431b4a57726
15,361
def matrix_horizontal_stack(matrices: list, _deepcopy: bool = True): """ stack matrices horizontally. :param matrices: (list of Matrix) :param _deepcopy: (bool) :return: (Matrix) """ assert matrices for _i in range(1, len(matrices)): assert matrices[_i].basic_data_type() == matri...
83419b0f77fc055145026b61ab8a0200172fcb62
15,362
def inds_to_invmap_as_array(inds: np.ndarray): """ Returns a mapping that maps global indices to local ones as an array. Parameters ---------- inds : numpy.ndarray An array of global indices. Returns ------- numpy.ndarray Mapping from global to local. """ re...
25dc5fa9f1225cb9da64a513ebea3dff935c3c44
15,363
from sys import path def install_plugin_urls(): """ urlpatterns - bCTF original urlpatterns """ urls = [] for plugin in list_plugins(): urls.append(path('{0}/'.format(plugin), include('plugins.{0}.urls'.format(plugin)))) return urls
798706e47b1e79d2af99583b209eb7078db95902
15,364
def ident_keys(item, cfg): """Returns the list of keys in item which gives its identity :param item: dict with type information :param cfg: config options :returns: a list of fields for item that give it its identity :rtype: list """ try: return content.ident_keys(item) except E...
e911ea9bb0dbccbdf4d0ab5cdfeb5742297ae9e8
15,365
def playlists_by_date(formatter, albums): """Returns a single playlist of favorite tracks from albums sorted by decreasing review date. """ sorted_tracks = [] sorted_albums = sorted(albums, key=lambda x: x["date"], reverse=True) for album in sorted_albums: if album["picks"] is None: ...
0448fd941c0219f6e854a15df62e4811c1cecf3e
15,366
def merge_two_sorted_array(l1, l2): """ Time Complexity: O(n+m) Space Complexity: O(n+m) :param l1: List[int] :param l2: List[int] :return: List[int] """ if not l1: return l2 if not l2: return l1 merge_list = [] i1 = 0 i2 = 0 l1_len = len(l1) - 1 ...
2671d21707056741bbdc4e3590135e7e1be4c7e9
15,367
def regression_metrics(y_true,y_pred): """ param1: pandas.Series/pandas.DataFrame/numpy.darray param2: pandas.Series/pandas.DataFrame/numpy.darray return: dictionary Function accept actual prediction labels from the dataset and predicted values from the model and utilizes this two values/data...
085bf6d9006443c752f5b665480fce4f24e5f850
15,368
def convert_from_quint8(arr): """ Dequantize a quint8 NumPy ndarray into a float one. :param arr: Input ndarray. """ assert isinstance(arr, np.ndarray) assert ( "mgb_dtype" in arr.dtype.metadata and arr.dtype.metadata["mgb_dtype"]["name"] == "Quantized8Asymm" ), "arr should ...
50143a309108bf68cb65b266e2aec84090eb30e6
15,369
def classpartial(*args, **kwargs): """Bind arguments to a class's __init__.""" cls, args = args[0], args[1:] class Partial(cls): __doc__ = cls.__doc__ def __new__(self): return cls(*args, **kwargs) Partial.__name__ = cls.__name__ return Partial
7cdc96e314a2ce3c658ecb886922df4d7bda5b99
15,370
import os def load_xml(xml_path): """ Загружает xml в etree.ElementTree """ if os.path.exists(xml_path): xml_io = open(xml_path, 'rb') else: raise ValueError(xml_path) xml = objectify.parse(xml_io) xml_io.close() return xml
ef02b163fbcabca797ba8346c5fc0bf0bd185365
15,371
def alphabetize_concat(input_list): """ Takes a python list. List can contain arbitrary objects with .__str__() method (so string, int, float are all ok.) Sorts them alphanumerically. Returns a single string with result joined by underscores. """ array = np.array(input_list, dtype=st...
4bac3712696fd776b96ca8501f696c505c05e699
15,372
def kick(state, ai, ac, af, cosmology=cosmo, dtype=np.float32, name="Kick", **kwargs): """Kick the particles given the state Parameters ---------- state: tensor Input state tensor of shape (3, batch_size, npart, 3) ai, ac, af: float """ with tf.name_scope(name): state = tf.convert_to_te...
e7deeca9001fccc078f2f8ab7e51ac38d72a1125
15,373
def check_similarity(var1, var2, error): """ Check the simulatiry between two numbers, considering a error margin. Parameters: ----------- var1: float var2: float error: float Returns: ----------- similarity: boolean """ if((var1 <= (var2 + error)) and (v...
305fd08cf4d8b1718d8560315ebf7bd03a4c7e2a
15,374
def model_type_by_code(algorithm_code): """ Method which return algorithm type by algorithm code. algorithm_code MUST contain any 'intable' type :param algorithm_code: code of algorithm :return: algorithm type name by algorithm code or None """ # invalid algorithm code case if algorith...
bcd811e200855cc026134ce05b67add807e176ca
15,375
def getCasing(word): """ Returns the casing of a word""" if len(word) == 0: return 'other' elif word.isdigit(): #Is a digit return 'numeric' elif word.islower(): #All lower case return 'allLower' elif word.isupper(): #All upper case return 'allUpper' elif word[0...
2af70926c0cbbde6310abb573ccc3ee8260b86bd
15,376
def normalize_angle(deg): """ Take an angle in degrees and return it as a value between 0 and 360 :param deg: float or int :return: float or int, value between 0 and 360 """ angle = deg while angle > 360: angle -= 360 while angle < 360: angle += 360 return angle
cd4788819bbc8fce17ca7c7b1b320499a3893dee
15,377
from datetime import datetime from dateutil import tz import math def current_global_irradiance(site_properties, solar_properties, timestamp): """Calculate the clear-sky POA (plane of array) irradiance for a specific time (seconds timestamp).""" dt = datetime.datetime.fromtimestamp(timestamp=timestamp, tz=tz....
d8e180b9768d5cf6c3064a7d30a2e7d918307366
15,378
from datetime import datetime def date_formatting(format_date, date_selected): """Date formatting management. Arguments: format_date {str} -- Date date_selected {str} -- Date user input Returns: str -- formatted date """ if len(date_selected) == 19: date_selected...
48ff4cb59de3e8f75238420d8d211812148db34c
15,379
def parse_activity_from_metadata(metadata): """Parse activity name from metadata Args: metadata: List of metadata from log file Returns Activity name from metadata""" return _parse_type_metadata(metadata)[1]
c583d34a8cb0db8ddf26ff79d1a0885aab5c6af9
15,380
def mask_data_by_FeatureMask(eopatch, data_da, mask): """ Creates a copy of array and insert 0 where data is masked. :param data_da: dataarray :type data_da: xarray.DataArray :return: dataaray :rtype: xarray.DataArray """ mask = eopatch[FeatureType.MASK][mask] if len(data_da...
6639cc2cbf4956edbd637f07308fb33f00fcb8af
15,381
def makeFields(prefix, n): """Generate a list of field names with this prefix up to n""" return [prefix+str(n) for n in range(1,n+1)]
435571557ef556b99c4729500f372cc5c9180052
15,382
def process_input_dir(input_dir): """ Find all image file paths in subdirs, convert to str and extract labels from subdir names :param input_dir Path object for parent directory e.g. train :returns: list of file paths as str, list of image labels as str """ file_paths = list(input_dir.rglob('*....
569d4539368888c91a12538156c611d311da03b6
15,383
def fak(n): """ Berechnet die Fakultaet der ganzen Zahl n. """ erg = 1 for i in range(2, n+1): erg *= i return erg
9df6f4fa912a25535369f4deb0a06baef8e6bdcc
15,384
import csv def save(data, destination_path, **kwargs): """Generate a csv file from a datastructure. :param data: Currently data must be a list of dicts. :type data: list of dict :param destination_path: Path of the resulting CSV file. :type destination_path: str :raises ValueError: If the for...
b9b1d33ab72602a4887b0929f86d59e283d4193c
15,385
import re def create_sequences_sonnets(sonnets): """ This creates sequences as done in Homework 6, by mapping each word to an integer in order to create a series of sequences. This function specifically makes entire sonnets into individual sequences and returns the list of processed sonnets back t...
56087140fe5ed8934b64a18567b4e9023ddc6f59
15,386
import pathlib import sys import shutil def detect_venv_command(command_name: str) -> pathlib.Path: """Detect a command in the same venv as the current utility.""" venv_path = pathlib.Path(sys.argv[0]).parent.absolute() expected_command_path = venv_path / command_name if expected_command_path.is_file...
fbc7cbda5a4bf4ba9c2d3654176c2bc92692e884
15,387
def l_to_rgb(img_l): """ Convert a numpy array (l channel) into an rgb image :param img_l: :return: """ lab = np.squeeze(255 * (img_l + 1) / 2) return color.gray2rgb(lab) / 255
362a1ef926e780b311902c3637a5299afbce4c6a
15,388
def blockchain_assert_absolute_time_exceeds(condition: ConditionWithArgs, timestamp): """ Checks if current time in millis exceeds the time specified in condition """ try: expected_mili_time = int_from_bytes(condition.vars[0]) except ValueError: return Err.INVALID_CONDITION curr...
7b3ce8801239a524b150c9191b49eb24575b3fbb
15,389
def show_aip(mets_file): """Show a METS file""" mets_instance = METS.query.filter_by(metsfile='%s' % (mets_file)).first() level = mets_instance.level original_files = mets_instance.metslist dcmetadata = mets_instance.dcmetadata divs = mets_instance.divs filecount = mets_instance.originalfile...
606dfd4dba45fe8dae918f795f27bfeddb0fcd70
15,390
def testCartesianEpehemeris( ephemeris_actual, ephemeris_desired, position_tol=1*u.m, velocity_tol=(1*u.mm/u.s), magnitude=True, raise_error=True ): """ Tests that the two sets of cartesian ephemeris are within the desired absolute tolerances of each other...
5ab38140ed7ff446f0f961e147e7d8af3e6c97e0
15,391
import requests def get_longitude_latitude(city_info, station): """ 利用高德地图查询对应的地铁站经纬度信息,下面的key需要自己去高德官网申请 https://lbs.amap.com/api/webservice/guide/api/georegeo :param city_info: 具体城市的地铁,如:广州市地铁 :param station: 具体的地铁站名称,如:珠江新城站 :return: 经纬度 """ addr = city_info + station print('*要查...
9b0132702e14af9dec1ce65724139af0188b14a0
15,392
def make_resource_object(resource_type, credentials_path): """Creates and configures the service object for operating on resources. Args: resource_type: [string] The Google API resource type to operate on. credentials_path: [string] Path to credentials file, or none for default. """ try: api_name, ...
018cac83513b61c8bc99e06a07ded004685016b2
15,393
def AreBenchmarkResultsDifferent(result_dict_1, result_dict_2, test=MANN, significance_level=0.05): """Runs the given test on the results of each metric in the benchmarks. Checks if the dicts have been created from the same benchmark, i.e. if metric names match (e.g. first_non_em...
d9e1eaa16c2329511dd3e1fc7e5cad63cab0c208
15,394
def _load_pascal_annotation(image_index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ #image_index = _load_image_set_index() classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', ...
e656d78003d17ca7b8dae204ed9ea2812e5871dc
15,395
def create_global_var(shape, value, dtype, persistable=False, force_cpu=False, name=None): """ This function creates a new tensor variable with value in the global block(block 0). Parameters: ...
0d64b4bd15c97b2f32058bfe298249c3e528ec16
15,396
def select(population, fitness_val): """ 选择操作,用轮盘赌法进行选择 :param population: 种群基因型 :param fitness_val: 种群适应度 :return selected_pop: 选择后的种群 """ f_sum = sum(fitness_val) cumulative = [] for i in range(1, len(fitness_val)+1): cumulative.append(sum(fitness_val[:i]) / f_sum) ...
dd3529eaf6ac35801c589152078e7fe1dd0ed9fe
15,397
def _nan_helper(y, nan=False, inf=False, undef=None): """ Helper to handle indices and logical indices of NaNs, Infs or undefs. Definition ---------- def _nan_helper(y, nan=False, inf=False, undef=None): Input ----- y 1d numpy array with possible missing values Optional ...
742433c2140f4827f11e79c691e3a16be124ef99
15,398
def unpacking(block_dets, *, repeat=False, **_kwargs): """ Identify name unpacking e.g. x, y = coord """ unpacked_els = block_dets.element.xpath(ASSIGN_UNPACKING_XPATH) if not unpacked_els: return None title = layout("""\ ### Name unpacking """) summary_bits = [] for unp...
512238569efe4c17ef7afd3a26e2bc17a0f77cfb
15,399