content
stringlengths
22
815k
id
int64
0
4.91M
def make_dirs(path): """ Creates any folders that are missing and assigns them the permissions of their parents """ logger.log(u"Checking if the path " + path + " already exists", logger.DEBUG) if not ek.ek(os.path.isdir, path): # Windows, create all missing folders if os.name ...
22,900
def download(url, filename, proxies=None): """ Telechargement de l'URL dans le fichier destination :param url: URL a telecharger :param filename: fichier de destination """ error = '' try: req = requests.get(url, proxies=proxies, stream=True) with open(filename, "wb") a...
22,901
async def validate_devinfo(hass, data): """检验配置是否缺项。无问题返回[[],[]],有缺项返回缺项。""" # print(result) devtype = data['devtype'] ret = [[],[]] requirements = VALIDATE.get(devtype) if not requirements: return ret else: for item in requirements[0]: if item not in json.loads(d...
22,902
def plot_artis_spectrum( axes, modelpath, args, scale_to_peak=None, from_packets=False, filterfunc=None, linelabel=None, plotpacketcount=False, **plotkwargs): """Plot an ARTIS output spectrum.""" if not Path(modelpath, 'input.txt').exists(): print(f"Skipping '{modelpath}' (no input.txt f...
22,903
def worldbank_date_to_datetime(date): """Convert given world bank date string to datetime.date object.""" if "Q" in date: year, quarter = date.split("Q") return datetime.date(int(year), (int(quarter) * 3) - 2, 1) if "M" in date: year, month = date.split("M") return datetime....
22,904
def PCopy (inCleanVis, outCleanVis, err): """ Make a shallow copy of input object. Makes structure the same as inCleanVis, copies pointers * inCleanVis = Python CleanVis object to copy * outCleanVis = Output Python CleanVis object, must be defined * err = Python Obit Error/message...
22,905
def isinf(x): """ 判断``x``是否是无限的,是则返回`True` """ pass
22,906
def select( key: bytes, seq: Sequence[BucketType], *, seed: bytes = DEFAULT_SEED ) -> BucketType: """ Select one of the elements in seq based on the hash of ``key``. Example partitioning of input on ``stdin`` into buckets:: bucketed_lines = {} # type: Dict[int, str] for line in sys.st...
22,907
def unescape(s): """ unescape html """ html_codes = ( ("'", '&#39;'), ('"', '&quot;'), ('>', '&gt;'), ('<', '&lt;'), ('&', '&amp;') ) for code in html_codes: s = s.replace(code[1], code[0]) return s
22,908
def ua_mnem(*args): """ua_mnem(ea_t ea, char buf) -> char""" return _idaapi.ua_mnem(*args)
22,909
def tic(*names): """ Start timer, use `toc` to get elapsed time in seconds. Parameters ---------- names : str, str, ... Names of timers Returns ------- out : float Current timestamp Examples -------- .. code-block:: python :linenos: :emph...
22,910
def convert_func_types_to_type_for_json(functions, types): """Converts parameters and return type of function declaration to json representation.""" for name, f_info in functions.items(): t = parse_type_to_type_for_json(f_info.ret_type_text, types) if t.type_hash not in types: types[...
22,911
def tile(fnames, resize=(64,64), textonly=0, rows=None, cols=None): """Tiles the given images (by filename) and returns a tiled image""" maxsize = [0, 0] assert fnames todel = set() for fname in fnames: try: im = Image.open(fname) maxsize = [max(m, s) for m, s in zip(...
22,912
def get_ctrls(controls, timeout=10): """Get various servod controls.""" get_dict = {} cmd = 'dut-control %s' % controls (retval, _, out) = do_cmd(cmd, timeout, flist=['Errno', '- ERROR -']) if retval: for ctrl_line in out.split('\n'): ctrl_line = ctrl_line.strip() if ...
22,913
def retrieve_database(): """Return the contents of MongoDB as a dataframe.""" return pd.DataFrame(list(restaurant_collection.find({})))
22,914
def test_package_inference(): """correctly identify the package name""" name = get_package_name(CachingLogger) assert name == "scitrack"
22,915
def try_download_ted3(target_dir, sample_rate, min_duration, max_duration): """ Method to download ted3 data set. Creates manifest files. Args: target_dir: sample_rate: min_duration: max_duration: Returns: """ path_to_data = os.path.join(os.path.expanduser("~"),...
22,916
def readAbstractMethodsFromFile(file: str) -> List[AbstractMethod]: """ Returns a list of `AbstractMethods` read from the given `file`. The file should have one `AbstractMethod` per line with tokens separated by spaces. """ abstractMethods = [] with open(file, "r") as f: for line in f:...
22,917
def create_file_object(list_of_files,repo) : """ This function create from the list of files stored in the repo the corresponding file_object """ for e in list_of_files : cat_and_ext = re.split(r'\.',e); f = file_object(e, re.sub('[^a-zA-Z]+', '',cat_and_ext[0]), ca...
22,918
def _find_possible_tox(path, toxenv): """Given a path and a tox target, see if flake8 is already installed.""" # First try to discover existing flake8 while(path and path != '/'): path = os.path.dirname(path) # the locations of possible flake8 venv = path + "/.tox/%s" % toxenv ...
22,919
def recursive_descent(data: np.ndarray, function: Callable): """ **Recursivly process an `np.ndarray` until the last dimension.** This function applies a callable to the very last dimension of a numpy multidimensional array. It is foreseen for time series processing expecially in combinatio...
22,920
def write_item_mtime(item, mtime): """Write the given mtime to an item's `mtime` field and to the mtime of the item's file. """ if mtime is None: log.warn(u"No mtime to be preserved for item '{0}'", util.displayable_path(item.path)) return # The file's mtime on disk...
22,921
def watt_spectrum(a, b): """ Samples an energy from the Watt energy-dependent fission spectrum. Parameters ---------- a : float Spectrum parameter a b : float Spectrum parameter b Returns ------- float Sampled outgoing energy """ return _dll.watt_spect...
22,922
def get_definition_from_stellarbeat_quorum_set(quorum_set: QuorumSet) -> Definition: """Turn a stellarbeat quorum set into a quorum slice definition""" return { 'threshold': quorum_set['threshold'], 'nodes': set(quorum_set['validators']) if 'validators' in quorum_set else set(), 'childre...
22,923
def values(names): """ Method decorator that allows inject return values into method parameters. It tries to find desired value going deep. For convinience injects list with only one value as value. :param names: dict of "value-name": "method-parameter-name" """ def wrapper(func): @wraps...
22,924
def select_user(with_dlslots=True): """ Select one random user, if can_download is true then user must have download slots available :returns User """ with session_scope() as db: try: query = db.query(User).filter(User.enabled.is_(True)) if with_dlslots: ...
22,925
def set_rf_log_level(level): """Set RooFit log level.""" if level not in RooFitLogLevel: return ROOT.RooMsgService.instance().setGlobalKillBelow(level)
22,926
def silero_number_detector(onnx=False): """Silero Number Detector Returns a model with a set of utils Please see https://github.com/snakers4/silero-vad for usage examples """ if onnx: url = 'https://models.silero.ai/vad_models/number_detector.onnx' else: url = 'https://models.sil...
22,927
def etaCalc(T, Tr = 296.15, S = 110.4, nr = 1.83245*10**-5): """ Calculates dynamic gas viscosity in kg*m-1*s-1 Parameters ---------- T : float Temperature (K) Tr : float Reference Temperature (K) S : float Sutherland constant (K) nr : ...
22,928
def refine_markers_harris(patch, offset): """ Heuristically uses the max Harris response for control point center. """ harris = cv2.cornerHarris(patch, 2, 5, 0.07) edges = np.where(harris < 0, np.abs(harris), 0) point = np.array(np.where(harris == harris.max())).flatten() point += offset return...
22,929
def test_teams_join_post(): """Can a user post /teams/join""" app = create_ctfd(user_mode="teams") with app.app_context(): gen_user(app.db, name="user") gen_team(app.db, name="team") with login_as_user(app) as client: r = client.get('/teams/join') assert r.sta...
22,930
def get_realtime_price(symbol): """ 获取实时股价 :param symbol: :return: """ try: df = get_real_price_dataframe() df_s = df[df['code'] == symbol] if len(df_s['trade'].get_values()): return df_s['trade'].get_values()[0] else: return -1 except:...
22,931
def create_employee(db_session: Session, employee: schemas.EmployeeRequest): """ Create new employee """ new_employee = Employee( idir=employee.idir, status=employee.status, location=employee.location, phone=employee.phone) db_session.add(new_employee) db_session.commit()...
22,932
def export_xr_as_nc(ds, filename): """ Takes a xarray dataset or array and exports as a netcdf file. Parameters ---------- ds: xarray dataset/array Input xarray dataset or data array with any number of dimensions. filename : str Name of putput path and filename. ...
22,933
def sim_categorical(var_dist_params, size): """ Function to simulate data for a categorical/Discrete variable. """ values = var_dist_params[0] freq = var_dist_params[1] data_sim = np.random.choice(a=values, p=freq, size=size) return data_sim
22,934
def make_dirs(path): """ Creates directory and all intermediate parent directories. Does not fail if some of the directories already exist. Basically, it is python version of sh command "mkdir -p path". """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIS...
22,935
def flip_team_observation(observation, result, config, from_team, to_team): """Rotates team-specific observations.""" result['{}_team'.format(to_team)] = rotate_points( observation['{}_team'.format(from_team)]) result['{}_team_direction'.format(to_team)] = rotate_points( observation['{}_team_direction...
22,936
def test_contains(): """Test that bounds know if a Value is contained within it.""" bounds = CompositionBounds({"C", "H", "O", "N"}) assert bounds.contains(EmpiricalFormula('C2H5OH')._to_bounds()) assert not bounds.contains(EmpiricalFormula('NaCl')._to_bounds())
22,937
def test_load_managed_mode_directory(create_config, monkeypatch, tmp_path): """Validate managed-mode default directory is /root/project.""" monkeypatch.chdir(tmp_path) monkeypatch.setenv("CHARMCRAFT_MANAGED_MODE", "1") # Patch out Config (and Project) to prevent directory validation checks. with pa...
22,938
def test_rules(): """ Yield each uri so we get granular results. """ for uri, keys in RULES.items(): yield uri, assert_proper_keys, uri, keys
22,939
def validSolution(board: list) -> bool: """ A function validSolution/ValidateSolution/valid_solution() that accepts a 2D array representing a Sudoku board, and returns true if it is a valid solution, or false otherwise :param board: :return: """ return all([test_horizontally(board), test_vertically...
22,940
async def test_create_saves_data(manager): """Test creating a config entry.""" @manager.mock_reg_handler("test") class TestFlow(data_entry_flow.FlowHandler): VERSION = 5 async def async_step_init(self, user_input=None): return self.async_create_entry(title="Test Title", data="T...
22,941
def get_videos_from_channel(service, channel_id): """Essentially a wrapper (but not really) for get_videos_from_playlist() See get_videos_from_playlist() to see return values. Parameters ---------- service: As obtained from googleapiclient.discovery.build() channel_id: str ...
22,942
def drawingpad(where=None, x=0, y=0, image=None, color=0xffffff, fillingColor=0x000000, thickness=3): """Create a drawing pad. Args: where (np.ndarray) : image/frame where the component should be rendered. x (int) : Position X where the component should be placed. y (int) : Position Y ...
22,943
def json_request(url, **kwargs): """ Request JSON data by HTTP :param url: requested URL :return: the dictionary """ if 'auth_creds' in kwargs and 'authentication_enabled' in kwargs['auth_creds']: if 'sessionToken' in kwargs: url += "&sessionToken=%s" % kwargs['auth_creds'...
22,944
def write_patch(source,target,stream,**kwds): """Generate patch commands to transform source into target. 'source' and 'target' must be paths to a file or directory, and 'stream' an object supporting the write() method. Patch protocol commands to transform 'source' into 'target' will be generated and ...
22,945
def list(): """ List all added path """ try: with io.open(FILE_NAME, 'r', encoding='utf-8') as f: data = json.load(f) except: data = {} return data
22,946
def load(filename): """ Load an EigenM object """ with open(filename, 'rb') as f: return pickle.load(f)
22,947
def resize_image_bboxes_with_crop_or_pad(image, bboxes, xs, ys, target_height, target_width, mask_image=None): """Crops and/or pads an image to a target width and height. Resizes an image to a target width and height by either centrally cropping the image or padding ...
22,948
def sharpe_ratio(R_p, sigma_p, R_f=0.04): """ :param R_p: 策略年化收益率 :param R_f: 无风险利率(默认0.04) :param sigma_p: 策略收益波动率 :return: sharpe_ratio """ sharpe_ratio = 1.0 * (R_p - R_f) / sigma_p return sharpe_ratio
22,949
def save_table(pgcursor, table, df): """Clear existing data from postgres table and insert data from df.""" clr_str = "TRUNCATE TABLE " + table + ";" pgcursor.execute(clr_str) columns = '' values = '' for col in df.columns.values: columns += col + ', ' values += '%s, ' ...
22,950
def xr_vol_int_regional(xa, AREA, DZ, MASK): """ volumen integral with regional MASK input: xa, AREA, DZ .. same as in 'xr_vol_int' MASK .. 2D xr DataArray of booleans with the same dimensions as xa output: integral, int_levels .. same as in 'xr_vol_int' ...
22,951
def save_feature(df: pd.DataFrame, feature_name: Union[int, str], directory: str = './features/', with_csv_dump: bool = False, create_directory: bool = True, reference_target_variable: Optional[pd.Series] = None, overwrite: bool = False): """ Save pandas dataframe as feather-fo...
22,952
def test_nn_functional_interpolate_bicubic_scale_factor_tuple(): """ api: paddle.nn.functional.interpolate op version: 11 """ op = Net(mode='bicubic', scale_factor=(1.5, 1.5)) op.eval() # net, name, ver_list, delta=1e-6, rtol=1e-5 obj = APIOnnx(op, 'nn_functional_interpolate', [11]) ...
22,953
def test( coverage: bool = typer.Option( # noqa: B008 default=False, help='Generate coverage information.' ), html: bool = typer.Option( # noqa: B008 default=False, help='Generate an html coverage report.' ), ) -> List[Result]: """Run tests.""" coverage_flag = [f'--cov={PACKAGE...
22,954
def _get_win_folder_from_registry(csidl_name: Any) -> Any: """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.""" if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { ...
22,955
def transitions2kernelreward(transitions, num_states, num_actions): """Transform a dictionary of transitions to kernel, reward matrices.""" kernel = np.zeros((num_states, num_actions, num_states)) reward = np.zeros((num_states, num_actions)) for (state, action), transition in transitions.items(): ...
22,956
def _inline_svg(svg: str) -> str: """Encode SVG to be used inline as part of a data URI. Replacements are not complete, but sufficient for this case. See https://codepen.io/tigt/post/optimizing-svgs-in-data-uris for details. """ replaced = ( svg .replace('\n', '%0A') .r...
22,957
def delete(email, organization=None): """ Delete user EMAIL. """ if organization: org = models.Organization.get_by_slug(organization) deleted_count = models.User.query.filter( models.User.email == email, models.User.org == org.id ).delete() else: deleted_c...
22,958
def update_msgs_name(person_pk): """Back date sender_name field on inbound sms.""" from apostello.models import Recipient, SmsInbound person_ = Recipient.objects.get(pk=person_pk) name = str(person_) number = str(person_.number) for sms in SmsInbound.objects.filter(sender_num=number): s...
22,959
def draw_random_DNA(current_base_turtle, base_index, letter): """ Draw a random sequence to be used later to create the complementary base pair :param current_base_turtle: a turtle object :param base_index: an index, to help position the turtle :param letter: the letter being drawn :return: Non...
22,960
def plot_extreme_edges(gdf: gpd.geodataframe.GeoDataFrame, aoi: gpd.geodataframe.GeoDataFrame, **kwargs) -> None: """ Plots extreme depths along edges along with an overview map showing current plotted domain versus all other domains. :param gdf: :param ...
22,961
def contact_infectivity_asymptomatic_00x40(): """ Real Name: b'contact infectivity asymptomatic 00x40' Original Eqn: b'contacts per person normal 00x40*infectivity per contact' Units: b'1/Day' Limits: (None, None) Type: component b'' """ return contacts_per_person_normal_00x40() * i...
22,962
def implemented_verified_documented(function): """ Common story options """ options = [ click.option( '--implemented', is_flag=True, help='Implemented stories only.'), click.option( '--unimplemented', is_flag=True, help='Unimplemented stories only...
22,963
def create_collection(self, name, url, sourceType, **options): """Creates a new collection from a web or S3 url. Automatically kick off default indexes""" (endpoint, method) = self.endpoints['create_collection'] try: headers = {'Authorization': self.token.authorization_header()} data = { 'name': ...
22,964
def rmse(estimated: np.ndarray, true: np.ndarray) -> Union[np.ndarray, None]: """ Calculate the root-mean-squared error between two arrays. :param estimated: estimated solution :param true: 'true' solution :return: root-mean-squared error """ return np.sqrt(((estimated - true) ** 2).mean(ax...
22,965
def use_default_driver(): """ Use the default driver as the current driver. """ global current_driver current_driver = None
22,966
def energy_com(data): """ Calculate the energy center of mass for each day, and use this quantity as an estimate for solar noon. Function infers time stamps from the length of the first axis of the 2-D data array. :param data: PV power matrix as generated by `make_2d` from `solardatatools.data_tra...
22,967
def cifar_noniid(dataset, no_participants, alpha=0.9): """ Input: Number of participants and alpha (param for distribution) Output: A list of indices denoting data in CIFAR training set. Requires: cifar_classes, a preprocessed class-indice dictionary. Sample Method: take a uniformly sampled 10-dimen...
22,968
def example_metadata( request, l1_ls5_tarball_md_expected: Dict, l1_ls7_tarball_md_expected: Dict, l1_ls8_folder_md_expected: Dict, ): """ Test against arbitrary valid eo3 documents. """ which = request.param if which == "ls5": return l1_ls5_tarball_md_expected elif which...
22,969
def register_middleware(app: FastAPI): """ 请求响应拦截 hook https://fastapi.tiangolo.com/tutorial/middleware/ :param app: :return: """ @app.middleware("http") async def logger_request(request: Request, call_next): # https://stackoverflow.com/questions/60098005/fastapi-starlette-get-...
22,970
def test_dtmc__matrix_copied(): """ Validate that if matrix is passed as an array, it is copied, so changes in the argument don't affect the chain matrix. """ matrix = np.asarray([[0.5, 0.5], [0.5, 0.5]]) chain = DiscreteTimeMarkovChain(matrix) matrix[0, 0] = 0.42 assert chain.matrix[0, ...
22,971
def asfarray(a, dtype=_nx.float_): """ Return an array converted to float type. Parameters ---------- a : array_like Input array. dtype : string or dtype object, optional Float type code to coerce input array `a`. If one of the 'int' dtype, it is replaced with float64. ...
22,972
def handle_no_cache(context): """Handle lack-of-cache error, prompt user for index process.""" logger.error( f"Could not locate wily cache, the cache is required to provide insights." ) p = input("Do you want to run setup and index your project now? [y/N]") if p.lower() != "y": exit(...
22,973
def test_single_dihedral(tmpdir): """Test running a torsiondrive for a molecule with one bond.""" with tmpdir.as_cwd(): mol = Ligand.from_file(get_data("ethane.sdf")) # build a scanner with grid spacing 60 and clear out avoided methyl qc_spec = QCOptions(program="rdkit", method="uff", ba...
22,974
def remove_stored_files(srr_file, store_files): """Remove files stored inside a SRR file. srr_file: the SRR file to remove stored files from store_files: list of files to be removed must contain the relative path when necessary raises ArchiveNotFoundError, NotSrrFile, TypeError""" rr = Ra...
22,975
def test_green_color(): """Test GREEN Constant""" assert settings.Colors.GREEN == (0, 255, 0)
22,976
def read_geotransform_s2(path, fname='MTD_TL.xml', resolution=10): """ Parameters ---------- path : string location where the meta data is situated fname : string file name of the meta-data file resolution : {float,integer}, unit=meters, default=10 resolution of the grid...
22,977
def embed_into_hbox_layout(w, margin=5): """Embed a widget into a layout to give it a frame""" result = QWidget() layout = QHBoxLayout(result) layout.setContentsMargins(margin, margin, margin, margin) layout.addWidget(w) return result
22,978
def make_word_ds(grids, trfiles, bad_words=DEFAULT_BAD_WORDS): """Creates DataSequence objects containing the words from each grid, with any words appearing in the [bad_words] set removed. """ ds = dict() stories = grids.keys() for st in stories: grtranscript = grids[st].tiers[1].make_si...
22,979
def fslimage_to_qpdata(img, name=None, vol=None, region=None, roi=False): """ Convert fsl.data.Image to QpData """ if not name: name = img.name if vol is not None: data = img.data[..., vol] else: data = img.data if region is not None: data = (data == region).astype(np.int) ...
22,980
def xgb_cv( data_, test_, y_, max_depth,gamma, reg_lambda , reg_alpha,\ subsample, scale_pos_weight, min_child_weight, colsample_bytree, test_phase=False, stratify=False, ): """XGBoost cross validation. This function will instantiate a XGBoost classifier with parameters such ...
22,981
def _infer_elem_type(list_var): """ Returns types.tensor. None if failed to infer element type. Example: Given: main(%update: (2,fp32)) { block0() { %list: List[unknown] = tf_make_list(...) # unknown elem type %while_loop_0:0: (i32), %while_loop_0:1: List[(2,fp32)] = while_lo...
22,982
def plot_hairy_mean_binstat_base( list_of_pred_true_weight_label_color, key, spec, is_rel = False, err = 'rms' ): """Plot binstats of means of relative energy resolution vs true energy.""" spec = spec.copy() if spec.title is None: spec.title = 'MEAN + E[ %s ]' % (err.upper()) else: ...
22,983
def log_system_status(): """ Print the status of the system """ module_available=True try: import psutil except ImportError: module_available=False if module_available: try: # record the memory used memory = psutil.virtual_memory(...
22,984
def del_all(widget, event, data): """ Returns Deletes all parameters from the sheet data table ------- """ sheet.items = []
22,985
def parse_csv_file(file_contents): """ The helper function which converts the csv file into a dictionary where each item's key is the provided value 'id' and each item's value is another dictionary. """ list_of_contents = file_contents.split('\n') key, lines = (list_of_contents[0].split(',')...
22,986
def get_config(): """ Returns the current bot config. """ return BOT_CONFIG
22,987
def SensorLocation_Meta(): """SensorLocation_Meta() -> MetaObject""" return _DataModel.SensorLocation_Meta()
22,988
def plot_sample_eval(images: list, sub_titles=None, main_title=None, vmin=None, vmax=None, label_str=None, pred_str=None, additional_info=None, show_plot=False, save_as=None): """ Plots ...
22,989
def predict(): """ Get data and do the same processing as when we prototyped, because we need to normalize based on training data summary stats :return: """ data = pd.read_csv('data.csv') df = data.drop("Unnamed: 32", axis=1) df = data.drop("id", axis=1) df.drop(columns=["Unnamed: ...
22,990
def test_eqpt_creation(tmpdir): """ tests that convert correctly creates equipment according to equipment sheet including all cominations in testTopologyconvert.xls: if a line exists the amplifier should be created even if no values are provided. """ xls_input = DATA_DIR / 'testTopologyconvert.xls' ...
22,991
def format_number(number, num_decimals=2): """ Format a number as a string including thousands separators. :param number: The number to format (a number like an :class:`int`, :class:`long` or :class:`float`). :param num_decimals: The number of decimals to render (2 by default). If no...
22,992
def test_fov_standard(): """ NB: For tests on #STARS section, see test_fov_stare_and_star_list() above.""" fov_name = "Std_SA100" f = fov.Fov("Std_SA100", TEST_FOV_DIRECTORY) assert f.fov_name == fov_name assert f.format_version == CURRENT_SCHEMA_VERSION assert f.ra == util.ra_as_degrees("08:53:...
22,993
def query_rockets(): """ request all rockets """ query = ''' { rockets { id } } ''' return query
22,994
def copyfile(path, dest_dir, workspace = ""): """ path the full filepath to a file dest_dir destination for copy returns the full filepath of the new destination removes the workspace from the filepath to give a workspace relative filepath. """ if os.path.isfile(path): ...
22,995
def test_particular_store_search(browser): """This test fails because store finder filter doesn't work.""" pass
22,996
def get_block_len(built_prims, prim_type): """ Calculates the maximum block length for a given primitive type """ retval = 0 for _, p in built_prims: if p.prim_type == prim_type: retval = max(retval, p.block_len) return retval
22,997
def test_cat3(capsys, thresh_files, args): """ Test the behavior of CAT on a simple file and creating a column""" args = ("A=" + str(thresh_files["pass_a.txt"]) + " cat" + args).split() thresh.main(args) out, err = capsys.readouterr() assert out == """ a ...
22,998
def _interpolate_gather(array, x): """ Like ``torch.gather(-1, array, x)`` but continuously indexes into the rightmost dim of an array, linearly interpolating between array values. """ with torch.no_grad(): x0 = x.floor().clamp(min=0, max=array.size(-1) - 2) x1 = x0 + 1 f0 = _gat...
22,999