content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import pickle import os def getAllTraj () : """ get all trajectories from C.TRAJ_DIR """ def loadPickle (f) : with open(osp.join(C.TRAJ_DIR, f), 'rb') as fd : return pickle.load(fd) return list(map(loadPickle, os.listdir(C.TRAJ_DIR)))
b7d5bfda197445723d024800ec276d7e2050a987
3,652,700
def _get_count(_khoros_object, _user_id, _object_type): """This function returns the count of a specific user object (e.g. ``albums``, ``followers``, etc.) for a user. :param _khoros_object: The core :py:class:`khoros.Khoros` object :type _khoros_object: class[khoros.Khoros] :param _user_id: The User I...
5e0cb02a74a819984ab271fcaad469a60f4bdf43
3,652,701
def antiSymmetrizeSignal(y, symmetryStep): """ Dischard symmetric part of a signal by taking the difference of the signal at x[n] and x[n + symmetry_step] get your corresponding x data as x[0:len(y)/2] Parameters ---------- y : array_like numpy array or list of...
0936d5fc3883d3ce6ee2f6c77fb9b4bc59177426
3,652,702
def lms_to_rgb(img): """ rgb_matrix = np.array( [[0.0809444479, -0.130504409, 0.116721066], [0.113614708, -0.0102485335, 0.0540193266], [-0.000365296938, -0.00412161469, 0.693511405] ] ) """ rgb_matrix = np.array( [[ 2.85831110e+00, -1.62870796e+00, -2.481...
76ce7a5f73712a6d9f241d66b3af8a54752b141d
3,652,703
import time def timeit(func): """ Decorator that returns the total runtime of a function @param func: function to be timed @return: (func, time_taken). Time is in seconds """ def wrapper(*args, **kwargs) -> float: start = time.time() func(*args, **kwargs) total_time = ...
68723a74c96c2d004eed9533f9023d77833c509b
3,652,704
def merge_count(data1, data2): """Auxiliary method to merge the lengths.""" return data1 + data2
8c0280b043b7d21a411ac14d3571acc50327fdbc
3,652,705
def orthogonal_procrustes(fixed, moving): """ Implements point based registration via the Orthogonal Procrustes method. Based on Arun's method: Least-Squares Fitting of two, 3-D Point Sets, Arun, 1987, `10.1109/TPAMI.1987.4767965 <http://dx.doi.org/10.1109/TPAMI.1987.4767965>`_. Also see ...
5818c67e478ad9dd59ae5a1ba0c847d60234f222
3,652,706
def make_model(arch_params, patch_size): """ Returns the model. Used to select the model. """ return RDN(arch_params, patch_size)
6cf91ea68bcf58d4aa143a606bd774761f37acb0
3,652,707
def calc_error(frame, gap, method_name): """Calculate the error between the ground truth and the GAP prediction""" frame.single_point(method_name=method_name, n_cores=1) pred = frame.copy() pred.run_gap(gap=gap, n_cores=1) error = np.abs(pred.energy - frame.energy) logger.info(f'|E_GAP - E_0|...
9a3eb0b115c394703cb7446852982fa1468607ad
3,652,708
def find_model(sender, model_name): """ Register new model to ORM """ MC = get_mc() model = MC.get((MC.c.model_name==model_name) & (MC.c.uuid!='')) if model: model_inst = model.get_instance() orm.set_model(model_name, model_inst.table_name, appname=__name__, model_path='') ...
4c78f135b502119fffb6b2ccf5f09335e739a97a
3,652,709
def list_subtitles(videos, languages, pool_class=ProviderPool, **kwargs): """List subtitles. The `videos` must pass the `languages` check of :func:`check_video`. All other parameters are passed onwards to the provided `pool_class` constructor. :param videos: videos to list subtitles for. :type vi...
f5d9fa450f0df5c71c320d972e54c2502bbfd37d
3,652,710
def public_incursion_no_expires(url, request): """ Mock endpoint for incursion. Public endpoint without cache """ return httmock.response( status_code=200, content=[ { "type": "Incursion", "state": "mobilizing", "staging_solar_s...
31d008b6479d8e2a5e4bc9f2d7b4af8cc4a40b03
3,652,711
def bad_topics(): """ Manage Inappropriate topics """ req = request.vars view_info = {} view_info['errors'] = [] tot_del = 0 if req.form_submitted: for item in req: if item[:9] == 'inapp_id_': inapp_id = int(req[item]) db(db.zf_topic_inappropri...
64c40b98a77c5934bd0593c9f5c4f31370980e8a
3,652,712
def get_min_id_for_repo_mirror_config(): """ Gets the minimum id for a repository mirroring. """ return RepoMirrorConfig.select(fn.Min(RepoMirrorConfig.id)).scalar()
21a99988a1805f61ede9d689494b59b61c0391d8
3,652,713
def check_series( Z, enforce_univariate=False, allow_empty=False, allow_numpy=True, enforce_index_type=None, ): """Validate input data. Parameters ---------- Z : pd.Series, pd.DataFrame Univariate or multivariate time series enforce_univariate : bool, optional (default=F...
5831c75953b8953ec54982712c1e4d3cccb22cc8
3,652,714
def B(s): """string to byte-string in Python 2 (including old versions that don't support b"") and Python 3""" if type(s)==type(u""): return s.encode('utf-8') # Python 3 return s
b741bf4a64bd866283ca789745f373db360f4016
3,652,715
def gather_tiling_strategy(data, axis): """Custom tiling strategy for gather op""" strategy = list() base = 0 for priority_value, pos in enumerate(range(len(data.shape) - 1, axis, -1)): priority_value = priority_value + base strategy.append(ct_util.create_constraint_on_tensor(tensor=data...
afceb113c9b6c25f40f4f885ccaf08860427291f
3,652,716
from typing import Optional import requests import time def fetch( uri: str, auth: Optional[str] = None, endpoint: Optional[str] = None, **data ) -> OAuthResponse: """Perform post given URI with auth and provided data.""" req = requests.Request("POST", uri, data=data, auth=auth) prepared = req.prepare...
c9fc1cf96fa0f0037b50ec30a68d17ea05d892d9
3,652,717
def redscreen(main_filename, back_filename): """ Implements the notion of "redscreening". That is, the image in the main_filename has its "sufficiently" red pixels replaced with pized from the corresponding x,y location in the image in the file back_filename. Returns the resulting "redscreened"...
96824872ceb488497fbd56a662b8fb5098bf2341
3,652,718
def density_speed_conversion(N, frac_per_car=0.025, min_val=0.2): """ Fraction to multiply speed by if there are N nearby vehicles """ z = 1.0 - (frac_per_car * N) # z = 1.0 - 0.04 * N return max(z, min_val)
95285a11be84df5ec1b6c16c5f24b3831b1c0348
3,652,719
import logging def connect_to_amqp(sysconfig): """ Connect to an AMQP Server, and return the connection and Exchange. :param sysconfig: The slickqaweb.model.systemConfiguration.amqpSystemConfiguration.AMQPSystemConfiguration instance to use as the source of information of how to conn...
82a14bfd757caa1666c172d4aba64a2053ad5810
3,652,720
def int_to_datetime(int_date, ds=None): """Convert integer date indices to datetimes.""" if ds is None: return TIME_ZERO + int_date * np.timedelta64(1, 'D') if not hasattr(ds, 'original_time'): raise ValueError('Dataset with no original_time cannot be used to ' 'convert ints to dateti...
2e081ff019628800fb5c44eec4fa73333d755dde
3,652,721
def show_plugin(name, path, user): """ Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpre...
fded4735eda73dc19dd51dc13a1141345505b3b9
3,652,722
def get_receiver_type(rinex_fname): """ Return the receiver type (header line REC # / TYPE / VERS) found in *rinex_fname*. """ with open(rinex_fname) as fid: for line in fid: if line.rstrip().endswith('END OF HEADER'): break elif line.rstrip().endswith...
7391f7a100455b8ff5ab01790f62518a3c4a079b
3,652,723
def is_cyclone_phrase(phrase): """Returns whether all the space-delimited words in phrases are cyclone words A phrase is a cyclone phrase if and only if all of its component words are cyclone words, so we first split the phrase into words using .split(), and then check if all of the words are cyclone w...
8014490ea2391b1acec1ba641ba89277065f2dd9
3,652,724
def wl_to_wavenumber(wl, angular=False): """Given wavelength in meters, convert to wavenumber in 1/cm. The wave number represents the number of wavelengths in one cm. If angular is true, will calculate angular wavenumber. """ if angular: wnum = (2*np.pi)/(wl*100) else: wnu...
ca34e3abc5f9ed0d555c836819c9f3c8d3ab9e4b
3,652,725
def easeOutCubic(n): """A cubic tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """ _checkRange(...
20aea25b2ee937618df2b674178f2a767c373da7
3,652,726
import torch import sys import copy def _evaluate_batch_beam(model, params, dico, batch, lengths, positions, langs, src_lens, trg_lens, \ gen_type, alpha, beta, gamma, dec_len, iter_mult, selected_pos, beam_size, length_penalty): """Run on one example""" n_iter = dec_len * iter_mult #...
0ea481615566e98f9d4d2769b8b2fe99a2392beb
3,652,727
import re def _fix_entries(entries): """recursive function to collapse entries into correct format""" cur_chapter_re, chapter_entry = None, None new_entries = [] for entry in entries: title, doxy_path, subentries = entry if subentries is not None: new_subentries = _fix_entr...
1f8ac466533c17c1ad4e7cf2d27f2e7ff098ae79
3,652,728
def _check_bulk_delete(attempted_pairs, result): """ Checks if the RCv3 bulk delete command was successful. """ response, body = result if response.code == 204: # All done! return body errors = [] non_members = pset() for error in body["errors"]: match = _SERVER_NOT_A_...
2bf99d74a23d3522a2a53a711fbb2c8d43748eb1
3,652,729
def get_frontend_ui_base_url(config: "CFG") -> str: """ Return ui base url """ return as_url_folder(urljoin(get_root_frontend_url(config), FRONTEND_UI_SUBPATH))
4c34a1830431e28ec084853be6d93f1e487865a9
3,652,730
def read_image(name): """ Reads image into a training example. Might be good to threshold it. """ im = Image.open(name) pix = im.load() example = [] for x in range(16): for y in range(16): example.append(pix[x, y]) return example
be510bfee0a24e331d1b9bfb197b02edaafd0d70
3,652,731
def l3tc_underlay_lag_config_unconfig(config, dut1, dut2, po_name, members_dut1, members_dut2): """ :param config: :param dut1: :param dut2: :param po_name: :param members_dut1: :param members_dut2: :return: """ st.banner("{}Configuring LAG between Spine and Leaf node.".format('...
de4c8775b178380e5d9c90ee3c74082d6553d97f
3,652,732
def _xrdcp_copyjob(wb, copy_job: CopyFile, xrd_cp_args: XrdCpArgs, printout: str = '') -> int: """xrdcp based task that process a copyfile and it's arguments""" if not copy_job: return overwrite = xrd_cp_args.overwrite batch = xrd_cp_args.batch sources = xrd_cp_args.sources chunks = xrd_cp_args...
ce4475329a6f75d1819874492f26ceef7113a0f2
3,652,733
import logging def merge_preclusters_ld(preclusters): """ Bundle together preclusters that share one LD snp * [ Cluster ] Returntype: [ Cluster ] """ clusters = list(preclusters) for cluster in clusters: chrom = cluster.gwas_snps[0].snp.chrom start = min(gwas_snp.snp.pos for gwas_snp in cluster.gwas...
fd5409c1fc8463a2c795b2cc2685c1cf1a77f4ad
3,652,734
def cross_recurrence_matrix( xps, yps ): """Cross reccurence matrix. Args: xps (numpy.array): yps (numpy.array): Returns: numpy.array : A 2D numpy array. """ return recurrence_matrix( xps, yps )
017fa50fdd3c68e4bf1703635365d84c3508d0b3
3,652,735
import numpy def define_panels(x, y, N=40): """ Discretizes the geometry into panels using 'cosine' method. Parameters ---------- x: 1D array of floats x-coordinate of the points defining the geometry. y: 1D array of floats y-coordinate of the points defining the geometry....
e34ae13a7cdddc8be69e5cbba84b964bd11e6ec3
3,652,736
def compile_for_llvm(function_name, def_string, optimization_level=-1, globals_dict=None): """Compiles function_name, defined in def_string to be run through LLVM. Compiles and runs def_string in a temporary namespace, pulls the function named 'function_name' out of that namespace, opt...
61494afcde311e63138f75fb8bf59244d5c6d4e0
3,652,737
def setup_svm_classifier(training_data, y_training, testing_data, features, method="count", ngrams=(1,1)): """ Setup SVM classifier model using own implementation Parameters ---------- training_data: Pandas dataframe The dataframe containing the training data for the classifi...
111937690db2c170852b57cdbfc3135c628ac26c
3,652,738
def buildHeaderString(keys): """ Use authentication keys to build a literal header string that will be passed to the API with every call. """ headers = { # Request headers 'participant-key': keys["participantKey"], 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': keys["subscrip...
4505fb679dec9727a62dd328f92f832ab45c417b
3,652,739
from typing import List from typing import cast def build_goods_query( good_ids: List[str], currency_id: str, is_searching_for_sellers: bool ) -> Query: """ Build buyer or seller search query. Specifically, build the search query - to look for sellers if the agent is a buyer, or - to ...
97cccadc265743d743f3e2e757e0c81ff110072b
3,652,740
def make_piecewise_const(num_segments): """Makes a piecewise constant semi-sinusoid curve with num_segments segments.""" true_values = np.sin(np.arange(0, np.pi, step=0.001)) seg_idx = np.arange(true_values.shape[0]) // (true_values.shape[0] / num_segments) return pd.Series(true_values).groupby(seg_idx)...
d6004488ae0109b730cb73dc9e58e65caaed8798
3,652,741
def convert_rational_from_float(number): """ converts a float to rational as form of a tuple. """ f = Fraction(str(number)) # str act as a round return f.numerator, f.denominator
f3a00a150795b008ccc8667a3a0437eb2de2e2af
3,652,742
def classname(obj): """Returns the name of an objects class""" return obj.__class__.__name__
15b03c9ce341bd151187f03e8e95e6299e4756c3
3,652,743
def train(epoch, model, dataloader, optimizer, criterion, device, writer, cfg): """ training the model. Args: epoch (int): number of training steps. model (class): model of training. dataloader (dict): dict of dataset iterator. Keys are tasknames, values are correspon...
41de6aa37b41c837d9921e673414a70cc798478b
3,652,744
def custom_timeseries_widget_for_behavior(node, **kwargs): """Use a custom TimeSeries widget for behavior data""" if node.name == 'Velocity': return SeparateTracesPlotlyWidget(node) else: return show_timeseries(node)
34b296ab98b0eb6f9e2ddd080d5919a0a7158adc
3,652,745
def db_tween_factory(handler, registry): """A database tween, doing automatic session management.""" def db_tween(request): response = None try: response = handler(request) finally: session = getattr(request, "_db_session", None) if session is not Non...
5e5150855db08931af8ba82e3f44e51b6caf54f3
3,652,746
import time def calibrate_profiler(n, timer=time.time): """ Calibration routine to returns the fudge factor. The fudge factor is the amount of time it takes to call and return from the profiler handler. The profiler can't measure this time, so it will be attributed to the user code unless it's s...
ee1f0af52f5530542503be4f277c90f249f83fb5
3,652,747
def getbias(x, bias): """Bias in Ken Perlin’s bias and gain functions.""" return x / ((1.0 / bias - 2.0) * (1.0 - x) + 1.0 + 1e-6)
0bc551e660e133e0416f5e426e5c7c302ac3fbbe
3,652,748
from typing import Dict from typing import Optional def get_exif_flash_fired(exif_data: Dict) -> Optional[bool]: """ Parses the "flash" value from exif do determine if it was fired. Possible values: +-------------------------------------------------------+------+----------+-------+ | ...
82b4fc095d60426622202243f141614b9632340f
3,652,749
import shlex import os def gyp_generator_flags(): """Parses and returns GYP_GENERATOR_FLAGS env var as a dictionary.""" return dict(arg.split('=', 1) for arg in shlex.split(os.environ.get('GYP_GENERATOR_FLAGS', '')))
51777f7b9ad87291dc176ce4673cb8a9cd5864f9
3,652,750
import requests import json def get_geoJson(addr): """ Queries the Google Maps API for specified address, returns a dict of the formatted address, the state/territory name, and a float-ified version of the latitude and longitude. """ res = requests.get(queryurl.format(addr=addr, gmapkey=gmapke...
500c2aa18c8b3b305c912b91efcc9f51121ca7b3
3,652,751
def display_data_in_new_tab(message, args, pipeline_data): """ Displays the current message data in a new tab """ window = sublime.active_window() tab = window.new_file() tab.set_scratch(True) edit_token = message['edit_token'] tab.insert(edit_token, 0, message['data']) return tab
a64b7ac4138b921a53adb96b9933f1825048b955
3,652,752
def _cost( q,p, xt_measure, connec, params ) : """ Returns a total cost, sum of a small regularization term and the data attachment. .. math :: C(q_0, p_0) = .01 * H(q0,p0) + 1 * A(q_1, x_t) Needless to say, the weights can be tuned according to the signal-to-noise ratio. """ s,r = params ...
193d23a11d9704867d0a89846a6a7187de1e953a
3,652,753
def get_full_lang_code(lang=None): """ Get the full language code Args: lang (str, optional): A BCP-47 language code, or None for default Returns: str: A full language code, such as "en-us" or "de-de" """ if not lang: lang = __active_lang return lang or "en-us"
1e0e49797dc5ed3f1fd148ac4ca1ca073231268c
3,652,754
def acquire_images(cam, nodemap, nodemap_tldevice): """ This function acquires and saves 10 images from a device. :param cam: Camera to acquire images from. :param nodemap: Device nodemap. :param nodemap_tldevice: Transport layer device nodemap. :type cam: CameraPtr :type nodemap: INodeMap ...
dd3454b3ddbff27dd73750c630ff5e63737fa50c
3,652,755
import importlib def apply_operations(source: dict, graph: BaseGraph) -> BaseGraph: """ Apply operations as defined in the YAML. Parameters ---------- source: dict The source from the YAML graph: kgx.graph.base_graph.BaseGraph The graph corresponding to the source Returns...
d78410d27da574efc30d08555eaefde0c77cb513
3,652,756
def tt_logdotexp(A, b): """Construct a Theano graph for a numerically stable log-scale dot product. The result is more or less equivalent to `tt.log(tt.exp(A).dot(tt.exp(b)))` """ A_bcast = A.dimshuffle(list(range(A.ndim)) + ["x"]) sqz = False shape_b = ["x"] + list(range(b.ndim)) if len(...
f543557a0b24159ede7d8cc0c8ed5df3ed2123f4
3,652,757
def _check_like(val, _np_types, _native_types, check_str=None): # pylint: disable=too-many-return-statements """ Checks the follwing: - if val is instance of _np_types or _native_types - if val is a list or ndarray of _np_types or _native_types - if val is a string or list of strings that can...
ab7875d329c09a491178b721c112b64142d2e566
3,652,758
def rotation_matrix(x, y, theta): """ Calculate the rotation matrix. Origin is assumed to be (0, 0) theta must be in radians """ return [np.cos(theta) * x - np.sin(theta) * y, np.sin(theta) * x + np.cos(theta) * y]
53f646429f7a4b719b197cacbc71442ebef719d4
3,652,759
from typing import List def create_players(num_human: int, num_random: int, smart_players: List[int]) \ -> List[Player]: """Return a new list of Player objects. <num_human> is the number of human player, <num_random> is the number of random players, and <smart_players> is a list of difficulty lev...
10a7e840992417d46c79d794e66e1de5de16dd95
3,652,760
import os import stat def file_info(path): """ Return file information on `path`. Example output: { 'filename': 'passwd', 'dir': '/etc/', 'path': '/etc/passwd', 'type': 'file', 'size': 2790, 'mode': 33188, 'uid': 0, ...
36d8c92a6cc20f95f73f3a2c6c986222f1e9633e
3,652,761
def extract_test_params(root): """VFT parameters, e.g. TEST_PATTERN, TEST_STRATEGY, ...""" res = {} ''' xpath = STATIC_TEST + '*' elems = root.findall(xpath) + root.findall(xpath+'/FIXATION_CHECK*') #return {e.tag:int(e.text) for e in elems if e.text.isdigit()} print(xpath) for e i...
ebd0e1d86af8d741ff993fc54b6ef4b3a7be6ac4
3,652,762
from typing import Optional from typing import List def csc_list( city: str, state: Optional[str] = None, country: Optional[str] = None, ) -> List[db.Geoname]: """ >>> [g.country_code for g in csc_list('sydney')] ['AU', 'CA', 'US', 'US', 'ZA', 'VU', 'US', 'US', 'CA'] >>> [g.name for g in c...
6c27a16c22a40d095bd3e3fad7660bbee867751e
3,652,763
from typing import Iterable from typing import Tuple def calculate_frame_score(current_frame_hsv: Iterable[cupy.ndarray], last_frame_hsv: Iterable[cupy.ndarray]) -> Tuple[float]: """Calculates score between two adjacent frames in the HSV colourspace. Frames should be split, e.g. cv2....
db5819ab0696364569f79f326ab7e28f0f0371b3
3,652,764
def huber_loss_function(sq_resi, k=1.345): """Robust loss function which penalises outliers, as detailed in Jankowski et al (2018). Parameters ---------- sq_resi : `float` or `list` A single or list of the squared residuals. k : `float`, optional A constant that defines at which dis...
bf8d5f3aa042297014b7b93316fe557784c4c5b1
3,652,765
import re def clean_sentence(sentence: str) -> str: """ Bertに入れる前にtextに行う前処理 Args: sentence (str): [description] Returns: str: [description] """ sentence = re.sub(r"<[^>]*?>", "", sentence) # タグ除外 sentence = mojimoji.zen_to_han(sentence, kana=False) sentence = neolog...
bf5f9df5ab04ff96ae7f8199dfbeafae30d764eb
3,652,766
from typing import Union from enum import Enum def assert_user(user_id: int, permission: Union[str, Enum] = None) -> bool: """ Assert that a user_id belongs to the requesting user, or that the requesting user has a given permission. """ permission = ( permission.value if isinstance(permiss...
6ef54d60a0b62e4ffb1330dba7bffeeac0df03c7
3,652,767
def single_prob(n, n0, psi, c=2): """ Eq. 1.3 in Conlisk et al. (2007), note that this implmentation is only correct when the variable c = 2 Note: if psi = .5 this is the special HEAP case in which the function no longer depends on n. c = number of cells """ a = (1 - psi) / psi F = (...
05c0c627a05bb683fa3c20cacefa121f5cddba14
3,652,768
def array_pair_sum_iterative(arr, k): """ returns the array of pairs using an iterative method. complexity: O(n^2) """ result = [] for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[i] + arr[j] == k: result.append([arr[i], arr[j]]) return...
c4f0eb5e290c784a8132472d85023662be291a71
3,652,769
def merge_named_payload(name_to_merge_op): """Merging dictionary payload by key. name_to_merge_op is a dict mapping from field names to merge_ops. Example: If name_to_merge_op is { 'f1': mergeop1, 'f2': mergeop2, 'f3': mergeop3 }, Then t...
ee20147b7937dff208da6ea0d025fe466d8e92ed
3,652,770
def euclidean_distance(this_set, other_set, bsf_dist): """Calculate the Euclidean distance between 2 1-D arrays. If the distance is larger than bsf_dist, then we end the calculation and return the bsf_dist. Args: this_set: ndarray The array other_set: ndarray The com...
7055c0de77cad987738c9b3ec89b0381002fbfd4
3,652,771
from typing import List from typing import Union import subprocess def run_cmd_simple(cmd: str, variables: dict, env=None, args: List[str] = None, libraries=None) -> Union[dict, str]: """ Run cmd with variables written in environment....
b16693f291ade54f470e4c7173cf06cca774cdf6
3,652,772
def host(provider: Provider) -> Host: """Create host""" return provider.host_create(utils.random_string())
36e1b6f0ddf8edc055d56cac746271f5d3801111
3,652,773
def bj_struktur_p89(x, n: int = 5, **s): # brute force """_summary_ :param x: _description_ :type x: _type_ :param n: _description_, defaults to 5 :type n: int, optional :return: _description_ :rtype: _type_ """ gamma, K = gamma_K_function(**s) b_j = np.empty((x.size, n + 1)) ...
d21fc501411ada9f2173da7ca447418e2f51a86f
3,652,774
def _get_pulse_width_and_area(tr, ipick, icross, max_pulse_duration=.08): """ Measure the width & area of the arrival pulse on the displacement trace Start from the displacement peak index (=icross - location of first zero crossing of velocity) :param tr: displacement trace :type tr: ob...
43598f797f2956def740881b33b38d8824ba7ff3
3,652,775
def load_backend(name, options=None): """Load the named backend. Returns the backend class registered for the name. If you pass None as the name, this will load the default backend. See the documenation for get_default() for more information. Raises: UnknownBackend: The name is not recogn...
1df4c1b0c0d9d81e607a5884f3391883ab6ea3c5
3,652,776
def test() -> ScadObject: """ Create something. """ result = IDUObject() result += box(10, 10, 5, center=True).translated((0, 0, -1)).named("Translated big box") result -= box(4, 4, 4, center=True) result += box(10, 10, 5) result *= sphere(7).translated((0, 0, 1)) return ( r...
2d8c413a6b60969de60746c4fb356da88a95e06a
3,652,777
def rollout(policy, env_class, step_fn=default_rollout_step, max_steps=None): """Perform rollout using provided policy and env. :param policy: policy to use when simulating these episodes. :param env_class: class to instantiate an env object from. :param step_fn: a function to be called at each step of...
d5ac3246338165d3cfdb5e37ae5a6cbbe5df0408
3,652,778
def get_source(location, **kwargs): """Factory for StubSource Instance. Args: location (str): PathLike object or valid URL Returns: obj: Either Local or Remote StubSource Instance """ try: utils.ensure_existing_dir(location) except NotADirectoryError: return Re...
6b240d7ad523c2a45ca21c3030a96ec5aebb69c2
3,652,779
def about(request): """ Prepare and displays the about view of the web application. Args: request: django HttpRequest class Returns: A django HttpResponse class """ template = loader.get_template('about.html') return HttpResponse(template.render())
ecf2a890e49a5fe786024f7d7f524e1396064f48
3,652,780
def url(parser, token): """Overwrites built in url tag to use . It works identicaly, except that where possible it will use subdomains to refer to a project instead of a full url path. For example, if the subdomain is vessel12.domain.com it will refer to a page 'details' as /details/ instead of /site/v...
191c7598cdf079fe97452d4914534191e7eb1fe4
3,652,781
import math import logging def getAp(ground_truth, predict, fullEval=False): """ Calculate AP at IOU=.50:.05:.95, AP at IOU=.50, AP at IOU=.75 :param ground_truth: {img_id1:{{'position': 4x2 array, 'is_matched': 0 or 1}, {...}, ...}, img_id2:{...}, ...} :param predict: [{'position':4x2 array, 'i...
ac44c514166f8e70a6625f4e1ad89b36564ffba4
3,652,782
def aumenta_fome(ani): """ aumenta_fome: animal --> animal Recebe um animal e devolve o mesmo com o valor da fome incrementado por 1 """ if obter_freq_alimentacao(ani) == 0: return ani else: ani['a'][0] += 1 return ani
377e3800e12877f1b8cd1cba19fe3a430ade0207
3,652,783
import warnings def match_inputs( bp_tree, table, sample_metadata, feature_metadata=None, ignore_missing_samples=False, filter_missing_features=False ): """Matches various input sources. Also "splits up" the feature metadata, first by calling taxonomy_utils.split_taxonomy() on it ...
92a97fc39c233a0969c24774d74fdd6b304f5442
3,652,784
def im_adjust(img, tol=1, bit=8): """ Adjust contrast of the image """ limit = np.percentile(img, [tol, 100 - tol]) im_adjusted = im_bit_convert(img, bit=bit, norm=True, limit=limit.tolist()) return im_adjusted
2bbccc08d4dd6aeed50c6fb505ff801e3201c73a
3,652,785
import math def FibanocciSphere(samples=1): """ Return a Fibanocci sphere with N number of points on the surface. This will act as the template for the nanoparticle core. Args: Placeholder Returns: Placeholder Raises: Placeholder """ points = [] phi = ma...
ea47b7c2eed34bd826ddff1619adac887439f5e0
3,652,786
import inspect def get_code(): """ returns the code for the activity_selection function """ return inspect.getsource(activity_selection)
3bae49b5feea34813c518a3ec3a62a4cde35445f
3,652,787
def calc_luminosity(flux, fluxerr, mu): """ Normalise flux light curves with distance modulus. Parameters ---------- flux : array List of floating point flux values. fluxerr : array List of floating point flux errors. mu : float Distance modulus from luminosity distance....
8cfebee024ae73355daf64b96260d45e57115c8f
3,652,788
from typing import Optional import os def download_file(url: str, destination: str, timeout: Optional[int] = None, silent: Optional[bool] = False) -> str: """ Downloads file by given URL to destination dir. """ file_name = get_file_name_from_url(url) file_path = join(destination,...
c49e8974b01c101cf0d0a0defe572ca8f65b780a
3,652,789
def inference(images): """Build the CIFAR-10 model. Args: images: Images returned from distorted_inputs() or inputs(). Returns: Logits. """ ### # We instantiate all variables using tf.get_variable() instead of # tf.Variable() in order to share variables across multiple GPU training runs. # If...
224c6792b4f2b066d8627d222e6f89b469921de3
3,652,790
def cluster_molecules(mols, cutoff=0.6): """ Cluster molecules by fingerprint distance using the Butina algorithm. Parameters ---------- mols : list of rdkit.Chem.rdchem.Mol List of molecules. cutoff : float Distance cutoff Butina clustering. Returns ------- pandas....
ba98342d10512b4ee08e756644a26bc8585f5abc
3,652,791
import timeit def exec_benchmarks_empty_inspection(code_to_benchmark, repeats): """ Benchmark some code without mlinspect and with mlinspect with varying numbers of inspections """ benchmark_results = { "no mlinspect": timeit.repeat(stmt=code_to_benchmark.benchmark_exec, setup=code_to_benchmar...
c4038b98968c9c44b5cbd0bfc9e92654dae8aca2
3,652,792
def detect_version(): """ Try to detect the main package/module version by looking at: module.__version__ otherwise, return 'dev' """ try: m = __import__(package_name, fromlist=['__version__']) return getattr(m, '__version__', 'dev') except ImportError: pass ...
c9cb3a30d84c7e9118df46dcc73ce37278788db5
3,652,793
def model(p, x): """ Evaluate the model given an X array """ return p[0] + p[1]*x + p[2]*x**2. + p[3]*x**3.
fe923f6f6aea907d3dc07756813ed848fbcc2ac6
3,652,794
def normalize(x:"tensor|np.ndarray") -> "tensor|np.ndarray": """Min-max normalization (0-1): :param x:"tensor|np.ndarray": :returns: Union[Tensor,np.ndarray] - Return same type as input but scaled between 0 - 1 """ return (x - x.min())/(x.max()-x.min())
6230077008c084bdcbebfc32d25251564c4266f0
3,652,795
import warnings import Bio def apply_on_multi_fasta(file, function, *args): """Apply a function on each sequence in a multiple FASTA file (DEPRECATED). file - filename of a FASTA format file function - the function you wish to invoke on each record *args - any extra arguments you want passed to the f...
e204322e512a0f1eb875d7a6434ab6e3356cff10
3,652,796
def resize_bbox(box, image_size, resize_size): """ Args: box: iterable (ints) of length 4 (x0, y0, x1, y1) image_size: iterable (ints) of length 2 (width, height) resize_size: iterable (ints) of length 2 (width, height) Returns: new_box: iterable (ints) of length 4 (x0, y0,...
3b6a309e6ccf0e244bb5a51a922bcf96303116ea
3,652,797
import time def perf_counter_ms(): """Returns a millisecond performance counter""" return time.perf_counter() * 1_000
55f1bbbd8d58593d85f2c6bb4ca4f79ad22f233a
3,652,798
import struct def make_shutdown_packet( ): """Create a shutdown packet.""" packet = struct.pack( "<B", OP_SHUTDOWN ); return packet;
6d696d76c9aa783e477f65e5c89106b2fff6db6d
3,652,799