content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def svn_wc_adm_probe_retrieve(*args): """svn_wc_adm_probe_retrieve(svn_wc_adm_access_t associated, char path, apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_adm_probe_retrieve(*args)
2716094e31c596212b5ccd7833b9ae10ef52d44e
3,641,300
def flights_preclean(df): """ Input: Raw dataframe of Flights table. Output: Cleaned flights table: - Remove cancelled rows, made available in new dataframe "df_can" - Drop columns ['Unnamed: 0', 'branded_code_share', 'mkt_carrier', 'cancelled', 'cancellation_code', 'flights', 'ai...
61dcfa6afd6ec7dd0abb5525187938d6ab978996
3,641,301
def convert_spectral_kernel_quint(sequences, list_seq_to_id): """ Return a list seq of nb of time the seq in list_seq_to_id appear in sequence""" final = [] for j in range(len(sequences)): sequence = sequences[j] dico_appear = {seq: 0 for seq in list_seq_to_id} for i in range(len(seq...
49f727dd26822834bad2c9a448136288dc1c426c
3,641,302
def grad_of_marginal_fit(c, h, tau, epsilon): """Computes grad of terms linked to marginals in objective. Computes gradient w.r.t. f ( or g) of terms in https://arxiv.org/pdf/1910.12958.pdf, left-hand-side of Eq. 15 (terms involving phi_star) Args: c: jnp.ndarray, first target marginal (either a or b in...
38b6b57766c97f8eda72162b6919e48c235cd880
3,641,303
def SuggestField(**kwargs): """ Query 'foo' to get the TextField, or 'foo.raw' to get the KeywordField, or 'foo.suggest' to get the CompletionField. """ return fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), }, ...
57f673bbc310a22432178ee078c8f5eec2355e12
3,641,304
import math def distance_on_unit_sphere(FoLat, FoLng, ToLat, ToLng): """ Convert latitude and longitude to spherical coordinates in radians.""" phi1 = math.radians(90.0 - FoLat) phi2 = math.radians(90.0 - ToLat) theta1 = math.radians(FoLng) theta2 = math.radians(ToLng) """Compute spherical d...
98c9294697e36c5b45cd165ba96529187f2750de
3,641,305
import pandas # noqa def check_pandas_support(caller_name): """Raise ImportError with detailed error message if pandsa is not installed. Plot utilities like :func:`fetch_openml` should lazily import pandas and call this helper before any computation. Parameters ---------- caller_name : ...
f3d484bb3a5dbca43a81cca83b7343e1fcd7cbcf
3,641,306
import argparse from datetime import datetime def parse_cmdline(): """Parse the command line arguments. Returns: argparse.Namespace. The parsed arguments or defaults. """ parser = argparse.ArgumentParser( description="Dataplane Automated Testing System, version " + __version__, ...
a9c95d12fe3a30a3fb130310ea0b9cb57fb20e0b
3,641,307
def summarize_sequence(summary_type, hidden, d_model, n_head, d_head, dropout, dropatt, input_mask, is_training, initializer, scope=None, reuse=None): """Summarize hidden sequence into a vector.""" tf.logging.info("===== Sequence summary =====") tf.logging.info(" - ...
50dd0e72c15adfa522847cb822e897c9892cd1cf
3,641,308
def encode_line(line, vocab): """Given a string and a vocab dict, encodes the given string""" line = line.strip() sequence = [vocab.get(char, vocab['<UNK>']) for char in line] sequence_length = len(sequence) return sequence, sequence_length
feb14d86dd6c219d57cffc4cd9d90d16c4e9c987
3,641,309
import math def get_like_from_mats(ky_mat, l_mat, alpha, name): """ compute the likelihood from the covariance matrix :param ky_mat: the covariance matrix :return: float, likelihood """ # catch linear algebra errors labels = _global_training_labels[name] # calculate likelihood like ...
8fb7842547ecee25425bdaf920ff69d3386b920b
3,641,310
import os import json def cached(*cache_args, **cache_kwargs): """General-purpose. Allows custom filename, with function fallback. Load/save cached function data. Also handle data types gracefully. Example: >>> cached('myfile.json', directory=SOME_DIR) >>> def my_thing(): >>...
c8f85b8f4ba80cbc991622c220e59bce80683863
3,641,311
def engulfing(data: pd.DataFrame): """ engulfing Positive numbers are multi-side, negative numbers are short-side 0 is abnormal, meaning that the ratio of the absolute value of the current Candle up or down to the previous one is more than 10 times. For machine learning convenience, a floating point...
2974a62afa6b77ae2d8d02b35d7293362dd90927
3,641,312
import os def create_dat_files(ipc_tests, test_results, dst_dir): """ Creates .dat files for all the test_results. @param ipc_tests: list of ipc tests which was used to created the data. @param test_results: dictionary containing all test results. @param dst_dir: directory where the .dat-files sh...
363a37046b9ad8c495bed2d92c3a6b2d5adcc505
3,641,313
def filter_matches(kp1, kp2, matches, ratio = 0.75): """ This function applies a ratio test :param kp1: raw keypoint 1 :param kp2: raw keypoint 2 :param matches: raw matches :param ratio: filtering ratio :return: filtered keypoint 1, filtered keypoint 2, keypoint pairs """ mkp1, mkp2...
a54d96e092019b9629852b1bf57511f9994aba46
3,641,314
import itertools def add_derived_columns( data: pd.DataFrame, differences: bool = True, second_differences: bool = True, multiplications: bool = True, rolling_means: int | None = 10, rolling_stds: int | None = 10, mean_distances: bool = True, ) -> pd.DataFrame: """This will create many...
080f3853f67ead678c55a3c95bf2a1c19614452c
3,641,315
from typing import List def parse_query( query: List[str], format, use_youtube, generate_m3u, lyrics_provider, threads, path_template, ) -> List[SongObject]: """ Parse query and return list containing song object """ songs_list = [] # Iterate over all search queries a...
a58e5bd6acf2c12de7eb7fae7824aab924188c26
3,641,316
import os import shutil import time def start_db_server(): """Spin up a test database server""" log.debug('start_db_server()') try: os.mkdir(DATA_DIR) except FileExistsError: shutil.rmtree(DATA_DIR) sp.check_call(['initdb', '-D', DATA_DIR]) db_proc = sp.Popen(['postgres', '-D',...
94bddfad0e926dd330672d55598686ae7c2fbb9f
3,641,317
def assert_address_book(address_book): """Fixture returning an object providing a custom address book asserts.""" return icemac.addressbook.testing.AddressBookAssertions(address_book)
fd9197472c86a59dd1c52dad14febe1a0b318c85
3,641,318
def make_shell_context(): """Open shell.""" db = get_db() return {"db": db, "Doi": Doi, "Url": Url, "FBRequest": FBRequest}
996988c06aa8039c7689126360ce0fea886ab392
3,641,319
import re def get_version(): """ Extracts the version number from the version.py file. """ VERSION_FILE = 'fleming/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Un...
b50df998254d83bd48d7a5c0863ba89b29ab529b
3,641,320
import os def get_cache_path(): """ Return a path suitable to store cached files """ try: os.mkdir(cache_path) except FileExistsError: pass return cache_path
2370a3433d3a29603b625a6b5ea8b6afe23d024d
3,641,321
import math def distance(s1, s2): """ Euclidean distance between two sequences. Supports different lengths. If the two series differ in length, compare the last element of the shortest series to the remaining elements in the longer series. This is compatible with Euclidean distance being used as an u...
61c308da89b98b4bbde1bba690c86559fd5e1400
3,641,322
def remove_test_set_gender_and_age(nodes): """Remove the gender feature from a subset of the nodes for estimation""" # todo: the 40k random can be adjusted if youre working with a subset test_profiles = np.random.choice(nodes["user_id"].unique(), 40000, replace=False) nodes["TRAIN_TEST"] = "TRAIN" ...
285ee3f99b49e52af52f5a03465021154c41c11b
3,641,323
import re def valid_attribute(attr_filter_key, attr_filter_val, hit): """Validates the hit according to a filter attribute.""" if (attr_filter_key != "None") and (attr_filter_val != "None"): try: # If key for filtering is not correct or doesn't exist-> error # should be ignored...
c7480008f24e011f0803d82f1243a5d00c5a4030
3,641,324
import calendar def dek_to_greg(dek_day: int, dek_month: int, dek_year: int) -> tuple: """Returns a Gregorian date from a Dekatrian date. Args: dek_day (int): Day of the month. dek_month (int): Month of the year. dek_year (int): Year. Return: tuple: A tuple with the day, ...
c190ff52fa104c4c522397eb46a82e263096dc84
3,641,325
def encrypt_message(kx, ky, message): """ Encrypts a message using ECC and AES-256 First generates a random AES key and IV with os.urandom() Then encrypts the original message with that key Then encrypts the AES key with the ECC key NOTE: This means that plaintext will not have the same cip...
e4bd462e8724a85ed0e183e048203ff23e349f34
3,641,326
from typing import List import os def _create_init_files(original_file_location: FilePath) -> List[str]: """Given the original file location of a handler, create the artifact paths for all the __init__.py files that make the handle a valid python modules Args: original_file_location (str): origin...
442f299e493bd25afd2798922b4ef0652dda0416
3,641,327
def mirror_notes(key_position: int) -> int: """ 指定したキーポジションを反転させた値を返します 引数 ---- key_position : int -> キーポジション 戻り値 ------ int -> キーポジションを反転したときのキーポジション """ return 512 - key_position
03ad894eca67405bb79cbf6ea1ecef12b19958ed
3,641,328
def import_odim_hdf5(filename, **kwargs): """Import a precipitation field (and optionally the quality field) from a HDF5 file conforming to the ODIM specification. Parameters ---------- filename : str Name of the file to import. Other Parameters ---------------- qty : {'RATE', ...
650875bb3d04627f4570507892ee26b42912c39e
3,641,329
def sugerir(update: Update, _: CallbackContext) -> int: """Show new choice of buttons""" query = update.callback_query query.answer() keyboard = [ [ InlineKeyboardButton("\U0001F519 Volver", callback_data=str(NINE)), InlineKeyboardButton("\U0001F44B Salir", callba...
e278c6bdab82e4fdfc38c7a4bb58a5511a003515
3,641,330
def clone_subgraph(*, outputs, inputs, new_inputs, suffix="cloned"): """ Take all of the tensorflow nodes between `outputs` and `inputs` and clone them but with `inputs` replaced with `new_inputs`. Args: outputs (List[tf.Tensor]): list of output tensors inputs (List[tf.Tensor]): list of...
b61d73d79635551f8277cbc0c2da97d0c5c2908e
3,641,331
async def refresh_replacements(db, sample_id: str) -> list: """ Remove sample file `replacement` fields if the linked files have been deleted. :param db: the application database client :param sample_id: the id of the sample to refresh :return: the updated files list """ files = await virt...
43667801bf6bb96edbeb59bf9d538b62c9bf9785
3,641,332
def torch_model (model_name, device, checkpoint_path = None): """ select imagenet models by their name and loading weights """ if checkpoint_path: pretrained = False else: pretrained = True model = models.__dict__ [model_name](pretrained) if hasattr (model, 'classifier'): ...
831cf1edd83b76049e7f6d60434961cbd44e4bd9
3,641,333
from typing import Tuple from datetime import datetime def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] ...
f73cedb8fb91c75a19104d4d8bef29f73bfb9b1a
3,641,334
from typing import List from typing import Tuple def get_model(input_shape: List[int], weight_array: np.array, batches_per_step: int, replication_factor: int, batch_size: int, channels: int, data_len: int, synthetic_data: bool, buffer_streams: bool) -> Tuple: """Get a sim...
ab71faae9faeb082c4139a52dddac6116ee0a194
3,641,335
from collections import OrderedDict import ast import json def shell_safe_json_parse(json_or_dict_string, preserve_order=False): """ Allows the passing of JSON or Python dictionary strings. This is needed because certain JSON strings in CMD shell are not received in main's argv. This allows the user to specif...
f812a3c13a4c460fac1569d7ca9fe143312e43b8
3,641,336
def get_timed_roadmaps_grid_common( ins: Instance, T: int, size: int, ) -> list[TimedRoadmap]: """[deprecated] get grid roadmap shared by all agents Args: ins (Instance): instance T (int): assumed makespan size (int): size x size grid will be constructed Returns: list[n...
9b8e283ad66db35132393b53af2bfa36fc4aaf83
3,641,337
def arithmetic_series(a: int, n: int, d: int = 1) -> int: """Returns the sum of the arithmetic sequence with parameters a, n, d. a: The first term in the sequence n: The total number of terms in the sequence d: The difference between any two terms in the sequence """ return n * (2 * a + (n - 1...
168f0b07cbe6275ddb54c1a1390b41a0f340b0a6
3,641,338
import re def get_arc_proxy_user(proxy_file=None): """ Returns the owner of the arc proxy. When *proxy_file* is *None*, it defaults to the result of :py:func:`get_arc_proxy_file`. Otherwise, when it evaluates to *False*, ``arcproxy`` is queried without a custom proxy file. """ out = _arc_proxy...
01f1040cd1217d7722a691a78b5884125865cf39
3,641,339
def pass_hot_potato(names, num): """Pass hot potato. A hot potato is sequentially passed to ones in a queue line. After a number of passes, the one who got the hot potato is out. Then the passing hot potato game is launched againg, until the last person is remaining one. """ name_queue = Queue() for name in n...
f78a635bdf3138809329ef8ad97934b125b9335a
3,641,340
import copy def convert_timeseries_dataframe_to_supervised(df: pd.DataFrame, namevars, target, n_in=1, n_out=0, dropT=True): """ Transform a time series in dataframe format into a supervised learning dataset while keeping dataframe intact. Returns the transformed pandas DataFrame, the name of the targ...
b62296680f6a871f20078e55eefa20f09392b012
3,641,341
def build_graph(adj_mat): """build sparse diffusion graph. The adjacency matrix need to preserves divergence.""" # sources, targets = adj_mat.nonzero() # edgelist = list(zip(sources.tolist(), targets.tolist())) # g = Graph(edgelist, edge_attrs={"weight": adj_mat.data.tolist()}, directed=True) g = Gr...
bdc8dc5d1c107086c4c548b500f6958bdbe48103
3,641,342
def retrieve_context_path_comp_service_end_point_end_point(uuid): # noqa: E501 """Retrieve end-point Retrieve operation of resource: end-point # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: List[str] """ return 'do some magic!'
e3169e139b5992daf00411b694cf77436fb17fba
3,641,343
def get_external_repos(gh): """ Get all external repositories from the `repos.config` file """ external_repos = [] with open("repos.config") as f: content = f.readlines() content = [x.strip() for x in content] for entry in content: org_name, repo_name = entry.sp...
a83515acd77c7ef9e30bf05d8d4478fa833ab5bc
3,641,344
def handle_standard_table(pgconn, table_name, columns, record): """ :param pgconn: :param table_name: :param columns: :param record: :return: """ data = dict(record) log.debug("Standard handler: {}".format(data)) if 'id' in columns: data_exists = pgconn.execute( ...
c6414b2f60cf90ed6a671c0b7affcb2d6b9e75c9
3,641,345
import json def load_fit_profile(): """ This methods return the FIT profile types based on the Profile.xslx that is included in the Garmin FIT SDK (https://developer.garmin.com/fit/download/). The returned profile can be used to translate e.g. Garmin product names to their corresponding integer product id...
13108546c2d88d77d090b222c1b3ff2b59208310
3,641,346
def mmethod(path, *args, **kwargs): """ Returns a mapper function that runs the path method for each instance of the iterable collection. >>> mmethod('start') is equivalent to >>> lambda thread: thread.start() >>> mmethod('book_set.filter', number_of_pages__gte=100) is equivalent to ...
6ded620d190d338d981c433514018a4182b7e207
3,641,347
def generate_test_demand_design_image() -> TestDataSet: """ Returns ------- test_data : TestDataSet 2800 points of test data, uniformly sampled from (price, time, emotion). Emotion is transformed into img. """ org_test: TestDataSet = generate_test_demand_design(False) treatment = org...
238cf11480e0d23f30b426ed19877126edc010fa
3,641,348
def value_iteration(game, depth_limit, threshold): """Solves for the optimal value function of a game. For small games only! Solves the game using value iteration, with the maximum error for the value function less than threshold. This algorithm works for sequential 1-player games or 2-player zero-sum games,...
2a9ae3903666ee16e86fe30a0458707394fe4695
3,641,349
import typing def printable_dataframe(data: typing.List[typing.Mapping], ignore_phase: bool = True) -> pd.DataFrame: """ Print performance results using pandas data frames. TODO: Re-write me. """ columns = {'name': 'Model', 'input_shape': 'Input shape', 'num_parameters': '#Parameters', ...
c76841d06891da4019e32194347f8d87c11dbea1
3,641,350
def _import_and_infer(save_dir, inputs): """Import a SavedModel into a TF 1.x-style graph and run `signature_key`.""" graph = ops.Graph() with graph.as_default(), session_lib.Session() as session: model = loader.load(session, [tag_constants.SERVING], save_dir) signature = model.signature_def[ sign...
1610c4d52fa8d18a770f1f347b9cd30b4652ab8b
3,641,351
import os def new_module(fname, main=False, parser_vmx=None): """ `fname` is Python str (or None for internal Module) `main` is Python True for main program (from command line) `argv` is Python list of str (if main is True) `parser_vmx` is Python str for parser VMX file to use returns (CModule...
c5732841b213d41e8bb466fb755804dd3f0902f2
3,641,352
def url_by_properties( config_properties, db_type, submit_dir=None, top_dir=None, rundir_properties=None, cl_properties=None, props=None, ): """ Get URL from the property file """ # Validate parameters if not db_type: raise ConnectionError( "A type should be p...
3f742af88320eccdacd81603ceeaf94116852798
3,641,353
def nth(seq, idx): """Return the nth item of a sequence. Constant time if list, tuple, or str; linear time if a generator""" return get(seq, idx)
cca44dca33d19a2e0db355be525009dce752445c
3,641,354
import psutil def get_internal_plot_drive_to_use(): """ Same as above but returns the next drive. This is the drive we will use for internal plots. We do this to make sure we are not over saturating a single drive with multiple plot copies. When you run out of drives, these scripts will fa...
de86c7a6bb61ba9ebbf7555dae2d07576f8ccb3e
3,641,355
def _build_discretize_fn(value_type, stochastic, beta): """Builds a `tff.tf_computation` for discretization.""" @computations.tf_computation(value_type, tf.float32, tf.float32) def discretize_fn(value, scale_factor, prior_norm_bound): return _discretize_struct(value, scale_factor, stochastic, beta, ...
75f9f50ec376b1a10b5fcb629527a873b8768235
3,641,356
def expand_mapping_target(namespaces, val): """Expand a mapping target, expressed as a comma-separated list of CURIE-like strings potentially prefixed with ^ to express inverse properties, into a list of (uri, inverse) tuples, where uri is a URIRef and inverse is a boolean.""" vals = [v.strip() for...
b4a4f08d39728c8f61b7b373a521890f88d6f912
3,641,357
def home(request): """Handle the default request, for when no endpoint is specified.""" return Response('This is Michael\'s REST API!')
a37a2eaa68366de4d8542357c043c4e29ac7a9f9
3,641,358
def create_message(sender, to, subject, message_text, is_html=False): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: ...
2b5dc225df5786df9f2650631d209c53e3e8145b
3,641,359
def get_agent(runmode, name): # noqa: E501 """get_agent # noqa: E501 :param runmode: :type runmode: str :param name: :type name: str :rtype: None """ return 'do some magic!'
065302bb7793eff12973208db5f35f3494a83930
3,641,360
def find_splits(array1: list, array2: list) -> list: """Find the split points of the given array of events""" keys = set() for event in array1: keys.add(event["temporalRange"][0]) keys.add(event["temporalRange"][1]) for event in array2: keys.add(event["temporalRange"][0]) ...
c52f696caddf35fa050621e7668eec06686cee14
3,641,361
def to_subtask_dict(subtask): """ :rtype: ``dict`` """ result = { 'id': subtask.id, 'key': subtask.key, 'summary': subtask.fields.summary } return result
5171d055cc693b1aa00976c063188a907a7390dc
3,641,362
from typing import Tuple from typing import Optional def _partition_labeled_span( contents: Text, labeled_span: substitution.LabeledSpan ) -> Tuple[substitution.LabeledSpan, Optional[substitution.LabeledSpan], Optional[substitution.LabeledSpan]]: """Splits a labeled span into first line, intermediate...
6f22341d32c03ba0057fbfd6f08c88ac8736220f
3,641,363
def is_active(relation_id: RelationID) -> bool: """Retrieve an activation record from a relation ID.""" # query to DB try: sups = db.session.query(RelationDB) \ .filter(RelationDB.supercedes_or_suppresses == int(relation_id)) \ .first() except Exception as e: rais...
352f44e2f025ac0918519d0fe8e513b3871be7b9
3,641,364
def vectorize_with_similarities(text, vocab_tokens, vocab_token_to_index, vocab_matrix): """ Generate a vector representation of a text string based on a word similarity matrix. The resulting vector has n positions, where n is the number of words or tokens in the full vocabulary. The value at each position indicate...
5b843ffbfdefbf691fb5766bbe6772459568cf78
3,641,365
def get_puppet_node_cert_from_server(node_name): """ Init environment to connect to Puppet Master and retrieve the certificate for that node in the server (if exists) :param node_name: Name of target node :return: Certificate for that node in Puppet Master or None if this information has not been found ...
7f7fa2164bf7f289ce9dbc1b35f2d8aea546bb60
3,641,366
from typing import Optional def get_notebook_workspace(account_name: Optional[str] = None, notebook_workspace_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awaitabl...
d9020323c0ea520951730a31b2f457ab80fcc931
3,641,367
def get_current_player(player_one_turn: bool) -> str: """Return 'player one' iff player_one_turn is True; otherwise, return 'player two'. >>> get_current_player(True) 'player one' >>> get_current_player(False) 'player two' """ if player_one_turn: return P1 else: retu...
6bade089054513943aef7656972cadd2d242807c
3,641,368
import os import glob def CityscapesGTFine(path: str) -> Dataset: """`CityscapesGTFine <https://www.cityscapes-dataset.com/>`_ dataset. The file structure should be like:: <path> leftImg8bit/ test/ berlin/ berlin_000000_000019_l...
70e1adb939519fe6641f1a390ed6b011b27fc1ec
3,641,369
def is_word(s): """ String `s` counts as a word if it has at least one letter. """ for c in s: if c.isalpha(): return True return False
524ed5cc506769bd8634a46d346617344485e5f7
3,641,370
def index_all_messages(empty_index): """ Expected index of `initial_data` fixture when model.narrow = [] """ return dict(empty_index, **{'all_msg_ids': {537286, 537287, 537288}})
ea2c59a4de8e62d2293f87e26ead1b4c15f15a11
3,641,371
def compute_affine_matrix(in_shape, out_shape, crop=None, degrees=0.0, translate=(0.0, 0.0), flip_h=False, flip_v=False, resize=False, ...
0c3786c44d35341e5e85d3756e50eb59dd473d64
3,641,372
def Bern_to_Fierz_nunu(C,ddll): """From semileptonic Bern basis to Fierz semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.""" ind = ddll.replace('l_','').replace('nu_','') return { 'F' + in...
4f08f79d6614c8929c3f42096fac71b04bfe7b4b
3,641,373
def enforce_boot_from_volume(client): """Add boot from volume args in create server method call """ class ServerManagerBFV(servers.ServerManager): def __init__(self, client): super(ServerManagerBFV, self).__init__(client) self.bfv_image_client = images.ImageManager(client) ...
4ae4d2624f216c96722e811d9d44cb04caa46e1d
3,641,374
def img_to_yuv(frame, mode, grayscale=False): """Change color space of `frame` from any supported `mode` to YUV Args: frame: 3-D tensor in either [H, W, C] or [C, H, W] mode: A string, must be one of [YV12, YV21, NV12, NV21, RGB, BGR] grayscale: discard uv planes return: ...
002506b3a46fa6b601f4ca65255c8f06b990992d
3,641,375
def assemblenet_kinetics600() -> cfg.ExperimentConfig: """Video classification on Videonet with assemblenet.""" exp = video_classification.video_classification_kinetics600() feature_shape = (32, 224, 224, 3) exp.task.train_data.global_batch_size = 1024 exp.task.validation_data.global_batch_size = 32 exp.ta...
3356b6ea758baf04cc98421d700f25e342884d5a
3,641,376
import math import torch def channel_selection(inputs, module, sparsity=0.5, method='greedy'): """ 현재 모듈의 입력 채널중, 중요도가 높은 채널을 선택합니다. 기존의 output을 가장 근접하게 만들어낼 수 있는 입력 채널을 찾아냅니댜. :param inputs: torch.Tensor, input features map :param module: torch.nn.module, layer :param sparsity: float, 0 ~ 1 h...
957cbcc799185fd6c2547662bfe79205389d44da
3,641,377
import six def format_host(host_tuple): """ Format a host tuple to a string """ if isinstance(host_tuple, (list, tuple)): if len(host_tuple) != 2: raise ValueError('host_tuple has unexpeted length: %s' % host_tuple) return ':'.join([six.text_type(s) for s in host_t...
f4822aec5143a99ccc52bb2657e1f42477c65400
3,641,378
import psutil def get_cpu_stats(): """ Obtains the system's CPU status. :returns: System CPU static. """ return psutil.cpu_stats()
f538977db72083f42c710faa987a97511959c973
3,641,379
from typing import Dict from typing import Union import os import re def load_gene_metadata(gtf_file : str) -> Dict[str, Dict[str, Union[int, str]]]: """ Read gene metadata from a GTF file. Args: gtf_file (str): path to GTF file Returns: A Dict with ea...
bc5f096f7a14579fcdee5a862f3f800d21012244
3,641,380
import sys import glob import os import pathlib import importlib def get_plugins() -> dict[str, Plugin]: """ This function is really time consuming... """ # get entry point plugins # Users can use Python's entry point system to create rich plugins, see # example here: https://github.com/Piore...
234a86b1ee142b9ccf1cfc39a6bc3947bd103488
3,641,381
import json def _deserialise_list_of(collection_type, kind, owning_cls, field, value): """ Deserialise a list of items into a collection objects of class `kind`. Note that if the value is None, we return None here so that we get a more meaningful error message later on. Args: kind: Type t...
8dc7dfa88966d90bb29714c887a2457d9aeb1e8f
3,641,382
def get_minmax_array(X): """Utility method that returns the boundaries for each feature of the input array. Args: X (np.float array of shape (num_instances, num_features)): The input array. Returns: min (np.float array of shape (num_features,)): Minimum values for each feature in array. ...
5453371759af5bf6d876aa8fe5d2caf88ee6eb08
3,641,383
def getAllHeaders(includeText=False): """ Get a dictionary of dream numbers and headers. If includeText=true, also add the text of the dream to the dictionary as 'text' (note that this key is all lowercase so it will not conflict with the usual convention for header names, even if "Text" would be an...
2bbd78d9c9cbfaa50a62e99c25148844d7c5e330
3,641,384
def zscore(arr, period): """ ZScore transformation of `arr` for rolling `period.` ZScore = (X - MEAN(X)) / STDEV(X) :param arr: :param period: :return: """ if period <= 0: raise YaUberAlgoArgumentError("'{}' must be positive number".format(period)) # Do quick sanity checks of a...
8a49afe3ecefc326b3bd889279085cccd1d19a61
3,641,385
import glob import pandas def _load_event_data(prefix, name): """Load per-event data for one single type, e.g. hits, or particles. """ expr = '{!s}-{}.csv*'.format(prefix, name) files = glob.glob(expr) dtype = DTYPES[name] if len(files) == 1: return pandas.read_csv(files[0], header=0, ...
04b2e4a7483ba56fdd282dc6355e9acb2d6da7b1
3,641,386
from datetime import datetime def check_file(file_id: str, upsert: bool = False) -> File: """Checks that the file with file_id exists in the DB Args: file_id: The id for the requested file. upsert: If the file doesn't exist create a placeholder file Returns: The file object ...
2f4e94a064d0bdfea8f001855eb39675f78ab6e5
3,641,387
def parse(volume_str): """Parse combined k8s volume string into a dict. Args: volume_str: The string representation for k8s volume, e.g. "claim_name=c1,mount_path=/path1". Return: A Python dictionary parsed from the given volume string. """ kvs = volume_str.split(",") ...
f6984faf90081eb8ca3fbbb8ffaf636b040c7ffc
3,641,388
def longest_common_substring(text1, text2): """最长公共子字符串,区分大小写""" n = len(text1) m = len(text2) maxlen = 0 span1 = (0, 0) span2 = (0, 0) if n * m == 0: return span1, span2, maxlen dp = np.zeros((n+1, m+1), dtype=np.int32) for i in range(1, n+1): for j in range(1, m+1)...
ed892739d22ee0763a2fe5dd44b48b8d1902605e
3,641,389
def make_subclasses_dict(cls): """ Return a dictionary of the subclasses inheriting from the argument class. Keys are String names of the classes, values the actual classes. :param cls: :return: """ the_dict = {x.__name__:x for x in get_all_subclasses(cls)} the_dict[cls.__name__] = cls ...
36eb7c9242b83a84fcd6ee18b4ca9297038f9ee6
3,641,390
import time def _parse_realtime_data(xmlstr): """ Takes xml a string and returns a list of dicts containing realtime data. """ doc = minidom.parseString(xmlstr) ret = [] elem_map = {"LineID": "id", "DirectionID": "direction", "DestinationStop": "destination" } ack = _singl...
90958c7f66072ecfd6c57b0da95293e35196354c
3,641,391
def tocopo_accuracy_fn(tocopo_logits: dt.BatchedTocopoLogits, target_data: dt.BatchedTrainTocopoTargetData, oov_token_id: int, pad_token_id: int, is_distributed: bool = True) -> AccuracyMetrics: """Computes accuracy metrics. ...
828b7d3db40d488a7e05bbfe1f3d2d94f58d8efa
3,641,392
def cols_from_html_tbl(tbl): """ Extracts columns from html-table tbl and puts columns in a list. tbl must be a results-object from BeautifulSoup)""" rows = tbl.tbody.find_all('tr') if rows: for row in rows: cols = row.find_all('td') for i,cell in enumerate(cols): ...
94bef05b782073955738cf7b774af34d64520499
3,641,393
from typing import List from typing import Tuple def get_score_park(board: List[List[str]]) -> Tuple[int]: """ Calculate the score for the building - park (PRK). Score 1: If ONLY 1 park. Score 3: If the park size is 2. Score 8: If the park size is 3. Score 16: If the par...
2bf1629aeb9937dfd871aa118e675cd9358b65ef
3,641,394
def kernel_epanechnikov(inst: np.ndarray) -> np.ndarray: """Epanechnikov kernel.""" if inst.ndim != 1: raise ValueError("'inst' vector must be one-dimensional!") return 0.75 * (1.0 - np.square(inst)) * (np.abs(inst) < 1.0)
7426e068c3a939595b77c129af4f8d30bbfc89fb
3,641,395
def submission_parser(reddit_submission_object): """Parses a submission and returns selected parameters""" post_timestamp = reddit_submission_object.created_utc post_id = reddit_submission_object.id score = reddit_submission_object.score ups = reddit_submission_object.ups downs = reddit_submiss...
d2b406f38e799230474e918df91d55e48d27f385
3,641,396
def dashboard(): """Displays dashboard to logged in user""" user_type = session.get('user_type') user_id = session.get('user_id') if user_type == None: return redirect ('/login') if user_type == 'band': band = crud.get_band_by_id(user_id) display_name = band.display...
1cec9fcd17a963921f23f03478a8c3195db9a18e
3,641,397
from bs4 import BeautifulSoup def parse_site(site_content, gesture_id): """ Parses the following attributes: title, image, verbs and other_gesture_ids :param site_content: a html string :param gesture_id: the current id :return: { title: str, img: str, id: number, compares...
b9719dbbd2ca7883257c53410423de5e3df3fe93
3,641,398
from multiprocessing import Pool import multiprocessing def test_multiprocessing_function () : """Test parallel processnig with multiprocessing """ logger = getLogger ("ostap.test_multiprocessing_function") logger.info ('Test job submission with module %s' % multiprocessing ) ncpus = mu...
a59635b844b4ff80a090a1ec8e3661e340903269
3,641,399