content
stringlengths
22
815k
id
int64
0
4.91M
def get_window(window_type: str, window_size: int, device: Union[str, torch.device], periodic: Optional[bool] = True, padding: Optional[Tuple[int, int]] = (0, 0) ) -> Tensor: """LRU cached window functions. Wrapper around PyTorch functions. ...
5,294,000
def process_log_token(logtoken): """ processLogToken retrieve username and password from a given login token (!)Override this method to manage more complex and secure algorithms; tester code uses the following encrypted string to store user credentials: username=<username>:password=<pa...
5,294,001
def _normalize_longitude(lon: float) -> float: """Normalize longitudes between [-180, 180]""" return ((lon + 180.0) % 360.0) - 180.0
5,294,002
def copy_assets(app, exception): """ Copy asset files to the output """ if "getLogger" in dir(logging): log = logging.getLogger(__name__).info warn = logging.getLogger(__name__).warning else: log = app.info warn = app.warning builders = get_compatible_builders(app) if...
5,294,003
def get_objection_text(): """ Client sends a list of objection ids, we respond with a dictionary of id:text elements. """ objection_labels = request.form.getlist('objections[]') result = [] for label in objection_labels: objection_text = DATABASE.get_objection_text(label) res...
5,294,004
def test_fallback_max(): """ Feature: JIT Fallback Description: Test max() in graph mode. Expectation: No exception. """ @ms_function def foo(): x = max([1, 2, 3]) return x assert foo() == 3
5,294,005
def get_tf_tensor_shape(tensor): """Get tensor shape, if there is unkown tensor, set it as None""" shape = [] try: shape = tensor.get_shape().as_list() if any(s is None for s in shape): return None return shape except Exception: # pylint: disable=broad-except shape = None return shape
5,294,006
def _update_selected_experiment_table_rows( last_select_click, last_clear_click, experiment_table_indices ): """The callback to select or deselect all rows in the experiment table. Triggered when the select all or clear all button is clicked. """ last_select_click = last_select_click if last_select...
5,294,007
def clear_config(clear_constants=False): """Clears the global configuration. This clears any parameter values set by `bind_parameter` or `parse_config`, as well as the set of dynamically imported modules. It does not remove any configurable functions or classes from the registry of configurables. Args: ...
5,294,008
def save_stl_ascii_multi(surface_list, **kwargs): """ Saves multiple surfaces as an ASCII .stl file. :param surface_list: list of surfaces to be saved :type surface_list: Multi.MultiAbstract Keyword Arguments: * file_name (str): name of the output file * vertex_spacing (int): size of t...
5,294,009
def get_answer_slow(input_data: List[str], steps: int) -> int: """ The iteration in process(template, rules) causes the program to run out of memory on large steps Use get_answer instead """ template, rules = parse_input(input_data) for i in range(steps): template = process(template, ru...
5,294,010
def get_strategies() -> List[MaskingStrategy]: """Returns all supported masking strategies""" return [e.value for e in SupportedMaskingStrategies]
5,294,011
def add2dict(dict, name, item): """ checks whether name is in dict before adding the item. file is a string containing a file name, """ if debug and name in dict: print("\nWarning: the key ", name, "already in dict will be overwritten") print("old value=",dict[name]) print("n...
5,294,012
def rc4Decrypt(data, key): """RC4 algorithm""" x = 0 box = list(range(256)) for i in range(256): x = (x + int(box[i]) + int(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box...
5,294,013
def _move_tutor_version_groups(table): """Tutored moves are never the same between version groups, so the column collapsing ignores tutors entirely. This means that we might end up wanting to show several versions as having a tutor within a single column. So that "E, FRLG" lines up with "FRLG", there h...
5,294,014
def load_from_module(path=None, workspace=None): """Load opener interface from path or from python environment. Opener can be defined as an Opener subclass or directly has a module. Return an OpenerWrapper instance. """ interface = utils.load_interface_from_module( 'opener', interf...
5,294,015
def setup(cli_arguments): """Perform BAF setup.""" log.info("Setup") with log.indent(): input_file = get_input_file(cli_arguments) dry_run = cli_arguments.dry generate_text = cli_arguments.text generate_html = cli_arguments.html generate_csv = cli_arguments.csv ...
5,294,016
def getTotalBalance(cli): """Wrapper function for the relevant RPC function call. Args: cli (str): Full path to cli binary associated with coin. Returns: String: String containing the command output. """ command = CLI_GET_BALANCE.format(cli) return...
5,294,017
def make_code_format(light_theme: bool = False) -> str: """Create code format template for rich.""" theme = "light" if light_theme else "dark" code_format = textwrap.dedent( f"""\ <div class="terminal-container"> <div class="terminal {theme}-terminal"> <div ...
5,294,018
def mqtt_connected(func): """ MQTTClient coroutines decorator which will wait until connection before calling the decorated method. :param func: coroutine to be called once connected :return: coroutine result """ @wraps(func) async def wrapper(self, *args, **kwargs): if n...
5,294,019
def to_canonical(fn, self, arg, orig_t): """Check and convert an argument to the canonical representation. Arguments: arg: The argument to convert. orig_t: The type of the argument as returned by to_abstract. Returns: A version of the argument where classes/dicts become tuples ...
5,294,020
def test_get_L(): """ Simulate data similar to observed and carry out get_L in simplest way possible. """ T = 160 S, J = 40, 2 # normalize across S and J axes omega = np.random.rand(S).reshape(S, 1) omega = omega/omega.sum() lambdas = np.random.rand(J).reshape(1, J) ...
5,294,021
def copy_dsa(data: dsa.PolyData) -> dsa.PolyData: """Deep copy a PolyData""" res = dsa.WrapDataObject(vtk.vtkPolyData()) res.VTKObject.DeepCopy(data.VTKObject) return res
5,294,022
async def test_setup_invalid_missing_template(opp): """Test setup with invalid and missing template.""" assert await setup.async_setup_component( opp, binary_sensor.DOMAIN, { "binary_sensor": { "platform": "template", "sensors": {"test": {"devi...
5,294,023
def run_get_output(cmd, chk_err=True, log_cmd=True): """ Wrapper for subprocess.check_output. Execute 'cmd'. Returns return code and STDOUT, trapping expected exceptions. Reports exceptions to Error if chk_err parameter is True """ if log_cmd: logger.verbose(u"run cmd '{0}'", cmd) t...
5,294,024
def modify_network_interfaces( self, if_info: list, ) -> bool: """Modify interface information on appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - networkInterfaces - POST - /networkInterfaces :pa...
5,294,025
def _wrapped_value_and_num(value): """Returns a list containing value plus the list's length.""" if isinstance(value, (list, tuple)): return value, len(value) else: return [value], 1
5,294,026
def commit_change(path, author, comment, timestamp): """ Commit the current file. """ default_user = DEFAULT_GITHUB_USER if not default_user: # Create a default git user on the fly if one is not configured. default_user = (author, '{} <anonymous@example.com>'.format(author)) git...
5,294,027
def main(): """ Does not use the KTrans Sequence of ProstateX This script only uses the provided T2 masks """ det_data_dir = Path(os.getenv('det_data')) task_data_dir = det_data_dir / "Task021_ProstateX" # setup raw paths source_data_dir = task_data_dir / "raw" if not source_data_di...
5,294,028
def perform_fit(cfmclient, fabric_uuid, name, description): """ Request a full fit across managed Composable Fabrics. :param cfmclient: CFM Client object :param fabric_uuid: Valid Fabric UUID of an existing fabric :param name: Simple name of the fit :param description: Longer Description of the ...
5,294,029
def __get_host_vol_dict(k8s_conf): """ Returns a dict of configured host volumes where the key is the name and the value is the size :param k8s_conf: the k8s configuration used to deploy the cluster :return: dict :raises Exception """ out = dict() host_vols = config_utils.get_host_vo...
5,294,030
def normalize(value, *normalizers, **options): """ normalizes the given value. :param str value: value to be normalized. :param str normalizers: normalizer names to be used. they will be used in the order of their appearance. if not provided, all...
5,294,031
def rescale(image): """ If the input video is other than network size, it will resize the input video :param image: a frame form input video :return: scaled down frame """ scale_side = max(image.shape) # image width and height are equal to 192 scale_value = config["input_width"] / scale_...
5,294,032
def remove_noise(frame): """ Remove noise using morphological operation: erode, then diate.""" ### Morphology: Opening ### kernel = np.ones((3,3),np.uint8) frame = cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernel, iterations=1) return frame
5,294,033
def get_password_from_vault(): """Call pass and return the output.""" pass_path = find_pass() command_line = f'{pass_path} {VAULT_NAME}' command_args = shlex.split(command_line) process = subprocess.Popen( command_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, s...
5,294,034
def get_specific_host(service, container): """Return the hostname/address of a specific container/instance of the given service.""" try: return os.environ['{}_{}_HOST'.format(_to_env_var_name(service), _to_env_var_name(container))] except Exception: ...
5,294,035
def get_instrument_names() -> np.ndarray: """Return the names of each instrument in the metadata cache.""" image_metadata = preprocessing.image_meta.read_metadata() return np.unique(image_metadata["Instrument"])
5,294,036
def get_reads_with_subseq(subseq: str, run: Fast5run, outfile=None, revcompl=False): """ Get all reads containing specific subsequence :param subseq: sequence to be looked for :param run: Fast5run object, where to search :param outfile: file, where the selected reads should be written to :param...
5,294,037
def process_dump(input_file, out_file, file_size, file_compress): """ :param input_file: name of the wikipedia dump file; '-' to read from stdin :param out_file: directory where to store extracted data, or '-' for stdout :param file_size: max size of each extracted file, or None for no max (one file) ...
5,294,038
def qnt_jogadores(): """ -> Irá ler o arquivo de configurações e analisar o parâmetro "qnt_jogadores" :return: retornará o valor do parâmetro """ try: linha = ler_linha(linha=2, inicio_linha_index=15) return int(linha) except: raise FileNotFoundError("Arquivo não encontra...
5,294,039
def connected_amp_protocol(): """ :return: ``AMP`` hooked up to transport. """ p = AMP() p.makeConnection(StringTransport()) return p
5,294,040
def check_converge(pf, abs_tol=1e-4): """ Return Y/N, converged pf/ raw pf, relative changes """ is_converge = isConverge(pf, abs_tol) if len(pf) >= 2: abs_err = abs(pf[-2]-pf[-1]) else: abs_err = None if is_converge: res = (True, pf[-1], abs_err) else: ...
5,294,041
def extract_trajectories(n_true, n_tot, idxs, threshold): """Extract frequency trajectories for different positions on the genome. See the documentation of `extract_trajectory`""" times = sorted(list(n_tot.keys())) trajs = {} for idx in idxs: trajs[idx] = extract_trajectory(n_true, n_tot, id...
5,294,042
def test_unique_id_generation(): """ Ensure that every id generated is unique per questionnaire. """ # Mock the app.data_model.list_store.random_string method to return duplicates. with patch( "app.data_model.list_store.random_string", side_effect=["first", "first", "second"], ):...
5,294,043
def ensure_tf_install(): # pylint: disable=g-statement-before-imports """Attempt to import tensorflow, and ensure its version is sufficient. Raises: ImportError: if either tensorflow is not importable or its version is inadequate. """ # Only check the first time. global _ensure_tf_install_called i...
5,294,044
def load_file(file_adress: str): """ load data from file of type pickle, intended to be used with the method save_file, check if the file exist before open. args: file_adress: full adress to the file to be open returns: if the file exist returns the content, if not returns None. ...
5,294,045
def straight_through_estimator(input: torch.Tensor) -> torch.Tensor: """ straight through estimator >>> straight_through_estimator(torch.randn(3, 3)) tensor([[0., 1., 0.], [0., 1., 1.], [0., 0., 1.]]) """ return _STE.apply(input)
5,294,046
def bbox_transform_inv(boxes, deltas, mean=None, std=None): """Adjust boxes based on deltas Args boxes : collection of box in the format (x1, y1, x2, y2) deltas : amount of shifting needed to be done to each box mean : fixed distance to shift in each direction std : degree...
5,294,047
def os_zipfolder( dir_tozip="/zdisks3/output", zipname="/zdisk3/output.zip", dir_prefix=True, iscompress=True ): """ shutil.make_archive('/zdisks3/results/output', 'zip', root_dir=/zdisks3/results/', base_dir='output') os_zipfolder('zdisk/test/aapackage', 'zdisk/test/...
5,294,048
def test_get_connection_options(): """Test get_connection_options function""" data = { "paramiko": { "hostname": "host1", "port": 22, "platform": "cisco_iosxe", } } result = { "extras": None, "hostname": "host1", "port": 22, ...
5,294,049
def make_task_hashable(task): """ Makes a task dict hashable. Parameters ---------- task : dict task that shall be made hashable. Returns ------- TYPE hashable task. """ if isinstance(task, (tuple, list)): return tuple((make_task_hashable(e) for e in task)...
5,294,050
def clear_pycodeflow_env_vars(): """ Remove any existing Pycodeflow env vars and reset them after test execution """ existing_env_vars = set(ENVIRONMENT_VARIABLES) & set(os.environ.keys()) env_var_cache = {env_var: os.environ.pop(env_var) for env_var in existing_env_vars} yield os.environ.update(en...
5,294,051
def mainMenu(): """ Start of the program, asks the user which mode they'd like to write their data in (r, w, a) """ print(cblink + bold + blue + "\n\t\t\t\tWELCOME\n" + white + cend) print(yellow + 'Enter either "r" for reading a file, "w" for creating a new file, "a" to edit a file.\n' + white) choi...
5,294,052
def select_roi(image, title): """ Select a region of interest with PyQtGraph """ global app # created when loading the module X = image.shape[0] Y = image.shape[1] disp_shape = (max(800, X + 100), max(800, Y + 100)) w = pg.GraphicsWindow(size=disp_shape, border=True) w.setWindowTitle('Selec...
5,294,053
def read_collections_config(request): """Load settings for a minor repo with shared tree collections""" conf = get_conf_object(request) collections_repo_parent = conf.get("apis","collections_repo_parent") collections_repo_remote = conf.get("apis", "collections_repo_remote") try: git_ssh ...
5,294,054
def parent(path: str): """Returns the parent `Path` of the given path.""" from pathlib import Path return Path(path).parent.resolve()
5,294,055
def get_records(table): """ Retrieve all the records in a DynamoDB table. """ kwargs = {} while True: resp = table.scan(**kwargs) yield from resp["Items"] # DynamoDB results are paginated, with the ``LastEvaluatedKey`` in # the response defining a parameter to be pas...
5,294,056
def train_step( env: gym.Env, env_step: TFStep, initial_state: tf.Tensor, actor: tf.keras.Model, critic: tf.keras.Model, actor_optimizer: tf.keras.optimizers.Optimizer, critic_optimizer: tf.keras.optimizers.Optimizer, gamma: float, max_steps_per_ep...
5,294,057
def get_class_means_between_and_within_covs(samples, classids, bias=True): """ Return class means and the between and shread within class covariance matrix. Args: samples (np.array): input data classids (np.array): identification of classes bias (bool): type of normalization, see np.cov...
5,294,058
def get_phone_number(phone_number): """ Following suggested RFC 3966 protocol by open id expect: +111-1111-111111 format """ if '-' in phone_number: phone_split = phone_number.split('-') if len(phone_split) > 2: #if had country code return phone_split[2] ...
5,294,059
def isGroup(obj): """Returns true if the object is a group, false if not @return: If the object is a group @rtype: bool""" # isinstance is needed here due to NestedGroup's inheritance # pylint: disable=unidiomatic-typecheck return ( type(obj) == opencue.wrappers.group.Group or (...
5,294,060
def AppTypeInsert(json_data): """ Insert AppType objects into DB """ result = [] for r in json_data: apptype = AppType(id=int(r['id']), desc=r['desc']) print("[-] apptype: Insert %s ..." % r) db.merge(apptype) result.append(apptype) db.commit() return result
5,294,061
def get_selections( selection: Selection, *, typename: Optional[str] = None, ) -> Dict[str, SelectedField]: """Resolve subselections considering fragments. Args: selection: The selection to retrieve subselections from typename: Only resolve fragments for that...
5,294,062
def show_topics(A, vocabulary, topn=5): """ find the top N words for each of the latent dimensions (=rows) in a """ topic_words = ([[vocabulary[i] for i in np.argsort(t)[:-topn-1:-1]] for t in A]) return [', '.join(t) for t in topic_words]
5,294,063
def execute_after_delay(time_s, func, *args, **kwargs): """A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledT...
5,294,064
def parse( handle, sequences=None, query_file=None, query_ids=None, max_evalue=0.01, min_identity=30, min_coverage=50, ): """Parse Tabular results from remote BLAST search performed via API. Since the API provides no option for returning query coverage, which is a metric we want...
5,294,065
def test_navigation_bar_not_logged_in(test_client): """ GIVEN a Flask application configured for testing WHEN the '/' page is requested (GET) when the user is not logged in THEN check that the 'Register' and 'Login' links are present """ res = test_client.get('/') assert res.status_code == 2...
5,294,066
def read_graph(in_graph, in_graph_is_binary=True): """Reads input graph file as GraphDef. :param in_graph: input graph file. :param in_graph_is_binary: whether input graph is binary, default True. :return: input graphDef. """ assert gfile.Exists(in_graph), 'Input graph pb file %s does not exist...
5,294,067
def test_generate_xml_with_nested(client: Eve, sample_schema: dict): """Test to xml can be generated with nested values :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["num_rows"] = 1 sample_schema["file_form...
5,294,068
def _find_anomalies(cy_ims, iqr_bounds): """ Given a cy stack of images for a field, find the anomalies. Arguments: cy_ims: array (n_cycles, height, width) iqr_bounds: The inter-quartile-range to use on the distribution to things outside of the normal range. Returns: ...
5,294,069
def new_contract_from_user(data: Mapping[str, Any]) -> "SmartContractModel": """ Used in creating new contracts Input: SmartContract::L1::Create DTO Returns: SmartContractModel object """ if data.get("version") in ["3", "latest"]: sc_model = SmartContractModel( txn_type=data....
5,294,070
def setup(progname,logfile=None,syslog_verbosity=0,terminal_verbosity=0,logfile_verbosity=0): """define what type of messages will be logged and how""" global logger ### get a logger and set log system ### if progname=None the root logger is used logger = logging.getLogger(progname) #logging.basicConfig(filename=...
5,294,071
def mes_com_acentos(mes_a_mudar): """Retorna Mês com Maiúsculas e Acentos.""" meses_a_exibir = { 'janeiro': 'Janeiro', 'fevereiro': 'Fevereiro', 'marco': 'Março', 'abril': 'Abril', 'maio': 'Maio', 'junho': 'Junho', 'julho': 'Julho', 'agosto': 'Agos...
5,294,072
def _load_glove(path): """ Loads GloVe pre-trained embedding model via gensim """ tmp_file = get_tmpfile('temp_glove_w2v_format.txt') glove2word2vec(path, tmp_file) return gensim.models.KeyedVectors.load_word2vec_format(tmp_file)
5,294,073
def change_settings(settings: SettingsModel) -> bool: """ Change downloader settings by re-initializing the downloader. ### Arguments - settings: The settings to change. ### Returns - returns True if the settings were changed. """ settings_dict = settings.dict() # Create shallow ...
5,294,074
def meeting_app_launcher() -> None: """Launches either Calendar or Outlook application which is required to read meetings.""" if meeting_file == 'calendar.scpt': os.system('open /System/Applications/Calendar.app > /dev/null 2>&1') elif meeting_file == 'outlook.scpt': os.system("open /Applica...
5,294,075
def printElements(elements, index=None, mark=None): """ Print the given list of :py:class:`GreensfElement` in a nice table :param elements: list of :py:class:`GreensfElement` to be printed :param index: optional list of indices to show instead of the default index in the list :param mark: optional ...
5,294,076
def flip_chars(items): """Flip all chars in an input str of items.""" return ''.join([flip_char(x) for x in items])
5,294,077
def test_parse_fail_scenario_loop_without_iterations(parser): """The parser should fail if a Scenario Loop has no Iterations block""" # given feature_file = """ Feature: My Feature Scenario Loop: My Scenario Loop Given there is a Step """ # then with pytest....
5,294,078
def delete_raggedarray(ra): """ Delete Darr ragged array data from disk. Parameters ---------- ra: RaggedArray or path to RaggedArray to be deleted. """ try: if not isinstance(ra, RaggedArray): ra = RaggedArray(ra, accessmode='r+') except: raise TypeError(f"...
5,294,079
def run_prog(code): """Meh """ mem = {} mask = None for line in code: op, args = parse_line(line) if op == "MASK": mask = args elif op == "MEMSET": for addr in apply_mask(mask, args["addr"]): mem[addr] = args["value"] return sum(m...
5,294,080
def get_best_k(use_saved_k, labvitals_time_series_list_val, labels_val, k_list): """gets the best_k either from the database or from finding it with the help of the method find_best_k Args: use_saved_k (Bool): should the value be taken from the databse? labvitals_time_series_list_val (Li...
5,294,081
def interp_operator_2d( dims_in, dims_out, pack_index_in=None, pack_index_out=None ): """Make one interpolation operator to work on a "flattened" 2D array Do this by tiling and repeat the separate interpolation operators Parameters ---------- di...
5,294,082
def x2p(X = Math.array([]), tol = 1e-5, perplexity = 30.0): """Performs a binary search to get P-values in such a way that each conditional Gaussian has the same perplexity.""" # Initialize some variables print("Computing pairwise distances...") (n, d) = X.shape; sum_X = Math.sum(Math.square(X), 1); D = Math.add...
5,294,083
def b64encode(value): """ Encode a value in base64 """ return base64.b64encode(value)
5,294,084
def load_module_attrs(pkg_path, func, recursive=False): """Get attributes from modules, use ``func`` to filter attributes, ``func`` must return a list. """ attrs = list() root_pkg = os.path.basename(ROOT_DIR) pkg_name = root_pkg + pkg_path.split(root_pkg)[1].replace('/', '.') for _, name, i...
5,294,085
def get_audio_embedding_model_path(input_repr, content_type): """ Returns the local path to the model weights file for the model with the given characteristics Parameters ---------- input_repr : "linear", "mel128", or "mel256" Spectrogram representation used for model. content_type ...
5,294,086
def test_multiple_setModel(qtbot): """ Check that repeated calls to setModel do not duplicate the items in the plot """ w = tpg.TaurusTrend() qtbot.addWidget(w) for i in range(5): w.setModel(["eval:rand(2)"]) sets = w.getTrendSets() assert Counter(w.getPlotItem().list...
5,294,087
def get_git_sha1(): """Try to get the git SHA1 with git rev-parse.""" git_dir = os.path.join(os.path.dirname(sys.argv[0]), '..', '.git') try: git_sha1 = subprocess.check_output([ 'git', '--git-dir=' + git_dir, 'rev-parse', 'HEAD', ], stderr=ope...
5,294,088
def update(profile_id): """ Update A Profile --- /api/profiles/edit/{profile_id}: put: summary: Update A Profile. security: - APIKeyHeader: [] tags: - Profile parameters: - in: path name: profile_id required: true schema: ...
5,294,089
def assert_allclose( actual: numpy.ndarray, desired: numpy.ndarray, err_msg: Literal["bartlett, 37"] ): """ usage.scipy: 2 """ ...
5,294,090
def colormap(x, y, z, clabel="color label", vmin=None, vmax=None): """ Plot the colormap of z in the x,y plane. clabel is the label of the colorbar (label for z). vmin, vmax are the min/max values for the colorbar. Values of z below vmin are plotted with the color corresponding to vmin, and values above vma...
5,294,091
def kornia_list(magn: int = 4): """ Returns standard list of kornia transforms, each with magnitude `magn`. Args: magn (int): Magnitude of each transform in the returned list. """ transform_list = [ # spatial K.RandomHorizontalFlip(p=1), K.RandomRotation(degrees=90.0...
5,294,092
def phrase_replacement(structured_phrases, short_phrases): """replaces phrases in structred_phrases with phrases from short_phrases if the short phrase is contained in the longer phrase""" short_set = set(short_phrases) return [_rewrite_doc(doc, short_set) for doc in structured_phrases]
5,294,093
def struct(typename, field_names, verbose=False): """Returns a new class with named fields. >>> Point = struct('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p...
5,294,094
def zip_tasks_verbose_output(table, stdstreams): """Zip a list of strings (table) with a list of lists (stdstreams) :param table: a formatted list of tasks :param stdstreams: for each task, a list of lines from stdout/stderr tail """ if len(table) != len(stdstreams): raise ValueError('Can on...
5,294,095
def stable_softmax(x, axis=2): """ Numerically stable softmax: softmax(x) = e^x /(sum(e^x)) = e^x / (e^max(x) * sum(e^x/e^max(x))) Args: x: An N-dimensional array of floats axis: The axis for normalizing over. Returns: output: softmax(x) along the specifi...
5,294,096
def test_loopback_filter(do_test, ptfadapter, setup, tx_dut_ports, pkt_fields, ports_info): """ @summary: Create a packet drops by loopback-filter. Loop-back filter means that route to the host with DST IP of received packet exists on received interface """ ip_dst = None vm_name = setu...
5,294,097
def remove_file(filename, from_local=False, sas_url=None, print_msgs=False): """ If from_local is True, removes file from local If sas_url is not None, removes file from Azure, if there. Returns: None """ if from_local: if print_msgs: print('Remove from local, if availabl...
5,294,098
def is_chinese(x: Union[int, str]) -> bool: """Recognizes whether the server/uid is chinese :param x: A server or a genshin uid """ return str(x).startswith(("cn", "1", "2", "5"))
5,294,099