content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def integrated_circular_gaussian(X=None, Y=None, sigma=0.8): """Create a circular Gaussian that is integrated over pixels This is typically used for the model PSF, working well with the default parameters. Parameters ---------- X, Y: `numpy.ndarray` The x,y-coordinates to evaluate the ...
63201f6c37fba1e3750881cd692057c2bd5011b0
26,686
def nPairsToFracPairs(hd_obj, all_pairs_vs_rp, redshift_limit = 2): """ Function to convert the number of pairs into a fractional number density per shell @redshift_limit :: the initial redshift limit set on the sample (needed for opening dir) """ num_pairs = all_pairs_vs_rp[1:] - all_pairs_vs_rp[:-...
d9d8f72d8f05cff4e984b43f4a22da406dfe1c05
26,687
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
36e0b4b13cb357d74cee20623e5a71cf9a5dd02a
26,689
def attention_guide(dec_lens, enc_lens, N, T, g, dtype=None): """Build that W matrix. shape(B, T_dec, T_enc) W[i, n, t] = 1 - exp(-(n/dec_lens[i] - t/enc_lens[i])**2 / (2g**2)) See also: Tachibana, Hideyuki, Katsuya Uenoyama, and Shunsuke Aihara. 2017. “Efficiently Trainable Text-to-Speech System Base...
2af05dedb5260e52150d96b181fab063cd17efb8
26,690
def two_step_colormap(left_max, left, center='transparent', right=None, right_max=None, name='two-step'): """Colormap using lightness to extend range Parameters ---------- left_max : matplotlib color Left end of the colormap. left : matplotlib color Left middle of the colormap. ...
226dfd9a9beaadf5a47167c6080cdb3ba8fa522f
26,692
def _broadcast_arg(U, arg, argtype, name): """Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg...
3a441b9156f7cf614b2ab2967159349252802bed
26,693
import signal def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): """ Mimic a hand-drawn line from (x, y) data Definition ---------- def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): Input ----- x, y ...
ea36487d6e2f4f9d5d0bc9d5cea23459a5b8a5a4
26,695
def generate_mutation() -> str: """ Retrieve staged instances and generate the mutation query """ staged = Node._get_staged() # localns = {x.__name__: x for x in Node._nodes} # localns.update({"List": List, "Union": Union, "Tuple": Tuple}) # annotations = get_type_hints(Node, globalns=global...
789e6042226ed25451d7055bc9b383b81fd10ddf
26,696
from datetime import datetime def start(fund: Fund, start_date: datetime) -> Fund: """ Starts the fund by setting the added USD and the market value of the manager as the current market value. Meaning that at the beginning there is only the manager's positions. :param fund: The fund to start :...
e7f4a273b4c48eb3f9e440f663fee45847df902a
26,697
def _make_experiment(exp_id=1, path="./Results/Tmp/test_FiftyChain"): """ Each file specifying an experimental setup should contain a make_experiment function which returns an instance of the Experiment class with everything set up. @param id: number used to seed the random number generators @p...
6cf51f8957e091175445b36aa1d6ee7b22465835
26,698
def find_largest_digit_helper(n, max_n=0): """ :param n: int,待判別整數 :param max_n: int,當下最大整數值 :return: int,回傳n中最大之 unit 整數 """ # 特殊情況:已達最大值9,就不需再比了 if n == 0 or max_n == 9: return max_n else: # 負值轉換為正值 if n < 0: n *= -1 # 用餘數提出尾數 unit_n = n % 10 # 尾數比現在最大值 if unit_n > max_n: max_n = unit_n ...
cd60a0cdb7cdfba6e2374a564bb39f1c95fe8931
26,699
def build_stats(loss, eval_result, time_callback): """Normalizes and returns dictionary of stats. Args: loss: The final loss at training time. eval_result: Output of the eval step. Assumes first value is eval_loss and second value is accuracy_top_1. time_callback: Time track...
cddde6bf9bd2797c94bc392be77f7be19a46271e
26,700
import random def random_resource_code2() -> str: """One random book name chosen at random. This fixture exists so that we can have a separate book chosen in a two language document request.""" book_ids = list(bible_books.BOOK_NAMES.keys()) return random.choice(book_ids)
04ea455fa85eea32c2c7e9d7d3a3dc98759b937b
26,701
def _to_str(value): """Helper function to make sure unicode values are converted to UTF-8. Args: value: String or Unicode text to convert to UTF-8. Returns: UTF-8 encoded string of `value`; otherwise `value` remains unchanged. """ if isinstance(value, unicode): return value.encode('utf-8') ret...
46186757a475c2b5fa877e8fb62c32a27770e6b7
26,702
def get_loss(loss_name): """Get loss from LOSS_REGISTRY based on loss_name.""" if not loss_name in LOSS_REGISTRY: raise Exception(NO_LOSS_ERR.format( loss_name, LOSS_REGISTRY.keys())) loss = LOSS_REGISTRY[loss_name] return loss
d91bde7ce34e2d4fe38a5c86a93ba96d153eb7c1
26,703
def collate_fn(batch): """ Data collater. Assumes each instance is a dict. Applies different collation rules for each field. Args: batches: List of loaded elements via Dataset.__getitem__ """ collated_batch = {} # iterate over keys for key in batch[0]: try: ...
718a6945d71a485fd4dbbbeaac374afbb9256621
26,704
def _rec_eval_in(g, a, v, i, j, K): """Recursive helper for :func:`dmp_eval_in`.""" if i == j: return dmp_eval(g, a, v, K) v, i = v - 1, i + 1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v)
51fbd9a45b4e1722ef98a5ab543575980d56b66b
26,705
def normalize(array): """ Normalize a 4 (or Nx4) element array/list/numpy.array for use as a quaternion :param array: 4 or Nx4 element list/array :returns: normalized array :rtype: numpy array """ quat = np.array(array) return np.squeeze(quat / np.sqrt(np.sum(quat * quat, axis=-1, keep...
020b1fb9b1050192254274ac3d716e655a5ff003
26,706
def dose_class_baseline(dose_num, df_test, df_targets): """Calculate the PR- baseline for each dose treatment""" dose_cpds_index = df_test[df_test['dose'] == dose_num].index df_class_targets = df_targets.loc[dose_cpds_index].reset_index(drop = True) class_baseline_score = calculate_baseline(df_class_targets) ...
0e0178573fc3ccfb08c8f898d264efa84fd10962
26,707
def xrange(mn: int, mx: int = None) -> list: """Built-in range function, but actually gives you a range between mn and mx. Range: range(5) -> [0, 1, 2, 3, 4] XRange: xrange(5) -> [0, 1, 2, 3, 4, 5]""" return list(range(0 if mx is None else mn, mn + 1 if mx is None else mx + 1))
4ab3059a51966cefd43008c4aa4c50cf42cb8fa2
26,708
def sous_tableaux(arr: list, n: int) -> list: """ Description: Découper un tableau en sous-tableaux. Paramètres: arr: {list} -- Tableau à découper n: {int} -- Nombre d'éléments par sous-tableau Retourne: {list} -- Liste de sous-tableaux Exemple: >>> sous_ta...
4f0a627ea00beafb5b6bc77490e71631e8a55e28
26,710
def get_previous_tweets(date_entry): """Return details about previous Tweets. Namely, retrieve details about the date_entry-th Tweets from 7 days ago, 30 days ago, and a random number of days ago. If a given Tweet does not exist, its corresponding entry in the output will be empty. Args: ...
a4b91b87f3cc897e720f745a1c0ad1097292774b
26,711
def changed_cat_keys(dt): """Returns keys for categories, changed after specified time""" return [root_category_key()]
fbc4d0380bb1deaf7f1214d526d1c623cceb4676
26,712
def create_client(CLIENT_ID, CLIENT_SECRET): """Creates Taboola Client object with the given ID and secret.""" client = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET) return client
bea955f5d944e47f11c74ae97c5472dc3c512217
26,713
def set_values_at_of_var_above_X_lat_2_avg(lat_above2set=65, ds=None, use_avg_at_lat=True, res='0.125x0.125', var2set=None, only_consider_water_boxes=True, ...
6040523af84f5046af373de2aa22447e66aef181
26,714
def _plot_xkcd(plot_func, *args, **kwargs): """ Plot with *plot_func*, *args* and **kwargs*, but in xkcd style. """ with plt.xkcd(): fig = plot_func(*args, **kwargs) return fig
a4bc526c115c54f37c5171b82639adf0c0a3f888
26,716
import requests def unfollow_user(): """UnfollowUser""" auth = request.headers user = request.args.get('userId') req = requests.post( '/api/v1/IsAuthenticated', {'id': auth['Authorization']} ) req.json() if req.authenticated: cur = MY_SQL.connection.cursor() ...
8e40b633b960070a4d433610f4f0d4e7f8b89a12
26,717
def isOverlaysEnabled(): """Returns whether or not the current client's quality overlay system is currently enabled. Returns: bool: True (1) if overlays are currently enabled. """ return False
d433b86b38bfa3c3ed28705888ef12710aaf4f96
26,718
def load_image(path, size=None, grayscale=False): """ Load the image from the given file-path and resize it to the given size if not None. """ # Load the image using opencv if not grayscale: # BGR format image = cv2.imread(path) else: # grayscale format image = cv2.imread(...
2d3d4a625a690800c2d5db8f8577e9c06a36001a
26,719
def brent_min(f, bracket, fnvals=None, tolerance=1e-6, max_iterations=50): """\ Given a univariate function f and a tuple bracket=(x1,x2,x3) bracketing a minimum, find a local minimum of f (with fn value) using Brent's method. Optionally pass in the tuple fnvals=(f(x1),f(x2),f(x3)) as a parameter. """ x1, x2, x3 = b...
ef4010e00ca67d1751b7f8eea497afc59e76364c
26,720
def best_validity(source): """ Retrieves best clustering result based on the relative validity metric """ # try: cols = ['min_cluster_size', 'min_samples', 'validity_score', 'n_clusters'] df = pd.DataFrame(source, columns = cols) df['validity_score'] = df['validity_score'].fillna(0) bes...
ba830ccca8c9f62758ecd8655576efb58892cdbc
26,721
import json def normalize_cell_value(value): """Process value for writing into a cell. Args: value: any type of variable Returns: json serialized value if value is list or dict, else value """ if isinstance(value, dict) or isinstance(value, list): return json.dumps(value)...
8ef421814826c452cdb6528c0645133f48bd448a
26,722
import numpy def _ancestry2paths(A): """Convert edge x edge ancestry matrix to tip-to-tip path x edge split metric matrix. The paths will be in the same triangular matrix order as produced by distanceDictAndNamesTo1D, provided that the tips appear in the correct order in A""" tips = [i for i i...
732ef3bbccff4696650c24a983fdbc338f1d8e24
26,723
def geometric_mean(x, axis=-1, check_for_greater_than_zero=True): """ Return the geometric mean of matrix x along axis, ignore NaNs. Raise an exception if any element of x is zero or less. """ if (x <= 0).any() and check_for_greater_than_zero: msg = 'All elements of x (except NaNs...
485780f7766857333a240d059d2bb1c526d3f5a8
26,724
def mongodb(): """ Simple form to get and set a note in MongoDB """ return None
a6de90429bb3ad3e23191e52e1b43484435747f9
26,725
def get_single_blog(url): """Получить блог по указанному url""" blog = Blog.get_or_none(Blog.url == url) if blog is None: return errors.not_found() user = get_user_from_request() has_access = Blog.has_access(blog, user) if not has_access: return errors.no_access() blog_dic...
b4a32278681af7eecbebc29ed06b88c7860a39c0
26,726
def test_section(): """Returns a testing scope context to be used in 'with' statement and captures testing code. Example:: with autograd.train_section(): y = model(x) compute_gradient([y]) with autograd.test_section(): # testing, IO, gradient upda...
6bcbc9aaaaeee5a9b5d8b6a3307f1fb69bf726ae
26,727
from typing import Optional import select async def get_installation_owner(metadata_account_id: int, mdb_conn: morcilla.core.Connection, cache: Optional[aiomcache.Client], ) -> str: """Load the native user ID who in...
925780ce87c14758cf98191cf39effcaf09a8aaa
26,728
def get_cflags(): """Get the cflag for compile python source code""" flags = ['-I' + get_path('include'), '-I' + get_path('platinclude')] flags.extend(getvar('CFLAGS').split()) # Note: Extrat cflags not valid for cgo. for not_go in ('-fwrapv', '-Wall'): if not_go in flags: ...
f1c171d5a70127bda98a3ef7625c60336641ea1f
26,729
import requests def request_post_json(url, headers, data): """Makes a POST request and returns the JSON response""" try: response = requests.post(url, headers=headers, data=data, timeout=10) if response.status_code == 201: return response.json() else: error_mess...
82d7ce423024ca1af8a7c513f3d689fbc77c591a
26,730
import random def get_rand_number(min_value, max_value): """ This function gets a random number from a uniform distribution between the two input values [min_value, max_value] inclusively Args: - min_value (float) - max_value (float) Return: - Random number between this range (float) ...
0eec094d05b291c7c02207427685d36262e643e5
26,731
def read(string): """ Given a single interval from a GFFv2 file, returns an Interval object. Will return meta lines if they start with #, track, or browser. """ if string.startswith(metalines): return interval(_is_meta=True, seqname=string) values = [] cols = string.split(delimiter) fo...
e4651216c9694935bc879c012b1fe74f529cb41d
26,734
from typing import Union from pathlib import Path from typing import Dict def average_results(results_path: Union[Path, str], split_on: str = " = ") -> Dict[str, float]: """ Average accuracy values from a file. Parameters ---------- results_path : Union[Path, str] The file to read results...
28b896d567d6ef18662766a2da64c6bdb262f3d7
26,735
def dict_collection_only(method): """ Handles the behavior when a group is present on a clumper object. """ @wraps(method) def wrapped(clumper, *args, **kwargs): if not clumper.only_has_dictionaries: non_dict = next(d for d in clumper if not isinstance(d, dict)) rais...
a84c3588942378157674e6862d2f1a8c785ba569
26,737
def country_name(country_id): """ Returns a country name >>> country_name(198) u'Spain' """ if country_id == '999': #Added for internal call - ie flag/phone.png return _('internal call').title() try: obj_country = Country.objects.get(id=country_id) return obj...
fdb44061d795e42d9e312bc25f8335a41c91ca11
26,738
def KLdist(P,Q): """ KLDIST Kullbach-Leibler distance. D = KLDIST(P,Q) calculates the Kullbach-Leibler distance (information divergence) of the two input distributions. """ P2 = P[P*Q>0] Q2 = Q[P*Q>0] P2 = P2 / np.sum(P2) Q2 = Q2 / np.sum(Q2) D = np.sum(P2*np.log(P2/Q2)) ...
380796f3688c5ad8483ba50ddc940eb797e4a973
26,744
def homepage(request: HttpRequest) -> HttpResponse: """ Render the home page of the application. """ context = make_context(request) person = get_person(TARGET_NICK) if not person: return render(request, "404.html", status=404) context["person"] = person technology_set = person.technol...
42f749a38543b456b603b5b7b923d5637ab84abe
26,746
def _call_rmat(scale, num_edges, create_using, mg): """ Simplifies calling RMAT by requiring only specific args that are varied by these tests and hard-coding all others. """ return rmat(scale=scale, num_edges=num_edges, a=0.1, b=0.2, c...
cf68a7e436919ad5296438708898eeb233112651
26,747
def value_loss(old_value): """value loss for ppo""" def loss(y_true, y_pred): vpredclipped = old_value + K.clip(y_pred - old_value, -LOSS_CLIPPING, LOSS_CLIPPING) # Unclipped value vf_losses1 = K.square(y_pred - y_true) # Clipped value vf_losses2 = K.square(vpredclipped -...
0888a411be6fa7e41469d15a2798cbebda46db01
26,748
import torch import warnings def split_by_worker(urls): """Selects a subset of urls based on Torch get_worker_info. Used as a shard selection function in Dataset.""" urls = [url for url in urls] assert isinstance(urls, list) worker_info = torch.utils.data.get_worker_info() if worker_info i...
1ddcf436fecc4359367b783f9c1c62fe84782468
26,749
def runge_kutta4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function ...
0f79962a3bd7bbe49bd3ae3eff6d5496182fbea8
26,751
def genBinaryFileRDD(sc, path, numPartitions=None): """ Read files from a directory to a RDD. :param sc: SparkContext. :param path: str, path to files. :param numPartition: int, number or partitions to use for reading files. :return: RDD with a pair of key and value: (filePath: str, fileData: Bina...
85ef3c657b932946424e2c32e58423509f07ceae
26,752
import requests def generate(): """ Generate a classic image quote :rtype: InspiroBotImageResponse :return: The generated response """ try: r = requests.get("{}?generate=true".format(url())) except: raise InsprioBotError("API request failed. Failed to connect") if r.st...
bc9a49909d9191f922a5c781d9fc68c97de92456
26,753
import pickle def inference_lstm(im_path, model_path, tok_path, max_cap_len=39): """ Perform inference using a model trained to predict LSTM. """ tok = pickle.load(open(tok_path, 'rb')) model = load_model( model_path, custom_objects={'RepeatVector4D': RepeatVector4D}) encoder =...
81cec1407b6227d7f65a697900467b16b2fce96e
26,754
def iterative_proof_tree_bfs(rules_dict: RulesDict, root: int) -> Node: """Takes in a iterative pruned rules_dict and returns iterative proof tree.""" root_node = Node(root) queue = deque([root_node]) while queue: v = queue.popleft() rule = sorted(rules_dict[v.label])[0] if n...
c7ce6f1e48f9ac04f68b94e07dbcb82162b2abba
26,755
def get_host_buffer_init(arg_name, num_elem, host_data_type, host_init_val): """Get host code snippet: init host buffer""" src = get_snippet("snippet/clHostBufferInit.txt") src = src.replace("ARG_NAME", arg_name) src = src.replace("NUM_ELEM", str(num_elem)) src = src.replace("HOST_DATA_TYPE", host_d...
7f94d2727a3c6f861f5c6402c5c8d2211d32dd71
26,756
def get_setting(setting, override=None): """Get setting. Get a setting from `muses` conf module, falling back to the default. If override is not None, it will be used instead of the setting. :param setting: String with setting name :param override: Value to use when no setting is available. D...
7e4a05ee3b077023e04693a37d3cbeaaa6025d8d
26,757
def extract_year_month_from_key(key): """ Given an AWS S3 `key` (str) for a file, extract and return the year (int) and month (int) specified in the key after 'ano=' and 'mes='. """ a_pos = key.find('ano=') year = int(key[a_pos + 4:a_pos + 8]) m_pos = key.find('mes=') month...
b52dc08d393900b54fca3a4939d351d5afe0ef3c
26,758
def depolarize(p: float) -> DepolarizingChannel: """Returns a DepolarizingChannel with given probability of error. This channel applies one of four disjoint possibilities: nothing (the identity channel) or one of the three pauli gates. The disjoint probabilities of the three gates are all the same, p /...
247dd040844cdd3cd44336ca097b98fcf2f3cac3
26,759
import re def verilog_to_circuit( netlist, name, infer_module_name=False, blackboxes=None, warnings=False, error_on_warning=False, fast=False, ): """ Creates a new Circuit from a module inside Verilog code. Parameters ---------- netlist: str Verilog code. ...
4dc8e59ff8bea29f32e64219e3c38ed7bfec4aef
26,760
def load_all_channels(event_id=0): """Returns a 3-D dataset corresponding to all the electrodes for a single subject and a single event. The first two columns of X give the spatial dimensions, and the third dimension gives the time.""" info = load_waveform_data(eeg_data_file()) locs = load_channel_l...
17dd6dfc196a3f88f4bf7f0128da1a0b027f9072
26,761
def parentheses_cleanup(xml): """Clean up where parentheses exist between paragraph an emphasis tags""" # We want to treat None's as blank strings def _str(x): return x or "" for em in xml.xpath("//P/*[position()=1 and name()='E']"): par = em.getparent() left, middle, right = _st...
b5a476cd6fd9b6a2ab691fcec63a33e6260d48f2
26,762
import numpy def filter_atoms(coordinates, num_atoms=None, morphology="sphere"): """ Filter the atoms so that the crystal has a specific morphology with a given number of atoms Params: coordinates (array): The atom coordinates num_atoms (int): The number of atoms morphology (str):...
9763f2c7b14a26d089bf58a4c7e82e2d4a0ae2bd
26,763
def weekly(): """The weekly status page.""" db = get_session(current_app) #select id, user_id, created, strftime('%Y%W', created), date(created, 'weekday 1'), content from status order by 4, 2, 3; return render_template( 'status/weekly.html', week=request.args.get('week', None), ...
b5c1e5a8d981fb217492241e8ee140898d47b633
26,765
from typing import List import pathlib from typing import Sequence def parse_source_files( src_files: List[pathlib.Path], platform_overrides: Sequence[str], ) -> List[LockSpecification]: """ Parse a sequence of dependency specifications from source files Parameters ---------- src_files : ...
47a6e66b56ca0d4acd60a6b388c9f58d0cccbb2c
26,766
def delete_registry( service_account_json, project_id, cloud_region, registry_id): """Deletes the specified registry.""" # [START iot_delete_registry] print('Delete registry') client = get_client(service_account_json) registry_name = 'projects/{}/locations/{}/registries/{}'.format( ...
baa8cad0d324f2e564052822f9d17f45a581a397
26,767
def bundle(cls: type) -> Bundle: """ # Bundle Definition Decorator Converts a class-body full of Bundle-storable attributes (Signals, other Bundles) to an `hdl21.Bundle`. Example Usage: ```python import hdl21 as h @h.bundle class Diff: p = h.Signal() n = h.Signal() ...
bf1b68791dbdc5b6350d561db4d784ff92c0bbae
26,768
import time import calendar def previousMidnight(when): """Given a time_t 'when', return the greatest time_t <= when that falls on midnight, GMT.""" yyyy, MM, dd = time.gmtime(when)[0:3] return calendar.timegm((yyyy, MM, dd, 0, 0, 0, 0, 0, 0))
0821eb46115a1e5b1489c4f4dbff78fab1d811b5
26,769
def compute_net_results(net, archname, test_data, df): """ For a given network, test on appropriate test data and return dataframes with results and predictions (named obviously) """ pretrain_results = [] pretrain_predictions = [] tune_results = [] tune_predictions = [] for idx in r...
b971f269bbee7e48f75327e3b01d73c77ec1f06c
26,770
def _distance_along_line(start, end, distance, dist_func, tol): """Point at a distance from start on the segment from start to end. It doesn't matter which coordinate system start is given in, as long as dist_func takes points in that coordinate system. Parameters ---------- start : tuple ...
2f168b068cc434fe9280e2cdf84ae3f0f93eb844
26,771
def exploits_listing(request,option=None): """ Generate the Exploit listing page. :param request: Django request. :type request: :class:`django.http.HttpRequest` :param option: Action to take. :type option: str of either 'jtlist', 'jtdelete', 'csv', or 'inline'. :returns: :class:`django.htt...
941ab4e3da6273f17f4a180aebe62d35f7133080
26,773
from typing import Sequence from typing import Tuple def find_command(tokens: Sequence[str]) -> Tuple[Command, Sequence[str]]: """Looks up a command based on tokens and returns the command if it was found or None if it wasn't..""" if len(tokens) >= 3 and tokens[1] == '=': var_name = tokens[0] ...
4b46b03f6dd0fb4a6cbcda855029d0a42958a49f
26,774
def clean(df: pd.DataFrame, completelyInsideOtherBias: float = 0.7, filterCutoff: float = 0.65, algo: str = "jaccard", readFromFile: bool = True, writeToFile: bool = True, doBias: bool = True) -> pd.DataFrame: """Main function to completely clean a restaurant dataset. Args: df: a pa...
6c7873958c61bab357abe1d099c57e681c265067
26,775
def create_list(value, sublist_nb, sublist_size): """ Create a list of len sublist_size, filled with sublist_nb sublists. Each sublist is filled with the value value """ out = [] tmp = [] for i in range(sublist_nb): for j in range(sublist_size): tmp.append(value) out....
1ecf6c88390167584d1835430c359a7ed6d6b40b
26,776
from datetime import datetime import re def parse_time(date_str: str) -> datetime: """ Parses out a string-formatted date into a well-structured datetime in UTC. Supports any of the following formats: - hh:mm In this format, we treat the value of the hh section to be 24hr format. I...
6009342d1e9c1c3f9b255758adf685e4fe7ca2f0
26,778
def gen_r_cr(): """ Generate the R-Cr table. """ r_cr = [0] * 256 for i in range(256): r_cr[i] = int(1.40199 * (i - 128)) return r_cr
43e014bb62c40d038c5fbd124e834e98e9edb5e3
26,779
def fallible_to_exec_result_or_raise( fallible_result: FallibleProcessResult, description: ProductDescription ) -> ProcessResult: """Converts a FallibleProcessResult to a ProcessResult or raises an error.""" if fallible_result.exit_code == 0: return ProcessResult( stdout=fallible_result...
6b46a78897f0fcbd10e4a0c9b733f1834f638af0
26,780
def tf_pose_to_coords(tf_pose): """Convert TransformStamped to Coordinates Parameters ---------- tf_pose : geometry_msgs.msg.Transform or geometry_msgs.msg.TransformStamped transform pose. Returns ------- ret : skrobot.coordinates.Coordinates converted coordinates. """ ...
3bfaf7d566e90c9ac0c0d8a34060497e2c0c0f78
26,781
def make_graph_indep_graphnet_functions(units, node_or_core_input_size, node_or_core_output_size = None, edge_input_size = None, edge_output_size = None, global_input_size = None, global_output_size = None, aggregation_function = 'mean', **kwargs): "...
63694e7765896d0b369b65d4362edca29b6592d0
26,782
import typing def is_generic(t): """ Checks if t is a subclass of typing.Generic. The implementation is done per Python version, as the typing module has changed over time. Args: t (type): Returns: bool """ # Python 3.6, 3.5 if hasattr(typing, "GenericMeta"): ...
b085d7799ffe034b4bdeccea250d36f4ff372aea
26,783
def getGpsTime(dt): """_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime """ total = 0 days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc. total += days*3600*24 total += dt.hour * 3600 total += dt.minute * 60 total += dt.second return(tot...
16caa558741d8d65b4b058cf48a591ca09f82234
26,784
from re import T def make_support_transforms(): """ Transforms for support images during inference stage. For transforms of support images during training, please visit dataset.py and dataset_fewshot.py """ normalize = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [...
38d17b780fc8faf6a77074c53ef36733feb1f756
26,785
def single_label_normal_score(y_pred, y_gold): """ this function will computer the score by simple compare exact or not Example 1: y_pred=[1,2,3] y_gold=[2,2,3] score is 2/3 Example 2: it can also compute the score same way but for each label y_pred=[1,2,3,2,3] y_gold=[2,2,3,1,3...
3f906aca6cc5280b932c2dc0a73bfcedad63bd65
26,786
def get_tuning_curves( spike_times: np.ndarray, variable_values: np.ndarray, bins: np.ndarray, n_frames_sample=10000, n_repeats: int = 10, sample_frac: float = 0.4, ) -> dict: """ Get tuning curves of firing rate wrt variables. Spike times and variable values are both in mill...
ecdc4a71cc5a65dbb51dd69ef7a710c8ff596fec
26,787
def get_custom_feeds_ip_list(client: PrismaCloudComputeClient) -> CommandResults: """ Get all the BlackListed IP addresses in the system. Implement the command 'prisma-cloud-compute-custom-feeds-ip-list' Args: client (PrismaCloudComputeClient): prisma-cloud-compute client. Returns: ...
bcaf44dcefe0fda10943b29cae5e9ba72e561e27
26,789
import logging def setup_new_file_handler(logger_name, log_level, log_filename, formatter, filter=None): """ Sets up new file handler for given logger :param logger_name: name of logger to which filelogger is added :param log_level: logging level :param log_filename: path to log file :param fo...
1ffd48250d17232eea94f13dd52628993ea04c2e
26,791
import hashlib def _gen_version(fields): """Looks at BotGroupConfig fields and derives a digest that summarizes them. This digest is going to be sent to the bot in /handshake, and bot would include it in its state (and thus send it with each /poll). If server detects that the bot is using older version of th...
0052c655ca355182d0e962e37ae046f63d1a5066
26,792
import logging def get_callee_account(global_state, callee_address, dynamic_loader): """ Gets the callees account from the global_state :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Account belonging to ...
28a95b2155b1f72a2683ac7c7029d1d5739305f3
26,794
from typing import Iterable def get_products_with_summaries() -> Iterable[ProductWithSummary]: """ The list of products that we have generated reports for. """ index_products = {p.name: p for p in STORE.all_dataset_types()} products = [ (index_products[product_name], get_product_summary(pr...
0d9e23fecfebd66ba251bc62b750e2d43b20c7fa
26,795
def _round_to_4(v): """Rounds up for aligning to the 4-byte word boundary.""" return (v + 3) & ~3
c79736b4fe9e6e447b59d9ab033181317e0b80de
26,797
def bool_like(value, name, optional=False, strict=False): """ Convert to bool or raise if not bool_like Parameters ---------- value : object Value to verify name : str Variable name for exceptions optional : bool Flag indicating whether None is allowed strict : b...
42d16ae228140a0be719fbd238bdc25dafc1cb64
26,799
def process_2d_sawtooth(data, period, samplerate, resolution, width, verbose=0, start_zero=True, fig=None): """ Extract a 2D image from a double sawtooth signal Args: data (numpy array): measured trace period (float): period of the full signal samplerate (float): sample rate of the acqu...
f7b212d54637e04294cda336e154910eb718b3e5
26,800
def lower_threshold_projection(projection, thresh=1e3): """ An ugly but effective work around to get a higher-resolution curvature of the great-circle paths. This is useful when plotting the great-circle paths in a relatively small region. Parameters ---------- projection : class ...
165c657f1ec875f23df21ef412135e27e9e443c6
26,801
def post_benchmark(name, kwargs=None): """ Postprocess benchmark """ if kwargs is None: kwargs = {} post = benchmarks[name].post return post(**kwargs)
900f60435ae31e8ec09312f23ab9f98a723d22af
26,802
def tag_view_pagination_counts(request,hc,urls,tag_with_items): """ retrieve the pagination counts for a tag """ hc.browser.get(urls['https_authority']) try: po = hc.catalog.load_pageobject('TagsPage') po.goto_page() po.search_for_content([tag_with_items]) po = hc....
7130ffdbb2b8f90fadf1a159d15726012511ddee
26,803
def arts_docserver_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Create a link to ARTS docserver. Parameters: name (str): The role name used in the document. rawtext (str): The entire markup snippet, with role. text (str): The text ma...
8f20cc4adb9f7fa17514116fe984562d9f0174f3
26,804
def arima_model(splits, arima_order, graph=False): """ Evaluate an ARIMA model for a given order (p,d,q) and also forecast the next one time step. Split data in train and test. Train the model using t = (1, ..., t) and predict next time step (t+1). Then add (t+1) value from test dataset to history and f...
07ca1349e5ebe02793fbf798cbd4e5ce20128a74
26,805
import ctypes def srfscc(srfstr, bodyid): """ Translate a surface string, together with a body ID code, to the corresponding surface ID code. The input surface string may contain a name or an integer ID code. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfscc_c.html :...
9f32b6929c2fd5d482db5f79f4b00f1fe41b114b
26,806
import json import requests def pr_comment( message: str, repo: str = None, issue: int = None, token=None, server=None, gitlab=False, ): """push comment message to Git system PR/issue :param message: test message :param repo: repo name (org/repo) :param issue: pull-req...
7115ec59fca36459a15e07906ce5c58b305bcfdc
26,807
from typing import Sequence def windowed_run_count_1d(arr: Sequence[bool], window: int) -> int: """Return the number of consecutive true values in array for runs at least as long as given duration. Parameters ---------- arr : Sequence[bool] Input array (bool). window : int Minimum dur...
ff7b18380cd77ad046fc5d5aa678e7393c72d495
26,810