content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from functools import reduce import os def process_flat_files(df, red_path): """ Args: df (pandas.DataFrame) : a data-frame containing the all the data being processed. red_path (str) : the path where the reduced data is stored. Returns: updated_table (pandas.DataFrame) : ...
0b41eedf8b6c37ad555815bfe319800eb5600920
68,500
def plot_contributions(ax, top_n, bar_dims, bar_colors, plot_params): """ Plots all of the type contributions as horizontal bars Parameters ---------- ax: Matplotlib ax Current ax of the shift graph top_n: int The number of types being plotted on the shift graph bar_dims: di...
035137cdc6dfde8cc473c34bc05df12f97296788
68,501
def ast_evaluate_dict_values(edict): """Ast evaluates dict entries and returns the evaluated dict.""" returndict = {} for key, value in edict.items(): if isinstance(value, dict): value = ast_evaluate_dict_values(value) if isinstance(value, str): # Only evaluate str values all ot...
f7fb9e94d3bb28250581d6c9d6f6e0e275a58830
68,502
def compare_runs(runs, value, board=None): """Compare a value between runs and return indication of better/worse. :return: HTML symbol to indicate status. """ if "Previous" in runs: if board: last = runs["Last"]["Boards"][board][value] if board in runs["Previous"]["Boar...
3fdceb49e4b78050c0063851e4cf3dded1ab6293
68,503
def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ################################ epochs=300, ...
cc55ef7bd87bae5389117d3a9f07b36a54876c0e
68,504
def plot_xyz(data, x='time', y='amp', z=None, pol='absI', labels=None, sigma=1.0, band='all', power_in_dB=False, compact=True, monotonic_axis='auto', ax=None, **kwargs): """Generic plotting of 2 or 3 quantities extracted from sequence of scans. This is a very generic plotting routine that plots qu...
a3726c2a358fef46e85307f497f501454548aecf
68,505
def drhodr_Newt(r, M, M_dm, rho, EOS, EOS_deriv, m_dm): """ Hydrostatic equilibrium for a star modelled as a Newtonian body """ M_tot = M + M_dm return -cg.G * M_tot * rho / r / r / EOS_deriv(rho, m_dm)
822ab8feaea5e58e1e2dba1bac536a157c913dcd
68,506
import os def use_notebook(notebook=""): """Reads config file and returns the DEFAULT notebook. If no notebook is specified then the USE notebook is set to the DEFAULT notebook :param notebook: Title of notebook to USE, optional :type notebook: str :return: Returns True on successful write of n...
cdc29808bdbe1d10ae18a00f2e1cacf4a4f8da6d
68,507
def gen_pkfield(npix=32, alpha=-11.0 / 3, fknee=1, res=1): """Generate a 2D square map with P(k) field""" ufreq = np.fft.fftfreq(npix, d=res) kfreq = np.sqrt(ufreq[:, np.newaxis] ** 2 + ufreq ** 2) with np.errstate(divide="ignore"): psd = 2 * P(kfreq, alpha=alpha, fknee=fknee) psd[0, 0] = ...
5dba55fb00d4310c5e3bcdf2806b9ca9244f0b5b
68,508
import os import logging def get_port(): """ Parses the port where the server should listen Exists the program if the environment variable is not an int or the value is not positive Returns: The port where the server should listen """ try: server_port = int(os.getenv(_PORT...
2bfcdaadf1a64dd29fd89267b743f6b0cb76c194
68,509
def rsi(df, nb=14): """ Compute RSI (Relative Strength Index). RSI measures the speed and change of price movements. RSI = 100 - (100 / (1 + RS)) where RS = average gain / average loss over 14 days. """ column_rsi = f"RSI{nb}" avg_gain = None avg_loss = None if len(df) >= nb: for...
48b54c786f926f46061a39fab767c063cd38760d
68,510
def _build_people_params(distinct_id, set, add, token): """ Returns a new params dictionary appropriate for people tracking. """ if not set and not add: raise InvalidPeopleProperties("People analytics requires either $set or $add") if set and add: raise InvalidPeopleProperties("Mixpa...
51cef6585a0f6b676d4e431de12fb6391efabbe9
68,511
def is_run() -> bool: """ Test if the graphics system is running. :return: True if the graphics system is running. """ return _is_run
42d7777446d672596884d4a313a9eddd04b1fca4
68,512
def getRelationToZOI(collarData, pointIdx, lyr_in): """ Classify 2 consecutive daily locations as: Outside: Outside of ZOI (2 FALSE days) Enter: Entering ZOI (1 FALSE and 1 TRUE day) Stay: Stay in ZOI (2 TRUE days) Leave: Leaving Zone of Influence (1 TRUE and 1 FALSE day) ...
85f3a0b0caf57cd2e1d547e5a151ad7481eaee9a
68,513
def stations_highest_rel_level(stations, N): """Return the N stations with the highest relative water levels. Only N values are returned regarless of any tie conditions. Fewer than N may be returned if len(stations) < N Parameters ---------- stations : list[MonitoringStation] generate...
d2bf0cd53866286e1739f367833ff15298eb6bd5
68,514
def singularityintegrate(f, x): """ This function handles the indefinite integrations of Singularity functions. The ``integrate`` function calls this function intenally whenever an instance of SingularityFunction is passed as argument. The idea for integration is the following: - If we are dea...
4460624363d6428040cccfb1bf2fd768198cb81a
68,515
def helicsBrokerDisconnect(broker: 'helics_broker') -> "void": """ get the network address associated with a broker Parameters ---------- * `broker` : the broker to query * `identifier` : storage space to place the identifier string * `maxlen` : the maximum space a...
f1ecd63e0dbe2f22ecdb6ed67d65c92dad7ae874
68,516
import ast def lambda_in_rhs(node: AnyAssign) -> bool: """Return `True` if the RHS of the given assignment contains a lambda.""" _iterable = (ast.Tuple, ast.List) if isinstance(node.value, ast.Lambda): return True elif isinstance(node.value, _iterable): return any(isinstance(v, ast.La...
9a733bc720da6176102959ecc74e128c97f83603
68,517
import re def parse_log_entry(msg): """ Parse a log entry from the format $ip_addr - [$time_local] "$request" $status $bytes_sent $http_user_agent" to a dictionary """ data = {} # Regular expression that parses a log entry search_term = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+\-\s+\[(...
f237696e8215793b4cf17e7b20543ac01494b686
68,518
def create_stats(measures: "List of function timings.", col: "Current Column.", row: "Current Row", scenario: "Current Scenario.") -> dict: """Helper function to create result dataset.""" return {"scenario": scenario, "no_column": col, "data_length": row...
81baee4dd587b26eb360c72ea16a9c90b17d373b
68,519
import time import sys def get_item_test(key_count, iterations, dyn_resource=None): """ Gets items from the table a specified number of times. The time before the first iteration and the time after the last iteration are both captured and reported. :param key_count: The number of items to get fro...
aaf64be2c4885a25952f835ae4734696448f330e
68,520
def build(sch, inputs, outputs, name="hybrid_func"): """Dump the corrent schedule to hybrid module Parameters ---------- sch: Schedule The schedule to be dumped inputs: An array of Tensors or Vars The inputs of the function body outputs: An array of Tensors The outputs...
5a84a9eb11e3f370fdaa716e10c8b1af74c0da7e
68,521
from typing import Optional from typing import Union from typing import Sequence from operator import invert def psqi(data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None) -> pd.DataFrame: """Compute the **Pittsburgh Sleep Quality Index (PSQI)**. Parameters ---------- data : :...
5f64d336415db1ce595114fc5a3bd15ddf3c630f
68,522
from typing import List def create_app(routes: List[web.RouteDef]) -> web.Application: """Create web application.""" app = web.Application() app.add_routes(routes) return app
54d21870d7e3e1ac59c849910c499f4f7a61b0dc
68,523
def PositionCallback(cb): """Creates a position callback from a function pointer.""" return OSVR_PositionCallback(cb)
7041e412c885e95d10ac4f9028ea1808b0c63b16
68,524
def split_database(database=[], labels =[], test_size =float): """ Método que separa a base em vetores de treino e teste de acordo com uma porcentagem, dada no intervalo [0-1] :param database: matriz de dados já extraídos utilizando alguma técnica de extração :param labels: Classificação ref...
e382387a3e09708a5ac23222cba5925ef9f2d9ae
68,525
from typing import List def has_no_illegal_char(password: List[int]) -> bool: """True if the password contains none of the illegal chars.""" return not any(is_illegal_char(char) for char in password)
96973236b2a7462e5bb3a29796e904dad2bd26ac
68,526
def generate_distance_map(system): """ Precomputes a distance-map for all tasks in the system. """ dist = dict() for r in system.resources: for t in r.tasks: dist[t] = dijkstra(t) return dist
bd5deec714430581096edacff71f91a734de3317
68,527
def selection(): """Returns user selection and catches input errors. """ input_value = input("Select a number: ").strip() if input_value == "break": return "break" # catch input errors try: input_value = int(input_value) if (input_value > 0) and (input_value < 5): ...
ddbd04a0f14395543bf37ac8d29e19c9b3ccd8f2
68,528
from sys import path import os def plot_spectrum(sim, snap, num, low=0, high=-1, offset=0,subdir="", box=10): """Plot a spectrum""" hspec = get_hspec(sim, snap, snr=20., box=box) sdir = path.join(outdir,"spectra/"+subdir) if not path.exists(sdir): os.mkdir(sdir) xoff = hspec.plot_spectrum(...
7d0d6879cec52ad675326b896a783d9e91596936
68,529
def convert_to_feature(item, type): """Convert item to FeatureList. Args: item: item to be converted type: string denoting the type of item. Can be "float", "byte", or "int" """ if type == "float": item = tf.train.FloatList(value=item) item = tf.train.Feature(float_list=item) elif type == "by...
6b4990633a3e40fcad8107961cb4e33e7c882e49
68,530
from datetime import datetime def get_last_elapsed_tax_year() -> int: """Get last ended tax year.""" now = datetime.datetime.now() if now.date() >= datetime.date(now.year, 4, 6): return now.year - 1 return now.year - 2
ed7db4d597f2f125549e028651b5e88761ab641e
68,531
import copy def _consolidate_allocation_requests(areqs): """Consolidates a list of AllocationRequest into one. :param areqs: A list containing one AllocationRequest for each input RequestGroup. This may mean that multiple resource_requests contain resource amounts of the same class f...
d97e4ec9ba83cebca35c2a9a0538089ea713079a
68,532
from typing import List from re import T from typing import Dict def get_difference(previous_list: List[T], current_list: List[T]) -> Dict[int, T]: """ Get the difference between two lists. :param previous_list: First iteration of the list. :param current_list: Second iteration of the list :return...
df0833c3bdf66003075d84ed57f34dbd6285d1a4
68,533
def make_table(excel_file, excel_sheet, define_module, sheet_name): """从Sheet取出table来""" table = {} col_list = [] col_defines = {} key_name = define_module.config['key'] for row, row_values in enumerate(excel_sheet.rows): if row == 0: # 第1列为字段 for col_name in row_values: col_list.append(col_name) col...
e8ff77c4b53600208c800aa6ce1d35405e2054bb
68,534
def load_two_sp_sod_data(fle): """ Given filename `fle` corresponding to Sod shocktube spacetime data, return: space: 1D spatial coordinates of shocktube time: 1D temporal coordinates of shocktube sc_1 -> sc_2 : two spacecraft trajectories (x,t) through spacetime st_data: raw plasma var...
866b11ef7214856ae0ffd6e2496cd0cb81b5ffb5
68,535
import torch def ry(phi): """Single-qubit rotation for operator sigmay with angle phi. ------- result : torch.tensor for operator describing the rotation. """ return torch.cat((torch.cos(phi / 2).unsqueeze(dim=0), -1 * torch.sin(phi / 2).unsqueeze(dim=0), torch.sin(phi / 2).u...
c1ec83ecf85132f7522770db646b7e0e54a52279
68,536
def minmatch_factor_validator( count_df: DataFrame, column_index: int, min_match: float = 10, factor: float = 2 ) -> bool: """Validates min_match and factor for adapter/organism to be considered as resulting adapter/organism. Args: count_df: adapter: Adapters sequence co...
8d422dfafdd202a608713343a37689417c4d660b
68,537
from typing import Concatenate def CMTL(input_shape=None, num_classes=10): """ 定义模型 :param input_shape: :param num_classes: :return: """ inputs = Input(shape=input_shape) # shared layer shared = Conv2D(16, (9, 9), padding='same')(inputs) shared = PReLU(shared_axes=[1, 2])(shar...
4e26f7a2a32ba7c9de9406d692503d957be2b605
68,538
import numpy import torch def image_to_text(captions, images, npts=None, verbose=False): """ Images->Text (Image Annotation) Images: (5N, K) matrix of images Captions: (5N, K) matrix of captions """ if npts == None: npts = images.size()[0] / 5 npts = int(npts) ranks = nump...
88e10f7507f3d1e8cc0fc3860c582d1a2af0abde
68,539
def saveper(): """ Real Name: b'SAVEPER' Original Eqn: b'TIME STEP' Units: b'Month' Limits: (0.0, None) Type: component b'The frequency with which output is stored.' """ return time_step()
2be0ebe821720ef01e91987caddeebacb076dea1
68,540
def snr_ecc_evolving(m_1, m_2, f_orb_i, dist, ecc, harmonics_required, t_obs, n_step, position=None, polarisation=None, inclination=None, t_merge=None, interpolated_g=None, interpolated_sc=None, n_proc=1, ret_max_snr_harmonic=False, ret_snr2_by_harmonic=Fal...
84b1ba3a748bf24f18b97e1f5e11272f4613ce24
68,541
def paramvals_to_lindblad_projections(paramvals, ham_basis_size, other_basis_size, param_mode="cptp", other_mode="all", Lmx=None): """ Construct the separate arrays of Hamiltonian and non-Hamiltonian Lindblad-term projections from t...
e81fdfe52c781cb9982536e2dbe920ec64993e7d
68,542
import os from pathlib import Path def get_created_files(folder): """Return the generated tree of files (and their hash) and folders.""" files = {} for name in os.listdir(folder): path = Path(folder) # Current path # Add files and their hash if not isdir(path / name): ...
c4c1ef55b90ed2da17e06a01767122f684fe2080
68,543
def make_plural(word): """Makes word plural if it's a noun or verb. Returns None.""" # special if word == "I": return add_s(word) # elif is_foreign_origin(word): # return add_s(word) # fix this # elif is_irr_noun(word): return IRRNOUNS.get(word) # common elif final_es(...
a92046a5ff6f5fbc22a0e60124a91455c1582bc7
68,544
import time def execute_s3_tests(client_node, build): """ Execute the s3-tests Args: client_node: node to execute tests from Returns: 0 - Success 1 - Failure """ log.info("Executing s3-tests") try: base_cmd = "cd s3-tests; S3TEST_CONF=config.yaml ~/virtual...
71a11d5764b0ad02da284ff7f6b0f55e12136b60
68,545
from typing import List def read_odim(odim_file: str, lazy_load: bool = True, **kwargs) -> List: """ Read an ODIM H5 file. Parameters: =========== odim_file: str ODIM H5 filename. lazy_load: bool Lazily load the data if true, read and load in memory the entire dataset ...
ae3150d0b0eb13dc54a757c4169ae9be7cf5d50a
68,546
import sys import math def determine_material(state, verbosity=0): """ Determine the material, diameter, or mass, provided the other two are known. If all three are known or less than two are known, this does nothing. If material is given, but not material_density, material_density is taken from...
07fd6cf2cb2cb93989fb9faafc2b80ce3971fabe
68,547
def objdict_to_dict(objdict): """ convenience for debugging/comparing dictionaries of objects """ return dict(zip(map(str, objdict.keys()), map(vars, objdict.values())))
c396fe3f1c86511635b6589dd269d30e2ce038c1
68,548
import getpass def getSystemUserName(): """Finds out user inf (currently just the logged user name) for Windows and Posix machines. sets a USER_NAME variable containing the logged user name defines a UNKNOWN_USER variable to which username falls back. :return: (str) current user name """ try:...
71ca83d73358d2ef220071ecf52af8a3975db17f
68,549
def get_backbone(l_sites, r_sites, rootsMask=None, N=None, include_tails=True): """Find the positions between the root loops aka the backbone. """ backboneidxs = [] if rootsMask is None: rootsMask = get_roots(l_sites, r_sites) rootsSorted = np.where(rootsMask)[0][np.argsort(l_sites[rootsMas...
034075eaf00111d535446bdc79642eaa56da7b63
68,550
import argparse def parse_commandline(): """ Parse command line arguments. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--config_file', type=str, default='', action='store', help='JSON co...
af45518da3ed15cfbcf77c2c40a354abda25ca4b
68,551
from typing import Optional def get_json_download(prefix: str) -> Optional[str]: """Get the download link for the latest OBOGraph JSON file.""" entry = get_resource(prefix) if entry is None: return None return get_external(prefix, "obofoundry").get("download.json")
ab973e0bcb850fea194324b5cd58e23026d79ff1
68,552
import math def most_probable_isotopic_composition(*args, **kwargs): """Calculate the most probable isotopic composition of a chemical formula or |Composition| object. For each element, only two most abundant isotopes are considered. Parameters ---------- formula : str, optional A st...
f649f86cc777c2e0c9bdb72c1cfecbe42a437058
68,553
def get_new_thread_name(extra_prefix=""): """ <Purpose> Returns a new and unique name that can be associated with a new thread. This is used so that threads can be uniquely identified. This call is thread safe, and guarentees unique-ness. <Arguments> extra_prefix: This is an optional...
69cb2024c2fa331b7e3a53e5399164ec50fba037
68,554
import numpy def partition(a, b, n): """ Utility routine to construct the non-uniform partition, t, for the interval [a,b] using (n+1) nodes. For convenience I just use the Chebyshev nodes of the second kind. Returns t as a column vector. """ return ((a+b)/2 - (b-a)/2*numpy.cos(numpy.linspac...
68d6e0093a6e7115ebeadfc5852132f531e2260e
68,555
import binascii def opcode_list(script): """Disassemble the given script. Returns a list of opcodes.""" opcodes = [] pc = 0 while pc < len(script): opcode, data, pc = get_opcode(script, pc) if len(data) > 0: opcodes.append(binascii.hexlify(data).decode("utf8")) ...
3a0cb9c8059fd1e95049dc68243f2f1a001be3e3
68,556
def make_subfolder(path, subfolder): """helper method that puts given file in given subfolder""" basename, dirname = path.name, path.parent path = dirname.joinpath(subfolder, basename) path.parent.mkdir(exist_ok=True, parents=True) return path
473f71f6ac74fe40eeb1b96c584a37f4d16d130b
68,557
def swap_diff(start, goal, limit): """A diff function for autocorrect that determines how many letters in START need to be substituted to create GOAL, then adds the difference in their lengths. """ # BEGIN PROBLEM 6 list_start = list(start) list_goal = list(goal) def count_changes(lst_st...
436ac431133e9b5e0aeb9d0df930e521eb329ee9
68,558
def xrf_peak(name=None, amplitude=1, sigma=0.1, center=None, shape='gaussian', sigma_params=None, **kws): """create an XRF Peak Parameters: ----------- name: name of peak -- may be used for auto-setting center 'Fe Ka1', 'Pb Lb1', etc amplitude: center: si...
67202dec44c2530e0a886f077cdc6309e664e7ad
68,559
def GetColumns(dBase, table, fieldString, user='sysdba', password='masterkey', join='', cn=None): """ gets a set of data from a table **Arguments** - dBase: database name - table: table name - fieldString: a string with the names of the fields to be extracted, this should be a comm...
c21d80d495a9fe5c65ffe6994a67630b3aa46153
68,560
import os import fnmatch def match_file(filename, exclude): """Return True if file is okay for modifying/recursing.""" base_name = os.path.basename(filename) if base_name.startswith('.'): return False for pattern in exclude: if fnmatch.fnmatch(base_name, pattern): return ...
1cbbb851d1f06aef401e348150ae6da2727963d6
68,561
def read_csv_labels(fname): """读取fname来给标签字典返回一个文件名""" with open(fname, 'r') as f: # 跳过文件头行(列名) lines = f.readlines()[1:] tokens = [l.rstrip().split(',') for l in lines] return dict(((name, label) for name, label in tokens))
bb5a6c9ddacb6566b3b5d44af5f55b09fb6691ea
68,562
def foodHeuristic(state, problem): """ Your heuristic for the FoodSearchProblem goes here. This heuristic must be consistent to ensure correctness. First, try to come up with an admissible heuristic; almost all admissible heuristics will be consistent as well. If using A* ever finds a solutio...
2f8c46700b983641a840b5975fa115343b48923a
68,563
def cw_cloed_form(time_span, n, delta_r0, delta_v0): """ Computes the closed form solution of the CW equations in the LVLH frame Arguments: time_span : time_span of the orbit n : mean motion delta_r0 : Initial conditions of position delta_r0 = [x,...
45d77d6cc056a2c6549ac7c958880db8d5238551
68,564
def emojify_hunger(level: int) -> str: """Create a hunger emoji track.""" filled = level unfilled = 5 - level hunger = [__hungermoji(True) for _ in range(filled)] unfilled = [__hungermoji(False) for _ in range(unfilled)] hunger.extend(unfilled) return " ".join(hunger)
4bc5ee055af8701ae7f857927d01d877aca662dc
68,565
def assemble_helmholtz_kernel( sources, targets, wavenumber, dtype=np.complex128, parallel=True ): """ Assemble the Helmholtz kernel matrix for many targets and sources. Returns the Helmholtz kernel matrix for the Green's function g(x, y) = exp(1j * k * | x- y| ) / (4 pi * | x - y |) Paramete...
35d8077866a69f631d053364611ad5a6f4ebe245
68,566
def exists(name): """Returns true if the evaluation exists""" if reseval.is_local(name): return False try: # Get config config = reseval.load.config_by_name(name) # Get credentials credentials = reseval.load.credentials_by_name(name, 'crowdsource') except File...
987aede5b62d59bed47db367e62a19d058b92689
68,567
def voxelPathList2matrix(voxelPathList): """ voxelPathList: ['~/Datasets/3d-r2n2-datasat/ShapeNetVox32/03001627/1a8bbf2994788e2743e99e0cae970928', ...] Returns: List_size x 1 x 32 x 32 x 32 (numpy array) """ size = len(voxelPathList) voxels = np.zeros((size,) + g.VOXEL_INPUT_SHAPE, dtype=np.floa...
d9abb9dceae0daa24a785b331735a3d1af1bce05
68,568
def test_twoAxesOffAxis(l, n): """Test for a system with two axes. Three values, two on-axis, one off-axis. >>> test_twoAxesOffAxis(0, 0) 0 >>> test_twoAxesOffAxis(1, 1) 50.0 >>> test_twoAxesOffAxis(2, 2) 200.0 >>> test_twoAxesOffAxis(1, 0) 100.0 >>> test_twoAxesOffAxis(0, 1) ...
79c065294063e6c0e70bcb54264e6cfb66e28a95
68,569
def fix_orientation(img, save_over=False): """ `img` can be an Image instance or a path to an image file. `save_over` indicates if the original image file should be replaced by the new image. * Note: `save_over` is only valid if `img` is a file path. """ path = None if not isinstance(img, Im...
65b24c6db2c09859e697caf61ce958071b324b28
68,570
import os def parse_edl(edl_path, fps): """Parse EDL and return list with EDL Events. Args: edl_path (str): Absoulte path to EDL. fps (float): Frame Rate for EDL calculations. Returns: Edl: EDL instance. """ edl = None parser = Parser(fps) # Clear members, so th...
b52b6c1bb700380638d5b920286191b9996d4d00
68,571
import tempfile def get_logprop_file(logger, template, pattern, project): """ Return the filename of file with logging properties specific for given project. """ with open(template, 'r') as f: data = f.read() data = data.replace(pattern, project) with tempfile.NamedTemporaryFile...
061254a5e65a08c7e5ee8367c94abaee04238e61
68,572
def load_img(image_buffer): """ 画像ファイル(バイトデータ)をPILで読み込む :param image_buffer: 画像ファイルのバイトデータ :return: PIL.Imageオブジェクト """ return Image.open(BytesIO(image_buffer))
e3b2546f9a515726787e90265949e74622a13b7a
68,573
from datetime import datetime import os def create_working_dir(): """ Create working directory for running metrics. All files generated by the metrics evaluation are written to this directory. """ working_dir = 'metrics-' + str(datetime.datetime.now().timestamp()).split('.')[0] os.mkdir(workin...
5e2fb11cd039a634ca6158b80939386597db6ccd
68,574
def get_driver_list(): """ Return the names of the registered object storage drivers :return: list of strings from driver names """ return object_store.ObjectStorageDriver.registry.keys()
c992e933c1d002518b604d41a7983e37f051691d
68,575
from typing import Dict def colour_style(use_style: Boolean = True) -> Dict: """ Returns *Colour* plotting style. Parameters ---------- use_style Whether to use the style and load it into *Matplotlib*. Returns ------- :class:`dict` *Colour* style. """ constan...
ba969f603c5724002a38102ed19676140b59b386
68,576
def quantize(image, nlevels): """Quantize an image into integers 0, 1, ..., nlevels - 1. image -- a numpy array of type float, range [0, 1] nlevels -- an integer """ tmp = np.array(image // (1.0 / nlevels), dtype="i1") return tmp.clip(0, nlevels - 1)
3746b6aa322561ccd02654a6b0c1b034e5cdce0f
68,577
def _parser_parse_expr_to_str(text): """Return parse tree from `tla.parser.parse_expr`.""" r = parser.parse_expr(text, nodes=to_str.Nodes) text = r.to_str(width=80) return r
f53c7d2cd2b48bb4d1ae114969aff9ce30a13b00
68,578
def Iyy_beam(b, h): """gets the Iyy for a solid beam""" return 1 / 12. * b * h ** 3
8912b769b1bf8f91d2bb7eefad261c0e4f9f4026
68,579
import ctypes def create_rects(rect_list): """ Create a vertex buffer for a set of rectangles. """ v2f = [] for shape in rect_list: v2f.extend([-shape.width / 2, -shape.height / 2, shape.width / 2, -shape.height / 2, shape.width / 2, shape.height / 2, ...
34de899d55523ddae3998ca87248608de3cfb7ce
68,580
def _get_grouped_pathways(end_nodes_dict): """ From end_nodes_dict, makes a list of grouped_pathway lists""" grouped_pathways = [] for end_nodes in end_nodes_dict: for reactions in end_nodes_dict[end_nodes]: for scores in end_nodes_dict[end_nodes][reactions]: grouped_path...
7d969fa8f18061847f3f71de0a02799e845fc55d
68,581
import posixpath def relpath(path, start): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = posixpath.abspath(start).split(posixpath.sep) path_list = posixpath.abspath(path).split(posixpath.sep) # Work out how much of the filepath i...
c2f5b054387a565a11a21643b96a8a82781475ff
68,582
def _get_client_ip(request) -> str: """ Get client ip address from request instance. We can fetch ip address from these classes. - django.core.handlers.wsgi.WSGIRequest - rest_framework.request.Request """ ip: str x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if ...
950169b8b1052057eec14e03e8d6fbc9d162662d
68,583
import re def tokenize(tweet): """Removes punctuation & excess whitespace, sets to lowercase, and stems tweets. Returns a list of stemmed tokens.""" tweet = " ".join(re.split("[^a-zA-Z]*", tweet.lower())).strip() # tokens = re.split("[^a-zA-Z]*", tweet.lower()) tokens = [stemmer.stem(t) for t in t...
f89578a80873c74e58c03811d91f51b5eb088c4e
68,584
from typing import Dict import json def generate_rewards_in_range( chain: str, start: int, end: int, save: bool, past_tree: Dict, tree_manager: TreeManager, boosts: Dict, ): """Generate chain rewards for a chain within two blocks :param chain: chain to generate rewards :param ...
c0a6627ee30ac1f34965d22c91444ad63eeb06b0
68,585
def is_up(element1, element2): """Is element2 on the up of element1. Args: element1: XML element1 dump from UI. element2: XML element2 dump from UI. Returns: Whether element2 is on the up of element1. """ [e1_x1, e1_y1, e1_x2, e1_y2] = get_element_bounds(element1) [e2_x1, e2_y1, e2_x2, e2_y2] ...
1c5d0b2c6171e63dff47e245e1eb6b2b7fcfe26e
68,586
from typing import Callable import torch from typing import Tuple def im_path_to_tensor(im: str, transform: Callable[[Image.Image], torch.Tensor]) -> Tuple[torch.Tensor, Tuple[float, float]]: """Converts an image into a network input. Parameters ---------- im : str a color image in BGR order ...
f6b8a476696bb55997997525634bcb4a7426a1bf
68,587
import os def findResourceFile(module, resourceFile=None): """we look for the file specified in argument in the following directories: 1 - current directory 2 - user's home directory 3 - the package to which this instance belongs to Returns a list of three tuples ('home',path),('currentdir',pa...
6a5f964fcc4e0a2b5c4c5e530542848dac48d2e3
68,588
from typing import Dict from typing import Tuple import logging import os def get_engines(connection_dict: Dict[str, str]) -> Tuple[Engine, Engine]: """ Generates Snowflake and Postgres engines from env vars and returns them. """ logging.info("Creating database engines...") env = os.environ.copy(...
f4c452f7f9d39315ad97323a490e7f886ebfb030
68,589
import os def test_read_aws_credentials_profile(monkeypatch): """Test read_aws_credentials() if through a profile environment variable. """ v = {'LTD_MASON_AWS_ID': 'key-id', 'LTD_MASON_AWS_SECRET': 'key-secret', 'LTD_MASON_AWS_PROFILE': 'aws-profile'} missing = ('LTD_MASON_AWS_ID', ...
97598139e1696e8e2b24003e91bf851c6724bc71
68,590
import logging def read_contours_text(boxed_image, contours, img): """store on the location where it is located in the image. here it will be top-left pixel location as the key""" logging.info('Reading the text inside the contour plotted') image_text_dict = get_text_with_location(boxed_image, contours, im...
dc4f426d823a1dc7e11e4db502048714cf632a5c
68,591
def convert_audio_segment(audio_segment): """ Create a GCS AudioSegment """ audio_segment \ .set_channels(1) \ .set_sample_width(2) \ .set_frame_rate(__sample_rate(audio_segment)) return audio_segment
ca100cee32fa715b039a79fa2d1018d0fb9c6052
68,592
import logging import os import itertools def get_handler(filename: 'str | os.PathLike[str]') -> logging.FileHandler: """Cycle log files, then give the required file handler.""" name, ext = os.path.splitext(filename) suffixes = ('.5', '.4', '.3', '.2', '.1', '') try: # Remove the oldest one....
3968dd6d12353b3e05116b12d6a4964f6b39c878
68,593
import sys def si2_power_req(eta, To, Ts): """" Calculates energy requirements for S-I 2 case. Values from 'Efficiency of hydrogen production systems using alternative nuclear energy technologies', Yildiz et al., May 2005. Parameters: ----------- eta: thermal-to-electrical conversion effic...
c0f897bf3f12a64406dd08aea043e31a797d0e15
68,594
def _Volume(kwargs): """成交量图""" df = kwargs.get('df') limit_start = kwargs.get('limit_start') limit_end = kwargs.get('limit_end') colors = kwargs.get('colors') data = df.loc[limit_start:limit_end, :] hovertext = _get_date_hovertext(data) trace = go.Bar( x=np.arange(data.shape[0])...
c7d3456fa2005df192e52793fa640f5331197fd7
68,595
def get_logging_format_string(package): """Get format string for all loggers Discovers all modules to determine the space needed to nicely format log messages from all modules. """ module_names = get_dot_separated_submodule_names(package) max_module_name_length = max(len(name) for name in modul...
7b81ffeec2767c8687cf1757dca5a4a31c4d0557
68,596
def multicast(self, subject=None, subject_selector=None, selector=None): """Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each subscription to the resulting sequence causes a separate multicast invocation, exposing ...
b9dd224e5a3fff883072f5dde058bdd37c20adfe
68,597
import tqdm import torch def compute_compression(model, data, context, batch_size, verbose=False, tbw=None, tok=None, skip=0): """ Compute the _compression_ of a dataset under a model. That is, given a model, in how many bits could we represent the dataset. This requires us to tu...
3db6da12eb00b4250bd4df34dff37e00a8e2d16a
68,598
def panel2array(panel): """convert the panel to datatensor (numpy array) without btc """ without_btc = np.transpose(panel.values, axes=(2, 0, 1)) return without_btc
4efc88dd11cde14fa291547f6bc4def95f3860d1
68,599