content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import shutil def cmd_exists(cmd): """Returns True if a binary exists on the system path""" return shutil.which(cmd) is not None
0d43181532b9b71cb06b6a5d1f207bbb19899129
3,604,531
def read_viewpoint_quats(f): """Reads viewpoint qauternion from file Args: f (string): Path to the .mat file Returns: dict: A dictionary of viewpoint quaternions, indexed by the class id number. """ vp_data = loadmat(f) vpq = vp_data['viewpoints']['quaternion'][0][0] quat_di...
c9e8607f98ad36c3e5290b96f8a3bad6f774e6a3
3,604,532
import requests def get_swapi_resource(url, params=None): """This function initiates an HTTP GET request to the SWAPI service in order to return a representation of a resource. The function defines two parameters, the resource url (str) and an optional params (dict) query string of key:value pairs may be ...
3a5de57fc498da1e25de4f2b3e61cae8508ad7c7
3,604,533
def svm_accuracy_in_euc_space_params(X, labels, params, folds=3): """SVM classifier accuracy in an Euclidean Space. Args: X (np.ndarray): The data array. labels (list, np.ndarray): The data labels. params (dict): Dictionary of parameters and its values. folds (int): Amount of fo...
f5ae96a642b3025168e8eaad7cb522a784d323f5
3,604,534
def get_user_categories(user: User): """ Retrieves a User's Categories. :param user: A User :return: A list of a User's Categories """ return Category.categories.filter(user_storage__id=user.id).order_by('name')
253f53b3788133d49e80fe58ca725d5ab97c9249
3,604,535
def _normalize_results(inputs, outputs, results, return_rank1=False): """normalize_results() does standard return value handling for a given set of ufunc actual parameters and results. Ufunc inputs are assumed to be arrays or scalars, ufunc outputs can be arrays or unspecified, and ufunc "preliminary r...
aa187e4e294afb847261e968e02910e9aa60a3f5
3,604,536
def assertify(text): """Wraps text in the (assert ).""" return '(assert ' + text + ')'
da7af0fe5d27759d8cef4589843796bee8e74383
3,604,537
def remove_nodata_records(df_records, nodata_value=-999): """ Read a numpy record array and remove nodata records. Parameters ---------- df_records: pandas dataframe A pandas dataframe type containing values extracted from env variables. nodata_value : int, float, np.nan A int, ...
5523bad6bde93ef2b425110b37696d07e43ad6de
3,604,538
def get_config(config_file_path): """ :param config_file_path: :return: """ return parse_config_utils.Config(config_path=config_file_path)
8f4f717c14d44de586dd567564e2379d8e10ffa7
3,604,539
def create_uniform_layer( num_components, component_fn, combiner_fn, router_fn): """Creates a layer of components with the same architecture and router. Args: num_components: (int) number of components. component_fn: function that creates a new component. combiner_fn: function that creates a combin...
780dbe32b404c7dd45192439a96b91a48bf67929
3,604,540
import time def wait_for_services(cloud_name, host=None, service=None, admin_up_only=True, retries=18, timeout=10, **kwargs): """Ensure the service is up and running on specified host. :param host: name of a host where service is running :param admin_up_only: do not check status for admin disa...
9f831e12f54522e328a5b184620380e356dd7558
3,604,541
import PIL def resize_image(img:PIL.Image, size:int)->PIL.Image: """ resize PIL-image """ w, h = img.size if w == size and h == size: return img else: return img.resize((size, size), PIL.Image.BICUBIC)
d9548e12730b0972803ed7a0e485a65b1cc07db2
3,604,543
def find_resp_subject(subj, RESP): """Find if there is one matching subject in RESPECT database based on the channel names""" matching_subj = [] sessions = [x for x in subj.list_sessions() if x.name == 'IEMU'] for sess in sessions: for chan in sess.list_channels(): matched = find...
897d72c16d87a7b44c5a03673725de0a4c91ea57
3,604,545
def mjed_from_tdb(tdb): """Modified Julian Ephemeris Date from TDB seconds.""" return tdb/86400. + MJED_OF_J2000
95c20b0838fd0e9a89f44581c215cc8cb0f6a89c
3,604,547
def deseasonalize(ts): """ removing monthly mean climatology """ dt_year = (ts.time[12]-ts.time[0]).values # ts_ds = ts.copy() yrly = ts.groupby_bins('time', np.arange(0,len(ts.time)+1,12)/12*dt_year, right=False).mean(dim='time').rename({'time_bins':'time'}) for j in range(12): m = ts.isel...
b97ac236ebafb21544b9e5ff620af4403e38e1a2
3,604,548
def load_variable(checkpoint_dir, name): """See `tf.contrib.framework.load_variable`.""" return checkpoint_utils.load_variable(checkpoint_dir, name)
cf0ad703242287f85cd3399beb167bfc6dc4305f
3,604,549
from typing import Optional def parse_json_and_match_value(line: str, value: str) -> Optional[LogType]: """Parse a line as JSON log and check if it a valid log.""" log = parse_json(line) if log: key = "logbook_type" if key not in log or log[key] != value: log = None return ...
5468995f710aa5691a45a49fcfbd0c58db53df87
3,604,550
def get_images_from_multi_tiff(path, nb_img=False): """ Import .tif file from a given path and convert it to a 3d np.array where the first dimension represent the image index. Parameters ---------- path : str .tif file path. the tif file must carry only 2d arrays of the same dim...
d5b28dfbe1816098eb538d42c5847edc6f44c87a
3,604,551
def test_print_validate_tuple(): """ Feature: JIT Fallback Description: Support print. Expectation: No exception. """ @ms_function def print_func(): x = Tensor(np.array([1, 2, 3, 4, 5])) y = Tensor(np.array([1, 2, 3, 4, 5])) tensor_sum = x + y print("tensor_su...
f4100d80ff6526cd4848f47ba571ab103ff23410
3,604,552
def about_time(all_df): """ elapsed time remaining time Note: remaining time not collected anymore! """ # time_list = [all_df['elapsed'].iloc[-1], all_df['remaining_time'].iloc[-1]] time_list = [all_df['elapsed'].iloc[-1], None] if len(time_list) != 2: print("***len(time_list): ...
780a426c05ed8484796d718ca1aabaec1b648d03
3,604,553
def remove_repository(s3_client, bucket, prefix): """Remove a P2 repository from a prefix on an S3 bucket :param s3_client Boto s3_client object to apply :param bucket: Bucket to remove from :param prefix: Prefix at which to remove the repository :return: True if repository was removed, else False ...
d23a54195751a4ccfbe77a7fb099a8d4743bb83a
3,604,554
import typing def func_pq_annotate(*, p: "3" = "p", q="q") -> typing.Tuple: """func. Parameters ---------- p, q: str, optional Returns ------- p, q: str """ return None, None, None, None, None, p, q, None
c65555a391e05248aecec5abcce6b6d0c60ef3ec
3,604,555
def multi_row_selector(table, keyword, value_list, row_selector=None, **kwargs): """Returns lists of indices into a table, one list per value of `keyword` Parameters ---------- table : `~astropy.table.Table` Usually a `ccdproc.ImageFileCollection.summary`, hence the use ...
d5de585afe3f97355dded18a59d3ec60576b55ee
3,604,556
import requests from bs4 import BeautifulSoup def commitstrip_scraper(): """ Filenames are in an javascript object on the mainpage. """ try: except ModuleNotFoundError: raise CartoonError("Packages for scraping not installed. Install requests and beautifulsoup4. " ...
815d7684f9bec00a5d3bc376bc69f9eca3a38320
3,604,557
def invert_instruction(f, args): """ Transform a parsed instruction into its inverse """ if f in (swap_position, swap_char, move): args.reverse() elif f == rotate: args[0] = -args[0] elif f == rotate_position: f = rotate_position_inverse return f, args
132ce0996daa26f0e69eccc1f86e1e3ac92ae800
3,604,558
def new_fountain(): """ Drinking from the fountain makes the player stronger. """ fountain = Composite() set_dungeon_feature_components(fountain) fountain.set_child(Description("Fountain", ("A Fountain full of clean water", "...
6640ce957517c425961581a22617a6f4b13ac505
3,604,560
def _chunk_outline(chunk: ChunkData) -> np.ndarray: """Return the line verts that outline this single chunk. Parameters ---------- chunk : ChunkData Create outline of this chunk. Return ------ np.ndarray The chunk verts for a line drawn with the 'segments' mode. """ ...
fb8db1c4c1bb2cc95a9701e48733cb4b6c3abb2a
3,604,561
def shuffle(batches): """Shuffle the data. This method groups the batches together in pairs and within each pair shuffles the data between the two members. Args: batches (List[Tuple[ObjectID, ObjectID]]): This is a list of tuples, where each tuple consists of two object IDs. The first component is a...
8180bf3f972f9206d7fa0b0e2deb1ffe175df98d
3,604,562
import logging def create_network(batch_size, update_freq): """Create a linear regression network for performing SVRG optimization. :return: an instance of mx.io.NDArrayIter :return: an instance of mx.mod.svrgmodule for performing SVRG optimization """ head = '%(asctime)-15s %(message)s' loggi...
fb878f4f796a195b4e1c258f5742d034b7c272c2
3,604,563
def bubble_sort(items): """Sort given items by swapping adjacent items that are out of order, and repeating until all items are in sorted order. Running time: O(n**2) because it passes through n/2 (on average) elements n-1 times, which simplifies to n elements n times, n**2 Memory usage: O(1), a...
88748e0d552f0d08e228049f12268e34aed4907b
3,604,564
import numbers def is_special_slice(key) -> bool: """Does the key contain a list, ndarray, or logical ndarray? """ # Slices and int-like numbers are fine. for elem in to_tuple(key): if not (isinstance(elem, (numbers.Number, slice)) or np.isscalar(elem)): return True return Fal...
e7d5888002048472688f0f491b684d68fbd5014d
3,604,565
def human_list(_list) -> str: """Convert a list of items into 'a, b or c'""" last_item = _list.pop() result = ", ".join(_list) return "%s or %s" % (result, last_item)
04ee703d1878ac7602ba33aaf1831ccc188ee9e2
3,604,566
import base64 import io def preprocess(data): """ This method decodes base64 encoded image, resizes it to 299 x 299 shape, and turns it into tensor digestable by the model """ decoded_image = base64.b64decode(data); image = Image.open(io.BytesIO(decoded_image)); resized_image = image.res...
ecfc2efa8f68a1263e94f7457e2ced9289b10774
3,604,568
import logging def recluster(particles, Rjet,jetdef_tree): """Recluster the jet constituents""" # Recluster the jet constituents and access the clustering history #set up our jet definition and a jet selector if jetdef_tree=='antikt': tree_jet_def = fj.JetDefinition(fj.antikt_algorithm, Rjet) ...
85196c3c477328570c06f61bfb8d7f8fc3b33efd
3,604,569
def netcsf2sql(file_name: str, rootgrp: Dataset, xr_file, force_save_db): """_summary_ Args: file_name (str): _description_ rootgrp (Dataset): _description_ Returns: bool: _description_ """ error = False for name in settings.vars: try: tempc = rootgr...
391a779526be9b70f9222aa1fb69bf4a40869032
3,604,570
def segment_mean(x, segment_ids): """ Computes the mean along segments of a tensor. Parameters ---------- x : tensor The tensor to segment_mean. Should have real numeric type. segment_ids : tensor A 1-D tensor whose size is equal to the size of data's first dimension. Values sho...
232800aad718554162a48d4b5d418d5b4e18879a
3,604,571
def compute_distances_squared(xi1, xi2): """ Return matrix of squared Euclidian distance between all pairs of points in d-dimensions. Args: xi1 (ndarray): Sample locations in d-dimensions, shape `(n1, d)`. xi2 (ndarray): Sample locations in d-dimensions, shape `(n2, d)`. Return: out (ndarray): Shape `(n1...
7177e0a08bf09257b1e8402040c8a8d7e6e2884e
3,604,572
def is_unique_chars_v2(str): """ Let N be the string length Dictionary construction: O(N); d[k] = v is O(1), done N times Containment check: O(N) => O(N) time => O(N) space """ chars_map = defaultdict(int) for char in str: chars_map[char] += 1 return 2 not in chars_map.va...
256bab14de37f9a1a86e6f2354085d4936382fff
3,604,573
def get_session_detail_list_for_recover(session_list): """ 根据集群名称列表,查询补全详细的信息("cluster_group", "cluster_label", "cluster_name", "version") :param session_list: 集群名称列表 :return: """ session_detail_list = [] for cluster_name in session_list: res = ResourceCenterHelper.get_cluster_info( ...
5566892541d4214e7321aaaf120b9b5e5f810ec2
3,604,574
def mixup( alpha, beta, sample_1, label_1, *, sample_2=None, label_2=None, repeat=1, shuffle=True ): """ The interface of mixup functions. """ if sample_2 is None: return _mixup_samples( alpha, beta, sample_1, label_1, sample_1, label_1, repeat, shuffl...
3a704fe0ca3bc054accafc5f544c9146bf9d2df4
3,604,575
def operate(id, event, qstate, qdata): """ Perform action on pending query. Accepts a new query, or work on pending query. You have to set qstate.ext_state on exit. The state informs unbound about result and controls the following states. Parameters: id - module identifier (integer) ...
368687808b53c92e6346af26ebbf457815676f87
3,604,576
def readOpenMMReporterFile(reporter_file): """ Creates a dictionary containing all the entries in the reported data reporter_file Parameters ---------- reporter_file : str Path to the reporter output file """ with open(reporter_file, 'r') as ef: lines = ef.readlines() ...
9f7d3c958ef82994764f276bdd854868099c7960
3,604,577
def run_parallel(workflow, n_threads): """Run a workflow in parallel threads. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :returns: evaluated workflow. """ scheduler = Scheduler() threaded_worker = Queue...
0aa3674a3a964a130c21d64a08cd21592eda3492
3,604,578
def parse_chain(chain_desc): """Parse user input chain assign id to each nf and group nf by location assgin offloadability to each nf """ global nf_offlodability nf_id = 0 cur_location = None cur_group = None nf_groups = {} for nf in chain_desc: # assign id first ...
925463a29789ce2fee118ba4a90691604cc3223c
3,604,579
def sobel_fg_alpha(idepth, beta=5.0): """Computes foreground alpha with sobel edges. Alphas will be low when there are strong sobel edges. Args: idepth: [B, H, W, 1] inverse depth tensor. beta: (float) Higher the beta, higher the sensitivity to the idepth edges. Returns: alpha: [B, H, W, 1] alpha...
4eab004f66d301f778cf453b7d939dcd8c8aa3b1
3,604,580
def hat_3d(xi): """ Converts a 3D twist to its corresponding 4x4 matrix representation Args: xi - (6,) ndarray: the 3D twist Returns: xi_hat - (4,4) ndarray: the corresponding 4x4 matrix """ if not xi.shape == (6,): raise TypeError('xi must be a 6-vector') xi_hat =...
932074306716e933cd557f57a6f9809c34332abb
3,604,581
def colourise(value, colour, condition=None): """Colour a piece of text. If a condition callback is passed in, the text will only be coloured if the condition is met. """ if condition is not None: if not condition(value): return str(value) return f"{colour}{value}{Fore.RESET}"
e70af19a68a049ff4a4b680c1547417dc89ff4a2
3,604,582
def get_cohort_by_name(course_key, name): """ Return the CourseUserGroup object for the given cohort. Raises DoesNotExist it isn't present. """ return CourseUserGroup.objects.get( course_id=course_key, group_type=CourseUserGroup.COHORT, name=name )
d29170ec078a58e56d77b2daee76c7be03a35bf5
3,604,583
from typing import List from typing import Optional from typing import Dict def merge_records_gnss( records_gnss_list: List[Optional[kapture.RecordsGnss]], sensor_mappings: List[Dict[str, str]]) -> kapture.RecordsGnss: """ Merge several gnss records list into one list with new identifiers for ...
1bc128662172691c44c48bec90a639f51900c496
3,604,584
import math def attention(query, key, value, mask=None, dropout=None): """Compute 'Scaled Dot Product Attention. Inputs: - query: [batch_size, num_heads, num_objects, feat_dim] - key: [batch_size, num_heads, num_objects, feat_dim] - value: [batch_size, num_heads, num_objects, feat_dim] - m...
9718f8f75629cb46072df1f721e8ce32c561531e
3,604,585
def make_random_walks(dataset, k, L): """Computes random walks.""" cfg = { 'walker-name': 'uniform', 'args': {'walk_length': L, 'num_walks': k} } graph = to_undirected(dataset['graph']) walker = ng_walkers.make_walker(cfg) rws = ng_rw_util.precompute_rws_par( g=graph, ...
e7c3928c539beb298bec0f2eb67ab610935f0a17
3,604,587
import inspect def full_class_name(cls): """Returns the full qualified name of given class.""" assert isinstance(cls, type) return inspect.getmodule(cls).__name__ + '.' + cls.__name__
876ced2ab0aa95af6d1a71f37c7c70da5ac8d5bf
3,604,588
def form_node_label_prediction_matrix(y_pred, y_test): """ Given the discriminator distances, this function forms the node-label prediction matrix. It is assumed that the number of true labels is known. Inputs: - y_pred: A NumPy array that contains the distance from the discriminator for each label f...
ccfe961dbc744dc85c5ea9e586e825383b1e48b4
3,604,589
from typing import List def check_pool_exist(pool: str, region: str) -> bool: """ Check that we have slaves in the provided pool and region """ system_paasta_config = load_system_paasta_config() expected_slave_attributes = system_paasta_config.get_expected_slave_attributes() if expected_slave_attr...
1f159ada404dd67aa00a7dcf419571249c030036
3,604,590
from typing import Optional def get_databases(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabasesResult: """ ## Example Usage ```python import pulumi import pulumi_snowflake as snowflake this = snowflake.get_databases() ``` """ __args__ = dict() if opts is N...
0aef42b26a6b25d1b63edc1fab98613f3c3387e2
3,604,591
from typing import Callable from typing import Optional import pathlib from typing import Sequence import logging import torch import pprint def maybe_launch( main: Callable, *, exp_root: Optional[pathlib.Path], overrides: Sequence[str], cfg: pathlib.Path, mode: util.ModeType, adhoc: bool ...
e985a3088e63974fc0326b3def7a39f30aed45d0
3,604,593
from typing import Optional def estimate_high_probability_upper_bound_bias( reward: np.ndarray, iw: np.ndarray, iw_hat: np.ndarray, q_hat: Optional[np.ndarray] = None, delta: float = 0.05, ) -> float: """Helper to estimate a high probability upper bound of bias in OPE. Parameters ----...
b5639db126029f0f24c641c39b443cd64e3aed99
3,604,594
def error_handler(error): """ Logs errors and renders specific, if available, or generic error page """ # For 4XX and 5XX level HTTP errors, save specific info if isinstance(error, HTTPException): code = error.code description = error.get_description(request.environ) name = ...
16ba9672058555602e8b1eba4d5c08f31a704066
3,604,595
def compute_lr( cv_in_2d_front: np.ndarray, lr_2d_previous: np.ndarray, disp: int, p1_in_1d: np.ndarray, p2_in_1d: np.ndarray, current_segm_1d: np.ndarray, previous_segm_1d: np.ndarray, ): """ Compute Lr of current plane, at a given disparity :param cv_in_2d_front: cost volume ...
a78f5c14a8a77dead230aa7f75b53c4b06789e98
3,604,596
import typing def ssub(s1: SliceRangeT, *rest: typing.Iterable[SliceRangeT]) -> SliceRangeSeqT: """Subtracts n >= 1 ranges""" res = (s1,) for i, el2 in enumerate(rest): res1 = () for el1 in res: res1 += ssub2(el1, el2) res = res1 return res
eb1ea275e7cd58172ad3ee3a60605cda211e6d82
3,604,597
def logout(request, next_page=None, template_name='myregistration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): """ Logs out the user and displays 'You are logged out' message. """ auth_logout(request) if next_page...
4b2b4cf98a3c1fc8ccc658ea7ee33290622dc942
3,604,598
def make_response_409() -> jsonify(): # Conflict """This method is used to return request params related errors. Missing params or misspelling error handled""" response_msg: dict = { "Server Message": "The request could not be completed due to a conflict with the current state of the resource." } ...
d548cccfb1aef3c0f4e1de45b98f05e7f8b4eb8c
3,604,599
import logging from datetime import datetime def check_date(schedule, msg): """ Check with a regex the data as user input, can accept several formats """ match = REGEX_DATE.match(msg.content) if not match: schedule.custom_response = "Votre format de date est invalide." logging.info...
f7d9a31f063525d2a0c66c87fdcfccc53d21f28a
3,604,600
def choose_word(file_path, index): """ :param file_path: :param index: :return: tuple (num of words without duplicates, the word of the given index in the file """ file_input = open(file_path, "r") count_of_words = len(set(file_input.read().split(" "))) file_input.seek(0) lines = fil...
9c038574509918a4e91c316cde749dda322ef0e1
3,604,601
def getCommentsByThread(dbSession, tid): """gets all comments associated with a thread, ordered by time""" comments = dbSession.query(Comment).filter(Comment.thread_id == tid).order_by(Comment.time_created.desc()) if comments: return comments.all() return None
6a9c7e4f708cb68da0922c29154b0869cedff257
3,604,602
import json def get_l2_t_from_file(diffusion_file): """ :param diffusion_file: json file with diffusion results :return: The function takes from the file the experimental values of D and lifetime, It returns a list with values of time from 0 to lifetime. With D computes the respective values of l². ...
c284e39af1e15bd6adf236a52455da45aae22382
3,604,603
def generate_false_pertinents_replace(text, present, m, neighbors, n_best_co_occurrence, proba_change=0.5, forbidden=[], forbidden_tags=['PRP$'], forbidden_words=['be'], top_n=50, temperature=.4, pos=['NOUN', 'VERB', 'ADJ', 'ADV', 'ADP', 'DET'], use_proba=T...
3104877924b4dbbd8108b9ed64cc3feae398858c
3,604,604
def eigenfaces(X: ndarray, n_comp): """ Performs PCA to project faces in a reduced space. Parameters ---------- X: ndarray faces to project (shape: (n_samples, w*h)) n_comp: int number of principal components Returns ------- tuple proj_faces: the projected f...
0d5f76c1848c91128a5ae7d2d8357c756e313062
3,604,607
def assignment(G, weight="weight", resolution=1): """ Assign community partition to the graph by Louvain method""" if G.number_of_edges(): part = community.best_partition( G, weight=weight, resolution=resolution) modu = community.modularity(part, G) else: part = {n: n for...
f9b24cbf2ea1b1c1c512781a44a2204b0354d6f8
3,604,608
import select async def create_code(session: AsyncSession, longUrl: str): """Encodes a URL to a shortened URL. """ code = await generate_code() generate_count = 0 while generate_count < 10 and (await session.execute(select(models.LongToCode).where(models.LongToCode.code == code))).first(): ...
4476ab4e75767cb4c65ecd0cc953c49f99c39cf8
3,604,609
def load_train_data(): """ Loading the train data from data set :return: Training components """ # Data preparation for train and test raw_data_set = data_controller.load_data_file(FLAGS.positive_train_data_path, FLAGS.negative_train_data_path, ...
6696209e7ffdae8951c14462cd2345460506857e
3,604,610
def collect_trainable_variables(modules): """Collects all trainable variables of modules. Trainable variables included in multiple modules occur only once in the returned list. Args: modules: A (list of) instance of the subclasses of :class:`~texar.modules.ModuleBase`. Returns...
e478563a59cfd940138f2344747037280c1c7447
3,604,611
def _get_split_cnn_model(img_dim, n_channels, num_partitions, blocks_per_partition): """Creates a test model that is split into `num_partitions` smaller models.""" models = [tf.keras.Sequential() for _ in range(num_partitions)] models[0].add(layers.Input(shape=(img_dim, img_dim, n_channel...
f626bc31bd0392aa888ce99067611a5642207d14
3,604,612
def ccall_except_check(x): """ >>> ccall_except_check(41) 42 >>> ccall_except_check(-2) -1 >>> ccall_except_check(0) Traceback (most recent call last): ValueError """ if x == 0: raise ValueError return x+1
f4a877f63a189b39fea477af218438de2e6c2a78
3,604,613
from pathlib import Path import tokenize def convert_to_tracer(file, placeholder): """ Eats a filename of a text file. Normalizes and tokenizes the text. Converts it to tsv in the TRACER input format. Writes the tsv file. Depends on normalize(), save_abbreviations() and tokenize(...
90a4dc0acd9a051a77935a0907da07b4a6178f01
3,604,614
def loadSVMLightData(filename): """ Load a file containing train/test data following the svmlight input format. :param filename: The input data file :return: The tuple (ITEMS, COMMENTS), where ITEMS is a list of tuples (TARGET, [(FEATURE,VALUE)], INFO) and COMMENTS is a list of comment line...
21ead993836806e27bee6846f23643051b2c3230
3,604,615
import scipy def get_rotation_matrix(a,b,c,Order): """ [R, Q] = GetRotationMatrix(a,b,c,Order) Computes a rotation matrix R between the coefficients of Spherical Harmonic sound field descriptions before and after rotation. Note that R is block diagonal, since rotations only involve coefficien...
8b360a0fd19e90e6babe247665950b3731a01865
3,604,618
def packet_write(dxl_id, reg0, *register_values): """Create an instruction packet to write data in the DXL control table. Args: dxl_id: An integer representing the DXL ID number reg0: An integer representing the register index in the control table *register_values: A list containing inte...
991fe6a983858bb2febc9b8f1d8008e50f2560f2
3,604,620
def WbDiscover( network, forTime = 5 ): """ This function looks for webbricks on the provided network. The network parameter is in the form nn.nn.nn.nn/bits and identifies a subnet accessible to the current computer. The result is a list of dictionaries where there is a dictionary entry for each ...
64df27860a70e36c52f262ade1256c9723324804
3,604,621
def num_fragmentations(df, obj_frequencies): """Total number of switches from tracked to not tracked.""" fra = 0 for o in obj_frequencies.index: # Find first and last time object was not missed (track span). Then count # the number switches from NOT MISS to MISS state. dfo = df[df.OI...
5d7bcebfeb486499eb8c102789db6cf9141f9247
3,604,622
def canon_did(uri: str) -> str: """ Convert a URI into a DID if need be, left-stripping 'did:mydata:' if present. Args: uri: input URI or DID Raises: ValueError: for invalid input. """ if ok_did(uri): return uri if uri.startswith("did:mydata:"): mydata_di...
62a5363759c88efeba5283bcce13710e1b2b23a8
3,604,623
def sort_tss_tts_files(tss, tts, genome_size): """ Sort the tss and tts files and combine them into a TS file # IDEA: create a function where you sort only and another one to merge and clean the TS file. """ # combine the two file to keep the lines consistents/together ts = pd.me...
d76c19e3fdb449f5892c8ba502ea8c054ac83181
3,604,624
def input_prompt(prompt): """ Get user input :param prompt: the prompt to display to the user """ return input(prompt)
b780278c37f048d1ea61f36af0947b683c5f9b9c
3,604,625
def retail_score(flu_space, access_variables): """ Scores/weights for retail development. """ # access columns prox_pers = 'persons_to_within15_OpAuto' prox_jobs = 'sb_jobs_to_within15_OpAuto' prox_retail_jobs = 'sb_jobs_in_retl_to_within15_OpAuto' prox_retail_space = 'job_spaces_in_ret...
95e47991d5cbeaaf4db0e2b99e95a146813a17e1
3,604,626
from peachpy.x86_64.registers import Register, MaskedRegister from peachpy.x86_64.pseudo import Label from peachpy.x86_64.function import LocalVariable from peachpy.literal import Constant from peachpy import Argument from peachpy.util import is_int, is_int64 from copy import copy, deepcopy from copy import copy, deepc...
7c727f0965caad6c37df68d90e2e0d618374be5f
3,604,627
def virtualaddress(target, **kwds): """Returns a pointer to /target/ where value is a va""" kwds.setdefault('__name__', 'virtualaddress') if 'type' in kwds: return dyn.opointer(target, CalculateRelativeAddress, kwds.pop('type'), **kwds) return dyn.opointer(target, CalculateRelativeAddress, **kwd...
d1c6082e897bf8737aae58cf473e4ae73da93e88
3,604,628
def safeintorbignumber(value): """safely converts value to integer or 10M""" try: return int(value) except ValueError: return 10000000
de665dc11ba27c6846412b706cf833e46dc26758
3,604,629
import numpy import math def sigmamix(pfile, j, a, b, r1 , r2 = None): """returns sigma corresponding to r1 and r2 radius for mixed window. w1(a) corresponds to r1, w2(b) corresponds r2""" k, p = numpy.loadtxt(pfile, unpack = True) if r2 is None: r2 = r1 if a == "T": w1 ...
103fb8d0102b57f0eebde953fc6db8cc7996d4ed
3,604,630
import requests import re import json def get_figshare_article(article_id): """ Given a figshare article id, return a JSON object containing the article metadata :param article_id: :return: JSON object containing Figshare metadata """ version = re.compile('v[0-9]*') article_result = reques...
375bbb36226f002e8a7c85b8e2b1a28f13f52443
3,604,631
def isNumber(s): """ Tests whether an input is a number Parameters ---------- s : string or a number Any string or number which needs to be type-checked as a number Returns ------- isNum : Bool Returns True if 's' can be converted to a float Returns False if con...
bd1bae27814ddca22c39d6411df3581e8116c324
3,604,632
from typing import Callable from typing import Optional def get_authenticated_user_data( handler: AuthenticationHandler, username: str, password: str, password_checker: Callable[[str, str], bool] ) -> Optional[UserAuthData]: """Get user data if the authentication credentials match.""" user_dat...
279150caea1484b6f84fe71c08ea1e4b0405bdf8
3,604,634
from typing import List def get_ss_for_one_toad(name: str, variable: List[str]): """Get small series plot for one specific toad. :param name: The name of the desired toad. :param variable: Variable of interest. :return: Two plots, the kinematic and force plate small series. """ # Get the proc...
f5f1c7b4a39198e7997d5ce5393a8be02de2735b
3,604,635
def generate_road_map(sample_x, sample_y, rr, obstacle_kd_tree, height=0): """ Road map generation of the free workspace. Returned graph is wholly connected. Inputs: sample_x: [m] x positions of sampled points sample_y: [m] y positions of sampled points rr: Robot Radius[m] ob...
61043a2bea05c08d3db72d49c795143e0862a7ae
3,604,636
import cv2 def _process_contours(image, contours, hierarchy, callback, index=0, size_filter=True): """Traverse a hierachy of contours (contours containing contours) and returns bounding boxes of the smallest possible objects that still remain of interest. Parameters --------...
c4b1b88bfa97caf12fef7229d967a2b0da0eef02
3,604,637
def svn_fs_set_access(fs, access_ctx): """svn_fs_set_access(svn_fs_t * fs, svn_fs_access_t * access_ctx) -> svn_error_t""" return _fs.svn_fs_set_access(fs, access_ctx)
8eef1e5a46fbbdcc5ccbbf3140d6b64a86d8a8f1
3,604,638
def rescore_problem(entry_id, xmodule_instance_args): """Rescores a problem in a course, for all students or one specific student. `entry_id` is the id value of the InstructorTask entry that corresponds to this task. The entry contains the `course_id` that identifies the course, as well as the `task_in...
f9c1005793d38a341e87e6d129e28c300b0be498
3,604,639
def KeplerH(z, m, grav_const=1): """ with shapes (bs,2nd)""" bs, D = z.shape # of ODE dims, 2*num_particles*space_dim q = z[:, : D // 2].reshape(*m.shape, -1) p = z[:, D // 2 :].reshape(*m.shape, -1) potential_energy = KeplerV(q, m, grav_const=grav_const) kinetic_energy = EuclideanK(p, m) a...
160e4bcc6be3659265a02af15ac7e2553a771c45
3,604,640
def dGElnorm(w: Wilson, El): """Normalized distribution 1D El""" return tauBp / Btaul * dGEl(w, El)
df23eeb16f09544e09a9bebdc579afe95d88168d
3,604,641
import re def convert_to_utc(timestamp, timezone, printtz=None): """ Convert to UTC from timezone :param1 timestamp: timestamp in ISO format or YYYY-MM-DD HH24:MI:SS :param2: timezone: src timezone, :param3: printtz: return string with timezone information return: converted timestamp """ ...
4df0661ab8d5b2460a9b55a6aa664fa8592a37a8
3,604,642
def generate_log_filename(): """ Return a timestamped log filename """ return "LOG_"+strftime("(%Y-%m-%d)_%H-%M-%S", gmtime())+".txt"
507b8a1ca128fc19566f41d32437bdbeacb30b93
3,604,643