content
stringlengths
22
815k
id
int64
0
4.91M
def remove_sus_from_Reff(strain, data_date): """ This removes the inferred susceptibility depletion from the Reff estimates out of EpyReff. The inferred Reff = S(t) * Reff_1 where S(t) is the effect of susceptible depletion (i.e. a factor between 0 and 1) and Reff_1 is the Reff without the effect of a...
10,300
def test_get_notification_by_id_raise(): """Will return information for notifications with id. :return: Should catch the ValueError. """ syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", username="admin", password="password") with pytest.raises(ValueError) as excinfo: syn.get_n...
10,301
def test_save_matplotlib_figures(gallery_conf, ext, req_mpl, req_pil): """Test matplotlib figure save.""" if ext == 'svg': gallery_conf['image_scrapers'] = (matplotlib_svg_scraper(),) import matplotlib.pyplot as plt # nest these so that Agg can be set plt.plot(1, 1) fname_template = os.path...
10,302
def word2bytes(word, big_endian=False): """ Converts a 32-bit word into a list of 4 byte values. """ return unpack_bytes(pack_word(word, big_endian))
10,303
def statfcn(status, _id, _ret): """ Callback for libngspice to report simulation status like 'tran 5%' """ logger.warn(status.decode('ascii')) return 0
10,304
def decode_eventdata(sensor_type, offset, eventdata, sdr): """Decode extra event data from an alert or log Provide a textual summary of eventdata per descriptions in Table 42-3 of the specification. This is for sensor specific offset events only. :param sensor_type: The sensor type number from th...
10,305
def get_log_path(): """ Requests the logging path to the external python library (that calls the bindings-common). :return: The path where to store the logs. """ if __debug__: logger.debug("Requesting log path") log_path = compss.get_logging_path() if __debug__: logger.d...
10,306
def do_monitor_redis_check_create(client, args): """ Create redis check monitor """ kwargs = { 'group_id': args.redis_id, 'metric': args.metric, 'threshold': args.threshold, 'operator': args.operator, } if args.tenant: kwargs['tenant'] = ar...
10,307
def about_incumbent(branch_df): """ number of incumbent updates incumbent throughput: num_updates / num_nodes max_improvement, min_improvement, avg_improvement avg incumbent improvement / first incumbent value max, min, avg distance between past incumbent updates distance between last update...
10,308
def unique_chars(texts: List[str]) -> List[str]: """ Get a list of unique characters from list of text. Args: texts: List of sentences Returns: A sorted list of unique characters """ return sorted(set("".join(texts)))
10,309
def adaptive_max_pool1d(input, output_size): """Apply the 1d adaptive max pooling to input. Parameters ---------- input : dragon.vm.torch.Tensor The input tensor. output_size : Union[int, Sequence[int]] The target output size. Returns ------- dragon.vm.torch.Tensor ...
10,310
def test_is_card_useful_already_played(card_value, played_value): """ If a card's number is less than or equal to the played stack of its color, it should no longer be useful. """ game = Game([]) game.stacks[cards.Colors.BLUE] = played_value card = cards.Card(cards.Colors.BLUE, card_value) ...
10,311
def download_file(url, path): """Download a file. :param string url: The URL of the remote file. :param string path: The path to save the file to. """ r = requests.get(url, stream=True) with open(path, 'wb') as f: size = int(r.headers.get('content-length')) / 1024 + 1 for chunk ...
10,312
def cmd_log(ctx, *args): """ logs the args """ print(*args)
10,313
def get_return_nb(input_value, output_value): """Get return from input and output value.""" if input_value == 0: if output_value == 0: return 0. return np.inf * np.sign(output_value) return_value = (output_value - input_value) / input_value if input_value < 0: return_...
10,314
def get_rocauc(val,num_iterations): """ Trains a logistic regression and calculates the roc auc for classifying products as >=4 stars """ recalls = np.zeros(num_iterations) precisions = np.zeros(num_iterations) f1s = np.zeros(num_iterations) roc_aucs = np.zeros(num_iterations) factory = lr_wrapper(val,featur...
10,315
def split_expList(expList, max_nr_of_instr: int=8000, verbose: bool=True): """ Splits a pygsti expList into sub lists to facilitate running on the CCL and not running into the instruction limit. Assumptions made: - there is a fixed instruction overhead per program - th...
10,316
def __make_node_aliases(data: list[str]): """Alias a genes ID to their families in order to build edges between them""" famcom = {} elems = [tokens for tokens in data if tokens[2] in ["FAMILY", "COMPLEX"]] # Add all (gene) containers first for tokens in elems: famcom[tokens[1]] = AliasIt...
10,317
def poly_edges_min_length(P, T, distFcn=norm): """ Returns the per polygon min edge length Parameters ---------- P : Tensor a (N, D,) points set tensor T : LongTensor a (M, T,) topology tensor Returns ------- Tensor the (T, M,) min edge length tensor """...
10,318
def reportData_to_report(report_data: ReportData) -> Report: """Create a report object from the given thrift report data.""" main = { "check_name": report_data.checkerId, "description": report_data.checkerMsg, "issue_hash_content_of_line_in_context": report_data.bugHash, "locatio...
10,319
def new_order(sender, instance, created, **kwargs): """ Freeze the amount needed to fulfill the order when it is created. Perform the trade if there are compatible orders to match. """ if created: instance_wallet = get_object_or_404(Wallet, profile=instance.profile) if instance.type...
10,320
def play_against_human( player, env_algorithm: Callable, opponent: str, env_algorithm_kwargs=None ): """Executes a function controlling the player while facing opponent. The env_algorithm function is executed with the player environment as first argument. It exposes the open ai gym API. Add...
10,321
def softmax(x): """A softmax implementation.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)
10,322
def get_cazy_class_fam_genbank_records(args, session, config_dict): """GenBank acc query results from the local CAZyme database for CAZyme from specific classes/fams :param args: cmd-line argument parser :param session: open SQLite db session :param config_dict: dict, defines CAZy classes and fami...
10,323
def assign_bias_ID(data, bias_params=None, bias_name='bias_ID', key_name=None, bias_model=None): """ Assign a value to each data point that determines which biases are applied to it. parameters: data: pointCollection.data instance bias_parameters: a list of parameters, each unique combinati...
10,324
def check(s): """ :param s:str. the input of letters :return: bool. """ if len(s) == 7 and len(s.split(' ')) == 4: for unit in s.split(' '): if unit.isalpha(): return True
10,325
def pyeval(*args): """ .. function:: pyeval(expression) Evaluates with Python the expression/s given and returns the result >>> sql("pyeval '1+1'") pyeval('1+1') ------------- 2 >>> sql("select var('test')") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ....
10,326
def test_hinge_loss_backward(): """ Tests the backward pass of the hinge loss function """ from your_code import HingeLoss X = np.array([[-1, 2, 1], [-3, 4, 1]]) w = np.array([1, 2, 3]) y = np.array([1, -1]) loss = HingeLoss(regularization=None) _true = np.array([-1.5, 2, 0.5]) ...
10,327
def is_buggy(battery: Dict) -> bool: """ This method returns true in case an acpi bug has occurred. In this case the battery is flagged unavailable and has no capacity information. :param battery: the battery dictionary :return: bool """ return battery['design_capacity'] is None
10,328
def with_hyperparameters(uri: Text): """Constructs an ImporterNode component that imports a `standard_artifacts.HyperParameters` artifact to use for future runs. Args: uri (Text): Hyperparameter artifact's uri Returns: ImporterNode """ return ImporterNode( instance_name='with_h...
10,329
def update_user_controller(user_repository_spy): # pylint: disable=W0621 """montagem de update_user_controller utilizando spy""" usecase = UpdateUser(user_repository_spy, PasswordHash()) controller = UpdateUserController(usecase) return controller
10,330
def blockList2Matrix(l): """ Converts a list of matrices into a corresponding big block-diagonal one. """ dims = [m.shape[0] for m in l] s = sum(dims) res = zeros((s, s)) index = 0 for i in range(len(l)): d = dims[i] m = l[i] res[index:index + d, index:index + d] = m ...
10,331
def log_new_fit(new_fit, log_gplus, mode='residual'): """Log the successful refits of a spectrum. Parameters ---------- new_fit : bool If 'True', the spectrum was successfully refit. log_gplus : list Log of all previous successful refits of the spectrum. mode : str ('positive_re...
10,332
def prepare_hr_for_compromised_credentials(hits: list) -> str: """ Prepare human readable format for compromised credentials :param hits: List of compromised credentials :return: Human readable format of compromised credentials """ hr = [] for hit in hits: source = hit.get('_source...
10,333
def test_walk_directory_artifacts(): """Ensure walk_directory_artifacts works as expected.""" for filepath in archive.walk_directory_artifacts( TEST_DIRECTORY_PATH, include={"test_*.py"}, exclude={"test_archive.py"} ): assert filepath.is_file() assert filepath.name.startswith("test_...
10,334
def red_bg(text): """ Adds a red background to the given text. """ return colorize(text, "\033[48;5;167m")
10,335
def update_inc_admins_statistics_row_name(row_name: str) -> None: """ row_name must only be in (orioks_scheduled_requests, orioks_success_logins, orioks_failed_logins) """ if row_name not in ('orioks_scheduled_requests', 'orioks_success_logins', 'orioks_failed_logins'): raise Exception('update_i...
10,336
def model_utils(decoy: Decoy) -> ModelUtils: """Get mock ModelUtils.""" return decoy.mock(cls=ModelUtils)
10,337
def getLeftTopOfTile(tilex, tiley): """Remember from the comments in the getStartingBoard() function that we have two sets of coordinates in this program. The first set are the pixel coordinates, which on the x-axis ranges from 0 to WINDOWWIDTH - 1, and the y-axis ranges from 0 to WINDOWHEIGHT - 1. Lembrando...
10,338
def count_str(text, sub, start=None, end=None): """ Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``. Optional arguments start and end are interpreted as in slice notation. :param text: The string to search :type text: ``str`` :param ...
10,339
def test_alarm_set_get(monkeypatch): """ test set functions """ act = AlarmAction.RAISE assert act is not None sev = AlarmSeverity.CRITICAL assert sev is not None det = AlarmDetail("1", "2", 3, AlarmSeverity.MINOR, "4", "5") assert det[alarm.KEY_MANAGED_OBJECT_ID] == "1" assert...
10,340
async def test_password_status(): """ Test password status. """ service = PasswordService(user) res = await service.password_status() assert isinstance(res, dict) assert res.get("status") == "change"
10,341
def tanh(x, out=None): """ Raises a ValueError if input cannot be rescaled to a dimensionless quantity. """ if not isinstance(x, Quantity): return np.tanh(x, out) return Quantity( np.tanh(x.rescale(dimensionless).magnitude, out), dimensionless, copy=False )
10,342
def epacems( states: Optional[Sequence[str]] = None, years: Optional[Sequence[int]] = None, columns: Optional[Sequence[str]] = None, epacems_path: Optional[Path] = None, ) -> dd.DataFrame: """Load EPA CEMS data from PUDL with optional subsetting. Args: states: subset by state abbreviati...
10,343
def check_termination_criteria( theta: Optional[float], num_iterations: Optional[int] ) -> Tuple[float, int]: """ Check theta and number of iterations. :param theta: Theta. :param num_iterations: Number of iterations. :return: Normalized values. """ # treat theta <= 0 as No...
10,344
def test_real_complex(): """Test converting ScalarValue to float/complex""" val = ScalarValue(1 - 2j) with pytest.raises(TypeError): float(val) c = complex(val) assert c == 1 - 2j assert c == val assert c.real == 1 assert c.imag == -2 assert isinstance(c, complex) val = ...
10,345
def _get_rank_info(): """ get rank size and rank id """ rank_size = int(os.environ.get("RANK_SIZE", 1)) if rank_size > 1: rank_size = int(os.environ.get("RANK_SIZE")) rank_id = int(os.environ.get("RANK_ID")) else: rank_size = 1 rank_id = 0 return rank_size, ...
10,346
def verify_password(password, hash): """Verify if a hash was generated by the password specified. :password: a string object (plaintext). :hash: a string object. :returns: True or False. """ method = get_hash_algorithm(flask.current_app.config['HASH_ALGORITHM']) return method.verify(pass...
10,347
def _conversion_sample2v_from_meta(meta_data): """ Interpret the meta data to extract an array of conversion factors for each channel so the output data is in Volts Conversion factor is: int2volt / channelGain For Lf/Ap interpret the gain string from metadata For Nidq, repmat the gains from the ...
10,348
def read_split_csv(input_files, delimiter='\t', names=['src', 'dst'], dtype=['int32', 'int32']): """ Read csv for large datasets which cannot be read directly by dask-cudf read_csv due to memory requirements. This function takes large input split into smaller files (number of input_fi...
10,349
def _gnurl( clientID ): """ Helper function to form URL to Gracenote_ API service. :param str clientID: the Gracenote_ client ID. :returns: the lower level URL to the Gracenote_ API. :rtype: str """ clientIDprefix = clientID.split('-')[0] return 'https://c%s.web.cddbp.net/webapi/xml...
10,350
def test_pep8_conformance(): """Test source code for PEP8 conformance""" try: import pep8 except: print("Skipping pep8 Tests because pep8.py not installed.") return # Skip test if pep8 is not new enough pep8_version = parse_version(get_distribution('pep8').version) need...
10,351
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. js...
10,352
def fetch_item_info(session, observations, claims, verbose=False): """ Fetches information about wikidata items. :Parameters: session : :class:`mwapi.Session` An API session to use for querying observations : `iterable`(`dict`) A collection of observations to annotat...
10,353
def draw_bboxes(img,boxes,classes): """ Draw bounding boxes on top of an image Args: img : Array of image to be modified boxes: An (N,4) array of boxes to draw, where N is the number of boxes. classes: An (N,1) array of classes corresponding to each bounding box. Outputs: ...
10,354
def main(dataset_name): """Clean the data from the clinical datasets. We removed excluded subjects outside the age range [47,73] based on the UK Biobank data. """ # ---------------------------------------------------------------------------------------- participants_path = PROJECT_ROOT / 'data' / d...
10,355
def test_grdcut_file_in_file_out(): """ grdcut an input grid file, and output to a grid file. """ with GMTTempFile(suffix=".nc") as tmpfile: result = grdcut("@earth_relief_01d", outgrid=tmpfile.name, region="0/180/0/90") assert result is None # return value is None assert os.pat...
10,356
def markdown(context, template_path): """ {% markdown 'terms-of-use.md' %} """ return mark_safe(get_markdown(context, template_path)[0])
10,357
def investorMasterGetSubaccAssetDetails(email, recvWindow=""): """# Query managed sub-account asset details(For Investor Master Account) #### `GET /sapi/v1/managed-subaccount/asset (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- email |STRING |...
10,358
def ema_indicator(close, n=12, fillna=False): """EMA Exponential Moving Average via Pandas Args: close(pandas.Series): dataset 'Close' column. n_fast(int): n period short-term. fillna(bool): if True, fill nan values. Returns: pandas.Series: New feature generated. "...
10,359
def connect(addr=None, proto=None, name=None, pgrok_config=None, **options): """ Establish a new ``pgrok`` tunnel for the given protocol to the given port, returning an object representing the connected tunnel. If a `tunnel definition in pgrok's config file matches the given ``name``, it will be loade...
10,360
def u_glob(U, elements, nodes, resolution_per_element=51): """ Compute (x, y) coordinates of a curve y = u(x), where u is a finite element function: u(x) = sum_i of U_i*phi_i(x). Method: Run through each element and compute cordinates over the element. """ x_patches = [] u_patches = [] ...
10,361
def date(value) -> DateValue: """Return a date literal if `value` is coercible to a date. Parameters ---------- value Date string Returns ------- DateScalar A date expression """ raise NotImplementedError()
10,362
def aggregate_experiments_results(precomputed_name = "", multianno_only = True): """ Load all of the results from the SALAMI experiment and plot the annotator agreements """ # Step 1: Extract feature-based agreements names = ['MFCCs', 'Chromas', 'Tempogram', 'Crema', 'Fused Tgram/Crema', 'Fused ...
10,363
def test_queue_enqueue_multiple_nodes(): """ Can successfully enqueue multiple items into a queue """ grocery_checkout_queue = Queue() grocery_checkout_queue.enqueue('Adam') grocery_checkout_queue.enqueue('Sue') grocery_checkout_queue.enqueue('Michael') assert grocery_checkout_queue.fro...
10,364
def keyring_rgw_create(**kwargs): """ Create rgw bootstrap keyring for cluster. Args: **kwargs: Arbitrary keyword arguments. cluster_uuid : Set the cluster UUID. Defaults to value found in ceph config file. cluster_name : Set the cluster name. Defaults to "ce...
10,365
def read_tm224_data(filename: str, folder: str = None) -> pandas.DataFrame: """ Read data stored by Lakeshore TM224 temperature monitor software. Args: filename: string name of ".xls" file on disk folder: string location of file on disk Returns: df : pa...
10,366
def create_db_system(**kwargs): """Creates a DbSystem with the given id If no id is given, it will prompt the user for the id. Args: **kwargs: Optional parameters Keyword Args: db_system_name (str): The new name of the DB System. description (str): The new descriptio...
10,367
def load_keypoints2d_file(file_path, njoints=17): """load 2D keypoints from keypoint detection results. Only one person is extracted from the results. If there are multiple persons in the prediction results, we select the one with the highest detection score. Args: file_path: the json file path. njo...
10,368
def read_csv(filepath_or_buffer: str, usecols: List[int]): """ usage.modin: 2 """ ...
10,369
def filter_params(module, train_bn=True): """Yields the trainable parameters of a given module. Args: module: A given module train_bn: If True, leave the BatchNorm layers in training mode Returns: Generator """ children = list(module.children()) if not children: i...
10,370
def utf8_bytes(string): """ Convert 'string' to bytes using UTF-8. """ return bytes(string, 'UTF-8')
10,371
def line_search(f, xk, pk, old_fval=None, old_old_fval=None, gfk=None, c1=1e-4, c2=0.9, maxiter=20): """Inexact line search that satisfies strong Wolfe conditions. Algorithm 3.5 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-61 Args: fun: function of the form f(x) where x is...
10,372
def _get_value(session_browser, field): """Get an input field's value.""" return session_browser.evaluate_script('$("#id_%s").val()' % field)
10,373
def search_2d(arr, target): """ TODO same func as in adfgvx """ for row in range(len(arr)): for col in range(len(arr)): if arr[row][col] == target: return row, col raise ValueError
10,374
def scale_large_images_landmarks(images, landmarks): """ scale images and landmarks up to maximal image size :param list(ndarray) images: list of images :param list(ndarray) landmarks: list of landmarks :return tuple(list(ndarray),list(ndarray)): lists of images and landmarks >>> scale_large_image...
10,375
def home(): """Post-login page.""" if flask.request.method == 'POST': rooms = get_all_open_rooms() name = "anon" if flask.request.form['name'] != "": name = flask.request.form['name'] player_id = flask_login.current_user.id game_id = "" if flask.re...
10,376
def ik(T, tf_base) -> IKResult: """ TODO add base frame correction """ Rbase = tf_base[:3, :3] Ree = T[:3, :3] Ree_rel = np.dot(Rbase.transpose(), Ree) # ignore position # n s a according to convention Siciliano n = Ree_rel[:3, 0] s = Ree_rel[:3, 1] a = Ree_rel[:3, 2] A = np...
10,377
def standarize_ms(datas, val_index, max=(2^32 - 1)): """ Standarize milliseconds lapsed from Arduino reading. Note: Only takes height for one circulation of ms from Arduino. datas: List of data readings val_index: Index of ms value in reading data entry max: Max time of...
10,378
def test_list_int_min_length_2_nistxml_sv_iv_list_int_min_length_3_1(mode, save_output, output_format): """ Type list/int is restricted by facet minLength with value 7. """ assert_bindings( schema="nistData/list/int/Schema+Instance/NISTSchema-SV-IV-list-int-minLength-3.xsd", instance="ni...
10,379
def corr_bias(x_data, y_data, yerr, pdz1_x, pdz1_y, pdz2_x, pdz2_y): """ Given a correlation measurement and associated PDZs, generate a model and fit as a bias to the measurement. Return: 1) the model [unbiased] (x and y float arrays) 2) best fit bias (float) 3) the bias PDF (x ...
10,380
def confidence_ellipse( x=None, y=None, cov=None, ax=None, n_std=3.0, facecolor="none", **kwargs ): """ Create a plot of the covariance confidence ellipse of `x` and `y` Parameters ---------- x, y : array_like, shape (n, ) Input data. cov : array_like, shape (2, 2) covarianc...
10,381
def lsR(root: Path) -> Iterator[Path]: """Recursive list a directory and return absolute path""" return filter(lambda p: ".git" not in p.parts, itertools.chain.from_iterable( map( lambda lsdir: list(map(lambda f: Path(lsdir[0]) / f, lsdir[2])), os.walk(root), ) ))
10,382
def adapted_fields(type) -> List[Attribute]: """Return the attrs format of `fields()` for attrs and dataclasses.""" if is_dataclass(type): return [ Attribute( attr.name, attr.default if attr.default is not MISSING else ( ...
10,383
def get_parms(): """ Use get_args to get the args, and return a dictionary of the args ready for use in pump software. @see get_args() :return: dict: parms """ parms = {} args = get_args() for name, val in vars(args).items(): if val is not None: parms[name] = val...
10,384
def mv_files(source, target, workflow): """Move files within workspace.""" absolute_source_path = os.path.join(workflow.workspace_path, source) if not os.path.exists(absolute_source_path): message = "Path {} does not exist".format(source) raise REANAWorkflowControllerError(message) if n...
10,385
def report_missing(item_type, output, expect, filename, reverse=False): """Print a message indicating a missing file.""" if reverse: sys.stderr.write('Extra %s %s\n' % (item_type, os.path.join(expect, filename))) else: sys.stderr.write('Missing %s %s\n' ...
10,386
def set_rating(request, rating_form): """ Checks if rating for books exists. If exists, changes it. If not, creates a new one. """ try: book_rating = BookRating.objects.get(id_user=TheUser.objects.get(id_user=request.user), id_book=Book.objects.get(id...
10,387
def cloud_backup(backup_info: dict): """ Send latest backup to the cloud. Parameters ---------- backup_info: dict Dictionary containing information in regards to date of backup and batch number. """ session = ftplib.FTP_TLS("u301483.your-storagebox.de") session.login(user="u3014...
10,388
def redshift_session(_session_scoped_redshift_engine): """ A redshift session that rolls back all operations. The engine and db is maintained for the entire test session for efficiency. """ conn = _session_scoped_redshift_engine.connect() tx = conn.begin() RedshiftSession = sa.orm.sessionm...
10,389
def make_led_sample(n_samples=200, irrelevant=0, random_state=None): """Generate random samples from the 7-segment problem. Parameters ---------- n_samples : int, optional (default=200) The number of samples to generate. irrelevant : int, optional (default=0) The number of irreleva...
10,390
def handle_source_authorization_exception(e): """ Error handler: the data source requires authorisation This will be triggered when opening a private HDX dataset before the user has supplied their authorisation token. @param e: the exception being handled """ if e.message: flask.flash(e....
10,391
def RemoveExperimentFromManualList(experiment, knob): """Removes an experiment from the ManuallyDisabledExperiments knob. Args: experiment: str, the experiment name to remove. knob: str, the manual knob to modify Raises: PlistError: if the plist can't be modified. """ knobs = KNOBS.Knobs() if k...
10,392
async def bird(ctx): """gives a bird image""" birdimg = await alex_api.birb() embed = discord.Embed(title= ('BIRDS 0_0'),timestamp=datetime.datetime.utcnow(), color=discord.Color.green()) embed.set_footer(text=ctx.author.name , icon_url=ctx.author.avatar_url) embed.set_image(url=f"{birdimg}") ...
10,393
def agd_reader_multi_column_pipeline(upstream_tensorz, control_ops=None, verify=False, buffer_pool=None, share_buffer_pool=True, buffer_pool_args=pool_default_args, repack=None, name="agd_reader_multi_column_pipeline"): """ Create an AGDReader pipeline for an iterable of columns. Each column group is assumed to...
10,394
def findcosmu(re0, rp0, sublat, latc, lon): # considers latc to be plaentocentric latitudes, but sublat to be planetographic """Takes the equitorial and polar radius of Jupiter (re0, rp0 respectively), the sub-latitude of Jupiter, latitude and longitude (both in radians) to determine the "cos(mu)" of the ...
10,395
def RMS_energy(frames): """Computes the RMS energy of frames""" f = frames.flatten() return N.sqrt(N.mean(f * f))
10,396
def is_blacklisted_url(url): """ Return whether the URL blacklisted or not. Using BLACKLIST_URLS methods against the URLs. :param url: url string :return: True if URL is blacklisted, else False """ url = urllib.parse.urlparse(url).netloc for method in WHITELIST_URL: for whitelis...
10,397
def heading(yaw): """A helper function to getnerate quaternions from yaws.""" q = euler2quat(0.0, 0.0, yaw) quat = Quaternion() quat.w = q[0] quat.x = q[1] quat.y = q[2] quat.z = q[3] return quat
10,398
def check_login_required(view_func): """ A decorator that checks whether login is required on this installation and, if so, checks if the user is logged in. If login is required and the user is not logged in, they're redirected to the login link. """ def _check(*args, **kwargs): siteconf...
10,399