content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_task_status(bucket: Bucket, job_id: str, task_id: str) -> TaskStatus: """Get the status of a task. Parameters ---------- bucket : Bucket The Google Cloud Storage bucket that hosts th egiven job and task. job_id : str The ID of the job. task_id : str The ID of the...
f939d85beb8a6927150494e425f5eabad50bb9b5
3,608,100
import json def get_chosen_file_path(file_path='dataset/json/directory.json', key=None): """ This function returns the name of file which is selected from list of default methods. :param file_path: path to file from where the filename should be read against a given key. :param key: key for whi...
54336abd282f63e717c17c19b0d7270b28d29ecf
3,608,101
from ase import Atoms from ase.constraints import FixAtoms, FixScaled from ase.data import chemical_symbols import numpy as np def read_vasp(filename='CONTCAR'): """Import POSCAR/CONTCAR type file. Reads unitcell, atom positions and constraints from the POSCAR/CONTCAR file and tries to read atom types fr...
0eec2146da1ea5e08d10af3c722a5733667d0595
3,608,102
def _subject_update(context, values, subject_id, purge_props=False, from_state=None): """ Used internally by subject_create and subject_update :param context: Request context :param values: A dict of attributes to set :param subject_id: If None, create the subject, otherwise, fi...
ecc1094ef99ed61e72525208c6823f4e4e8e2681
3,608,103
def connect_db(path: str) -> str: """ Set up sqlite3 connection """ return 'sqlite://{}'.format(path)
ace41ad5609d927a987a9ed2d18f7abd64439bb3
3,608,104
import json def read_prediction_tokens(pred_file): """ Reads in the tokens from the tagger's output file. Returns: a String list """ tokens = [] with open(pred_file, encoding="utf-8") as f: for line in f: j = json.loads(line) tokens.extend(j["words"]) retur...
a8da9ff58a83db4df628f1f98b33133ff94805e0
3,608,105
from functools import reduce def get_color_list(timestamps, colors, rgbaf=False): """ Given a list of valid colors (rgb/rgba tuples, shorthand hex string or integer representation) and a list of time-stamps, create a Color object with rgba/rgbaf values of the form: [time_0, r_0, g_0, b_0,..., time_k, r_k,...
95d825eba87cc52fbaf2c2b8f0425088ac976994
3,608,106
def create_random_pdt_agent(depth, n_actions, window=1, temperature=1.0): """ Generate random PDT agent with specified depth and branching factor. Args: depth: int, depth of tree. n_actions: int, number of children at each node. temperature: float, controls entropy of distribution > 1.0 is more random, < 1.0 i...
34af92fed9af84b99b19cf331ca4753e1cf6cc38
3,608,107
import urllib def read_historical_data(start_date, end_date): """Read all of the historical data starting at start_date""" def daterange(start, end): for day in range(int((end-start).days)+1): yield start + dt.timedelta(day) result = [] for day in daterange(start_date, end_date): ...
22ab1099b2ec82237eff321526ed9374efdc0490
3,608,108
import math def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) ...
f2d2d6a7e731abbd9e4fa50e28abf26d3d691600
3,608,109
def make_test_set(filename): """ Read test data from the file whose path is filename. Return a list with the same form as the training set, except that each dictionary has an additional key "prediction" initialized to "none" that will be used to store the label predicted by the class...
b5603122b6e44e3cb9dd2326de9ce16b54fed59b
3,608,110
def pose_metrics(dE): """ Translation/Rotation/Scaling metrics from Sim3 """ t, q, s = dE.data.split([3, 4, 1], -1) ang = SO3(q).log().norm(dim=-1) # convert radians to degrees r_err = (180 / np.pi) * ang t_err = t.norm(dim=-1) s_err = (s - 1.0).abs() return r_err, t_err, s_err
02d21f7a3711c7f2f8ea852c1e4724c982b92230
3,608,111
def cli(ctx, name="", deleted=False, slug=""): """Get all published histories (by any user), or select a subset by specifying optional arguments for filtering (e.g. a history name). Output: List of history dicts. """ return ctx.gi.histories.get_published_histories(name=name, deleted=deleted, slug=slug...
3a0eca578e105f005d80380043296c9a47ace6a8
3,608,112
from typing import Dict def _deserialize_dict(x: Dict) -> Dict: """Deserialize dict. Args: x (Dict): value to deserialized. Returns: Dict: deserialized dictionary. """ out_dict = {} for k, v in x.items(): if v is None: # if {'key':None} out_dict[k] = None...
e4a609d0935cd08548902e055e3e429559757e84
3,608,113
def mode(numbers: list) -> dict: """ Returns the mode of a list of numbers as a dictionary. Parameters: numbers (list) : A list of numbers """ numbers.sort() ordered_list = [] i = 0 while i < len(numbers): ordered_list.append(numbers.count(numbers[i])) i += 1 ...
f0909d2ffe800c8cf159943bddc02fdced70b17f
3,608,114
import os def _get_legend_file(bars, output_dir): """ Get the legend basename :param bars: iterable pbreports.plot.helper.Bar :param output_dir: Where to write file :return (string) filename """ fig = PH.get_bar_plot_legend_fig(bars) fname = 'variants_plot_legend.png' fig.savefig(o...
b0607c2491d9f0d9560d20605f70915cf42d65b3
3,608,115
def calculate_prior(user_input, DF_obs, obs_flux_arr_dict, obs_err_arr_dict, grids_dict, grid_spec, grid_rel_err): """ Calculate the (linear probability space) prior over the grid, selecting the type of prior based on the request of the user (or the default). In...
f324da5688e1cd811b94b2951055d61f0b2b3791
3,608,116
def infection_rate_symptomatic_80x60(): """ Real Name: b'infection rate symptomatic 80x60' Original Eqn: b'Susceptible 60*Infected symptomatic 60x80*contact infectivity symptomatic 60x80*(self quarantine policy SWITCH self 60\\\\ * self quarantine policy 60+(1-self quarantine policy SWITCH self 60))/non con...
ec2fed1ebba19244c3c97e7723185eacd078cc27
3,608,117
def hamming_dist(a: bytes, b: bytes) -> int: """Find the bitwise Hamming distance between two bytestrings.""" return sum(bin(v).count("1") for v in strxor.strxor(a, b))
b4b682eb6d3aad93f4619407dadff90583ec84b9
3,608,118
def fill_array(blocklist, maxsize, numdata, numblocks, blocksize): """ Fills a new array of integers with the indices corresponding to the specified block structure. Parameters ---------- blocklist : list List of integers describen the block indices that go i...
4440847cb3b1ac07a5c53e76be2387131ddffd3e
3,608,119
from re import L def summarization_splitter(m, arch): """Custom param splitter for summarization models""" model = m.hf_model if (hasattr(m, 'hf_model')) else m if arch in ['bart', 'pegasus']: embeds = nn.Sequential( model.model.shared, model.model.encoder.embed_positions,...
9f855601efdd7ded92245a45b8b8fe4550990c1b
3,608,120
import multiprocessing import random def get_data( path = "../data/", language_list = ["chinese", "english"], encoding_list = ["UTF-8", "UTF-8"], shuffle = True ): """Get data from path Args: path: a string represents corpus path of each language. language_list: a list of string...
9c8f007d4c0ab121c5182817651884a0b9a50455
3,608,121
def birdsong_rec_xml_file(): """annotation file from Birdsong Recognition dataset""" return BIRDSONG_REC_ROOT / 'Bird0/Annotation.xml'
2179439caac004e23312d28dca5f8ee2182384bf
3,608,122
import os def parse_error(output_dir): """Add contents of eplusout.err and put it in the exception message. :param output_dir: str :return: str """ err_file = os.path.join(output_dir, "eplusout.err") if os.path.isfile(err_file): with open(err_file, "r") as f: ep_err = f.rea...
3ed08db4162d0a64909e65ce7942110406aad808
3,608,123
import sys def alpha_014(code, end_date=None, fq="pre"): """ 公式: CLOSE-DELAY(CLOSE,5) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name return JQDataClient.instance().get_alpha_...
6ebdcf1b32c3d9db9ec74f9a3a289132c202dc14
3,608,124
def is_buffer_empty(nvim: Nvim) -> bool: """is_buffer_empty Checks if the buffer is empty. """ return get_buffer_contents(nvim) == [""]
dce9ec9b7d9ac0420a6faeda077412ca149985eb
3,608,125
def _displace_matrix(max_repeat): """This is a helper function for cell_list_nl""" d = [] n_repeat = max_repeat*2 + 1 tot_repeat = tf.reduce_prod(n_repeat) for i in range(3): d.append(tf.cumsum(tf.ones(n_repeat, tf.int32), axis=i) - max_repeat[i] - 1) d = tf.reshape(tf.s...
f4de7b9d13f525b7532a1d4598a99f2101e28cac
3,608,126
def divide_line_by_count(line, n_segments): """ Returns a list whose length is equal to n_segments of LineStrings divided from the line input :param line: LineString :param n_segments: int :return: """ assert len(line) == len(n_segments), AssertionError("Arrays of different sizes") splitters = [[ln.in...
af3de59ee9a6741cc15d44d4f3897169edcd0605
3,608,127
def get_genotype(chrom, rsid): """:TODO switch to reading HDF5 """ geno_path = ('/home/hsuj/lustre/geno/' 'CCF_1000G_Aug2013_Chr{0}.dose.double.ATB.RNASeq_MEQTL.txt') geno_gen = pd.read_csv(geno_path.format(str(chrom)), sep=" ", chunksize = 10000) for i in geno_gen: ...
d70fafcaeb40fe8f9b6788c0cc11a79859bb51dd
3,608,128
def nuisance_shift_scale(fit): """Determine a shift and scale factor that rescales nuisance parameters to be centered at 0 and varying by O(1).""" return par_shift_scale(fit.par_obj, fit.nuisance_parameters)
23fa32659aa1badf3f7d19e655389ed4c5772d36
3,608,129
import numpy def get_coverage_from_cost(spending, inflection_cost, saturation, unit_cost, popsize, alpha=1.): """ Estimate the coverage associated with a spending in a program. Args: spending: The amount of money allocated to a program (absolute value, not a proportion of all funding) inf...
81ea2c2e2067be8237de3f5f6a134c6c5f1aafee
3,608,130
def expireNonFungible(id): """Expire non fungible product reservation This does not delete the record. This call marks it expired. --- parameters: - in: path name: id required: true description: non fungible product reservation ID type: integer responses: ...
589bf39de78e0330980fd08b0e0a95d0ba72fd12
3,608,131
def str2bool(to_test): """ Convert a string into a boolean. Example: >>> str2bool("False") False >>> str2bool("True") True """ if to_test == "True": return True elif to_test == "False": return False else: return None
73f7e8429dda134cb283e012f0eae853ae5e3eb6
3,608,132
def protected_sqrt(x1): """Closure of square root for negative arguments.""" return cp.sqrt(cp.abs(x1))
5be0d35c0cbd80841acacba98c0132e7eeb9c29c
3,608,133
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 10) # 4 * 3 * 2 * 1 # Only n times!! 24 """ if (n > k): tota...
f33935ee505ef2d0c570003ee4661f4c923a1037
3,608,134
import json def json_dumps(value, indent=2): """ JSON dumps that supports Unicode and the :code:`as_raw` property of objects if available. """ return json.dumps(value, indent=indent, ensure_ascii=False, cls=JsonAsRawEncoder)
e3b505cdf0e94419c15aa5b102c35691b91ac7cd
3,608,135
import ast def parse_version(fpath): """ Statically parse the version number from a python file """ if not exists(fpath): raise ValueError('fpath={!r} does not exist'.format(fpath)) with open(fpath, 'r') as file_: sourcecode = file_.read() pt = ast.parse(sourcecode) class F...
71f0f8f63cf8ef289188c9499d8d7c4ccf3128c4
3,608,136
from wbia import plottool as pt import vtool as vt def in_depth_ellipse(kp): """ Makes sure that I understand how the ellipse is created form a keypoint representation. Walks through the steps I took in coming to an understanding. CommandLine: python -m tests.test_ellipse --test-in_depth_...
508e5b8717e961ce0556e5ed1af9b3e76e384437
3,608,137
def _get_setting(setting=False,host=False,hostTag=False): """ Returns the host's settings (or the specified one) """ if not host: if not hostTag: host = env.host else: for hostName in env.settings_by_host: if _has_tag(hostTag, hostName): ...
8bff7901ba6bc355789f20d9a914faa7b2a6ef20
3,608,138
async def get_userinfo(request): """ Return a dict with session informations { "username" <Std> "user_id" <Int> "is_admin" <Bool> } """ username = request.cirrina.web_session.get("username") if username: user = ( request.cirrina.db_session.query(...
dc0f8e789331d02dec51e59bfb8bf90fd2e1d6e5
3,608,139
def update_batch_entry(db_path, id, status, start_time, end_time): """ Update the status and the start/end time of a specified batch entry Return True if update succeeded, False otherwise Parameters ---------- db_path : string id : integer status : string start_time : datetime strin...
0a1ac1d4014003a756962a1111c8b3d228cffac0
3,608,140
import re def split_element_symbol(element): """ From element symbol, split charge and occupancy symbol, occupancy, charge = split_element_symbol('Co3+') Any numbers appended by +/- are taken as charge, otherwise they are counted as occupancy. e.g. element > symbol | occupancy | ...
97496f26ea68f5ccd8d3c2be90f651990a3084e2
3,608,141
def stable_rs(r): """Calculates r_s from r under stable population variance, where r^2 + r_s^2 = 1""" return np.sqrt(1 - np.square(r))
1987d7941c30763ea517a95b9e9ccc4e5fc536ff
3,608,142
import time def GALE2(n_proc=10,frontSize=100,iters=1000,model=DTLZ2(n_dec=30, n_obj=3)): """ WHY do threads take more time than single processors?? FIX THIS!!! :param n_proc: :param frontSize: :param iters: :param model: :return: """ t = time() collect=[] final = [] popSize = [int(frontSize/n...
dee916e3bff91a45d92a7e821fad461f5d556028
3,608,143
def pmm_compute(pmm, x): """For a given PMM object and x-coordinate, compute the probability matched value (i.e. the x-coordinate for which the target CDF has the same value as the source CDF). Parameters ---------- pmm: dict A PMM object returned by pmm_init. x: float The c...
1ccc6dd4f8ca3872fcdf8fbb5a47303c4aa9ef51
3,608,144
from subroutines import Factorizer, euler_totient def euler_problem_69(bound=10 ** 6): """ Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine an...
3cc53510f51ea72b7599e2db726513095ce5bcdf
3,608,145
def lp_nonempty_eqs(boxsize): """Linear equations (as lists of coefficients) which correspond to every cell having one symbol.""" return [lp_nonempty_eq(cell, boxsize) for cell in cells(boxsize)]
06c8f573851f468d7bd51818a1c0219fd0931c4f
3,608,146
def mask_large_samples(data, thres, obs_min, static=None, return_mask=False): """Remove outliers by cutoff in order to fit data into memory (one outlier patient has 11k observation values).""" result_data = [] n = len(data) #number of data views of compact format (values, times, indices, ..) mask = data...
0657841ccc7c0357f83c23d1d05393b77e419968
3,608,147
def shortid(obsid): """ Compact format for the observation id, like QPT Parameters ---------- obsid : string Program id string Returns ------- shortid : string Compact format """ idvals = obsid.split('-') shortid = idvals[0][-1] + idvals[1][2:] + '-' + idv...
cb163886e7612fa46d016f2037b110526967c61f
3,608,148
import os def test_initialize_upload(monkeypatch, mode): """Test initialize_upload(). :param monkeypatch: pytest fixture. :param mode: Scenario to test for. """ monkeypatch.setattr(api, 'upload_ftime_updir_writeprotect', lambda *_: None) uploaded = list() script_size = os.stat(interface.L...
7ddeef0a1492d8d9fcbb2a5da604f082d21b3f9d
3,608,149
def make_metrics(predictions, labels, encoded_variants): """Creates our evaluation metrics.""" # Define the metrics we'll get for each variant selection: raw_metrics = { 'Accuracy': tf.metrics.accuracy, 'Precision': tf.metrics.precision, 'Recall': tf.metrics.recall, 'FPs': tf.metrics.false...
d31a97ef70001674ae99f2864d171ae5e96c9fb5
3,608,150
async def textExtract_infer(body: dict, extractType: str, response: Response) -> dict: """textExtract_infer - endpoint for sentence transformer inference Args: body: dict; json format of query {"text": "i am text"} Response: Response class; for status codes(apart of fastapi do not ne...
8cd89cb7f8a0a8788d774680b4d188eb46ab4d20
3,608,151
def make_figure(df,pa): """Generates figure. Args: df (pandas.core.frame.DataFrame): Pandas DataFrame containing the input data. pa (dict): A dictionary of the style { "argument":"value"} as outputted by `figure_defaults`. Returns: A Plotly figure """ #UPLOAD ARGUM...
2e1be9d1268c17bc4a247e7b6d30b760a8b050fc
3,608,152
from typing import Optional def get_automation(automation_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAutomationResult: """ The security automation resource. API Version: 2019-01-01...
21c4568ac5fc99e52a33cd56d6156bd7bd613d64
3,608,153
from typing import Counter def find_children(dancing_brigade): """ "aAbaBb" => "AaaBbb". """ new = '' s = [x.lower() for x in dancing_brigade] d = Counter(sorted(s)) for x in d: new += (x * d[x]).title() return new
81d7dd9661fc73e6fcb24bc0e5318e298c41c3e5
3,608,154
import argparse import http def _make_argument_parser(): """Create the option parser. """ parser = argparse.ArgumentParser( description='Run HTTP check program.') parser.add_argument('-n', '--check-name', dest='check_name', type=str, required=True, default=None, ...
32ad8c44e3f92b67167d729635004614429cbd26
3,608,155
def get_type_code(stage: ImportStage, value: ir.Value) -> ir.Value: """Gets the TypeCode (see C++ BuiltinTypeCode) associated with a value. This always returns an integer<32>, which is expected by macros which operate on type codes. """ return d.GetTypeCodeOp(d.IntegerType.get_explicit(32), value).result
caf0fc6f8ef81961d576138073317cdba60bbb53
3,608,156
import glob import os import re def FindTtyByDriver(driver_name, interface_protocol=None, multiple_ports=False): """Finds the tty terminal matched to driver_name and interface protocol. Checks the interface protocol if specified. In some situations where there may e...
cf09d25c47aa5c2b894db7d01d208300d9a7224c
3,608,157
def _sequential_gaussian_tensordot(gaussian): """ Integrates a Gaussian ``x`` whose rightmost batch dimension is time, computes:: x[..., 0] @ x[..., 1] @ ... @ x[..., T-1] """ assert isinstance(gaussian, Gaussian) assert gaussian.dim() % 2 == 0, "dim is not even" batch_shape = gaussian....
0e5142fcce3d4b967b3b1f7291bbc0f791b6d596
3,608,158
import struct def read_fmt(fmt, fp): """ Reads data from ``fp`` according to ``fmt``. """ fmt = str(">" + fmt) fmt_size = struct.calcsize(fmt) data = fp.read(fmt_size) try: assert len(data ) == fmt_size, 'read=%d, expected=%d' % (len(data), fmt_size) except A...
3bcee164ca137d64f0a97621f6b3917b7ad60899
3,608,159
def _is_slot_attr(a_name, base_attr_map): """ Check if the attribute name comes from a slot class. """ return a_name in base_attr_map and _is_slot_cls(base_attr_map[a_name])
58810031dee5ff0e3ff390e7cf17f0b55166f966
3,608,160
def get_root_url(link_string): """ Will always return a string with a correct trailing slash or None for invalid string link: a string of a url in the form https://help.github.com/enterprise/2.7/user/ utilized tld to obtain the subdomain and tld of the string in order to return a string of t...
086364752974d0af88273e016e578e3e5d986443
3,608,161
import re import warnings def parse_url(url, warning=True): """Parse URLs especially for Google Drive links. file_id: ID of file on Google Drive. is_download_link: Flag if it is download link of Google Drive. """ # test=url.split('drive') # print(test) # if len(test)>1: # url='https://drive.{}'.format(test...
a3ddd648e455474986449f71060cf138df84fd9d
3,608,162
def compute_bt(bx, by, bz, bx_err, by_err, bz_err, mask, bitmask, nx, ny): """function: compute_bt This function calculates B_t, the total field, in units of Gauss. (The magnetic field has native units of Gauss since the filling factor = 1). """ bt = np.zeros([ny,nx]) bt_err = np.zeros([n...
d77a1748852462373bc19d18ca9da8d58676108e
3,608,163
def stdin(pattern, starting_string=None, grep_args=None, format_chained=True, chained=None, chained_status=None): """ Given a target string, call ``grep`` to search for for ``pattern`` in that string. By default, the ``starting_string`` will have ``.format()`` called on it with ``chained`...
dbd89d70b14c7ed7a0722489f66eadfa5a863f75
3,608,164
def fib_g(n) : """ The function fib_g is used to find the nth fibonacci number using the golden ratio i.e. 1.618033 by using the formula : fibonacci = (phi**n) / 5**(0.5). This results in a floating answer hence we use round function to round it off to the nearest integer. """ phi ...
062cd16968eb34cc5135cd79120ea16fd81f486a
3,608,165
import os def read_stellar_mags_frames(frame_pair_list_list, bands=('g', 'r'), verbose=True): """ Return stellar magnitudes as measured by SAMI (via interpolation), for the input files. """ mag_frame = [] for frame_pair_list in frame_pair_list_list: mag_fra...
f1ca1af920476e1ecf6cc8878825e315ca0907f4
3,608,166
from typing import Tuple import shutil def user_id_folder(request: FixtureRequest) -> Tuple[str, str]: """Create return a test user folder and the fitting user_id as Tuple. A finalizer is added to remove the created user folder at the end of the test. """ user_id = "test-user" folder = create_use...
d4263aedfd7700906938df036db171af249ded63
3,608,167
def RSI(df, n): """ 相对强弱指标 Args: df (pandas.DataFrame): Dataframe格式的K线序列 n (int): 周期n Returns: pandas.DataFrame: 返回的DataFrame包含1列, 是"rsi", 代表计算出来的相对强弱指标 Example:: # 获取 CFFEX.IF1903 合约的相对强弱指标 from tqsdk import TqApi, TqSim from tqsdk.ta import RSI ...
27dfe34d5659ee1577a481c7c5bb0072b2b4570d
3,608,168
def naked_twins(values): """Eliminate values using the naked twins strategy. Args: values(dict): a dictionary of the form {'box_name': '123456789', ...} Returns: the values dictionary with the naked twins eliminated from peers. """ # Find all instances of naked twins for uni...
5a14f73c2e055be0c1d03fd6145c83c7f8b73f4b
3,608,169
def show_all(): """ 显示所有用户微博""" resp = make_response(redirect(url_for('.index'))) resp.set_cookie('show_followed', '', max_age=30*24*60*60) return resp
196f7a23d08155d34e25d9163916d72402954d20
3,608,170
def nacl_bindings_pick_scrypt_params(opslimit, memlimit): """Python implementation of libsodium's pickparams""" if opslimit < 32768: opslimit = 32768 r = 8 if opslimit < (memlimit // 32): p = 1 maxn = opslimit // (4 * r) for n_log2 in range(1, 63): # pragma: no branch...
509b011c75bd3c62add012b6808521bacba7c5ea
3,608,171
import copy import re def parse_metadata(notebook_metadata): """Parse the Notebook's metadata and update it when needed. Args: notebook_metadata (dict): metadata annotated by Kale. Refer to DEFAULT_METADATA for defaults Returns (dict): updated and validated metadata """ # check f...
f770e54d80d61d9f49b375d6a025e34b0ca1355f
3,608,172
import re def columns_to_add(column_names): """Subsets the list for elements that contain mean and then rename them so they aren't called mean, these will be the new names for columns to be simluated probabilistically Inputs: column_names - a list of parameter names / df indexes ...
227dc85dab3fe35f999e416a44208a37d7e77665
3,608,173
import time def send_command_ps( self, command_string, read_timeout=30, timeout=120, inter_loop_sleep=0.1, initial_sleep=0.1, strip_prompt=True, strip_command=True, normalize=True, cutoff=0.6, nowait=False, ): """ Execute command_string_ps on the SSH channel using p...
8de00bdf0f4a9e8e1d39c1e12131a02ed16a9b42
3,608,174
def forcefield(x_lims, basis, force_coeffs): """Compute and save the force field that have been fitted Parameters ---------- x_lims: array, shape (dim_x,3) Bounds of the plot basis: GLE_BasisTransform instance The instance of the basis projection force_coeffs: array-like ...
a7e809a9243d74e62fcc476b2497e4642388e67e
3,608,175
import argparse import sys def __get_options(): """ Return rgb_to_xyz option parser Returns: .argparse.ArgumentParser.args """ # Define parser description = 'Print RGB -> RGB matrix' parser = argparse.ArgumentParser(description=description) # RGB colorspace colorspaces = sort...
1c53dc95d241bde212c30ebbaa43121ff1dab7a6
3,608,176
def get_email_password(): """Helper function that returns the tuple of defaul email and password""" email = 'test@greatsoft.uz' password = 'password1234' return email, password
80fe300fa0e7c316dc484b2d8ed2cb031d0215f1
3,608,177
def polyfit(dates, levels, p): """ Function that finds the least-square fit polynomial from Args: dates (list): The list of dates for the x-axis. levels (list): The corresponding water level for each date, y-axis. p (int): The degree of polynomial that is desired. Retur...
98b483de29537a479c3ee318c6bcf09b8333da3c
3,608,178
def guided_grad_cam(grad_cam_mask, guided_backprop_mask): """ Guided grad cam is just pointwise multiplication of cam mask and guided backprop mask, returns this multiplication GRAD_CAM_MASK: Class activation map mask GUIDED_BACKPROP_MASK:Guided backprop mask Attribution: https://github.com/utku...
203916a5f49b7c94874a67d2e0486c16f125171d
3,608,179
def check_name(f): """ Some backends to shelve do not accept unicode variables as keys. This decorator therefore converts a unicode project_name to a string before calling the wrapped method. See http://bugs.python.org/issue1036490 """ def wrapped(self, project_name, *args): project_nam...
94695439b43eee65fe7b4830304bd26faccd3725
3,608,180
from typing import Dict from typing import Any import configparser import ast def parse_config(config_string: str) -> Dict[str, Dict[str, Any]]: """Parse config for pipeline. Args: config_string: Configuration file rendered as a string. Returns: A dictionary mapping parameters for each p...
36ad0258335de406cc9fa2cc9535c681a815e5ff
3,608,181
import os from typing import Counter def assess_mhc_genes(job, gene_expression, rna_haplotype, univ_options, reports_options): """ Assess the prevalence of the various genes in the MHC pathway and return a report in the tsv format. :param toil.fileStore.FileID gene_expression: fsID for the rsem gene ...
bbbc814c120b81db47fde2a8cfe4b0069b0ef093
3,608,182
def parse_type_line(type_line, rcb, loc): """Parses a type annotation specified as a comment. Example inputs: # type: (Tensor, torch.Tensor) -> Tuple[Tensor] # type: (Tensor, Tuple[Tensor, Tensor]) -> Tensor """ arg_ann_str, ret_ann_str = split_type_line(type_line) try: arg...
fb79e6d42c13b452994f9eaed39a38b0652fcaa2
3,608,183
def get_unique_words(): """ Runs a COUNT DISTINCT on the word_details table """ return _execute_query(_GET_WORD_COUNT_QUERY)[0][0]
1c8564854f94eb286de6e201d6dd814cf4bb2374
3,608,184
import os def generate_out_file( output_dir , input_filename ): """ Generate a well-formed full file path for writing output stats """ if( output_dir == None ): return( None ) else: ## TODO - replace this and all path generation strings with ## OS generic version ...
19b10cf2a8cfdb3a8e1df123c331b75f9876e173
3,608,185
def unit_of_work(func, *args, **kw): """ Decorator that handles beginning and ending a unit of work. """ with inline_unit_of_work(): return func(*args, **kw)
d7e8d4b1cf940eacf90873d4a6993bdeb6ff0495
3,608,186
def UserUrlToUserId(user_url: str) -> int: """用户个人主页 Url 转用户 ID Args: user_url (str): 用户个人主页 Url Returns: int: 用户 ID """ AssertType(user_url, str) AssertUserUrl(user_url) json_obj = GetUserJsonDataApi(user_url) result = json_obj["id"] return result
f6ef535aafe2351964fc8214bc53554afbd29dd6
3,608,187
from typing import OrderedDict def job_prep_release_status_list_table_format(result): """Format job prep-release-status list as a table.""" table_output = [] for item in result: table_row = OrderedDict() table_row['Pool Id'] = item['poolId'] table_row['Node Id'] = item['nodeId'] ...
5b93ade505b166cd45539bfde49e8f51f2ffb9fb
3,608,188
import torch def log_likelihood(a: Tensor, b_lower: Tensor, b_upper: Tensor, t: Tensor) -> Tensor: """ Graded Response Model の log likelihood を計算する。 Σ log( sigmoid(a * (t - b_lower)) - sigmoid(a * (t - b_upper)) ) だが、素朴に計算すると桁落ちで誤差が大きくなったりするので対...
a5c4f61c1cb8ff7b8e30f2ea7ba750afb186a507
3,608,189
def rinko_p_prime(N, t, A, B, C, D, E, F, G, H): """ Per RinkoIII manual: 'The film sensing the water is affect by environment temperature and pressure at the depth where it is deployed. Based on experiments, an empirical algorithm as following is used to correct data dissolved oxygen.' Parameters ...
482f2286819af3d147cde4dd258c36c04624a6e8
3,608,190
def resnet_v2_101(inputs, num_classes=None, global_pool=True, reuse=None, scope='resnet_v2_101'): """ResNet-101 Model of [1]. See resnet_v2() for arg and return description.""" blocks = [ Block( 'block1', bottleneck, [(256, 64, ...
9a67ffc2cb40decab15d1007b7738d70e2e8a09e
3,608,191
def Mh(a: float, mu: float, t_r: float, t: float) -> float: """ Mh = sqrt(mu / a ** 3) * (t - t_r) :param a: semi-major axis :type a: float :param mu: G * (m1 + m2) :type mu: float :param t_r: reference time :type t_r: float :param t: time :type t: float :return: Mh angle ...
05fbb11f4b189be97569bd9b72f160e7c3253c76
3,608,192
def NotationRole(role, rawtext, text, lineno, inliner, options={}, content=[]): #pylint: disable=unused-argument, dangerous-default-value """Any text using the notation syntax (``@id``, ``{+, …}``, etc.). Use this to explain tactic equivalences. For example, you might write this:: :n:`generali...
e5669827a365f9377c8d68950e883283ce6fb29b
3,608,193
from typing import List from typing import Dict from typing import Tuple import math def render_points( points: List["Point"], view: Dict[str, float], fit_params: Dict[str, "Point"] = None, dims: Tuple[int, int] = (320, 320), ) -> Image.Image: """Creates an image of the points and the fitted plane...
a6ed1c188fe8c30e25ccf227dca34ed6179d49f5
3,608,194
def _index(i, size, Cartesian=True): """If Cartesian=True, index 0 is swapped with index 1.""" if Cartesian: if i == 1: return 0 if i == 0: if size >= 2: return 1 return i
ace0ff4431b64b545f2857eddce85d555a0cf5f3
3,608,195
import re def find_meta(meta): """ Extract __*meta*__ from META_FILE. """ meta_match = re.search( r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise
0a8706c7d6e712578178a33542692437aa9545be
3,608,196
def test_inject_prent(injector): """Dependencies must not be providable via parent class""" class A: pass class B(A): pass b = B() @injector.consumer def consume(a_: B): assert a_ is b @injector.provider def bean() -> A: return b with pytest.raise...
8dd8607c08fa885251bd0913163c94277ae33a64
3,608,197
import os def get_key_vault_credentials(): """This tries to get a token using MSI, or fallback to SP env variables. """ if "APPSETTING_WEBSITE_SITE_NAME" in os.environ: return MSIAuthentication( resource='https://vault.azure.net' ) else: return ServicePrincipalCrede...
bb71d893d00042aef8fcf19b3bb5f4603ce14a9d
3,608,198
def client_request_unauthenticated(): """ gets a mock client request object which is unauthenticated. :rtype: CoreRequestMock """ test_session_services.clear_current_request() test_session_services.inject_new_request() payload = DTO(sub=400, auth='test') access_token = token_services.g...
b1a4f6ebd9de8b88016ab262e52793d9dcd2767d
3,608,199