content
stringlengths
22
815k
id
int64
0
4.91M
def analyze(request): """ 利用soar分析SQL :param request: :return: """ text = request.POST.get('text') instance_name = request.POST.get('instance_name') db_name = request.POST.get('db_name') if not text: result = {"total": 0, "rows": []} else: soar = Soar() if...
15,700
def test_1_6_4_systemd_coredump_package(host): """ CIS Ubuntu 20.04 v1.0.0 - Rule # 1.6.4 Tests if systemd-coredump package is installed """ assert host.package('systemd-coredump').is_installed
15,701
def sin(c): """ sin(a+x)= sin(a) cos(x) + cos(a) sin(x) """ if not isinstance(c,pol): return math.sin(c) a0,p=c.separate(); lst=[math.sin(a0),math.cos(a0)] for n in range(2,c.order+1): lst.append( -lst[-2]/n/(n-1)) return phorner(lst,p)
15,702
def _calc_metadata() -> str: """ Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. """ if not is_appveyor: ...
15,703
def authorization_required(func): """Returns 401 response if user is not logged-in when requesting URL with user ndb.Key in it or Returns 403 response if logged-in user's ndb.Key is different from ndb.Key given in requested URL. """ @functools.wraps(func) def decorated_function(*pa, **ka): # pylint:...
15,704
def pad_col(input, val=0, where='end'): """Addes a column of `val` at the start of end of `input`.""" if len(input.shape) != 2: raise ValueError(f"Only works for `phi` tensor that is 2-D.") pad = torch.zeros_like(input[:, :1]) if val != 0: pad = pad + val if where == 'end': r...
15,705
def seats_found_ignoring_floor(data: List[List[str]], row: int, col: int) -> int: """ Search each cardinal direction util we hit a wall or a seat. If a seat is hit, determine if it's occupied. """ total_seats_occupied = 0 cardinal_direction_operations = itertools.product([-1, 0, 1], repeat=2) ...
15,706
def main(module, dry_run=False, *arguments): """Load module to run module: module path dry_run: only parse input arguments and print them arguments: arguments of the imported module """ module = load_module(module)
15,707
def test_set_sample(fake_session): """Set value should find the second AllowableFieldType.""" fake_fv = fake_session.FieldValue.load( { "id": 200, "child_item_id": None, "allowable_field_type_id": None, "allowable_field_type": None, "parent_cla...
15,708
def product_design_space() -> ProductDesignSpace: """Build a ProductDesignSpace for testing.""" alpha = RealDescriptor('alpha', lower_bound=0, upper_bound=100, units="") beta = RealDescriptor('beta', lower_bound=0, upper_bound=100, units="") gamma = CategoricalDescriptor('gamma', categories=['a', 'b', '...
15,709
def compute_percents_of_labels(label): """ Compute the ratio/percentage size of the labels in an labeled image :param label: the labeled 2D image :type label: numpy.ndarray :return: An array of relative size of the labels in the image. Indices of the sizes in the array \ is corresponding to the...
15,710
def removepara(H,M,Hmin = '1/2',Hmax = 'max',output=-1,kwlc={}): """ Retrieve lineal contribution to cycle and remove it from cycle. **H** y **M** corresponds to entire cycle (two branches). I.e. **H** starts and ends at the same value (or an aproximate value). El ciclo M vs H se separa ...
15,711
def flush(): """ Remove all mine contents of minion. :rtype: bool :return: True on success CLI Example: .. code-block:: bash salt '*' mine.flush """ if __opts__["file_client"] == "local": return __salt__["data.update"]("mine_cache", {}) load = { "cmd": "_m...
15,712
def polygon_to_shapely_polygon_wkt_compat(polygon): """ Convert a Polygon to its Shapely Polygon representation but with WKT compatible coordinates. """ shapely_points = [] for location in polygon.locations(): shapely_points.append(location_to_shapely_point_wkt_compat(location)) ret...
15,713
def main(): """ 程序入口,完成初始化,定义神经网络结构,训练,打印等逻辑 Args: Return: """ # 初始化,设置是否使用gpu,trainer数量 paddle.init(use_gpu=False, trainer_count=1) # 配置网络结构和设置参数 cost, parameters, optimizer, feeding = network_config() # 记录成本cost costs = [] # 构造trainer,配置三个参数cost、parameters、update_equ...
15,714
def test_device_code_grant( requests_mock, oauth2client, token_endpoint, device_code, client_id, client_credential, public_jwk, client_auth_method_handler, device_code_grant_validator, public_app_auth_validator, client_secret_basic_auth_validator, client_secret_post_auth_...
15,715
def ccd_process(ccd, oscan=None, trim=None, error=False, masterbias=None, bad_pixel_mask=None, gain=None, rdnoise=None, oscan_median=True, oscan_model=None): """Perform basic processing on ccd data. The following steps can be included: * overscan correction ...
15,716
def get_role_keyids(rolename): """ <Purpose> Return a list of the keyids associated with 'rolename'. Keyids are used as identifiers for keys (e.g., rsa key). A list of keyids are associated with each rolename. Signing a metadata file, such as 'root.json' (Root role), involves signing or verifyin...
15,717
def _DX(X): """Computes the X finite derivarite along y and x. Arguments --------- X: (m, n, l) numpy array The data to derivate. Returns ------- tuple Tuple of length 2 (Dy(X), Dx(X)). Note ---- DX[0] which is derivate along y has shape (m-1, n, l). DX[1] ...
15,718
def load_spectra_from_dataframe(df): """ :param df:pandas dataframe :return: """ total_flux = df.total_flux.values[0] spectrum_file = df.spectrum_filename.values[0] pink_stride = df.spectrum_stride.values[0] spec = load_spectra_file(spectrum_file, total_flux=total_flux, ...
15,719
def included_element(include_predicates, exclude_predicates, element): """Return whether an index element should be included.""" return (not any(evaluate_predicate(element, ep) for ep in exclude_predicates) and (include_predicates == [] or any(evaluate_predicate(elem...
15,720
def ele_clear_input(context, selector=None, param2=None): """ Empty the selector element param1 and enter the value param2 :param context: step context :param selector: locator string for selector element (or None). :param param2: string to be input """ g_Context.step.ele_clear_input(context...
15,721
def tfm_setup(self:CameraProperties, more_setup:Callable[[CameraProperties],None] = None, dtype:Union[np.int32,np.float32] = np.int32): """Setup for transforms""" # for fast smile correction self.smiled_size = (np.ptp(self.settings["row_slice"]), self.settings["resolution"][1] - np.max(self.calibration["smi...
15,722
def _insertstatushints(x): """Insert hint nodes where status should be calculated (first path) This works in bottom-up way, summing up status names and inserting hint nodes at 'and' and 'or' as needed. Thus redundant hint nodes may be left. Returns (status-names, new-tree) at the given subtree, where ...
15,723
def make_sine(freq: float, duration: float, sr=SAMPLE_RATE): """Return sine wave based on freq in Hz and duration in seconds""" N = int(duration * sr) # Number of samples return np.sin(np.pi*2.*freq*np.arange(N)/sr)
15,724
def _widget_abbrev(o): """Make widgets from abbreviations: single values, lists or tuples.""" float_or_int = (float, int) if isinstance(o, (list, tuple)): if o and all(isinstance(x, string_types) for x in o): return DropdownWidget(values=[unicode_type(k) for k in o]) elif _matche...
15,725
def test_default_max_reads(device, scaling): """ Test read_measured_value_buffer() without passing the "max_reads" parameter. """ result = device.read_measured_value_buffer(scaling) assert type(result) is Sfc5xxxReadBufferResponse assert result.scaling == scaling assert result.read_count...
15,726
def get_conditions(): """ List of conditions """ return [ 'blinded', 'charmed', 'deafened', 'fatigued', 'frightened', 'grappled', 'incapacitated', 'invisible', 'paralyzed', 'petrified', 'poisoned', 'prone', ...
15,727
def negative_predictive_value(y_true: np.array, y_score: np.array) -> float: """ Calculate the negative predictive value (duplicted in :func:`precision_score`). Args: y_true (array-like): An N x 1 array of ground truth values. y_score (array-like): An N x 1 array of predicted values. R...
15,728
def flat_list(*alist): """ Flat a tuple, list, single value or list of list to flat list e.g. >>> flat_list(1,2,3) [1, 2, 3] >>> flat_list(1) [1] >>> flat_list([1,2,3]) [1, 2, 3] >>> flat_list([None]) [] """ a = [] for x in alist: if x is None: ...
15,729
def do_regression(X_cols: List[str], y_col: str, df: pd.DataFrame, solver='liblinear', penalty='l1', C=0.2) -> LogisticRegression: """ Performs regression. :param X_cols: Independent variables. :param y_col: Dependent variable. :param df: Data frame. :param solver: Solver. Def...
15,730
def describe_chap_credentials(TargetARN=None): """ Returns an array of Challenge-Handshake Authentication Protocol (CHAP) credentials information for a specified iSCSI target, one for each target-initiator pair. See also: AWS API Documentation Examples Returns an array of Challenge-Handshake Au...
15,731
def gaussian_smooth(var, sigma): """Apply a filter, along the time dimension. Applies a gaussian filter to the data along the time dimension. if the time dimension is missing, raises an exception. The DataArray that is returned is shortened along the time dimension by sigma, half of sigma on ...
15,732
def make_ood_dataset(ood_dataset_cls: _BaseDatasetClass) -> _BaseDatasetClass: """Generate a BaseDataset with in/out distribution labels.""" class _OodBaseDataset(ood_dataset_cls): """Combine two datasets to form one with in/out of distribution labels.""" def __init__( self, in_distributio...
15,733
def _title_case(value): """ Return the title of the string but the first letter is affected. """ return value[0].upper() + value[1:]
15,734
def test_vector_laplace_cart(ndim): """test different vector laplace operators""" bcs = _get_random_grid_bcs(ndim, dx="uniform", periodic="random", rank=1) print(bcs) field = VectorField.random_uniform(bcs.grid) res1 = field.laplace(bcs, backend="scipy").data res2 = field.laplace(bcs, backend="n...
15,735
def test_json_schema(runner): """Tests that the json schema is in sync with this code.""" schema_dir = os.path.dirname(os.path.realpath(__file__)) fname = os.path.join(schema_dir, f'schemas/pxm-manifest-{version}.json') with open(fname) as f: schema = json.load(f) result = runner.invoke...
15,736
def zoom_api_call(user, verb, url, *args, **kwargs): """ Perform an API call to Zoom with various checks. If the call returns a token expired event, refresh the token and try the call one more time. """ if not settings.SOCIAL_AUTH_ZOOM_OAUTH2_KEY: raise DRFValidationError( "...
15,737
def update_search_grammar(extra_consts, in_file, out_file): """let the user to provide constants to the synthesis target grammar.""" current_grammar = None with open(in_file, "r") as f: current_grammar = f.read() if extra_consts: consts = "enum SmallStr {{\n {0} \n}}".format(",".join(...
15,738
def copy_javascript(name): """Return the contents of javascript resource file.""" # TODO use importlib_resources to access javascript file content folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "js") with open(os.path.join(folder, name + ".js")) as fobj: content = fobj.read()...
15,739
def addHtmlImgTagExtension(notionPyRendererCls): """A decorator that add the image tag extension to the argument list. The decorator pattern allows us to chain multiple extensions. For example, we can create a renderer with extension A, B, C by writing: addAExtension(addBExtension(addCExtension(noti...
15,740
def mechaber(mechaber_name): """Route function for visualizing and exploring Mechabrim.""" mechaber = Mechaber.query.filter_by(mechaber_name=mechaber_name).first_or_404() # page = request.args.get("page", 1, type=int) # mekorot = sefer.mekorot.order_by(Makor.ref).paginate( # page, current_app.co...
15,741
def get_symmetry_projectors(character_table, conjugacy_classes, print_results=False): """ :param character_table: each row gives the characters of a different irreducible rep. Each column corresponds to a different conjugacy classes :param conjugacy_classes: List of lists of conjugacy class elemen...
15,742
def check_market_open(data, sheet, row): """Exits program if the date from the webpage is the same as the last entry in the spreadsheet :param data: dict (str:str) Contains values scraped from website with keys matching the column titles which are found in the titles list :param sheet: dict...
15,743
def is_permutation_matrix(matrix: List[List[bool]]) -> bool: """Returns whether the given boolean matrix is a permutation matrix.""" return (all(sum(v) == 1 for v in matrix) and sum(any(v) for v in matrix) == len(matrix))
15,744
def DPT_Hybrid(pretrained=True, **kwargs): """ # This docstring shows up in hub.help() MiDaS DPT-Hybrid model for monocular depth estimation pretrained (bool): load pretrained weights into model """ model = DPTDepthModel( path=None, backbone="vitb_rn50_384", non_negative=Tru...
15,745
def show_counts(input_dict): """Format dictionary count information into a string Args: input_dict (dictionary): input keys and their counts Return: string: formatted output string """ out_s = '' in_dict_sorted = {k: v for k, v in sorted(input_dict.items(), key=lambda item...
15,746
def encipher_railfence(message,rails): """ Performs Railfence Encryption on plaintext and returns ciphertext Examples ======== >>> from sympy.crypto.crypto import encipher_railfence >>> message = "hello world" >>> encipher_railfence(message,3) 'horel ollwd' Parameters ========...
15,747
def format_signature(name: str, signature: inspect.Signature) -> str: """Formats a function signature as if it were source code. Does not yet handle / and * markers. """ params = ', '.join( format_parameter(arg) for arg in signature.parameters.values()) if signature.return_annotation is sig...
15,748
def extract_ratios_from_ddf(ddf): """The same as the df version, but works with dask dataframes instead.""" # we basicaly abuse map_partition's ability to expand indexes for lack of a working # groupby(level) in dask return ddf.map_partitions(extract_ratios_from_df, meta={'path': str, 'ratio': str, ...
15,749
def check_if_prime(number): """checks if number is prime Args: number (int): Raises: TypeError: if number of type float Returns: [bool]: if number prime returns ,True else returns False """ if type(number) == float: raise TypeError("TypeError: entered float ty...
15,750
def get_signatures() -> {}: """ Helper method used to identify the valid arguments that can be passed to any of the pandas IO functions used by the program :return: Returns a dictionary containing the available arguments for each pandas IO method """ # Creates an empty dictionary to collect the ...
15,751
def test_neoxargs_load_arguments_6_7B_local_setup(): """ verify 6-7B.yml can be loaded without raising validation errors """ run_neox_args_load_test(["6-7B.yml", "local_setup.yml"])
15,752
def _load_flags(): """Load flag definitions. It will first attempt to load the file at TINYFLAGS environment variable. If that does not exist, it will then load the default flags file bundled with this library. :returns list: Flag definitions to use. """ path = os.getenv('TINYFLAGS') i...
15,753
def _get_indentation_option(explicit: Optional[Union[str, int]] = None) -> Optional[str]: """Get the value for the ``indentation`` option. Args: explicit (Optional[Union[str, int]]): the value explicitly specified by user, :data:`None` if not specified Returns: Optional[str]: t...
15,754
def batch_answer_same_context(questions: List[str], context: str) -> List[str]: """Answers the questions with the given context. :param questions: The questions to answer. :type questions: List[str] :param context: The context to answer the questions with. :type context: str :return: The answer...
15,755
def test_container_count(dockerc): """Verify the test composition and container.""" # stopped parameter allows non-running containers in results assert ( len(dockerc.containers(stopped=True)) == 1 ), "Wrong number of containers were started."
15,756
def complex_multiplication(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Multiplies two complex-valued tensors. Assumes the tensor has a named dimension "complex". Parameters ---------- x : torch.Tensor Input data y : torch.Tensor Input data Returns ------- ...
15,757
def dynamic_embedding_lookup(keys: tf.Tensor, config: de_config_pb2.DynamicEmbeddingConfig, var_name: typing.Text, service_address: typing.Text = "", skip_gradient_update: bool = False, ...
15,758
def register_unary_op(registered_name, operation): """Creates a `Transform` that wraps a unary tensorflow operation. If `registered_name` is specified, the `Transform` is registered as a member function of `Series`. Args: registered_name: the name of the member function of `Series` corresponding to ...
15,759
def add_climatology(data, clim): """Add 12-month climatology to a data array with more times. Suppose you have anomalies data and you want to add back its climatology to it. In this sense, this function does the opposite of `get_anomalies`. Though in this case there is no way to obtain the climatol...
15,760
def broadcast(name, message): """ Send a message to all users from the given name. """ print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass
15,761
def test(session): """Run tests.""" tests = session.posargs or [TESTS_DIR] session.install("-v", ".[tests]", silent=True) session.run("python", "-m", "coverage", "erase") session.run( "python", "-m", "pytest", "--numprocesses=auto", "--cov", PACKAGE_D...
15,762
def already_exists(statement: str, lines: List[str]) -> bool: """ Check if statement is in lines """ return any(statement in line.strip() for line in lines)
15,763
def uniform(lower_list, upper_list, dimensions): """Fill array """ if hasattr(lower_list, '__iter__'): return [random.uniform(lower, upper) for lower, upper in zip(lower_list, upper_list)] else: return [random.uniform(lower_list, upper_list) for _ in range(dim...
15,764
def prepare_data(files, voxel_size, device='cuda'): """ Loads the data and prepares the input for the pairwise registration demo. Args: files (list): paths to the point cloud files """ feats = [] xyz = [] coords = [] n_pts = [] for pc_file in files: pcd0 = o3d.io....
15,765
def test_select_via_env_var_implicit(env_var, tmpdir): """Config file selection can leverage default environmanent variables.""" conf_file = tmpdir.join("test-refgenconf-conf.yaml").strpath assert not os.path.exists(conf_file) with open(conf_file, "w"): pass assert os.path.isfile(conf_file) ...
15,766
def save_model(model, model_filepath): """ Function: Save a pickle file of the model Input: model: the classification model model_filepath (str): the path of pickle file """ with open(model_filepath, 'wb') as f: pickle.dump(model, f)
15,767
def reshape(box, new_size): """ box: (N, 4) in y1x1y2x2 format new_size: (N, 2) stack of (h, w) """ box[:, :2] = new_size * box[:, :2] box[:, 2:] = new_size * box[:, 2:] return box
15,768
def print_voxels_size(path: Path): """ Prints size of voxels in millimeters :param path: path to folder containing masks :return: """ for scan_path in path.iterdir(): if scan_path.name.endswith('mask.nii.gz'): print(nib.load(str(scan_path)).header.get_zooms())
15,769
def sort_actions(request): """Sorts actions after drag 'n drop. """ action_list = request.POST.get("objs", "").split('&') if len(action_list) > 0: pos = 10 for action_str in action_list: action_id = action_str.split('=')[1] action_obj = Action.objects.get(pk=actio...
15,770
def fetch_file(parsed_url, config): """ Fetch a file from Github. """ if parsed_url.scheme != 'github': raise ValueError(f'URL scheme must be "github" but is "{parsed_url.github}"') ghcfg = config.get('github') if not ghcfg: raise BuildRunnerConfigurationError('Missing configur...
15,771
def _build_and_test_cobalt_locally(git_revision): """ Assumes that the current working directory is a Cobalt repo. Checks out Cobalt at the given |git_revision| and then builds and tests Cobalt. Throws an exception if any step fails. """ subprocess.check_call(['git', 'checkout', git_revision]) _cobaltb('set...
15,772
def number_of_days(year: int, month: int) -> int: """ Gets the number of days in a given year and month :param year: :type year: :param month: :type month: :return: :rtype: """ assert isinstance(year, int) and 0 <= year assert isinstance(month, int) and 0 < month <= 12 c...
15,773
def safe_decode(text, incoming=None, errors='strict'): """Decodes incoming str using `incoming` if they're not already unicode. :param incoming: Text's current encoding :param errors: Errors handling policy. See here for valid values http://docs.python.org/2/library/codecs.html :returns: text o...
15,774
def medstddev(data, mask=None, medi=False, axis=0): """ This function computes the stddev of an n-dimensional ndarray with respect to the median along a given axis. Parameters: ----------- data: ndarray A n dimensional array frmo wich caculate the median standar deviation. ...
15,775
def load_npz(filename: FileLike) -> JaggedArray: """ Load a jagged array in numpy's `npz` format from disk. Args: filename: The file to read. See Also: save_npz """ with np.load(filename) as f: try: data = f["data"] shape = f["shape"] re...
15,776
def _egg_link_name(raw_name: str) -> str: """ Convert a Name metadata value to a .egg-link name, by applying the same substitution as pkg_resources's safe_name function. Note: we cannot use canonicalize_name because it has a different logic. """ return re.sub("[^A-Za-z0-9.]+", "-", raw_name) + "...
15,777
def my_view(request): """Displays info details from nabuco user""" owner, c = User.objects.get_or_create(username='nabuco') # Owner of the object has full permissions, otherwise check RBAC if request.user != owner: # Get roles roles = get_user_roles(request.user, owner) # Get ...
15,778
def handler500(request): """ Custom 500 view :param request: :return: """ return server_error(request, template_name='base/500.html')
15,779
def get_badpixel_mask(shape, bins): """Get the mask of bad pixels and columns. Args: shape (tuple): Shape of image. bins (tuple): CCD bins. Returns: :class:`numpy.ndarray`: 2D binary mask, where bad pixels are marked with *True*, others *False*. The bad pixels are foun...
15,780
def maTotalObjectMemory(): """__NATIVE__ /* Wrapper generated for: */ /* int maTotalObjectMemory(void); */ PmReturn_t retval = PM_RET_OK; int func_retval; pPmObj_t p_func_retval = C_NULL; /* If wrong number of args, raise TypeError */ if (NATIVE_GET_NUM_ARGS() != 0) { PM...
15,781
def main(argv=None): """Entry point for the CLI interface """ parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--fullness", nargs='?', const="", type=str, help="path to lfs_df text file; summarize fullness of OST...
15,782
def model_fn(nn_last_layer, correct_label, learning_rate, num_classes): """ Build the TensorFLow loss and optimizer operations. :param nn_last_layer: TF Tensor of the last layer in the neural network :param correct_label: TF Placeholder for the correct label image :param learning_rate: TF Placeholde...
15,783
def maybe_load_yaml(item): """Parses `item` only if it is a string. If `item` is a dictionary it is returned as-is. Args: item: Returns: A dictionary. Raises: ValueError: if unknown type of `item`. """ if isinstance(item, six.string_types): return yaml.load(item) ...
15,784
def histeq(im,nbr_bins=256): """histogram equalize an image""" #get image histogram im = np.abs(im) imhist,bins = np.histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() #cumulative distribution function cdf = 255 * cdf / cdf[-1] #normalize #use linear interpolation of cdf to ...
15,785
def txgamma(v, t, gamma, H0): """ Takes in: v = values at z=0; t = list of redshifts to integrate over; gamma = interaction term. Returns a function f = [dt/dz, d(a)/dz, d(e'_m)/dz, d(e'_de)/dz, d(...
15,786
def save_file(data, path, verbose=False): """Creates intermediate directories if they don't exist.""" dir = os.path.dirname(path) if not os.path.isdir(dir): os.makedirs(dir) if verbose: print(f"Saving: {path}") _, ext = os.path.splitext(path) if ext == ".pkl": with open...
15,787
def process_song_file(cur, filepath): """ Function Purpose: Open and process data from song data file to insert into {songs, artists} table Inputs: - filepath: the filepath where the JSON song data file is stored - cur: cursor Outputs: - 'song_data': Insert [song_id, title, artis...
15,788
def text_pb(tag, data, description=None): """Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this summary, ...
15,789
def sanitize_input(args: dict) -> dict: """ Gets a dictionary for url params and makes sure it doesn't contain any illegal keywords. :param args: :return: """ if "mode" in args: del args["mode"] # the mode should always be detailed trans = str.maketrans(ILLEGAL_CHARS, ' ' * len(ILL...
15,790
def test_prep_file(text, expected): """ Writes text to file, then processes the file (which writes to an output file), loads the output file and compares to the expected result :param text: :param expected: :return: """ infile, infile_filename = tempfile.mkstemp() outfile, outfile_fi...
15,791
def add_notebook(args, library_db): """add a notebook to sqlite database""" import os from src.praxxis.library import sync_library root = (os.path.sep).join(os.path.abspath(args.path).split(os.path.sep)[:-1]) notebook_name = args.path.split(os.path.sep)[-1] print(root) relative_path = "" ...
15,792
def sum_to(containers, goal, values_in_goal=0): """ Find all sets of containers which sum to goal, store the number of containers used to reach the goal in the sizes variable. """ if len(containers) == 0: return 0 first = containers[0] remain = containers[1:] if first > goal: ...
15,793
def Daq_DeleteProbe(label: str) -> None: """Removes probe compensation information from database Parameters ---------- label : str Compensation identifier """ CTS3Exception._check_error(_MPuLib.Daq_DeleteProbe( label.encode('ascii')))
15,794
def rt2add_enc_v1(rt, grid): """ :param rt: n, k, 2 | log[d, tau] for each ped (n,) to each vic (k,) modifies rt during clipping to grid :param grid: (lx, ly, dx, dy, nx, ny) lx, ly | lower bounds for x and y coordinates of the n*k (2,) in rt dx, dy | step sizes of the regular grid ...
15,795
def warning(*tokens: Token, **kwargs: Any) -> None: """Print a warning message""" tokens = [brown, "Warning:"] + list(tokens) # type: ignore kwargs["fileobj"] = sys.stderr message(*tokens, **kwargs)
15,796
def i_print_g(text=""): """ prints indented green text on terminal :param text: :return: """ print(Fore.GREEN + Style.BRIGHT + indent(text, prefix=" "))
15,797
def run_standard_p4_command(command, args): """Runs a standard p4 command. Uses exec, so this will be the last function you ever call. Used to transfer control to stock p4 for non-custom commands. """ if command: args = [command] + args os.execvp('p4', ['p4'] + args)
15,798
def draw_with_replacement(heap): """Return ticket drawn with replacement from given heap of tickets. Args: heap (list): an array of Tickets, arranged into a heap using heapq. Such a heap is also known as a 'priority queue'. Returns: the Ticket with the least ticket number in th...
15,799