content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple def watermark_pdf(input_file: str, wm_text: str, pages: Tuple = None): """ Adds watermark to a pdf file. """ result, wm_buffer = create_watermark(wm_text) if result: wm_reader = PdfFileReader(wm_buffer) pdf_reader = PdfFileReader(open(input_file, 'rb'), str...
3fb4d51a88db9c509842ee76b7fee22af30a358d
3,637,000
def wrapper_configuration_get(): # noqa: E501 """gets configuration details on the current wrapper configuration # noqa: E501 :rtype: object """ return 'do some magic!'
85ac6abbf09f93a08295584d7051aad2e8cad8d6
3,637,001
def update_qgs(): """Generate QGIS project files.""" try: # create ConfigGenerator generator = config_generator() qgs_writer_log = generator.write_qgs() return { 'message': "Finished writing QGIS project files", 'log': qgs_writer_log } except ...
1cb7f6f844fc40b611dc49b8f2b5a8de795e04e0
3,637,002
from typing import Tuple from typing import List import warnings def time_evolution_derivatives( hamiltonian: pyquil.paulis.PauliSum, time: float, method: str = "Trotter", trotter_order: int = 1, ) -> Tuple[List[circuits.Circuit], List[float]]: """Generates derivative circuits for the time evoluti...
fe793657d9fa199df174a288f59a390c7787598c
3,637,003
def had_cells_strength(strmfunc, min_plev=None, max_plev=None, lat_str=LAT_STR, lev_str=LEV_STR): """Location and signed magnitude of both Hadley cell centers.""" lat = strmfunc[lat_str] # Sometimes the winter Ferrel cell is stronger than the summer Hadley cell. # So find the glo...
ba8b4840a3e7e851a7156cd6aed1e3969e362692
3,637,004
def d_enter_waste_cooler(W_mass, rho_waste, w_drift): """ Calculates the tube's diameter of enter waste to waste cooler. Parameters ---------- W_mass : float The mass flow rate of waste, [kg/s] rho_waste : float The density of liquid at boilling temperature, [kg/m**3] w_drift...
651c1adc0b90a286c2c8685c389268bc8834ad73
3,637,005
async def finalize_round(request, persistence): """Finalize an owned round.""" game_id = request.match_info['game_id'] round_name = request.match_info['round_name'] user_session = await get_session(request) if not client_owns_game(game_id, user_session, persistence): return json_response({'...
21c07b35eb366d1ca78a90940bfb85772469683f
3,637,006
def _arrs_to_ds(arrs, names=None): """Combine DataArrays into a single Dataset.""" if names is None: names = [str(n) for n in range(len(arrs))] return xr.Dataset(data_vars=dict(zip(names, arrs)))
5672ba30c43d646a637d1db5735df23f916f012b
3,637,007
from datetime import datetime import time def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) ...
b36e68466c05eb33f178d2568b3c2ff21bc9c707
3,637,008
def exitFlow(x, n_classes): """ Create the exit flow section x : input to the exit flow section n_classes : number of output classes """ def classifier(x, n_classes): """ The output classifier x : input to the classifier n_classes : number of o...
95ac0696e03cb6e3320cebd20790e2f07c69d4ee
3,637,009
import os def get_files_for_variable(cmake_path, variables, variable): """ Returns the path values associated with |variable| and relative to the |cmake_path| directory. """ if not variable in variables: raise Exception('Variable %s does not exist' % variable) # Cmake file directory. ...
aaaeec33895b9cea3856f7ab9d304b15c34b152c
3,637,010
from typing import Optional def SingleChannelDDR4_2400(size: Optional[str] = "1024MB") -> SingleChannel: """ A single channel DDR3_2400. :param size: The size of the memory system. Default value of 1024MB. """ return SingleChannel("DDR4_4Gb_x8_2400", size)
10a83cd74b55f5ec93812fd1d52c8d753d9024d4
3,637,011
def convert_Pa_to_dBSPL(pa): """ Converts units of Pa to dB re 20e-6 Pa (dB SPL) """ return 20. * np.log10(pa / 20e-6)
a14991c7923b7ceb46f279a95b3ef64ff648ae57
3,637,012
def isPalindromic(seq): """ is a sequence palindromic? returns True or False """ if rc_expanded(seq.lower()) == seq.lower(): return(True) return(False)
bbe011e0b599f8df417ffc10eef0ace0d8f08d37
3,637,013
import os def get_corpus(data_dir): """Get list of words in the text. Args: data_dir: data directory. Returns: list of str words. """ corpus = [] files = os.listdir(data_dir) for filename in files: data_path = os.path.join(data_dir, filename) if not os.path...
57cbc16f3ab2767e5a44fd261e6a31b14b8ddb06
3,637,014
import numpy import random def randomPairsMatch(n_records_A: int, n_records_B: int, sample_size: int) -> IndicesIterator: """ Return random combinations of indices for record list A and B """ n: int = n_records_A * n_records_B if not sample_size: return iter([]) elif sample_size >= n:...
2cd6f905933149b4f23f656e9db44f57830e1eb9
3,637,015
import logging def GetScaffoldLengths(genome_fna_fp): """ This function gets the lengths of the scaffolds, returns a dict Args: genome_fna_fp: (str) Path to genome fna file (FASTA) Returns: Scaffold_To_Length: (dict) scaffold_name: (str) -> length (int) """ Scaffold...
cee4c6a3d9171dc86563e5f74dae6fbdfcb0556a
3,637,016
import re import os import time def approx_version_number(): """ In the event that git is unavailable and the VERSION file is not present this returns a "version number" in the following precedence: - version number from path downloads of viral-ngs from GitHub tagged re...
16adf3e5c274cf86bc9a7b3b53889e5340021798
3,637,017
def flip_mesh(mesh): """ It flips the mesh of a shape. ---------------------------- Args: mesh (obj: 'base.Trimesh'): The mesh of a shape Returns: mesh (obj: 'base.Trimesh'): The flipped mesh of the shape """ triangles = np.zeros((3, len(mesh.faces))) for i, index in en...
a527b47a4f1c184a97d4ee7005d05be7926e0258
3,637,018
def leaky_twice_relu6(x, alpha_low=0.2, alpha_high=0.2, name="leaky_relu6"): """:func:`leaky_twice_relu6` can be used through its shortcut: :func:`:func:`tl.act.ltrelu6`. This activation function is a modified version :func:`leaky_relu` introduced by the following paper: `Rectifier Nonlinearities Improve N...
17c4fce9bd8803cda254fb28cde72e5401760c3d
3,637,019
def fully_connected(inputs, num_outputs, scope, use_xavier=True, stddev=1e-3, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, ...
01646dd4d18a210b298c313b13a03274c69fd127
3,637,020
def _x_orientation_rep_dict(x_orientation): """"Helper function to create replacement dict based on x_orientation""" if x_orientation.lower() == 'east' or x_orientation.lower() == 'e': return {'x': 'e', 'y': 'n'} elif x_orientation.lower() == 'north' or x_orientation.lower() == 'n': return {...
83434a8aef7003146a19c470b831e8e9cfa85f19
3,637,021
def move_at_objc_to_access_note(access_notes_file, arg, offset, access_note_name): """Write an @objc attribute into an access notes file, then return the string that will replace the attribute and trailing comment.""" access_notes_file.write(u""" - Name: '{}' ObjC: true""".format(access_note_name)) ...
6037b6db15188ce43771d47f01518994f562d409
3,637,022
def test_idempotent_lambda_with_validator_util( config_without_jmespath: IdempotencyConfig, persistence_store: DynamoDBPersistenceLayer, lambda_apigw_event, timestamp_future, serialized_lambda_response, deserialized_lambda_response, hashed_idempotency_key_with_envelope, mock_function, ...
75e0d3a8aabb3e3520c06a0268a7e2d1e534d249
3,637,023
import os import shutil def load_pdbbind_fragment_coordinates(frag1_num_atoms, frag2_num_atoms, complex_num_atoms, max_num_neighbors, neighbor_cutoff, ...
b1ad0cba65ad7e199d167aed9a0c0b569d4cfedd
3,637,024
def get_version_if_modified(gh_type, repo_name, typ, force=False): """ Return the latest version if the latest version is different from the previously indexed version. Return None if no change. if force in True, always return the latest version """ latest_version = get_latest_version(gh_typ...
51dcd251dece6e6e401261f79007be8fcd653844
3,637,025
import requests import json def do_rest_request(**kwargs): """This function expects full_url or in absence of which, expects a combination of "url" and "query_params""" if 'full_url' in kwargs: query_url = kwargs['full_url'] elif 'rest_url' in kwargs and 'query_params' in kwargs: query_ur...
0ee2d7e20ca98e2c73b8d4b3e89d709a1b14a911
3,637,026
def variable(init_val, lb=None, ub=None): """ Initialize a scalar design variable. :param init_val: Initial guess :param lb: Optional lower bound :param ub: Optional upper bound :return: The created variable """ var = opti.variable() opti.set_initial(var, init_val) if lb is not N...
6cd346effba937a43c555e3e0e1e7b3fecf231e3
3,637,027
def current_user() -> str: """ Retorna o usuário corrente. """ session_id = request.get_cookie(cookie_session_name()) c = get_cursor() c.execute( """ select username from sessions where session_id = :session_id """, {"session_id": session_id}, ) ...
ec2b16f671a9fd11762160bcb73f770d9bc5eb7a
3,637,028
async def async_setup(hass, hassconfig): """Setup Component.""" hass.data.setdefault(DOMAIN, {}) config = hassconfig.get(DOMAIN) or {} hass.data[DOMAIN]['config'] = config hass.data[DOMAIN].setdefault('entities', {}) hass.data[DOMAIN].setdefault('configs', {}) hass.data[DOMAIN].setdefault('...
5708286ac76bc01ff8b979632d8d030192600e3f
3,637,029
def mplplot(peaklist, w=1, y_min=-0.01, y_max=1, points=800, limits=None): """ A no-frills routine that plots spectral simulation data. Arguments --------- peaklist : [(float, float)...] a list of (frequency, intensity) tuples. w : float peak width at half height y_max : flo...
92e6d268d1a2fcd818ca6f28e84ad0b925e09c7a
3,637,030
def get_node_centroids(mesh): """ Calculate the node centroids of the given elements. Parameters ---------- mesh : list of dicts or single dict each dict containing at least the following keywords nodes : ndarray Array with all node postions. ...
eb7244184921a9728ce12e0f7eaf46bd52cf2399
3,637,031
def find_saas_replication_price(package, tier=None, iops=None): """Find the price in the given package for the desired replicant volume :param package: The product package of the endurance storage type :param tier: The tier of the primary storage volume :param iops: The IOPS of the primary storage volu...
5f3abdd4a2edd24abd8c19752316b06e76212532
3,637,032
def _get_option_of_highest_precedence(config, option_name): """looks in the config and returns the option of the highest precedence This assumes that there are options and flags that are equivalent Args: config (_pytest.config.Config): The pytest config object option_name (str): The name of...
4f3bca4ff5b0a1eb04fbdc7a5d22bc09dbc95df6
3,637,033
def get_industry_categories(): """按编制部门输出{代码:名称}映射""" expr = STOCK_DB.industries.drop_field('last_updated') df = odo(expr, pd.DataFrame) res = {} for name, group in df.groupby('department'): res[name] = group.set_index('industry_id').to_dict()['name'] return res
5b50dc2845a903e56071b57b0ee8d307f5e52f27
3,637,034
def rate(t, y, dt, elph_tau, pol_tau, delay, start): """Rate equation function for two state model. y[0] is charge transfer state, y[1] is polaron state, elph_tau is electron-phonon scattering constant, pol_tau is polaron formation constant.""" dydt = [(pulse(t, dt, delay, start) - (y[0] - y[1])/elph_t...
dd98606f0ab4dd5c3334acfbd080959ac4921030
3,637,035
import copy def trace_module(no_print=True): """ Trace my_module_original exceptions """ with putil.exdoc.ExDocCxt() as exdoc_obj: try: docs.support.my_module.func('John') obj = docs.support.my_module.MyClass() obj.value = 5 obj.value except: ...
f407cba3f2ae8582bdaa685ae5bcba1ca908e9a9
3,637,036
def data_to_seq(X, Y, t_lag=8, t_future_shift=1, t_future_steps=1, t_sw_step=1, X_pad_with=None): """Slice X and Y into sequences using a sliding window. Arguments: ---------- X : np.ndarray with ndim == 2 Y : n...
477366408309483eb1c9dcc2d90c70f7bd3ab143
3,637,037
import time import os def masterbias(files,med=False,outfile=None,clobber=True,verbose=False): """ Load the bias images. Overscan correct and trim them. Then average them. Parameters ---------- files : list List of bias FITS files. med : boolean, optional Use the median of a...
43b6e905545d57e65b44b16787d67a5c8e2964e4
3,637,038
def get_model_kind(model): """Returns the "kind" of the given model. NOTE: A model's kind is usually, but not always, the same as a model's class name. Specifically, the kind is different when a model overwrites the _get_kind() class method. Although Oppia never does this, the Apache Beam framework...
58465fd8d9a7893aeb046b5e05e713a912ff4a2f
3,637,039
def get_Zvalence_from_pseudo(pseudo): """ Extract the number of valence electrons from a pseudo """ with open(pseudo.get_file_abs_path(),'r') as f: lines=f.readlines() for line in lines: if 'valence' in line: try: return int(float(...
aade59ef7d9d7d517c19f95d237993433f21ed7a
3,637,040
import ruptures as rpt def detect_data_shifts(time_series, filtering=True, use_default_models=True, method=None, cost=None, penalty=40): """ Detect data shifts in the time series, and return list of dates where these data shifts occur. Parameters ----...
d924d36a53f965b76943f1a466d3b88649cbe0ef
3,637,041
def read_rds(filepath): """Read an RDS-format matrix into a Pandas dataframe. Location can be data, scratch, or results. Index is populated from first column""" raw_df = pyreadr.read_r(filepath)[None] if raw_df.isnull().values.any(): raise ValueError("NaN's were found in the data matrix.") ...
c4b171638883fc2c3b32397e79a413a9441567f0
3,637,042
def history(): """Show history of transactions.""" # Read Transactions database for desired elements transactions = db.execute("SELECT symbol, share, price, method, timestamp FROM Transactions WHERE id = :uid", uid = session["user_id"]) # Convert prices to 2 decimal places for transaction in tr...
5eac4a49c473467db851fe2ea6e58b29cc1a9bfe
3,637,043
import os import urllib import torch def _load_expert_models(scenario_name, run_id, len_stream): """Load ExML experts. If necessary, the model are automatically downloaded. """ # base_dir = f'/raid/carta/EXML_CLVISION_PRETRAINED_EXPERTS/{scenario_name}' base_dir = default_dataset_location( ...
a972a04997ebf7f092c4ec4256a48f25eb8f3f0c
3,637,044
from typing import get_args def generate_args(job_name, common, cloud_provider, image, k8s_version, test_suite, job): """Returns a list of args fetched from the given fields.""" args = [] args.extend(get_args(job_name, common)) args.extend(get_args(job_name, cloud_provider)) args...
7f53dcf66269b0d14f9fad1c1079cf1716529f09
3,637,045
import math def isPrime(n): """ check is Prime,for positive integer. 使用试除法 """ if n <= 1: return False if n == 2: return True i = 2 thres = math.ceil(math.sqrt(n)) while i <= thres: if n % i == 0: return False i += 1 return True
458775fbd324dc976c91a035898b3122e6bc1109
3,637,046
from typing import Tuple import torch def reconstruction_loss(loss_type: str, in_dim: Tuple[int], x: torch.Tensor, x_reconstr: torch.Tensor, logits: bool = True, ) -> torch.Tensor: """ Compu...
30dbd75eddbc7f2d0994f867e2f9492b24f707b1
3,637,047
def NOR(*variables): """NOR. Return the boolean expression for the OR of the variables. Equivalent to ``NOT(OR(*variables))``. Parameters ---------- *variables : arguments. ``variables`` can be of arbitrary length. Each variable can be a hashable object, which is the label of t...
e3b9d5eb3c167ac04de66609828583bb5eeb7004
3,637,048
import io import time def timing_run(args, shell: bool = False, stdin=None, stdout=None, stderr=None, environ=None, cwd=None, resources=None, identification=None, shuffle=False) -> RunResult: """ Create an timing process with stream :param args: arguments for execution :param shell: use...
936d9611769dc5e04381131cd7bf18be73580bb3
3,637,049
def alterMethods(cls): """ Alter Monte methods on behalf of AutoHelp. Return the signatures of the altered methods. NOT_RPYTHON """ atoms = [] imports = set() def nextName(nameIndex=[0]): name = "_%d" % nameIndex[0] nameIndex[0] += 1 return name execNames...
9c1dcbda1a96196bdde3f31563d53f8c2be6eeb1
3,637,050
from typing import List from typing import Union def make_multiclouds(docs: List[Union[dict, object, str, tuple]], opts: dict = None, ncols: int = 3, title: str = None, labels: List[str] = None, show: bool = True, ...
9c1f6363d1cc6cd0e20591c1ab54b1761414d29c
3,637,051
def action_prop(param, val=1): """A param that performs an action""" def fdo(self): self.setter(param, val) return fdo
6a4f6e7e178e62755113d6b93a59534675dfa2dd
3,637,052
def find_or_create(find, create): """Given a find and a create function, create a resource if it doesn't exist""" result = find() return result if result else create()
ffe608bf2da1b83d662b93266f4309976424300f
3,637,053
import math def Gsigma(sigma): """Pickle a gaussian function G(x) for given sigma""" def G(x): return (math.e ** (-(x**2)/(2*sigma**2)))/(2 * math.pi* sigma**2)**0.5 return G
77eac3ca8b6ced0063074527b83c50e8681f980d
3,637,054
from indico.modules.events.contributions.ical import generate_contribution_component def session_to_ical(session, detailed=False): """Serialize a session into an iCal. :param session: The session to serialize :param detailed: If True, iCal will include the session's contributions """ calendar = i...
9f0cb5a5ce6f31c6690b71948fbe6e8eeb2f7080
3,637,055
def _normalize_hosts(hosts): """ Helper function to transform hosts argument to :class:`~elasticsearch.Elasticsearch` to a list of dicts. """ # if hosts are empty, just defer to defaults down the line if hosts is None: return [{}] # passed in just one string if isinstance(hosts,...
ef3a6cfadd6a297f31afdfec4b8a77a0f88cd08f
3,637,056
def data(self: Client) -> DataProxy: """Delegates to a :py:class:`mcipc.rcon.je.commands.data.DataProxy` """ return DataProxy(self, 'data')
072806ad6f27e8bd645bd04cf34619946a83bf06
3,637,057
def proximal_policy_optimization_loss(advantage, old_prediction, loss_clipping=0.2, entropy_loss=5e-3): """ https://github.com/LuEE-C/PPO-Keras/blob/master/Main.py # Only implemented clipping for the surrogate loss, paper said it was best :param advantage: :param old_prediction: :param loss_clip...
ca7e1a602a6da6236fbd85facb373fa623fc62d5
3,637,058
import re def tokenize_string(string): """Split a string up into analyzable characters. Returns a list of individual characters that can then be matched with the regex patterns. Note that all accent characters can be found with the range: \u0300-\u036F. Thus, strings are split by [an...
f3757e190f99d3430dee17ca51ea6a6d7fa70ff9
3,637,059
def compute_final_metrics(source_waveforms, separated_waveforms, mixture_waveform): """Permutation-invariant SI-SNR, powers, and under/equal/over-separation.""" perm_inv_loss = wrap(lambda tar, est: -signal_to_noise_ratio_gain_invariant(est, tar)) _, separated_waveforms = perm_inv_loss(source_waveforms,sepa...
3e7a6a52b8a26c4a4fa7fec9de17559617e4d467
3,637,060
import numpy import pandas def gen_sdc_pandas_series_rolling_impl(pop, put, get_result=result_or_nan, init_result=numpy.nan): """Generate series rolling methods implementations based on pop/put funcs""" def impl(self): win = self._window minp = self._min_...
8fb25c10e862d21af75b244053ac96075c1efa19
3,637,061
def gen_random_colors(num_groups, colors=None): """ Generates random colors. Parameters ---------- num_groups : int The number of groups for which colors should be generated. colors : list : optional (contains strs) Hex based colors that should be appended if no...
462835c6bacd5024ac20bab960d2c2e9d95e4dab
3,637,062
import os def get_file_creation_date(path): """ Get the file creation date. """ assert_file(path) creation_timestamp = os.path.getctime(path) creation_date = dt.datetime.fromtimestamp(creation_timestamp) return creation_date
87d5c985269448b1fc549fb03fb1cb09e7113f4f
3,637,063
import os import subprocess def eval_moses_bleu(ref, hyp): """ Given a file of hypothesis and reference files, evaluate the BLEU score using Moses scripts. """ assert os.path.isfile(hyp) assert os.path.isfile(ref) or os.path.isfile(ref + "0") assert os.path.isfile(BLEU_SCRIPT_PATH) com...
c15259875549a9d447b0270b1202bb62c290aa42
3,637,064
def build_graph(sorted_sequence): """ Each node points to a list of the nodes that are reacheable from it. """ elements = set(sorted_sequence) graph = defaultdict(lambda : []) for element in sorted_sequence: for i in [1, 2, 3]: if element + i in elements: grap...
a14d2278909df459856e23c7073d551b354f258d
3,637,065
from numpy import std def _findCentralBond(mol, distmat): """ Helper function to identify the atoms of the most central bond. Arguments: - mol: the molecule of interest - distmat: distance matrix of the molecule Return: atom indices of the two most central atoms (in order) """ # ge...
bbaca8c48bf8c5e1a5d2ffa317448f05235c834e
3,637,066
def transform(data, transformer): """This hook defines how DataRobot will use the trained object from fit() to transform new data. DataRobot runs this hook when the task is used for scoring inside a blueprint. As an output, this hook is expected to return the transformed data. The input parameters are p...
b52577c0b2a3f3edb1297dcf9c567f9845f04bd5
3,637,067
import asyncio import base64 async def sign_params(params, certificate_file, private_key_file): """ Signs params adding client_secret key, containing signature based on `scope`, `timestamp`, `client_id` and `state` keys values. :param dict params: requests parameters :param str certificate_file: p...
be9980e5fb0b60da8a21c77b4ac7c9795560b557
3,637,068
def sum_of_fourth_powers(matrix): """ :param matrix: (numpy.ndarray) A numpy array. :return: The fourth power of the four-norm of the matrix. In other words, the sum of the fourth power of all of its entries. """ squared_entries = matrix * matrix return np.sum(squared_entries * squared_e...
51039a259594205a88b223b1e3d8387e05581c0f
3,637,069
from typing import Dict def key_in_direction(start: Key, direction: str, keypad: Keypad) -> Key: """ Return the value of the key in the given direction. """ row = next(r for r in keypad if start in r) x_pos = row.index(start) col = [c[x_pos] for c in keypad] y_pos = col.index(start) d...
c0a8909517ec1de29325d0acc18e0c8968bda3b5
3,637,070
def vectorize_args(nums): """ Decorator for vectorization of arguments of a function. The positions of the arguments are given in the tuple nums. See numpy.vectorize. """ def wrap(func): @wraps(func) def wrapped(*args, ** kwargs): args = list(args) for i,...
cd9b13bdcd26f1c74a2eaa18396ebfb11ed02446
3,637,071
def parse_lambda_config(x): """ Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease # to 0 during the first 1000 iterations ...
d85980c2efd46284de8e939f42ef4f5dd49dfd73
3,637,072
def format_cols(colname, direction='in'): """Formats columns beween human-readable and pandorable Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero ... if direction == 'in': ...
a61dbedb2e08c4de03c719c4daff10de41e19304
3,637,073
def convert_decimal_to_binary(number): """ Parameters ---------- number: int Returns ------- out: str >>> convert_decimal_to_binary(10) '1010' """ return bin(number)[2:]
01a9be2e70c87091adc1d85759075668da9270f2
3,637,074
from typing import Optional import pathlib import tarfile def fetch_tgz( dataname: str, urlname: str, subfolder: Optional[str] = None, data_home: Optional[str] = None, ) -> pathlib.Path: """Fetch tgz dataset. Fetch a tgz file from a given url, unzips and stores it in a given directory. ...
00c4f91a657e37767a43b3af0766b5b407144617
3,637,075
def choisir_action(): """Choisir action de cryptage ou de décryptage Entree : - Sortie: True pour cryptage, False pour décryptage""" action_est_crypter = True action = input("Quelle est l'action, crypter ou décrypter ? \n<Entrée> pour crypter, autre touche pour decrypter, ou <Crtl> + Z ou X pour arréter.\n") ...
c0bceb748afb1fc32b865136c4a477f06a6412b2
3,637,076
def σ(u, p, μ): """Stress tensor of isotropic Newtonian fluid. σ = 2 μ (symm ∇)(u) - p I This method returns a UFL expression the whole stress tensor. If you want to plot, extract and interpolate or project what you need. For example, to plot the von Mises stress:: from dolfin import ...
03f61ea7c128503ee930714107a8f7a007641cee
3,637,077
async def cycle(command: Command, switches: PowerSwitch, name: str, portnum: int): """cycle power to an Outlet""" command.info(text=f"Cycle port {name}...") for switch in switches: current_status = await switch.statusAsJson(name, portnum) if current_status: break # print(...
7b5a17eaeecb4d8f1072f014de716bb1bb95dc97
3,637,078
def zk_delete_working_node(zk_client, server): """删除服务节点""" node_path, root_path = get_path_to_current_working_node(server) zk_client.ensure_path(root_path) result = zk_client.delete(node_path, ephemeral=True) return result
45effe39d8cd5eb22742c6eed19984ae40b0e192
3,637,079
import torch def construct_filters_from_2d(matrix, filter_starts, decomp_level): """ construct the filters in the proper shape for the DWT inverse forward step Parameters ---------- matrix filter_starts decomp_level Returns ------- """ exp = filter_starts[0] low = ma...
10411e774dc654586cd9b88b40e405b695a12919
3,637,080
def minpoly(firstterms): """ Return the minimal polynomial having at most degree n of of the linearly recurrent sequence whose first 2n terms are given. """ field = ring.getRing(firstterms[0]) r_0 = uniutil.polynomial({len(firstterms):field.one}, field) r_1 = uniutil.polynomial(enumerate(rev...
8cad899aa40859884b4cdbe01b0734de84782804
3,637,081
def scale_gradient(tensor, scale): """Scales the gradient for the backward pass.""" return tf.add(tensor * scale ,tf.stop_gradient(tensor) * (1 - scale))
e3ea3a7baf06ebab5de0510ea13260e89b9397ca
3,637,082
import torch import os import pickle def get_cluster_assignments(args, model, dataset, groups): """ """ # pseudo-labels are confusing dataset.sub_classes = None # swith to eval mode model.eval() # this process deals only with a subset of the dataset local_nmb_data = len(dataset) // a...
ece4965e17720ca03c2c34b093a01ce446cf833b
3,637,083
import ast import random def t_rename_local_variables(the_ast, all_sites=False): """ Local variables get replaced by holes. """ changed = False candidates = [] for node in ast.walk(the_ast): if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): if node.id not i...
8faeea81faac55d5d45b897776cd87cb508404a5
3,637,084
from typing import List def get_scale(notes: List[str]) -> int: """Convert a list of notes to a scale constant. # Args - *notes*: list of notes in the scale. This should be a list of string where each string is a note ABC notation. Sharps should be represented with a pound sign preceding...
91cbcc7bfa05df52adf741b85f78beeabf819966
3,637,085
import math def slurm_format_bytes_ceil(n): """ Format bytes as text. SLURM expects KiB, MiB or Gib, but names it KB, MB, GB. SLURM does not handle Bytes, only starts at KB. >>> slurm_format_bytes_ceil(1) '1K' >>> slurm_format_bytes_ceil(1234) '2K' >>> slurm_format_bytes_ceil(12345678) ...
ce48c778b9605105ed9b66a55d27796fb90499cc
3,637,086
def factory_payment_account(corp_number: str = 'CP0001234', corp_type_code: str = 'CP', payment_system_code: str = 'PAYBC'): """Factory.""" return PaymentAccount( corp_number=corp_number, corp_type_code=corp_type_code, payment_system_code=payment_system_code, ...
896fe2ac0162455c4da97bd629d0e3f2d9b2a1e2
3,637,087
import glob def p_l_species_input_geos(wd, ver='1.7', rm_multiple_tagged_rxs=False, debug=False): """ Extract prod/loss species (input.geos) and reaction tags (globchem.dat) Parameters ---------- wd (str): Specify the wd to get the results from a run. debug (boolean): legacy debug option, rep...
f316fe2616c8c37e129b88d50b7e1db1330bfd80
3,637,088
def foo(): """多参数函数的传参书写格式, 和类实例化的格式""" ret = foo_long(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8) # 类实例化,传多个参数的格式 object_ = ClassName( a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8 ) return ret
4571ef723cab1601acfa01eb0765eaf8002df2e0
3,637,089
def posture_seq(directory,postures,sampling_fraction): """posture_seq grabs samples locomotion files from a directory and converts them to strings of posture_sequences Input: directory = the directory containing locomotion files postures = the mat file or numpy array of template postur...
7e1554f85dfc68b293c9db5a5db3aa5bd6414bff
3,637,090
from ._finite_differences import _window1d, _lincomb import torch def membrane_diag(voxel_size=1, bound='dct2', dim=None, weights=None): """Diagonal of the membrane regulariser. If no weight map is provided, the diagonal of the membrane regulariser is a scaled identity with scale `2 * alpha`, where `...
3329c43aa5ae025a14660e1ddd4c1f658740e1d4
3,637,091
import os import tty def openpty(mode=None, winsz=None, name=False): """openpty() -> (master_fd, slave_fd) Open a pty master/slave pair, using os.openpty() if possible.""" master_fd, slave_fd = os.openpty() if mode: tty.tcsetattr(slave_fd, tty.TCSAFLUSH, mode) if tty.HAVE_WINSZ and winsz...
08dcc90967b32509775e86d6da338788e15014c4
3,637,092
def get_groups(parsed, store, conf): """ Return groups based on argument provided :param Namespace parsed: arguments parsed :param store: Otter scaling group collection :param dict conf: config :return: Deferred fired with list of {"tenantId": .., "groupId": ..} dict """ log = mock_log...
0441863984173236b09b50987c6f22838679a497
3,637,093
import json def get_content_details(site_code, release_uuid, content_type, content_key): """ get_content_details """ publisher_api = PublisherAPI() content_release = None try: if release_uuid: # get ContentRelease content_release = WSSPContentRelease.objects.get( ...
f71a4e4584474e24cfb6d25aad2465538575cbdf
3,637,094
import scipy def _czt(x, M=None, W=None, A=1.0): """Calculate CZT (Stripped down to the basics).""" # Unpack arguments N = len(x) if M is None: M = N if W is None: W = np.exp(-2j * np.pi / M) A = np.complex128(A) W = np.complex128(W) # CZT algorithm k = np.arange(...
a0852eacd8d4e35e0c6e96cc59e8692d9d806c5d
3,637,095
import subprocess import threading def measure_link_vsize(output_file, args): """ Execute |args|, and measure the maximum virtual memory usage of the process, printing it to stdout when finished. """ proc = subprocess.Popen(args) t = threading.Thread(target=measure_vsize_threadfunc, ...
ca918a111dd5c8a627538f30554cae21331f9558
3,637,096
from typing import Any from typing import Optional def build_obs_act_forward_fc( n_out: int, depth: int, hidden: int, act_layer: Any, last_layer: Optional[Any] = None, ) -> hk.Transformed: """Build a simple fully-connected forward step that takes an observation & an action. Args: ...
0d330910730ccf80213852aa7cd08950f09e6300
3,637,097
def update_nested(key, d, other): """Update *d[key]* with the *other* dictionary preserving data. If *d* doesn't contain the *key*, it is updated with *{key: other}*. If *d* contains the *key*, *d[key]* is inserted into *other[key]* (so that it is not overriden). If *other* contains *key* (and poss...
efbbfd576652710c92939581c48e32edce1a956e
3,637,098
def quicksort(arr, low, high): """ Quicksort function uses the partition helper function. """ if low < high: pi = partition(arr, low, high) quicksort(arr, low, pi-1) quicksort(arr, pi+1, high) return arr
aa51f8536f47f8529c2bda74ea96138062d939e7
3,637,099