content
stringlengths
22
815k
id
int64
0
4.91M
def plot_targets(targets=None, assignments=None, iexp=0, robots=True, hexagon=True, categories=[], observatory='apo'): """Plot targets in the field Parameters ---------- targets : ndarray target information as stored in Field assignments : ndarray ...
59,800
def python_text(text="is cool"): """prints Python is cool""" text = text.replace("_", " ") return "Python %s" % text
59,801
def matchesSyntax(line): """ parses a configuration line and returns whether it conforms to the syntax""" line = line[1:] # strip leading '+' or '-' s = line.split() (ok0, msg0) = matchesPatternSyntax(s[0]) if len(s) < 1 or ok0: pass else: return (False, msg0) (ok1, msg1) = match...
59,802
def linear_warmup_and_polynomial_decayed_lr(settings, global_step): """ settings.learning_rate_base settings.warmup_steps settings.decay_steps settings.learning_rate_minimum settings.lr_power settings.lr_cycle """ learning_rate = tf.constant(value = settings.learning_...
59,803
def test_orm_full_objects_chunks(n): """Load fully tracked ORM objects a chunk at a time using yield_per().""" sess = Session(engine) for obj in sess.query(Customer).yield_per(1000).limit(n): pass
59,804
def get_doc_string_generator(): """Returns the currently registered doc string generator.""" return _generate_doc_string_func
59,805
def _dual_bootstrap(variances): """ helper function to perform the dual bootstrap Takes a 3x... array of variances and computes the corrections assuming: variances[0] are the variances in the double bootstrap variances[1] are the variances in the rdm bootstrap variances[2] are the variances in the ...
59,806
def load_ref_system(): """ Returns l-ascorbic_acid as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" H 0.6888 -1.5618 -0.6197 C 0.3271 -0.5321 -0.3981 O 0.5813 -0.3520 ...
59,807
def medfilt_along_axis(x, n, axis=-1): """Applies median filter smoothing on one axis of an N-dimensional array. """ kernel_size = np.array(x.shape) kernel_size[:] = 1 kernel_size[axis] = n return medfilt(x, kernel_size)
59,808
def as_float_array(array: np.ndarray, min_float=np.float32) -> np.ndarray: """Convert array to a floating point array.""" array = np.asanyarray(array) dtype = np.result_type(array, min_float) return np.asanyarray(array, dtype=dtype)
59,809
def pcy(series, n=1): """Percent change over n years""" return (series/series.shift(n*series.index.freq.periodicity)-1)*100
59,810
def to_eval_str(value): """ Returns an eval(str(value)) if the value is not None. :param value: None or a value that can be converted to a str. :return: None or str(value) """ if isinstance(value, str): value = eval(str(value)) return value
59,811
def random_weights(w_cnt, op=lambda l: l): """ Generate random normalized weights Args: w_cnt: size of the weight vector op: additional operation to perform on the generated weight vector """ weights = np.random.random(w_cnt) weights = op(weights) weights /= np.sum(...
59,812
def latent_conditional_traversal_grid(model, x_data, y_data, use_y=True, z_dims=None, bound=5, steps=10, filepath=None): """ Walk across every dimension of the latent space of a trained model. """ model.eval() with no_grad(): x_hat, mean, logvar = model(x, y) # sample from posteri...
59,813
def get_random_string(size=8, chars=string.ascii_uppercase + string.digits): """ Получает случайную строку указанного размера и с указанными символами. """ return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
59,814
def count_edges_gen(): """ The way the counting is being done here is the following: Say, A+B+C -> D+E occurs via 2 different reaction rules. There will be edges from A->D, A->E, B->D, B->E, and so on. Each of them is counted as a distinct node. The sum of number of edges across generations should turn out to be ...
59,815
def _p_block(block, title=None): """Print info of a block """ if title is not None: print(title) block_info = [ ('Block hash', block.hash), ('Block height', block.height), ('State hash', block.state_hash), ('Miner', block.miner if hasattr(block, 'miner') else 'N/A'), ...
59,816
def company_denomination_year(denomination, year): """ Retrieve company information for a given year by company denomination. Path is /company/denomination/<string:denomination> GET method only and no strict slash. :param denomination: String, denomination of the company. :param year: Year of...
59,817
def TripleDes_Encryption24(data: A, key: A) -> A: """ :type key: object :type data: object """ encrypted_data = triple_des(key).encrypt(data, padmode=PAD_PKCS5) return encrypted_data
59,818
def dataset_metadata_before_calamus(): """Return dataset metadata fixture.""" from renku.core.models.jsonld import NoDatesSafeLoader path = Path(__file__).parent / ".." / ".." / "data" / "dataset-v0.10.4-before-calamus.yml" yield yaml.load(path.read_text(), Loader=NoDatesSafeLoader)
59,819
def raises(exception: Exception, pattern=None, matching=None) -> Matcher[Callable[..., Any]]: """Matches if the called function raised the expected exception. :param exception: The class of the expected exception :param pattern: Optional regular expression to match exception message. :param matchin...
59,820
def test_get_aggregated_tensor_from_aggregator(collaborator_mock, tensor_key, named_tensor, require_lossless): """Test that get_aggregated_tensor works correctly.""" collaborator_mock.client.get_aggregated_tensor = mock.Mock(return_value=named_tensor) nparray =...
59,821
def simulate_obs( physgrid_list, noise_model_list, output_catalog, nsim=100, compl_filter="F475W", weight_to_use='weight', ranseed=None, ): """ Wrapper for creating a simulated photometry. Parameters ---------- physgrid_list : list of strings Name of the physics ...
59,822
def GammaW(tempk, pres): """Function to calculate the moist adiabatic lapse rate (deg C/Pa) based on the environmental temperature and pressure. INPUTS: tempk (K) pres (Pa) RH (%) RETURNS: GammaW: The moist adiabatic lapse rate (Deg C/Pa) REFERENCE: http://glossary.ametsoc.org...
59,823
def write_template_file(infilename, outfilename, vars): """Read a file and perform template substitutions""" replacevars = dict(default_vars.items() + vars.items()) with open(outfilename, 'w') as f: f.write('%s\n' % template_file(infilename, replacevars))
59,824
def main(): """ Test. """ saved_qos_debug = get_qos_debug() cli_commands = get_qos_cli_commands() print "/*" print " * test_cmds created from:" print " *" for cli_command in cli_commands.splitlines(): print " * {}".format(cli_command) print " */" print "" qos_...
59,825
def np_concatenate(paths): """ :param paths: list of paths of .npy arrays :return c: concatenated array """ aa = [] print("\n".join(paths)) for path in paths: a = np.load(path) aa.append(a) pass c = np.concatenate(aa) return c
59,826
def read_multilayer_svg( file: Union[str, TextIO], quantization: float, crop: bool = True, simplify: bool = False, parallel: bool = False, default_width: float = _DEFAULT_WIDTH, default_height: float = _DEFAULT_HEIGHT, ) -> "Document": """Read a multilayer SVG file and return its content...
59,827
def main( name: str = typer.Option("John", hidden=True), lastname: str = typer.Option("Doe", "/lastname", show_default="Mr. Doe"), age: int = typer.Option(lambda: 42, show_default=True), nickname: str = typer.Option("", shell_complete=shell_complete), ): """ Say hello. """ typer.echo(f"H...
59,828
def win_path_check(path): """ Format a file path correctly for Windows """ if IS_WIN: return path.replace("\\", "/").replace(":", "\\:") return path
59,829
def shell(): """ start a local django shell :return: """ local('python manage.py shell')
59,830
def pyreq_nlu_export_trsx(httpreq_hdlr: HTTPRequestHandler, project_id: int, locale: str, out_trsx: str, export_types: List[str]): """ Export project NLU models to TRSX by sending requests to API endpoint with Python 'requests' package. API endpoint :: GET "/api/v1/dat...
59,831
def signal_or() -> Callable[[int, int], int]: """A circuit element performing a bitwise OR on two signals.""" return lambda x, y: limit_signal(x | y)
59,832
def create_github_issue_helper(ctx, issue): """Logic for dev command""" url = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/issues" headers = dict(Authorization=f"token {GITHUB_PAT}", Accept="application/vnd.github.v3+json") data = { "title": issue, "body": f...
59,833
def update_subjects_dir(obj, subjects_dir, depth=0): """Update NDVar SourceSpace.subjects_dir attributes Examine elements of ``obj`` recursively and replace ``subjects_dir`` on all NDVars with SourceSpace dimension that are found. Parameters ---------- obj : object Object to examine. ...
59,834
def domain_verification_failed(to_email, domain): """TBD """ mailer_kwargs = { 'namespace': 'sso', 'template': 'domain_verification_failed', 'subject': 'tbd', 'to_email': to_email, 'template_dict': { 'domain': domain, } } email.deliver.del...
59,835
def get_session(*args, **kwargs): """ .. deprecated:: 2.2 replaced by :func:`fastf1.get_session` """ # TODO remove warnings.warn("`fastf1.core.get_session` has been deprecated and will be" "removed in a future version.\n" "Use `fastf1.get_session` instead....
59,836
def add_user(): """ Endpoint to add user Json passed by POST: ex. { "id": "jibao" } :return: 201, object created or 409, object already exist """ user_id = request.json['id'] obj_created = db_manager.add_user(user_id) if not obj_created: abort(409) return make_re...
59,837
def get_report_format(self, filename): """各帳票フォーマットの格納場所を取得する。 :param self: :param filename: :return: """ prefix = 'reports/{}/'.format(self.parking_lot.name) return prefix + filename
59,838
def _encodehack(s): """ :param s: input string :type s: :class:str or :class:bytes: or :class:unicode Yields either UTF-8 decodeable bytestring (PY2) or PY3 unicode str. """ if sys.version_info[0] > 2: if type(s) == str: return s # type(s) is PY3<str> ...
59,839
def read_float(field: str) -> float: """Read a float.""" return float(field) if field != "" else float('nan')
59,840
def seconds_into_year(now): """Compute the number of seconds into the current year. Args: now: Current time. Returns: Number of seconds since January 1 at midnight on the same year as now. """ year_start = datetime.datetime(now.year, 1, 1, 0, 0, 0, tzinfo=now.tzinfo) return (now - ...
59,841
def get_available_quantity_for_stock(stock): """Count how many stock items are available.""" quantity_allocated = get_quantity_allocated_for_stock(stock) return max(stock.quantity - quantity_allocated, 0)
59,842
def test_Omega_m(): """ Testing Matter density at scale factor `a` """ M_d = MatterDominated(Omega0_m=0.3075) cosmo = flowpm.cosmology.Planck15() a = np.logspace(-3, 0) # Computing reference Omega_m value with old code Omega_back = M_d.Om(a) # Computing new Omega_m' function with tensorflow Omega_m_n...
59,843
def _to_rnn_cell(cell_or_type, num_units, num_layers): """Constructs and return an `RNNCell`. Args: cell_or_type: Either a string identifying the `RNNCell` type, a subclass of `RNNCell` or an instance of an `RNNCell`. num_units: The number of units in the `RNNCell`. num_layers: The number of laye...
59,844
def test_session_repr(): """Test Session.__repr__().""" session = Session('fake-host', 'fake-user', 'fake-pw') repr_str = repr(session) repr_str = repr_str.replace('\n', '\\n') # We check just the begin of the string: assert re.match(r'^{classname}\s+at\s+0x{id:08x}\s+\(\\n.*'. ...
59,845
def layout_aware_vocabulary_vector( results: List[Dict], number_of_words: int, classification_targets: List[str] ) -> List[str]: """Create a layout aware vocabulary vector Finds the most popular words per layout and sticks them together Each layout gets ceil(number_of_words/numb...
59,846
def main_menu_bar(widget): """ Create a main menu bar. This requires setting `menu_bar=True` in the `concur.integrations.glfw.main` method. Otherwise, space wouldn't be reserved for the menu bar, and it would lay on top of window contents. Main menu bar must be created outside any windows. Se...
59,847
def test_cli_verbose_logging(): """ Test UltraSync CLI Verbose Logging Options """ # Initialize our Runner runner = CliRunner() for no in range(0, 4): result = runner.invoke(cli.main, [ '-{}'.format('v' * (no + 1)), '-V' ]) # Spit version and ex...
59,848
def GetDestFromParam(param, prefix=None): """Returns a conventional dest name given param name with optional prefix.""" name = param.replace('-', '_').strip('_') if prefix: name = prefix + '_' + name return resource_property.ConvertToSnakeCase( re.sub('s?I[Dd]$', '', name)).strip('_')
59,849
def get_trigger_name(operation, source_table, when): """Non-PostgreSQL trigger name""" op_initial = operation.lower()[0] when_initial = when.lower()[0] return f"trigger_{source_table}_{when_initial}{op_initial}r"
59,850
def cycle_graph(n: int) -> Graph: """ Construct the unweighted cycle graph on :math:`n` vertices. :param n: The number of vertices in the graph :return: The cycle graph on :math:`n` vertices, as a `Graph` object. :raises ValueError: if the number of vertices is not a positive integer. :Example...
59,851
def load_canonical(exercise, spec_path): """ Loads the canonical data for an exercise as a nested dictionary """ full_path = os.path.join(spec_path, "exercises", exercise, "canonical-data.json") with open(full_path) as f: spec = json.load(f) spec["properties"] = get_tested_properties(spe...
59,852
def mailing_keyboard(mailing_status, notification_status, language_code): """Make keyboard for mailing parameters""" keyboard = [ [ # buttons names and callback according to current states make_button( (buttons.ALLOW_MAILING if mailing_status == c...
59,853
def preprocess_data(): """ This function is used to perform preprocessing and analysis of the data, including - loading the raw data from txt file to pandas data frame structure - visualizing the raw PIR and ultrasonic sensor data - visualizing the evolution and distribution of the tempe...
59,854
def calculate_fold_change(reads, normalized_counts, control_samples, treatment_samples, pseudocount, replicate): """ Create a dataframe with index as guide ids Calculate log2 ratio (foldchange) between treated and control reads :param reads: Dataframe containing read counts (guide level) :param norm...
59,855
def start_command_history_logger(log_dir: Optional[str]=None) -> None: """ logging of the history of the interactive command shell works only with ipython. Call function again to set new path to log file. Args: log_dir: directory where log shall be stored to. If left out, defaults t...
59,856
def del_ntp_server(ctx, ntp_ip_address): """ Delete NTP server IP """ if not clicommon.is_ipaddress(ntp_ip_address): ctx.fail('Invalid IP address') db = ctx.obj['db'] ntp_servers = db.get_table("NTP_SERVER") if ntp_ip_address in ntp_servers: db.set_entry('NTP_SERVER', '{}'.format(ntp...
59,857
def put_fileheader(f, fl): """ Write fileheader list to file (180-bytes). """ f.write(struct.pack('>10s 4c 9s 26s 80s 3x l 40s 4x', *fl)) return
59,858
def wrap_coroutine(func, event_loop, before_test): """Return a sync wrapper around an async function to be executed in the event loop.""" @functools.wraps(func) def inner(**kwargs): if before_test is not None: before_test() coro = func(**kwargs) task = asyncio.ensure_futu...
59,859
def get_deprt(lista): """Add together from row with same index.""" base = [] for item in lista: base.append(item) resultado = set(base) return resultado
59,860
def test_reordering_concurrently(dummy_attribute, assert_num_queries): """ Ensures users cannot concurrently reorder, they need to wait for the other one to achieve. This must be the first thing done before doing anything. For that, we ensure the first SQL query is acquiring the lock. """ ...
59,861
def dot_tree( root: behaviour.Behaviour, visibility_level: common.VisibilityLevel=common.VisibilityLevel.DETAIL, collapse_decorators: bool=False, with_blackboard_variables: bool=False, with_qualified_names: bool=False): """ Paint your tree on a pydot graph. .. seeals...
59,862
def copy_classification(preds, labels, img_paths, classes, output_dir): """Copy images of classification to folders. """ if os.path.exists(output_dir): shutil.rmtree(output_dir) os.makedirs(output_dir) for pred, label, img_path in zip(preds, labels, img_paths): label_dir = os.path.jo...
59,863
def reduce_dims(X=None, y=None, data_path=None, algorithm='pca', perplexity=50, labels=['M', 'R', 'HC', 'V', 'PO']): """visualize the data in a latent space with reduced dimensions""" if data_path is not None: X, y = load_tma_data(data_path) X = X.reshape(X.shape[0], X.shape[1] * X.shape[2]) ...
59,864
def get_events_with_abstract_reviewer_convener(user, dt=None): """ Return a dict of event ids and the abstract reviewing related roles the user has in that event. :param user: A `User` :param dt: Only include events taking place on/after that date """ data = defaultdict(set) # global re...
59,865
def h5gr_to_workup_input(gr, format): """Return a dictionary containing important parameters for working up a phasekick dataset. The dictionary contains: y: Cantilever oscillation data dt: spacing between t0: Initial time t1: Time with V = V_1 t2: Time wit...
59,866
def colocation_cm(colocation, name=None, op=None): """Gets a context manager to colocate ops.""" if colocation: return tf.colocate_with(tf.no_op(name) if op is None else op) return contextlib.suppress()
59,867
def inverse_helper_col_row_multiply(matrix, i, j, value): """Helper to multiply matrix with identity matrix having replaced value. Args: matrix: A matrix (list of lists). i: A column index. j: A row index. value: A value to place at the given row/column. Returns: A ...
59,868
def get_dummy_image_name(): """ Returns the name of the dummy image """ return "python-logo.jpeg"
59,869
def get_default_locale_callable(): """ Wrapper function so that the default mapping is only built when needed """ exec_dir = os.path.dirname(os.path.realpath(__file__)) xml_path = os.path.join(exec_dir, "data", "FacebookLocales.xml") fb_locales = _build_locale_table(xml_path) def default_l...
59,870
def s(*args, **kwargs): """ Create a RedisCluster instance with 'init_slot_cache' set to false """ s = _get_client(RedisCluster, init_slot_cache=False, **kwargs) assert s.connection_pool.nodes.slots == {} assert s.connection_pool.nodes.nodes == {} return s
59,871
def svd_thresh(input_data, threshold=None, n_pc=None, thresh_type='hard'): """Threshold the singular values. This method thresholds the input data using singular value decomposition. Parameters ---------- input_data : numpy.ndarray Input data array, 2D matrix threshold : float or numpy...
59,872
def decode_image(field): """Decode a base64 encoded image to a list of floats. Args: field: base64 encoded string Returns: numpy.array """ array = np.frombuffer(base64.b64decode(field), dtype=np.uint8) image_array = cv2.imdecode(array, cv2.IMREAD_ANYCOLOR) # BGR return image...
59,873
def compute_layer_style_cost(a_S, a_G): """ Arguments: a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G Returns: J_styl...
59,874
def check_punctuation(words): """Check to see if there's a period in the sentence.""" punctuation = [".", ",", "?"] return [word for word in words if word in punctuation]
59,875
def log_users(): """ API for authentication microservice. Creates an entry to be stored temporarily in a global dictionary. ''' """ global logged_in_users_flag # Receive response from Authenticate microservice new_user = request.json logged_in_users_flag[new_user[0]] = new_u...
59,876
def print_rangoli(n: int): """Prints alphabet rangoli with n chars. Args: n (int): chars in rangoli >>> print_rangoli(n=3): ----c---- --c-b-c-- c-b-a-b-c --c-b-c-- ----c---- """ height, width = get_height(n), get_width(n) max_char = get_max_ascii(n) for i in ra...
59,877
def create_trips(sql_dir, engine, suffix, mode='replace'): """ Configure trip info for each OTP query and save to MODEL.trips Parameters ---------- sql_dir : string Directory that stores create_model_trips.sql and append_model_trips.sql engine: a SQLAlchemy engine object suffi...
59,878
def test_missing_variable(): """Make sure that every data_source matches a name of a variable""" with pytest.raises(ValueError) as excinfo: TableConfig( name="foo", description="bar", datasets=[], rows=[], variables=[], columns=[ MeanColumn(data_source="density") ...
59,879
def sample3(): """ Here is a calculation of the psi and Delta parameters measured in ellipsometry. This reproduces Fig. 1.14 in Handbook of Ellipsometry by Tompkins, 2005. """ n_list = [1, 1.46, 3.87+0.02j] ds = linspace(0, 1000, num=100) #in nm psis = [] Deltas = [] fo...
59,880
def _GetIngressChanges(args): """Returns changes to ingress traffic allowed based on the flags.""" platform = platforms.GetPlatform() if platform == platforms.PLATFORM_MANAGED: return config_changes.SetAnnotationChange(service.INGRESS_ANNOTATION, args.ingress) e...
59,881
def get_current_socket_names(): """ Get all cybld socket names """ ret = list() for socket_file in os.listdir(get_base_path()): if socket_file.startswith(SOCKET_BASE_NAME): ret.append(socket_file) ret.sort() return ret
59,882
def get_page(page_number: int, cards: str, page_template: str, section_template: str, contexts: list, is_card_backs: bool=False, is_filler: bool=False, exclude_section: bool=False) -> str: """ Populate a page with cards. """ ...
59,883
def prepare_updates_dict(updates): """ Prepare a Theano `updates` dictionary. Ensure that both keys and values are valid entries. NB, this function is heavily coupled with its clients, and not intended for general use.. """ def prepare_key(key, val): if not isinstance(key, SharedVa...
59,884
def test_assumptions_builder_unsuitable_available_operations(): """ Check that when we provide unsuitable available operations then they're ignored, and we get same pipelines as without specifying available operations. """ task = Task(TaskTypesEnum.classification) train_input, _, _ = get_dataset(task_t...
59,885
def test_fragment_nucleotide(): """Summary.""" fragger = NucleosideFragmentor() peaks = fragger.fragment("adenosine") expected_mzs = np.array([119.03522254717, 136.0617716478]) assert ((peaks[:, 0] - expected_mzs) < 0.001).all()
59,886
def selector(module): """Figure out which object and which actions to take given the right parameters""" if module.params["target"] == "host": target = Host(module.params, module) target.site_facts() elif module.params["target"] == "hostgroup": # Validate target specific require...
59,887
def optimize_graph(graph: Graph) -> Graph: """ Perform a pass of the graph, removing any redundant DUP nodes that we added (which have Node.optimizable = True). A redundant DUP node is when a DUP node has only one output. In this case, the DUP node is superfulous and can be removed. """ par...
59,888
def get_label_conf(y_vec): """ Returns the confidence and the label of the most probable class given a vector of class confidences :param y_vec: (np.ndarray) vector of class confidences, nb of instances as first dimension :return: (np.ndarray, np.ndarray) confidences and labels """ assert len(y_...
59,889
def test_contact_form_posts( client, mocker, name, email, phone, subject, message, captcha, validity ): """Contact Form Tests on the template""" mocker.patch("captcha.fields.client.submit") mocker.return_value = RecaptchaResponse(is_valid=True) response = client.post( "/contact/", {...
59,890
def unique_rows_tol(data, tol=1e-12, return_index=False, return_inverse=False): """ This function returns the unique rows of the input matrix within that are within the specified tolerance. Parameters ---------- data: numpy array (m x n) tol: double tolerance of comparison for each ...
59,891
def hold(): """Keep the session alive until the browser page is closed by user. .. note:: After the PyWebIO session closed, the functions that need communicate with the PyWebIO server (such as the event callback of `put_buttons()` and download link of `put_file()`) will not work. You can call the ``ho...
59,892
def transformed_retrace( q_tm1: ArrayLike, q_t: ArrayLike, a_tm1: ArrayLike, a_t: ArrayLike, r_t: ArrayLike, discount_t: ArrayLike, pi_t: ArrayLike, mu_t: ArrayLike, lambda_: float, eps: float = 1e-8, stop_target_gradients: bool = True, tx_pair: TxPair = IDENTITY_PAIR, ) ...
59,893
def test_enum_strings_changed_incorrect_index(qtbot, signals, values, selected_index, expected): """ Test the widget's handling of incorrectly provided enum string index. Expectations: The widget will display an empty string. Parameters ---------- qtbot : fixture pytest-qt window f...
59,894
def api_all_feeds(request): """ This views to retreive feeds """ if request.is_ajax(): return JsonResponse(get_feeds())
59,895
def is_windows(): """ Return ``True`` if running on Windows. :rtype: bool """ return os.name == "nt"
59,896
def get_clip_info(clip_id, user): """Use given clip id to fetch info from Twitch API.""" # Note: Twitch recommends giving the API 15 seconds to fetch a newly # created clip. If 15 seconds passes and we receive nothing, we can # assume that no clip was created. failures = 0 payload_get_clip = {"...
59,897
def Accuarcy_find(pred, tar, device): """ This function calculates the the accuarcy and confussion matrix """ if device == "cpu": ft = torch.FloatTensor else: ft = torch.cuda.FloatTensor tar = tar.view(-1, tar.shape[-1]) art_pred = pred[:, 1] >= 0.5 # what the model predicts...
59,898
def resolve_ipv6(name, flags=0): """Lookup an AAAA record for a given *name*. To disable searching for this query, set *flags* to ``QUERY_NO_SEARCH``. Returns (ttl, list of packed IPs). """ waiter = Waiter() core.dns_resolve_ipv6(name, flags, waiter.switch_args) result, _type, ttl, addrs = ...
59,899