content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_ground_weather_one_place(dir_path): """ 1地点の地上気象データを取得する Args: dir_path(string) : ディレクトリパス Returns: DataFrame : ファイルの読込結果 """ # 地上気象データのファイル一覧取得 file_paths = read_csv.get_file_paths(dir_path) # 気象データを読み込み、DataFrameに格納する ground_df = None ...
b25c6008c1f1cf9760c16dc10fd44dee8e62ad55
5,200
def trash_description(spl, garbage, keyword, description="description_1"): """description_1 OR description_2""" relocate = spl[spl[description].str.contains(keyword, na=False, regex=True)] spl = spl[~spl[description].str.contains(keyword, na=False, regex=True)] garbage = pd.concat([garbage, relocate], i...
16a1512ddaf914bd5ebcd00f2dcdfa11d59ec73c
5,201
import random def prepositionalPhrase(): """Builds and returns a prepositional phrase.""" return random.choice(prepositions) + " " + nounPhrase()
33a6f1111f752c160ef90eedde4bf56b79b1100a
5,202
def check_possible_dtype(df): """Guess dtypes for each column in a dataframe, where dataframe must contains only string values. Raise an exception if dataframe contains non-string values. :param df: a DataFrame whose all values must be strings. """ column = [] int_cnt = [] dec_cnt = [] ...
0e9759959af04fbf1bb9db3672f6a188afe7f6ab
5,203
from typing import List def filter_objects_avoiding_duplicated(objects: List[Object], max_distance: int = 20) -> List[Object]: """Filtra los objetos evitando aquellas posibles que sean detecciones múltiples. El fundamento del algoritmo es que si se detectan dos objetos ...
042fee5df94dc1c72fb53635577c8006c57f73f9
5,204
import os def splitall(path): """ Credit goes to Trent Mick SOURCE: https://www.oreilly.com/library/view/python-cookbook/0596001673/ch04s16.html """ allparts = [] while 1: parts = os.path.split(path) if parts[0] == path: # sentinel for absolute paths allparts.i...
3d25bdfab5fd74d59e67100c864c950a2aaaa78b
5,205
import os def netstat(): """ Return list of all connections. Return list of TCP listenning connections and UDP connections. All localhost connections are filtered out. This script must run as root in order to be able to obtain PID values of all processes. For more information see: https:...
04884bd091438956012c1524671a1ffdfddc4c6f
5,206
def print_hdr(soup, hdr, file = None): """ :param soup: [bs4.BeautifulSoup] document context :param hdr: [dict] header node to process :param file: [stream] I/O stream to print to :return: [stream] pass on the I/O stream so descent continues """ tag = hdr['tag'] tag_id = tag['id'] in...
2c6fd613a5c6ddb5ec842fb7cee845d1a8771ccd
5,207
from unittest.mock import Mock def __empty_2(): """ Empty used as parent of cube_2 """ obj = Mock() obj.name = 'empty_2' obj.mode = 'OBJECT' obj.to_mesh.return_value = None obj.matrix_world = Matrix.Identity(4) obj.visible_get.return_value = False obj.hide_viewport = True obj.hide_...
024614d7967da5da6d6629167a20eda4188e812f
5,208
import argparse def parse_args(args): """Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="A scaffolding program...
8217e73fe219e18a8a7c8d0560fba95c5c3458df
5,209
def get_gradient(bf_data: np.ndarray, smooth=10): """ Removes first dimension, Computes gradient of the image, applies gaussian filter Returns SegmentedImage object """ data = strip_dimensions(bf_data) gradient = get_2d_gradient(data) smoothed_gradient = gaussian_filter(gradient, smo...
864b3bc118d08099c56657b2f2883e20de5c663e
5,210
def sum_seq(seq): """ Lambda wrapper for sum. """ return K.sum(seq, axis=1, keepdims=False)
e2bf342f6cda9bda50dc15814c7808a42e8a9925
5,211
def split_by_time(files_rad): """Separate a list of files by their timestamp""" out = {} if type(files_rad) == dict: for k in files_rad.keys(): out[k] = _split_by_time(files_rad[k]) else: out = _split_by_time(files_rad) return out
9a77b3db2e21c27198337b1a1852494bca5acefb
5,212
def make_general_csv_rows(general_csv_dict): """ Method for make list of metrics from general metrics dict. Rows using in general metrics writer :param general_csv_dict: dict with all metrics :type general_csv_dict: dict :return: all metrics as rows :rtype: list """ rows = [] f...
45ca165d312b39cd0b7088e0bcbfb402a92e7e2b
5,213
def build_hstwcs(crval1, crval2, crpix1, crpix2, naxis1, naxis2, pscale, orientat): """ Create an HSTWCS object for a default instrument without distortion based on user provided parameter values. """ wcsout = wcsutil.HSTWCS() wcsout.wcs.crval = np.array([crval1,crval2]) wcsout.wcs.crpix = n...
0247a8dc7e6aa083db50f21d82676216583be206
5,214
def build_regressor_for_ranking_positive_class(dataset, features, regression_target=TARGET_COLUMN): """This function builds a regressor based exclusively on positive class' examples present in the dataset """ if regression_target in features: print('The target for the regression task cannot be one of the f...
1312751425f79c1e4fec09f705f0ea551e2a60b3
5,215
def get_speakable_timestamp(timestamp): """Return a 'speakable' timestamp, e.g. 8am, noon, 9pm, etc.""" speakable = f"{timestamp.strftime('%I').lstrip('0')} {timestamp.strftime('%p')}" if speakable == '12 PM': return 'noon' elif speakable == '12 AM': return 'midnight' return speakab...
0b724686ebd5d3152d9017dc456d2945c78be0ee
5,216
def createColor(red: int, green: int, blue: int) -> tuple: """ Create color Parameters: red -> 0-255 green -> 0-255 blue -> 0-255 """ return tuple( max(min(red, 255), 0), max(min(green, 255), 0), max(min(blue, 255), 0) )
3e8ee43e9d458668f4312f9fd75050b5875036d7
5,217
from typing import List def export_nodeclass_list(node_classes: List[NodeClass]) -> str: """Writes the Node data as a XML string. Does not write to a file -- use ``with open(output_file) as out_stream:`` etc. """ # This is the data string, the rest is formalities node_classes_string = '\n'.join([s...
f50638e9b3a7ab2f1df6e49703b9ed3e39916f9d
5,218
import time def recognition(request): """ style transform service """ if request.method == 'POST': name = '' predicitons = '' try: # load image now = time.localtime() img = request.FILES['image'] image_name = '{}{}{}{}{}o...
d8de5ab5c33e6ca0c2ac5afbec81c402f7151187
5,219
def url(s): """Validate url input""" u = urlparse(s) if u.scheme not in ["http", "https"]: raise ValueError(s) return u.geturl()
82683af4ad6fb35b6d74409a9a429c4dfd81a723
5,220
import pickle def getGPLCs(df, savepath='./',plotpath='./', bands='ugrizY', ts='0000000', fn='GPSet'): """Short summary. Parameters ---------- df : type Description of parameter `df`. savepath : type Description of parameter `savepath`. plotpath : type Description of p...
755dec48771ae17c058565ef88087d6ec6a78aec
5,221
import torch def _featurize(inputs,model): """ Helper function used to featurize exemplars before feeding into buffer. """ with torch.no_grad(): # Forward pass outputs = model(*inputs).detach() #Featurize raw exem return outputs
191fd1b362f38309a35618284fcf3f1910a06bd6
5,222
def ligth_condition(img, args): """ Change ligthning condition in the image Inputs: img: Image to change ligthning args: Dictionary with "gamma" argument Return: Image with ligthning values changed """ invGamma = 1.0 / args["gamma"] table = np.array([((i / 255.0) ** i...
dc5273a1df8e13292147b00be45452a7ccf4a197
5,223
import numpy as np from sklearn.metrics import mean_squared_error def calc_RMSE(varx,vary,lats,lons,weight): """ Calculates root mean square weighted average Parameters ---------- varx : 2d array vary : 2d array lons : 1d array of latitude weigh...
150d08e0790f3a8ce59a2054cdc042ff6cdc2969
5,224
def sample(internal_nodes, alpha=0.5, beta=0.5, only_tree=False): """ Generates a junction tree with order internal nodes with the junction tree expander. Args: internal_nodes (int): number of nodes in the underlying graph alpha (float): parameter for the subtree kernel beta (float): pa...
d0cc00e7ad96491147149aa4be396af970a9f68f
5,225
def _get_version_tuple(): """ version as a tuple """ return major, minor, revision
1d82390224de07964dce7c4e7fd3e32595b189a0
5,226
def _fit_seasonal_model_with_gibbs_sampling(observed_time_series, seasonal_structure, num_warmup_steps=50, num_results=100, seed=None): """Bui...
c13d4df3eca25f1a53ed27cd94e5f2b4b102013c
5,227
def deskew(data, angle, dx, dz, rotate=True, return_resolution=True, out=None): """ Args: data (ndarray): 3-D array to apply deskew angle (float): angle between the objective and coverslip, in degree dx (float): X resolution dz (float): Z resolution rotate (bool, optional...
a39ff1d48777c266e83358e272b6ba7d6d7ce894
5,228
import os import tqdm def process_data(path,stage = 'train'): """ train test sample_submission """ # loading the data df = pd.read_csv(os.path.join(path,f'{stage}.csv')) MASK = -1 # fill NA with -1 T_HIST = 10 # time history, last 10 games # for cols "date", change to datatime for col in df.filter(regex=...
ff6542c8a4f7366c2a1b612d7b41e3aa539e34a4
5,229
import pandas as pd import numpy as np def rm_standard_dev(var,window): """ Smoothed standard deviation """ print('\n\n-----------STARTED: Rolling std!\n\n') rollingstd = np.empty((var.shape)) for ens in range(var.shape[0]): for i in range(var.shape[2]): for j in ...
d37cfa3c756f8fc062a28ac078e4e16557282951
5,230
import os def load_letter(folder, min_num_images): """Load the data for a single letter label.""" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) image_index = 0 print(folder) for image in os.listdir(folder)...
30324858e8481b348f004dfbc39bf790cd0ca930
5,231
def visualizeTimeSeriesCategorization(dataName, saveDir, numberOfLagsToDraw=3, autocorrelationBased=True): """Visualize time series classification. Parameters: dataName: str Data name, e.g. "myData_1" saveDir: str Path of directories pointing to data storage ...
b2fcac2179e3a689ee73e13519e2f4ad77c59037
5,232
from typing import Dict def refund(payment_information: Dict, connection_params) -> Dict: """Refund a payment using the culqi client. But it first check if the given payment instance is supported by the gateway. It first retrieve a `charge` transaction to retrieve the payment id to refund. And r...
75dff392c0748a1408eb801ad78ef65be988026c
5,233
import argparse import os def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Howler', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text', metavar='str', help='Inpu...
906e38ad510016068ca7d431c681b4680ee56f5d
5,234
import torch from typing import Tuple def _ssim_map( X: torch.Tensor, Y: torch.Tensor, data_range: float, win: torch.Tensor, K: Tuple[float, float] = (0.01, 0.03), scales: Tuple[float, float, float] = (1, 1, 1), gradient_based: bool = False, ) -> Tuple[torch.Tensor, torch.Tensor]: """ ...
3a1d34497228bb95d0bc295475fb0df38220107b
5,235
import numbers def check_random_state(seed): """Turn `seed` into a `np.random.RandomState` instance. Parameters ---------- seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` s...
57390806329776c77977a27e18e78fdad298fef9
5,236
def power3_sum_2method(): """ Input: nothing, it have everything it needs. Output: sum: summ of all numbers which is power of 3 and fit in between 0 and upper bound == 1000000 """ k = 0 sum = 0 while True: a = 3**k k += 1 if a < 1000000: s...
b86bfaeb2418e183a78054d2a4b76c58d58be388
5,237
def bitwise_right_shift(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None): """ The BitwiseRightShift operation The arguments for this function are as follows: :param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string :param ...
8d07a60a514466ee4aa0b15b0b442fb71b3347ed
5,238
import re def strip_comments(line): """Strips comments from a line and return None if the line is empty or else the contents of line with leading and trailing spaces removed and all other whitespace collapsed""" commentIndex = line.find('//') if commentIndex is -1: commentIndex = len(line...
09579031294d7b5787c97fa81807fa5ecfe12329
5,239
import logging def fft_pxscale(header,wave): """Compute conversion scale from telescope space to sky space. Parameters ---------- ima : array 2D Telescope pupil model. Returns ------- fftscale : float The frequency scale in sky space. Exam...
6935bdefe96aec771704a79952cfc25ffb55e8bb
5,240
def parse_git_submodules(gitmodules_data): """Parse a .gitmodules file to extract a { name -> url } map from it.""" result = {} # NOTE: configparser.ConfigParser() doesn't seem to like the file # (i.e. read_string() always returns None), so do the parsing # manually here. section_nam...
78d01ec70b68164189a2ea775c6084e256116d0a
5,241
import pathlib from typing import Dict import json def get_model_cases(dir_path: pathlib.Path) -> Dict[str, Dict[str, str]]: """ Returns the Zen model case for each test if it exists. :param dir_path: The path to the directory containing the DIFFERENCES directory. """ model_cases = defaultdict(di...
d35b4cf59cf9b99a6aeb9e05e0af3ee342b11f3b
5,242
def _format_date(event): """Returns formated date json object for event""" old_date = event["date"] term = event["term"] dates = old_date.split("-") if len(dates) == 1: is_range = False else: is_range = True is_range = (len(dates) > 1) if is_range: start_date =...
aa8bf9a41fe30b664920e895cdc31d6993a408b2
5,243
def fetch(bibcode, filename=None, replace=None): """ Attempt to fetch a PDF file from ADS. If successful, then add it into the database. If the fetch succeeds but the bibcode is not in th database, download file to current folder. Parameters ---------- bibcode: String ADS bibcode ...
7d264df3f0eab896a9cb4858e7b19e2590d8142b
5,244
def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1): """Randomly or centrally crop multiple images. Parameters ---------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.crop``. R...
61593029455a880d5309e8343cf4f6d1049f598f
5,245
def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma, epsilon, value_prediction_old=None): """Computes the value loss given the...
5896dd57e1e9d05eb71e5b31aab4071b61d0fdbf
5,246
def build_pkt(pkt): """Build and return a packet and eth type from a dict.""" def serialize(layers): """Concatenate packet layers and serialize.""" result = packet.Packet() for layer in reversed(layers): result.add_protocol(layer) result.serialize() return re...
afd84446d3bb545b03b9d4c42d80f096b6665342
5,247
def make_file_prefix(run, component_name): """ Compose the run number and component name into string prefix to use with filenames. """ return "{}_{}".format(component_name, run)
73ef37d75d9e187ee49ee058958c3b8701185585
5,248
def identifier_needs_escaping(text): """ Slightly slow, but absolutely correct determination if a given symbol _must_ be escaped. Necessary when you might be generating column names that could be a reserved keyword. >>> identifier_needs_escaping("my_column") False >>> identifier_needs_escaping(...
265f7acd1e92a954758f44eb03247b0b935d6d4d
5,249
from typing import Dict def initialize_lock_and_key_ciphers() -> Dict[str, VigenereCipher]: """[summary] Returns: Dict[VigenereCipher]: [description]""" ciphers = {} with open(CIPHER_RESOURCE, "r") as cipher_resource_file: cipher_data = load(cipher_resource_file, Loader=FullLoader) ...
1c0a27b36b4c0524b77dcb5c44a3bc840797b226
5,250
def add_service(): """ Used to register a new service """ form = ServiceForm() if form.validate_on_submit(): try: srv = Services() srv.populate_from_form(form) srv.authentication.value = {"db":request.form.get('authdb'),"user":request.form.get('authuser'...
56ce52c293d42710a9d4d5ac57b21f5ba1c0c0ac
5,251
def f_columnas_pips(datos): """ Parameters ---------- datos : pandas.DataFrame : df con información de transacciones ejecutadas en Oanda, después de haber ejecutado f_columnas_tiempos Returns ------- datos : pandas.DataFrame : df modificado Debugging ...
5d6d47d23dbe16f3619b7e1264d30e91a9acd8ce
5,252
def parse_resolution(resolution): """ return: width, height, resolution """ resolution = resolution.strip() splits = resolution.split(',') return int(splits[0]), int(splits[1]), int(splits[2])
de937e440c4540d11cedd868e3f4a046baa99f22
5,253
def link_cube(cube, locale, provider=None, namespace=None, ignore_missing=False): """Links dimensions to the `cube` in the `context` object. The `context` object should implement a function `dimension(name, locale, namespace, provider)`. Modifies cube in place, returns the cube. """ # ...
09062ff3fd9dcfeeac7a746557c7f5384e4560a6
5,254
import argparse def _parser() -> argparse.Namespace: """Take care of all the argparse stuff. :returns: the args """ # parser = GooeyParser(description='Remove : from data files') parser = argparse.ArgumentParser(description='Combines Nods using ') parser.add_argument('listspectra', help='List...
3edcefc24898d15fd67925729590710a4f0d1fb5
5,255
import inspect def get_arguments(func): """Returns list of arguments this function has.""" if hasattr(func, '__code__'): # Regular function. return inspect.getargspec(func).args elif hasattr(func, '__call__'): # Callable object. print(func) return _get_arguments(fun...
f93133f20c819c590c30e25b6c339c07732daebe
5,256
def _check(isamAppliance, name): """ Check if suffix exists """ ret_obj = get(isamAppliance) check_value, warnings = False, ret_obj['warnings'] if warnings == []: for suffix in ret_obj['data']: if suffix['name'] == name: logger.info("Suffix found in embedded ...
be2a6226ebdccb92ec3361df79e50165a22d6981
5,257
def check_listening_address(address: str) -> bool: """Check entered ip address for validity.""" if address == 'localhost': return True return address in get_local_addresses()
eaa5cecfee4e8be2947150a537213f4159ee6baf
5,258
import base64 def multibase_b64decode(data): """ Follow forge's base64 urlsafe encode convention to decode string Args: data(string): encoded string Returns: bytes Examples: >>> multibase_b64decode('aGVsbG8') b'hello' """ if isinstance(data, str): data =...
fdbc0f937e33d7994737a3a515973598cac3debd
5,259
from typing import List def parse_ordering_params(param: List[str]) -> List[str]: """ Ignores the request to sort by "ord". Returns a sorting order based on the params and includes "readable_id" sorting in passed params if the sorting request contains title otherwise, it returns the requested orde...
a6a5f4665515a292ad2367945a6b8407000d656a
5,260
def file_senzing_rabbitmq(): """#!/usr/bin/env bash # --- Functions --------------------------------------------------------------- function up { echo -ne "\033[2K${CONTAINER_NAME} status: starting...\r" mkdir -p ${RABBITMQ_DIR} chmod 777 ${RABBITMQ_DIR} if [ "${CONTAINER_VERSION}" == "latest" ]...
95396425074096d17561b20cd197e77f1d550476
5,261
def mse(predictions, targets): """Calculate MSE: (Mean squared error) """ return ((predictions - targets) ** 2).mean()
79d87a3422d4d24201cae86ee861614c83f6770f
5,262
def export1d(hist): """Export a 1-dimensional `Hist` object to uproot This allows one to write a coffea histogram into a ROOT file, via uproot. Parameters ---------- hist : Hist A 1-dimensional histogram object Returns ------- out A ``uproot_methods.cla...
ffe09495a268c68d26f9861e6d732649f2f74497
5,263
def filter_words(w_map, emb_array, ck_filenames): """ delete word in w_map but not in the current corpus """ vocab = set() for filename in ck_filenames: for line in open(filename, 'r'): if not (line.isspace() or (len(line) > 10 and line[0:10] == '-DOCSTART-')): line = lin...
efdef92093acf25c992dba86da25a4118ba728ec
5,264
def get_cache_template(sources, grids, geopackage, table_name="tiles"): """ Returns the cache template which is "controlled" settings for the application. The intent is to allow the user to configure certain things but impose specific behavior. :param sources: A name for the source :param grids: sp...
dc83a155d28e0b39f12a7dc7142b61a4bf27512b
5,265
from datetime import datetime def plotter(fdict): """ Go """ pgconn = get_dbconn('coop') ccursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) ctx = get_autoplot_context(fdict, get_description()) station = ctx['station'] lagmonths = ctx['lag'] months = ctx['months'] month ...
0f41a53336f2bf65805adaf83a8f3f17c006e161
5,266
def _action_spec(): """Returns the action spec.""" paddle_action_spec = dm_env_rpc_pb2.TensorSpec( dtype=dm_env_rpc_pb2.INT8, name=_ACTION_PADDLE) tensor_spec_utils.set_bounds( paddle_action_spec, minimum=np.min(_VALID_ACTIONS), maximum=np.max(_VALID_ACTIONS)) return {1: paddle_action_sp...
130b7b2fe9f56d925d4ec1206eb3fb2752fee716
5,267
def stdin(sys_stdin): """ Imports standard input. """ inputs = [x.strip("[]\n") for x in sys_stdin] a = [int(x) for x in inputs[0].split(",")] x = int(inputs[1][0]) return a, x
4c34e1bc80da31c6c7aff0d71a0c65f6fc01ed00
5,268
def _row_key(row): """ :param row: a normalized row from STATEMENT_METRICS_QUERY :return: a tuple uniquely identifying this row """ return row['database_name'], row['user_name'], row['query_signature'], row['query_hash'], row['query_plan_hash']
2984e0e0b5fcc4e51a26af188e51fe65c52077a2
5,269
from io import StringIO def get (url, user_agent=UA, referrer=None): """Make a GET request of the url using pycurl and return the data (which is None if unsuccessful)""" data = None databuffer = StringIO() curl = pycurl.Curl() curl.setopt(pycurl.URL, url) curl.setopt(pycurl.FOLLOWLOCATIO...
e18de239a598be249d81c2a15486a66af763bc85
5,270
def detect_callec(tree): """Collect names of escape continuations from call_ec invocations in tree. Currently supported and unsupported cases:: # use as decorator, supported @call_ec def result(ec): # <-- we grab name "ec" from here ... # use directly on a literal...
1980c2abd9d5b995a47eab381eb595eb71ced595
5,271
from typing import List from typing import Tuple from typing import Any def apply_filters( stream: StreamMeta, filters: List[Tuple[str, str]], config: Any ) -> StreamMeta: """Apply enabled filters ordered by priority on item""" filter_pool = get_filter_pool(filters, config) for filter_instance in fil...
2ff50b5d31e84ba69afe694b4beb4116dbc5fc55
5,272
def threading_d(func): """ A decorator to run function in background on thread Args: func:``function`` Function with args Return: background_thread: ``Thread`` """ @wraps(func) def wrapper(*args, **kwags): background_thread = Thread(target=func, args=(*args,)) ba...
ff4d86ded189737d68d4cdc98c0e9ba9f1a28664
5,273
def create_anchors_3d_stride( feature_size, sizes=[1.6, 3.9, 1.56], anchor_strides=[0.4, 0.4, 0.0], anchor_offsets=[0.2, -39.8, -1.78], rotations=[0, np.pi / 2], velocities=[], dtype=np.float32, ): """ Args: feature_size: list [D, H, W](zyx) sizes: [N, 3] list of list...
6834d20f44196f5dad19d1917a673196334adf9f
5,274
import hashlib def sha1_file(filename): """ Return the hex string representation of the SHA1 checksum of the filename """ s = hashlib.sha1() with open(filename, "rb") as f: for line in f: s.update(line) return s.hexdigest()
b993ac9f025d69124962905f87b1968617bb33f5
5,275
def unit_parameters(_bb_spine_db_export: dict, _grid_name: str, _node_name: str, _unit_name: str, _time_index, _alternative='Base', _eff_level=1, _p_unit=False, _node_name_if_output=None, _node_name_if_input=None ): """ :param _bb_spine_db_export: ...
698770193d23c8decb240132c462860cd59ef77b
5,276
def read_from_file(file_path): """ Read a file and return a list with all the lines in the file """ file_in_list = [] with open(file_path, 'r') as f: for line in f.readlines(): file_in_list.append(line) return file_in_list
5fef3a3f50528c1a9786451666ae7e43be282bf9
5,277
def count(predicate, iterable): """ Iterate over iterable, pass the value to the predicate predicate and return the number of times the predicate returns value considered True. @param predicate: Predicate function. @param iterable: Iterable containing the elements to count. @return: The number o...
1a2d9a05203f32a6f1a8349b6e31d14cb1b82b71
5,278
def get_object_from_path(path): """ :param path: dot seperated path. Assumes last item is the object and first part is module path(str) - example: cls = get_object_from_path("a.module.somewhere.MyClass") you can create a path like this: class_path = "{0}.{1}".format...
e722b040486288d53fe4a357d81ddec8dfc9820e
5,279
def _get_collection_memcache_key(collection_id, version=None): """Returns a memcache key for the collection. Args: collection_id: str. ID of the collection. version: int. Schema version of the collection. Returns: str. The memcache key of the collection. """ if version: ...
cc054d726d1d2642701803a816e214eed4d9663d
5,280
def biKmeans(dataSet, k, distMeas=calcEuclideanDistance): """ 二分K-均值算法 :param dataSet: :param k: :param distMeas: :return: """ m = np.shape(dataSet)[0] clusterAssment = np.mat(np.zeros((m, 2))) centroid0 = np.mean(dataSet, axis=0).tolist()[0] centList = [centroid0] # create...
1421dfa95c44e046bd7d729ad343e98eb83bbbcd
5,281
import glob import os import logging def get(directory): """Prepare df and gdf with solar atlas tiled data.""" files_list = glob.glob(os.path.join(directory, "*", "*.csv")) data = [] for file in files_list: logging.info(file) tiles = pd.read_csv(file, header=None) tiles.columns...
69a32931930ffc5793f84faa09c3aa4b09688b42
5,282
def cleanup(args, repo): """Clean up undeployed pods.""" if args.keep < 0: raise ValueError('negative keep: %d' % args.keep) def _is_enabled_or_started(pod): for instance in pod.iter_instances(): if scripts.systemctl_is_enabled(instance.unit_name): return True ...
b015c1dbfeb3ad50218afaadfe198123ff2ab6df
5,283
from typing import Dict def optimizer_builder( config: Dict): """ Instantiate an optimizer. :param config: :return: """ # --- argument checking if not isinstance(config, dict): raise ValueError("config must be a dictionary") # --- read configuration decay_rate = c...
2194408d74d4f03bc54371b98b12c8dbe85fb585
5,284
def psi(z: float, a: float, b: float) -> float: """Penalty function with uniformly bounded derivative (Eq. 20) Args: z: Relative distance a: Cohesion strength b: Separation strength """ c = np.abs(a - b) / (2 * np.sqrt(a * b)) return ((a + b) / 2) * (np.sqrt(1 + (z + c) ** 2)...
df88e57d80a32d95367f30ce52af84308349387a
5,285
def caselessSort(alist): """Return a sorted copy of a list. If there are only strings in the list, it will not consider case. """ try: return sorted(alist, key=lambda a: (a.lower(), a)) except TypeError: return sorted(alist)
7558a57e28255817c71846da84230ced49553bb6
5,286
def EnableRing(serialPort): """ Enable the ISU to listen for SBD Ring Alerts. When SBD Ring Alert indication is enabled, the 9602 asserts the RI line and issues the unsolicited result code SBDRING when an SBD Ring Alert is received. """ ...
7036610523802f659c7a69ae192f1009401a6ac3
5,287
def render(template, **context): """Render the given template. :param template: The template file name or string to render. :param **context: Context keyword-arguments. """ class Undefined(BaseUndefined): def _fail_with_undefined_error(self, *args, **kwargs): try: ...
6680f163e1b89424e88b1a3046784083cdbb6520
5,288
import re from io import StringIO import os import json def read(pth, format=None, encoding=None, cols=None, **kwargs): """Returns the contents of a file into a string or format-dependent data type (with special handling for json and csv files). The format will either be inferred from the file extension ...
58f1b53b7ece08bc0da44dbd709e107e0ae46dbf
5,289
def audio(src: str) -> str: """ Insert audio tag The tag is currently not supported by Nuance, please use `audio_player` kit: docs/use_kits_and_actions.md :param src: :return: """ return f'<audio src="{src}"/>'
f9396d5f82eeca27089de41187fd7d5e967cc9cf
5,290
import os def read(*rnames): """ Read content of a file. We assume the file to be in utf8 """ return open(os.path.join(os.path.dirname(__file__), *rnames), encoding="utf8", mode="r").read()
15b1acf39188810080c3c47908b011011f4d35ca
5,291
import math def PerpendicularDistanceToFinish(point_b_angle: float, point_b: gps_pb2.Point) -> float: """ cos(B) = Adjacent / Hypotenuse https://www.mathsisfun.com/algebra/trig-finding-side-right-triangle.html """ return math.cos(math.radians(point_b_angle)) * point_b.star...
3c18c323c625893ab474c48eb00d48da543956ba
5,292
import requests from typing import List def get_revolut_stocks() -> List[str]: """ Gets all tickers offered on Revolut trading platform. Returns: list(str) """ req = requests.get("https://globefunder.com/revolut-stocks-list/") tickers = list(pd.read_html(req.content)[0]["Symbol"]) ...
3e7f41a04c653a954609cee618cbf89d962fef1d
5,293
def response_text(response_class): """ Return the UTF-8 encoding of the API response. :param response_class: class to cast the response to :return: Text of the response casted to the specified class """ def _inner(f): @wraps(f) def wrapper(obj, *args, **kwargs): res...
43f0d4cde4790128073440172ed30850794de7a9
5,294
from typing import Tuple def create_rankings( a: Dataset, b: Dataset, n_samples: int = 100, unravel: bool = False, **kwargs: int ) -> Tuple[ndarray, ndarray]: """ Sample a dataset 'a' with 'n' negative samples given interactions in dataset 'a' and 'b'. Practically, this function allows you to gen...
28282fc14d02b7f93d58d209d143a315e7b25422
5,295
def make_even(x): """Make number divisible by 2""" if x % 2 != 0: x -= 1 return x
10129eb6abd718414d0ada53915672dcf4d7b5b6
5,296
def get_num_vehicles(session, query_filters): """Gets the total number of annotations.""" # pylint: disable-msg=E1101 num_vehicles_query = session.query( func.count(Vehicle.id)) \ .join(Photo) \ .filter(Photo.test == True) \ # pylint: enable-msg=E1101 for query_filter i...
bf626edad29b136bb595dabb7e878649c08c0d84
5,297
def task_status_edit(request, status_id, response_format='html'): """TaskStatus edit""" status = get_object_or_404(TaskStatus, pk=status_id) if not request.user.profile.has_permission(status, mode='w'): return user_denied(request, message="You don't have access to this Task Status") if request...
593384ab55bf889a1e87d7909e848a2dbacad68e
5,298
import platform def is_windows_system(): """ | ##@函数目的: 获取系统是否为Windows | ##@参数说明:True or False | ##@返回值: | ##@函数逻辑: | ##@开发人:jhuang | ##@时间: """ return 'Windows' in platform.system()
6bfe296188b9dccf8338f0b2bbaaf146d9b22243
5,299