content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests from bs4 import BeautifulSoup def url_to_soup(url): """url -> soup""" html = requests.get(url) return BeautifulSoup(html.text, 'html.parser')
8b3e6a67c2123ca134d581631321cb8a8daf132a
3,596,514
import pandas import smtplib def send_email(subject, body, df=False, html=False, _from='dev.jonathan.coignard@gmail.com', _pwd='idontknow'): """ Convenient function to get automatic updates on simulations """ message = EmailMessage() message['From'] = _from messag...
8c5dd1ef08f767b2f494a5791d8661410c9d244c
3,596,515
def _CreateLocationBasedTags(build_id, step_name, test_name, normalized_step_name, normalized_test_name, component_mapping, team_mapping, watchlists): """Creates location-based tags for gtests and webkit layout tests.""" location = test_tag_util.GetTestLocat...
d1f9e91a66bc05a013f863f3d2e30eb2d7168e6f
3,596,516
import importlib def import_main_class(module_path): """Import a module at module_path and return its main class. """ module = importlib.import_module(module_path) main_cls_type = DatasetBuilder # Find the main class in our imported module module_main_cls = None for name, obj in module._...
163f6d1a57a5cec832134de11eb2f4eec785d015
3,596,517
from typing import Union def Var(X: BaseRandomVar[Number]) -> Union[Number, FloatType]: """ Variance: https://en.wikipedia.org/wiki/Variance """ return X.variance
b4a43aa6230faa5e0013a0eb2f39a61161892678
3,596,518
def group_info(request): """This context processor provides group information to all templates.""" group = Group.objects.get(pk=1) return {'group': group}
85e6055bb3494a0b647b0025bddbdcf5ea804367
3,596,519
import random import json def goDown(posX, posY, map): """Move the player down""" global playerPosY global playerPosX global map_level if map[posY + 1][posX] == 0: app.write('You can\'t go that way.') for i in map: app.write(i) elif map[posY + 1][posX] == 3: ...
f6fedd75b03cca9203443fd6510a1b722ceb3104
3,596,520
def is_vowel(char): """Check if it is vowel.""" return char in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
97f747d96e08cd15fe7a1b742b36f5ff6cc2f3fc
3,596,521
def _lgamma_positive(x): """Evaluate lgamma for positive arguments. See [3] for what's going on here. """ if x < 2.0: res = 0.0 if x < 1.0: # One step of the recurrence relation res = -np.log(x) x += 1.0 if x < 1.5: dx = x - 1.0 ...
e5eb8e854694bbe8aefbd9bf629aaee7ac478818
3,596,522
def execute_system_config(): """ Function to execute system config commands :return: Dict of project details """ run = SystemConfig() print('Starting to configure system for deployment...') run.config_env() run.select_project_directory() run.create_venv() run.setup_venv() ...
3f1de821b456271c4ba776b013bd01136735b440
3,596,523
def normalize_resources_qs_param(qs): """Given a query string parameter for resources, validate it meets the expected format and return a dict of amounts, keyed by resource class name. The expected format of the resources parameter looks like so: $RESOURCE_CLASS_NAME:$AMOUNT,$RESOURCE_CLASS_NAME:$...
2aadc10ad8900b31ca19cb1c5a1b030a433f8d99
3,596,524
def hdf5ToDict(filename, driver=None, include=None, exclude=None): """ Read an HDF5 file into a dictionary. This will only work for simple HDF files in which we only care about the data name and value. Keywords -------- exclude String or list of strings. Strings must be regular expr...
e885cd3659357a5d55fa9bc91d5262e5ff8f8739
3,596,525
def dict_to_array(d): """Convert a dictionary of lists (or single values) to a structured numpy.ndarray.""" # Convert all lists/values to 1-d arrays, in order to let numpy # figure out the necessary size of the string arrays. new_d = odict() for key in d: new_d[key] = np.atleast_1d(d[k...
dc04d99846dde52641af47d212c282fd6641a650
3,596,526
def _check_freq_bands(freq_bands): """Checks provided frequency bands and re-orders the frequency boundaries if necessary. Example: If vlf = (0.003, 0.06) and lf = (0.04, 0.15) the max frequency of VLF > min frequency of lf (overlapping boundaries). Fixed frequency bands: vlf = (0.004, 0.04) and lf = (...
d3847c71ae9e9f18ea5beab1aaf52e241b5e3741
3,596,527
def extrude_all_profiles(sketch, distance, component, operation) -> adsk.fusion.ExtrudeFeature: """ Create extrude features of all profiles in a sketch The new feature will be created in the given target component and extruded by a distance :param sketch: The sketch from which to get profiles :type ...
276c18ae754a62777b99601ddec947f2bb17b2ff
3,596,528
def baseline_model(input_shape, output_param_number=1, hidden_layer_size=16): """Return a fully connected model with 1 hidden layer""" if hidden_layer_size < output_param_number: raise ValueError("Neurons in the hidden layer (={}) \ should be > output param number (={})".format( ...
283d5e106ec9451410d307bb91d4c59c6220d667
3,596,529
import io def run(args): """ Run the command. :param args: Arguments given to the command """ metadata = templates.metadata(args.template, include=False) if not metadata: return 1 _clean_metadata(metadata) io.yaml_dump(metadata)
4844d94a901c8b9661c19f2c349e23e47ac5c660
3,596,530
def slidingwindow(m, n, xss): """Interleave n tracks from m playlists.""" return performmerge(xss, m, n, False, True)
3da226aa1247e94d6acc17b1a74fed016c41438c
3,596,532
def gs_block(men, women, pref, blocked): """ Gale-shapley algorithm, modified to exclude unacceptable matches Inputs: men (list of men's names) women (list of women's names) pref (dictionary of preferences mapping names to list of preferred names in sorted order) blocked ...
ea69e56604cac25d8f5c9d957157dbd2d9ad1b27
3,596,533
def withClass(classname, namespace=""): """Simplified version of :class:`withAttribute` when matching on a div class - made difficult because ``class`` is a reserved word in Python. Example:: html = ''' <div> Some text <div class="grid">1 4 0 1 0</div> ...
78da18d5e6a6f6598608626a5124d4b0379edd55
3,596,534
async def delete(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 1.0.0 Delete a load balancer. :param name: The name of the load balancer to delete. :param resource_group: The resource group name assigned to the load balancer. CLI Example: .. code-block:: bash ...
9ba8617c402e8df2a9370f36dffd020bca9abfaa
3,596,535
from typing import Iterable from typing import List def filter_wikipathways_files(file_names: Iterable[str]) -> List[str]: """Filter files that have not 'ttl' extension or not start with 'WP'.""" return [ file_name for file_name in file_names if file_name.startswith('WP') and file_name...
abac5be763309986b951d574a72c0f2652b2a981
3,596,536
import json def pre_save(sender, instance, raw, using, update_fields, **kwargs): """https://docs.djangoproject.com/es/1.10/ref/signals/#post-save""" if raw: # Return if loading Fixtures return try: with transaction.atomic(using=using): if not should_audit(instance): ...
4016a4fe2d5d85055b721ccc6f67e68583aa0bf6
3,596,537
def find_objects(search_box, image2): """ Identifies objects found in the search region. """ if not search_box['valid']: obj_found = np.array(-1) else: search_area = image2[search_box['x1']:search_box['x2'], search_box['y1']:search_box['y2']] obj_found = ...
15ba23c88f601d913ee1a1d70919c4ad48dc94f9
3,596,538
from typing import Sequence def test_map_reduce() -> None: """Test simple map-reduce.""" def split(a: bytes, b: bytes) -> list[dict[str, int]]: a = a.split() b = b.split() out = [] for ia, ib in zip(a, b): out += [ { "sum": int(i...
c8d81013daa103baf2fde14ecbeb0472423dc427
3,596,539
def constrain(x, low, high): """ Restrict a number to a range Args: x (number): the number to restrict low (number): lower bound high (number): upper bound Raises: Exception if any of the arguments aren't numbers Returns: x clamped to between low and high inclusive ...
5a650a7dc079c207b37169fca393c538349f716e
3,596,540
def attr_dict(cls: type, data: dict): """ Removes keys from the passed dict ``data`` which don't exist on ``cls`` (thus would get rejected as kwargs), then create and return an instance of ``cls``, passing the filtered data as keyword args. Ensures that any keys in your dictionary which don't exist on ...
c764cda2ad772de8b239fe34d39ef3ac92e658e5
3,596,541
import glob def _find_my_yamls(myc_folder, specific_files=None): """Load all .yaml files in a folder or a specific list of yaml files.""" selected_files = [] if specific_files: yaml_list = specific_files.replace(" ", "").split(",") all_files = [myc_folder + yaml for yaml in yaml_list] ...
badb9f2165470516c7dd9c5ba2a7e7c1c76d7913
3,596,542
def _build_portfolio_from_df(data, pf_allocation=None, datacolumns=["Adj. Close"]): """Returns a portfolio based on input in form of ``pandas.DataFrame``. :Input: :data: A ``pandas.DataFrame`` which contains prices of the stocks listed in pf_allocation :pf_allocation: (optional) ``pandas.Dat...
f07061f4eaf0ca1321f78449dd9de54c1103ec56
3,596,543
def fetch_hgnc(): """Fetch the hgnc genes file from ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt Returns: hgnc_gene_lines(list(str)) """ file_name = "hgnc_complete_set.txt" url = "ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/{0}".format(file_name)...
ccc121c7cd140388ca2fb870c6e2ad40c1c4f3b6
3,596,544
def fitfmin_powell(m, objf, x, y, yerr=None, **kwargs): """ Use scipy's fmin_powell to fit model. """ # Get keywords and default arguments defargs, _ = _introdefarg(sco.fmin_powell, **kwargs) if not yerr is None: defargs["args"] = (x, y, yerr) else: defargs["args"] = (x,...
17f08f7e5fb1f9d8adeae465755fda77af33cc69
3,596,545
def log_track_update(log_track): """count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached """ log_track[LOG_TRACK_COUNT] += 1 if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]: return False log_track[LOG_TRACK_COUNT] = 0 ...
23bf2de13abd3a6cb260467e74174e4334c189ad
3,596,546
from typing import List def sbd_3_bitwise(ids: List): """ Solution: Use bitwise XOR on a single variable for each element. Complexity: Time: O(n) Space: O(1) """ unique_id = 0 for item in ids: unique_id ^= item return unique_id
d964fe78b2d1cf8de9e4d1cc165ea03a38eb6387
3,596,547
def isrseuser(value): """ Return true for users who are RSEs. Value must eb a user. """ try: rse = RSE.objects.get(user=value) return True except ObjectDoesNotExist: return False
13e5f82a461da8aa19d80f9bcb6817b33e384c79
3,596,548
def annual_return(returns, period=DAILY): """ Determines the mean annual growth rate of returns. Parameters ---------- returns : pd.Series Periodic returns of the strategy, noncumulative. - See full explanation in :func:`~pyfolio.timeseries.cum_returns`. period : str, optional ...
2765c4beb5657ed445e812a76f69095492a3394c
3,596,549
def process_spatial(geo): """Process time range so it can be added to the dates metadata Parameters ---------- geo : list [minLon, maxLon, minLat, maxLat] Returns ------- polygon : dict(list(list)) Dictionary following GeoJSON polygon format """ polygon = { "type"...
4ff7dea7d7dcefd5b6bfb1605dd50345fc379527
3,596,550
def compute_leaf_packages(repositories): """ Compute the leaf packages in `repositories`. Leaf packages are packages with no reverse dependencies. Parameters ---------------- repositories : iterable of Repository objects Returns ----------- dependencies : set Set of leaf packag...
3af33eaa6958cadf919624b1a5b313131200a9d1
3,596,551
def split_file(filename, index, mode, number, out_dir="split"): """ :param filename: :param index: :param mode: :param number: :param out_dir: :return: """ r = [] LOG.info("%s process %r" % (index, filename)) prefix, fmt = get_seq_format(filename) if fmt == "fasta": ...
97c760c23b1e634b1de8314ffb701d969d3020c1
3,596,552
def lnprob(theta, data, model_function, priors): """ Computes the posterior log probability. """ lp = lnprior(theta, priors) if not np.isfinite(lp): # if the params are outside the prior range return -inf return -np.inf else: return lp + lnlike(theta, data, mode...
fd324fbe919c66b2138a014e23c168d2d4f4b022
3,596,553
from typing import Dict def collect_mutex_errors(parser, args: Dict[str, Try]): """ RadioGroups / MutuallyExclusiveGroup require extra care. Mutexes are not normal actions. They're not argument targets themselves, they have no `dest`, they're just parse-time containers for arguments. As such, ther...
c5ab6616aca92d51aaf8abc635fd946fc9bcbdf2
3,596,555
def center_opening_enabled(as_of=None): """ The center opening period is from midnight, two days before polling starts, to the end of polling, for in-person elections. (This can be overridden by ENABLE_ALL_TOOLS.) """ return (settings.ENABLE_ALL_TOOLS or Election.objects.get_electio...
6b6c7af0c9d500c4d3aeef9861ce13e2ce6f8374
3,596,556
def musicnet_partial_validation(): """Returns the logs for a partial MusicNet validation (validates a subset of data to save time)""" n_test_inputs = cnf.musicnet_n_test_batches * cnf.batch_size n_trials = 2 # calculate APS avg_prec_scores = [0.0] * n_trials for trial in range(n_trials): ...
33ef0bb813d2cc743794ae83990cedaf53b8554a
3,596,558
def normalized (string) : """Normalize a base32 encoded string.""" return string.upper ().replace ("-", "")
1998b41d9a27c78b5519983a880a1aa573a6e4ea
3,596,560
import pytz from datetime import datetime def now(): """Gets the current datetime (with timezone) as an object.""" timezone_obj = pytz.timezone(config.timezone) return datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(timezone_obj)
3993a7c2867a1a39265564a812cf8223f68076be
3,596,561
def check_number(obj): """ A helper method to check if obj is int, float, np.int64, etc. This is frequently needed, so is helpful. :param obj: the object to check the type :return: bool """ return isinstance(obj, int) or isinstance(obj, float) or isinstance(obj, np.number)
cb6eb009d323d04c601463af2221b151decf1075
3,596,562
def get_constraints(depth_selection, hemisphere_selection): """Get the constraints for loading input data.""" if depth_selection: level_constraint = iris.Constraint(depth=depth_selection) else: level_constraint = iris.Constraint() if hemisphere_selection == 'nh': la...
d7b5309d4e6e55319a717a0dc08fa87a45652d93
3,596,564
def list_bank_cards(account_id): # noqa: E501 """Return all bank cards for an account Return all cards for the specified account # noqa: E501 :param account_id: Id of account :type account_id: str :rtype: List[BankCard] """ return 'do some magic!'
6268d6a3584fa38cda3ae2294daaebb736f695d0
3,596,565
def visualize(l, y, t, dt, save=None): """ Args: l: Pendulum length, CartPole.l y: simulation outputs t: simulation timesteps dt """ a_x1 = y[:, 0] a_y1 = 0.0 a_x2 = l * np.sin(y[:, 2]) + a_x1 a_y2 = -l * np.cos(y[:, 2]) + a_y1 fig = plt.figure() ax ...
478e777435507f05e5ec88289a3e750afb440121
3,596,566
def int32(x): """Force conversion of x to 32-bit signed integer""" x = int(x) maxint = int(2**31-1) minint = int(-2**31) if x > maxint: x = maxint if x < minint: x = minint return x
854338b7fd748ba5ddbbbd8c697288c6331995c4
3,596,567
def evaluate(value, level=1, **kwargs): """Evaluate a value.""" if isinstance(value, BindingAccessor): return value.resolve(**kwargs) elif isinstance(value, dict): if level <= 0: raise ConditionRecursionError("resolve recursion depth exceeded") for operator_name, valu...
0da5552a5c5fbbaf038116c22acf5882b8cbb631
3,596,568
def video_no_found(error): """no such video exists""" return {'message': 'video does not exist'}, 404
ec4b3149e1c8f8c7d02e0ae7926cc41cc7e6ad29
3,596,569
def prepare_response(url, short_link): """ Creates a dictionary containing 1. url requested to be shorten 2. shortened url :param url: string :param short_link: string :return: dict """ if url is None or short_link is None: logger.error('Missing url or short_link.') ...
4d22320be61734ce4be3df5ec8616ec04c907175
3,596,571
import base64 def encrypt_filename(hashed_key, filename): """Encrypts a filename with the given key. @param hashed_key: The encryption key. A binary string that has BS length. See hashkey(). @param filename: A normal (non-binary) string containing a filename of arbitrary length. @retu...
e00701784b274523fa2c8d621d8a760773915f79
3,596,572
def get_type(transaction): """ :return: the type of the transaction """ return transaction['type']
4f66830f7c1e3bdc5d6b2c4ccc5db493014b9e5f
3,596,573
import re def annotateEffects(doc,record): """ Annotate variants effect""" doc['Eff'] = [] effects = record.INFO['EFF'] genes = [] locations = [] eff = {} for e in effects: m = re.search(r"(.*)\((.*)\)",e) if not m.group(1) in eff: eff[m.group(1)] = [] locations.append(m.group(1)) #efect_...
94709864f0738e643e66f24617e16bb9f3427998
3,596,574
def get_entities(soap_client, parent_id, type, start, count, version='8.1.0'): """ Returns an array of requested child objects for a given parent_id value :param soap_client: :param parent_id: :param type: :param start: :param count: :return: """ try: return soap_client....
d045f32e35de2fce5c4ed78a67bb3f0dac9e2ae9
3,596,575
def check(text): """Check the text.""" err = "skunked_terms.misc" msg = u"""'{}' is a bit of a skunked term, impossible to use without issue. Find some other way to say it.""" skunked_terms = [ "bona fides", "deceptively", "decimate", "effete", "fuls...
b11977bb06b94e52cbb2ecd99bad120464cc3cca
3,596,576
def render_page(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, grip_class=None): """ Renders the specified markup text to an HTML page an...
3c76a33527f0b6c746f2dc0ebded04ff7246658c
3,596,577
import six def masked_fully_connected( inputs, num_outputs, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=init_ops.zeros_initializer(), biases_regularizer=None, ...
33aabc3d9c187b9b3b80edac404a9c29dfaf1b42
3,596,578
def find_max_str(smiles: str) -> str: """ General functionality to choose a multi-smiles string, containing the longest string """ smiles = max(smiles.split("."), key=len) return smiles
8b3f495492e471c7aee5fa856745179ecb1e8f8f
3,596,579
from typing import List from typing import Any from typing import Optional import random def _subsample_array( arr: List[Any], max_values: int, can_modify_incoming_array: bool = True, rand: Optional[random.Random] = None, ) -> List[Any]: """Shuffles the array and returns `max_values` number of ele...
379d056fefbc7b4a828a56dd9999545683a46a30
3,596,580
def set_role(): """Set the role using stdin stream. Timeout arg for scan() can be specified using a space delimiter (e.g. 'S 10' calls `scan(10)`) """ user_input = ( input( "*** Enter 'S' to perform scan.\n" "*** Enter 'N' to display noise.\n" "*** Enter 'Q' t...
8dab45da1a45bfafd322bae76012102ff6fb8964
3,596,581
def map_station_id_to_station(station_id,system,session): """ Given a station_id string and a system obj, return a station ORM object with the latest 'created_by' date for that station_id and system """ qry = session.query(Station).join(System).filter(System.name==system.name) qry = qry.fil...
4ad3013dab999f4dba82223fe7c1487799129f88
3,596,583
def svn_stream_copy3(*args): """svn_stream_copy3(svn_stream_t * arg1, svn_stream_t * to, svn_cancel_func_t cancel_func, apr_pool_t pool) -> svn_error_t""" return _core.svn_stream_copy3(*args)
b9c71f46c16faf9e56c9f6bd00c25901f10e89dc
3,596,584
from typing import Tuple def get_worker_range(total: int) -> Tuple[int, int]: """Computes a processing range for a worker from a given total.""" dist_info = info() start = (dist_info.global_rank * total) // dist_info.global_world_size end = ((dist_info.global_rank + 1) * total) // dist_info.global_world_size ...
1fb76d87bcdf60d9cccd245840793250cc7ac9ff
3,596,586
def make_mosaic(data): """Reshape data into a mosaic plot Parameters --------- data : array of shape (dim1, dim2, dim3) input volume Returns ------ mosaic : array mosaic matrix that can be plotted with matshow """ # add extra slices top and bottom to make it div...
8ac40e2d8eb2bee30197f22d9a53c90b3788fa2d
3,596,587
import typing def create_overlapping_timeperiod( timeperiod: spec.Timeperiod, trim_start_relative: typing.SupportsFloat = None, trim_end_relative: typing.SupportsFloat = None, trim_start_absolute: spec.Timelength = None, trim_end_absolute: spec.Timelength = None, extend_start_relative: typing....
b38a95f1ef9e97ce58511babbb454dff8a90f2b5
3,596,588
def compute_std(predictions, reduction='mean', resolution=500): """Compute the standard deviation of the distribution predictions. Args: predictions (distribution): a batch of distribution predictions. reduction (str): the method to aggregate the results across the batch. Can be 'none', 'me...
5026cfcbd1b2396bf3a302ce6e0f6884f41e665e
3,596,589
def dot(a,b, strict=False): """Return the dot product of two 2D masked arrays a and b. Like the generic numpy equivalent, the product sum is over the last dimension of a and the second-to-last dimension of b. If strict is True, masked values are propagated: if a masked value appears in a row or column...
27e32d0e0eb2bd72ad929ce3f8c4da8f68bf1d17
3,596,590
def format_bytes(n): """Format bytes as text Copied from dask to avoid dependency. """ if n > 1e15: return "%0.2f PB" % (n / 1e15) if n > 1e12: return "%0.2f TB" % (n / 1e12) if n > 1e9: return "%0.2f GB" % (n / 1e9) if n > 1e6: return "%0.2f MB" % (n / 1e6)...
f82a135f7f5308a04bf53bd3b8d1a05ef5d96de0
3,596,591
def my_show(imgs, title='mask'): """ show a or a list of body mask Args: imgs: a or a list of SimpleITK images to show title: the title of this visualization Returns: True if no error """ if not isinstance(imgs, list): imgs = [imgs] arrs = [sitk.GetArrayFromImage(im...
13672bc4206eff103ac92fff4e28d7e5b4199070
3,596,592
def add_article_to_collection( article_number: ArticleNumber, collection_id: CollectionID ) -> CatalogArticleID: """Add article to collection.""" collection = db.session.query(DbCollection).get(collection_id) if collection is None: raise ValueError(f'Unknown collection ID "{collection_id}"') ...
19fdb02a8ac164c6165653571f7dd80dd758e5e8
3,596,593
async def submit_pids(pids: dict): """Submit device product number(s) to Cisco Support API""" eox_data = {"data": []} fetched_data = get_eox_from_cisco(pids) key = 0 for record in fetched_data["EOXRecord"]: # If PID is invalid or there is no EOL announced return error # description...
08b396e175596238bbc7932de684232d55ae107f
3,596,595
import math def cos_theta_spatial_func(time, doy, dr, lon, lat): """ Parameters ---------- time doy dr lon lat Returns ------- """ sc = et_common.seasonal_correction_func(doy) delta = et_common.delta_func(doy) omega = et_common.omega_func(et_common.solar_time...
068d85d9aa1679dee8a1a83c36d1361f3505f072
3,596,596
def register_affine(x, y, w, max_it=150, eps=1e-8, callback=None): """ Registers Y to X using the Coherent Point Drift algorithm, in affine fashion. Note: For affine transformation, t = y*b'+1*t'(* is dot). b is any random matrix here. Parameters ---------- x : ndarray The static shape t...
b8fea6f01046601df34e37a25a5d853694f15532
3,596,597
def expmap2euler(seq): """ :param seq: {n x 99} """ n_frames, dim = seq.shape assert dim == 99, 'dim is ' + str(dim) euler = np.copy(seq) for j in range(n_frames): for k in np.arange(0, 97, 3): idx = [k, k+1, k+2] R = expmap2rotmat(seq[j, idx]) eul...
4d3087b82711058271fd736421b5866bacbce64d
3,596,601
def scatter_segment(segment_vec: np.ndarray, segment: np.ndarray) -> np.ndarray: """Scatter segment_vec to each segment. Args: segment_vec: (C, segment_num) segment vector. segment: (H, W) segment mask, each segment has it's unique int label. Returns: (C, H, W) arr scattered from s...
e2ea8ba7268bc1216f4242bef11f74eeef1355c2
3,596,602
def semideviation(r): """ Returns the semi-deviation (Negative Deviation) of r , r must be a Series or DataFrame """ is_negative = r <0 return r [is_negative].std(ddof=0)
78eb4092f2c7ed5439ef4ee44b5ddef898bd53fa
3,596,603
def wildfire_model(a, b, T, N_x, N_t, # constants T_0, S_0, cT_a, dT_a, hT_a, cT_b, dT_b, hT_b, cS_a, dS_a, hS_a, cS_b, dS_b, hS_b, # functions A, B, C1, C2, v): # constants """Returns a solution to the wildfire PDE system. Returns a Crank-Nicolson approximation of ...
9b7a45bc0e903375932bce0293749eb2c8b8b3e4
3,596,604
def calc_svione_st(): """Calculates the ionization cross section using stacey thomas data Args: ne (float): takes ne in m^-3 Te (float): takes Te in keV Returns: svione (float): """ # populate interpolation data eion = np.array([[-2.8523E+01, -2.8523E+01, -2.8523E+01, ...
ec500a7342696946722316b43f99b598e9d6c0ba
3,596,605
def get_query(): """Return this module's Query class.""" return BridgeQuery
d9332806b5c76996fa6bb775327618a9ac9a3a45
3,596,606
def classify_from_iterator(events_iterator, status_fetcher=None): """Like classify(), but process batches of events from an iterator.""" merged = None labels = None comments = None reviewers = None distilled_events = None for events in events_iterator: merged = get_merged(events, me...
984495cf65cf058fb66539d621d27c464723f402
3,596,607
import pyarrow as pa def ST_Touches(geo1, geo2): """ Check whether geometries "touch". "Touch" here means two geometries have common points, and the common points locate only on their boundaries. :type geo1: Series(dtype: object) :param geo1: Geometries in WKB form. :type geo2: Series(dtype:...
8a7c0a30e3d51ec8e21c2fd8e708f877bac16956
3,596,608
def page_archive(): """ shows and old version of a page """ id = request.args(0) h = db.plugin_wiki_page_archive page = h(id) if not page or (not plugin_wiki_editor and (not page.is_public or not page.is_active)): raise HTTP(404) elif page and page.role and not auth.has_membershi...
5366f27ce5a41e76e1eaaceff5d7bfb909d20b4b
3,596,609
from typing import Tuple def calculate_total_size( s3_client, bucket: str, prefix: str, include_folder: bool = False, ) -> Tuple[int, int]: """ Perform the "Calculate Total Size" action in AWS S3 console. :param s3_client: ``boto3.session.Session().client("s3")`` object :param bucket:...
c9a02782a911f3199cb80900ae126a46f748e356
3,596,610
def front_matter(r): """ Output Jekyll front matter to md string """ md = "---\n" + FRONT_LAYOUT + "\n" # Folded Title: https://talk.jekyllrb.com/t/ # how-to-use-single-quote-and-double-quote-as-part-of-title-without-escaping/2705/9 md += FRONT_TITLE + ">\n " + r[TITLE] + '\n' if FRONT_S...
52420678bb86940dfd188122e8745bd12e3d105c
3,596,611
def compute_several_statistics(X, Args): """ A function to compute and stack the results of several statistics on data X. Inputs: * X = the data * Args = list constitued of statistics_list and statistics_args Outputs: * a list correspond to the value of each stati...
7cefa8a25ef22e85271a56339cfb43b796c74933
3,596,613
def barycentricCoordinates(p,p1,p2,p3): """ Returns the barycentric coordinates of points, given the triangles where they belong. For more information on barycentric coordinates, see `Wikipedia <http://en.wikipedia.org/wiki/Barycentric_coordinate_system>`_ Assumes:: 1) points are...
6b94b1e1492961552d7b2eadaa24b2764aaf9aac
3,596,614
def _data_bin(biomfile, taxnum, key): """ While the BIOM file collapse function collapses counts, it stores taxonomy in a manner that is not compatible with the OTU taxonomy; taxonomy is stored as observation ID and not as observation metadata. Here, new observation IDs are generated for agglomerate...
944aae97a0c1c092e3a8790a6a263206ca13a9c1
3,596,615
def cache_gather_beams(nested: PyTreeDef, beam_indices: jnp.ndarray, batch_size: int, old_beam_size: int, new_beam_size: int, one_hot: bool = True, offset: int = 0) -> jnp.ndarray: ...
10e1e383cfd63c74aac3c0711e047d8a88d10f28
3,596,617
def get_dataframe_of_T_for_each_loadsource_aggregating_all_lrsegs(mdl): """ Total Acres Available for each Load Source Args: mdl: Returns: pd.DataFrame """ my_component = mdl.alpha compsets = get_list_of_index_sets(my_component) d = [] for k, v in my_component.items()...
5991c57fdb118218822437b3bd3ebee01e8464d1
3,596,618
def preprocess_df(df, sep='|'): """Combines first_stage_processing and second_stage_processing into an end-to-end processing of a raw dataframe. """ first_stage_df = first_stage_processing(df, sep) return second_stage_processing(first_stage_df, sep)
7e3d31b76342f30183066946f76c84aed354f8e0
3,596,619
def get_preprocessor(name): """Get the preprocessor function specified by the name given. Args: name (str): name of preprocessor function to be called. Returns: (callable): preprocessor function. """ name = name.lower() if name == 'mel': return mel raise ValueErr...
d4273b153f90266cd6d60c94520ece32685a1983
3,596,620
def mcnemar_test(df1, df2, uid_key, prediction_key, true_label_key, verbose=True): """Runs McNemar test for signficance of difference of models' accuracy. See: https://en.wikipedia.org/wiki/McNemar%27s_test Args: df1: a Dat...
598fe6c6937d05a0deecc326077926f37f8163cf
3,596,621
def generate_xray_event_consumer(unformatted: bool = False) -> ObservabilityEventConsumer: """ Generates consumer instance with the given variables. If unformatted is True, then it will return consumer with formatters for just JSON. If not, it will return console consumer """ if unformatted: ...
efcc9e4751c78001dd6e3cbb32173e868417df46
3,596,622
def npm_install(name, **kwargs): """ Sanitizes the given name and creates a sanitized external target using the `_npm_install` rule. """ external = _external_name(name) rename = False from_pkg = kwargs.pop("from_package", None) pkg_name = name if from_pkg: pkg_name = from_pkg...
7605661ddf7179e0a490161227edaa1f8043bca1
3,596,623
import time def before_train(loaded_train_model, train_model, train_sess, global_step, hparams, log_f): """Misc tasks to do before training.""" stats = init_stats() info = {"train_ppl": 0.0, "speed": 0.0, "avg_step_time": 0.0, "avg_grad_norm": 0.0, "avg...
c447223824c781d11429b800c1c04cb86574b3ab
3,596,625
def minimum(left: ValueOrExpression, right: ValueOrExpression) -> BinaryExpression: """ Constructs a minimum expression. """ return ArithmeticBinary( operators.ArithmeticBinaryOperator.MIN, ensure_expr(left), ensure_expr(right) )
fa9754ae79d98635a1415a3733ba31243bb87d28
3,596,626
def get_processed_model(model, parameters): """returns model containing paths of target geometry for each face""" output_model = make_blank_model(model['attrib']) # output_model['attrib'] = model['attrib'] original_model = get_original_model(model) processed_model = process_joints( origina...
5b8565506ba9e9af1552ba649f83421c01326e0e
3,596,627
def first_in_set(seq, items): """Returns first occurrence of any of items in seq, or None.""" for s in seq: if s in items: return s
9dde480508172723d227434a79487291d352ee8d
3,596,628