content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def GetBotsUser(user): """Finds and return BotsUser. Args: user: Currently signed in GAIA user (UserProperty). Raises: TypeError: If required parameter is missing. Returns: Matching existing bots user (first user in case of more than one matching), else None. """ if not u...
463bb0301af137d3ca212a8c627667fa5d11aa08
75,051
def show_scene( sources, observation=None, norm=None, channel_map=None, show_observed=False, show_rendered=False, show_residual=False, label_sources=True, figsize=None, linear=True, ): """Plot all sources to recreate the scence. The functions provides a fast way of evalua...
0595d7116d17c366e081e5e706a506233fb60390
75,052
import math import fnmatch def sentiment(text): """ Returns a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ wordsAndEmoticons = str(text).split() #doesn't separate words from adjacent punctuation (keeps emoticon...
c0b415189cf8cf948dd1ea727ca8048875752f32
75,054
def get_all_objs(content, vimtype): """ Returns object from vCenter. :param content: :param vimtype: :return: """ obj = {} container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for managed_object_ref in container.view: obj.update({m...
0582c08bf8862039df0be743566d780830b412e0
75,055
def rotate_unit(shift: int, unit: str) -> str: """Rotates a unit of text using the given shift.""" # Case where unit is a lowercase letter. lower_index = lowercase2index.get(unit, None) if lower_index is not None: return ascii_lowercase[(lower_index + shift) % 26] # Case where unit is an upp...
182c4203967bc3d21d942b97f0ac9f259c8844ac
75,056
import time def run_minimize(obs={}, model=None, sps=None, noise=None, lnprobfn=lnprobfn, min_method='lm', min_opts={}, nmin=1, pool=None, **kwargs): """Run a minimization """ initial = model.theta.copy() lsq = ['lm'] scalar = ['powell'] # --- Set some options based on m...
8dda8692b74b9260e6e59c6154166874e6ac873f
75,057
from typing import Callable from typing import Coroutine def future_safe( function: Callable[..., Coroutine[_FirstType, _SecondType, _ValueType]], ) -> Callable[..., FutureResultE[_ValueType]]: """ Decorator to convert exception-throwing coroutine to ``FutureResult``. Should be used with care, since ...
ada2b27a341618de25ded7a1adabaf3eca6acd45
75,058
def radians(space, x): """radians(x) -> converts angle x from degrees to radians """ return space.wrap(x * degToRad)
c174260eef3bfd59e6c9b18c22884b5b3f34138e
75,059
def aug_train_fn(image: np.array, mask: np.array) -> DataPair: """Helper function to apply training augmentation. :param mask: :param image: :return: """ input_data = {"image": image, "mask": mask} aug_img, aug_mask = OxfordPetDataset.aug_comp_train(**input_data).values() return tf.cast...
4200fc8855927e582d7b4b580f0fe938de90e953
75,060
def bd_read_data(): """ Return X (features) and y (target) data. Returns ------- tuple[numpy.ndarray, numpy.ndarray] """ data = pd.read_csv('/tmp/data_10k.csv', header=None) X = data[['0', '1']].values y = data['2'].values return X, y
0636c6e275cd141087d59856860f853201e8f5f5
75,062
import random def get_networks_to_move(agent_id, max_networks_on_agent): """Get list of networks which should be moved to other DHCP agents :param agent_id: id of agent from which networks should be moved :param max_networks_on_agent: max number of networks which agent should ...
837ca236b88b5ae8d1bbe36dbfc4f7ba033158d4
75,063
def read_segments(name, bound_ids, inset=None): """ Reads segments from Hierarchy pickle. Arguments: """ # read threshold and connectivity pickled_obj = common.read_pickle(file_name=name) if isinstance(pickled_obj, pyto.segmentation.Labels): segments = pickled_obj elif isi...
05b78b813848251b962a6c4e8c60fc4c0ef68bd0
75,064
def is_anonymous_argument(c): """Test if one argument is anonymous (unnamed) In the declaration `void f(int x, int);` the second argument is unnamed """ return c.spelling is None or c.spelling == ''
1b262e4539b89c81dc21eebc585af8a4dfc9d342
75,065
def get_metrics(region): """ Get all metrics in specified region. """ client = cloudwatch.connect_to_region(region) if not client: raise Exception('Failed to connect to region: %s' % region) buf = [] next_token = None while True: if next_token: result = client...
35c014a9c6497aa61e826e089145058bd12b2dfe
75,066
def solve(lines: Lines) -> int: """Solve the problem.""" crabs = parse_input(lines[0]) best_cost = cost(crabs, crabs[0]) for move_to in range(min(crabs), max(crabs) + 1): move_cost = cost(crabs, move_to) if move_cost < best_cost: best = move_to best_cost = move_co...
f0aba2833f890d85b84da4004501922d66a7e396
75,068
def unsplit(t): """ Make a RI from a split RI(5-tuple). """ s = '' if t[0] is not None: s += t[0] s += '://' if t[1] is not None: s += t[1] if t[2] is not None: s += '/' s += t[2] if t[3] is not None: s += '?' s += t[3] if t[4] is not None: s += '#' s += t[4] return s
4ab5e703f98920522b626dd84d3a41805b46248a
75,069
def _parse_from_unicode(unicode_str): """ Parses the string and returns an etree tree """ utf8_parser = etree.XMLParser(encoding='utf-8', \ remove_blank_text=True, \ ns_clean=True) encoded_str = unicode_str.encode('utf-8') retur...
6d742a83b579f34136d53fdc47696c9a0589eda0
75,070
from typing import Set def get_valid_actions(user, company, offer_state: OfferState, roles=None): """ Return a list of valid actions for an user within a job """ if roles is None: roles_ = _get_roles(company, user) else: roles_ = roles actions: Set[str] = set() for role ...
09f3b342d8faca8f3e84bb71480dcc3dc2f92a6a
75,071
from typing import Callable import functools from typing import Optional import asyncio def async_nowait_middleware(middleware_func: Callable) -> Callable: """Execute middlware function asynchronously but don't wait for result Args: middleware_func: Returns: middleware_func """ ...
1c18153ed5aab2c8b65d8d3112ef57de653a0887
75,072
import random def select_greedy_energy(points, num_selected_points, existing_points=None, exponent=None, dist_matrix_function=None, callback=None): """Greedily select a subset according to ...
a8e69efc509e327499a77c78cf0cce93f17948c2
75,073
def _plot_cluster_averages(data, clusters, n, title, xlab = "Time (hour)", ylab = None, ylim_ = None, savename = False, savepath = False, test=False): """ Plot a scatterplot showing the clusters. Parameters ---------- clusters : numpy array ...
753c505ddfc84c945b060fd5bdc0c0fb0e50c2c5
75,074
def bcr(cashflows, i=0) -> float: """ Computes a Benefit-To-Cost ratio for a sequence of cashflows Sums the positive and negative amount of each Cashflow in a sequence of cashflows, then return the absolute quotient of the two as a ratio of benefits to costs. The interest is NOT considered, so thi...
04143bdbdc25fefdcbab02f0f86dce0087cfeb8e
75,075
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, pad_mode='pad', padding=1, has_bias=False)
b9c030c4b1ce97942aa7005b8e3734f998f535ba
75,076
def find_error_file(view, error_line): """Returns the filename that comes just before the given error line region.""" error_files = view.find_by_selector("entity.name.filename.error") if not error_files: return None error_eol = view.line(error_line).end() for i, file_region in enumerate(error_files): ...
30c4781d6f04e090bafa4222c28579c3364c835c
75,077
def get_group_status(sample, group): """Return if a sample is within a group or not.""" within_group = None if group == 'ba': within_group = True if SAMPLES[sample]['is_ba'] == 'True' else False elif group == 'bcg': within_group = True if SAMPLES[sample]['is_bcg'] == 'True' else False ...
b06595ff13a1ff62f30ab9cad76b648210b7fead
75,078
from typing import List from typing import Optional def pad_sequence( sequence: List[int], maxlen: int, value: Optional[int] = None, padding: str = 'post' ) -> List[int]: """ Pad sequence with given value like keras.preprocessing,sequence.pad_sequence. Args: sequence: Sequence to pad ...
30aeea8922af4796ee3a76b8801034dda8b57948
75,079
def getPrinter(name=None): """ Return a printer with the specified name, creating it if necessary. If no name is specified, return the root printer. """ if name: return Printer.manager.getPrinter(name) else: return print_root
523e4e274a1eb0a9336732e6966a75fad91bb1f2
75,080
def divide_round_up(a, b): """Calculates a / b rounded up to the nearest integer""" if a % b < b / 2: return a // b else: return (a // b) + 1
7ec28dfbe05c006e4e2cad340002a39c9b23f4b9
75,081
def get_tasks_route(): """GET /tasks Gets all tasks. Must be an admin. Can specify via request params whether you want just queued tasks or just started tasks. Example requests: * GET /tasks?query=queued * Only gets queued tasks * GET /tasks?query=started * Only get sta...
6ff5b6715da020eeccce0bfae04a7b1861e6994b
75,082
def get_transfer_rates(centre, neighbour_indexes, system, exciton_index): """ :param centre: Index of the studies excited molecule :param neighbour_indexes: neighbour indexes list :param system: Dictionary with the list of molecules and additional physical information :param exciton_index :retur...
d4d2d5bf60e8202b51b3076969a0c5ced12a972e
75,083
from typing import Dict from typing import List def get_cassandra_tables(credentials: Credentials, subscription_id: str, keyspace: Dict) -> List[Dict]: """ Returns the list of tables in a Cassandra Keyspace. """ try: client = get_client(credentials, subscription_id) cassandra_tables = ...
d61116ebee30ef19f914f69503d03c49b8e3ab02
75,084
from typing import Dict from typing import Type from pydantic import BaseModel # noqa: E0611 def build_model_from_params(signature: Dict[str, Parameter]) -> Type[BaseModel]: """ Build a validation model from the method parameters """ params = {} for key, param in signature.items(): if key...
b28fd85f18d1da92522252f5f6bf95142380d690
75,085
def process_samples(samples, proj_mask=ProjMask(xz=True,yz=True,xy=True), proj_zoom=ProjZoom(xz=[1.0, 1.0],yz=[1.0, 1.0],xy=[1.0, 1.0]), scale=False): """ Prepare samples for training or predictions. Get projections of interest, zoom them to fit a radar arena then scale and flatten. Note zoom is usual...
d62dbbe7b5d6485f88bd635d506429560e55f029
75,089
async def get_commons(): """ Returns a list of all registered commons :return: """ return await datastore.get_commons()
baecb12d9126a338df65d68624eaea65fed48562
75,091
def validate_number(number, min_number=1, max_number=None): """Validate the given 1-based page number.""" try: if isinstance(number, float) and not number.is_integer(): raise ValueError number = int(number) except (TypeError, ValueError): raise serializers.ValidationError...
39162d36596c9ccc53867eafb9a4445dd87a163c
75,092
import yaml def parse_yaml(file): """ Parse yaml file and return a dictionary :param file: yaml file to be parsed """ with open(file, 'r') as stream: return yaml.load(stream)
36f26597740e25b118566fd5e8ef95a9a685cb4b
75,093
import six from datetime import datetime def to_date(value, ctx): """ Tries conversion of any value to a date """ if isinstance(value, six.string_types): temporal = ctx.get_date_parser().auto(value) if temporal is not None: return to_date(temporal, ctx) elif type(value)...
8f0a6af60b880a30438d19778782aa2dc11d9ac2
75,094
def mcqa_ranking_I(psi, pci): """ :param psi: :param pci: :return: """ pri_psi = np.subtract(1, psi) pri_pci = np.subtract(1, pci) pri = np.add(pri_psi, pri_pci) return pri
a1b09d9cad7174177a0c31c71bae45d0d07a91d6
75,095
def _nest_stack(list_of_nests, axis=0): """Convert a list of nests to a nest of stacked lists.""" return tree.map_structure(lambda *ts: tf.stack(ts, axis=axis), *list_of_nests)
ad8bd50b1ea31c0bb77c11845575468475ea2cd0
75,099
def conv3x3_block(in_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, use_bias=False, use_bn=True, bn_eps=1e-5, activation=(lambda: F.relu)): ...
626c8b1650bf56016c34c1a051639f7d57c9f4f6
75,100
def setup_controller(robot, gait="fast_trot", run_on_robot=False, use_ground_truth_velocity=False): """Demonstrates how to create a locomotion controller. Args: robot: A robot instance. gait: The type of gait to use. run_on_robot: Whether t...
14f88836732e2e9b59526f178833f677f3c12822
75,101
import csv def map_sites(sample, settings): """Map insertions to nucleotide sites.""" # Placeholder for dictionary of mapped reads in format: # {(contig, position) : [left_counts, right_counts]} map_dict = {} # overall_total = denominator for cpm calculation overall_total = 0 bowtie_file =...
7f612a527aee2f914be151219933877c6902011a
75,102
import torch def roc_auc(data_loader, model): """Accuracy over all mini-batches. """ training = model.training model.eval() y_true, y_score = [], [] with torch.no_grad(): for data, target in data_loader: data, target = data.to(device), target.to(device) output =...
3e2db26fb0215da6c9ae1c285b223c5e853a264c
75,104
def permute_si_snr(xlist, slist, align=False): """ Compute Si-SNR between N pairs Arguments: x: list[vector], enhanced/separated signal s: list[vector], reference signal (ground truth) """ def si_snr_avg(xlist, slist): return sum([si_snr(x, s) for x, s in zip(xlist, slist)])...
40e843a63078c1b3f0705897e4dd9e103e576664
75,105
from pathlib import Path import logging import transformers import datasets def get_overwatch(path: Path, level: int, local_rank: int = 0) -> logging.Logger: """ Initialize logging.Logger with the appropriate name, console, and file handlers. :param path: Path for writing log file --> should be identical...
bdfa6e526f3a2043734c074011d0805de367857b
75,106
def routing_costs(sol: Solution) -> np.ndarray: """ Computes routing costs for each customer, as the cost made currently for having a customer in a route, against the alternative of not having said customer in the route: e.g., for customer [2] this compares the hypothetical route [1] -> [2] -> [3] w...
e26d3ab0f0084b5c9829bbc008cf145ba9031f1f
75,107
def make_eval_function(eval_on, height, width, progress_bar, plot_dir, num_plots): """Build an evaluation function for uflow. Args: eval_on: string of the format 'format0:path0;format1:path1', e.g. 'kitti:/usr/local/home/...'. height: int, the height to which the images should...
8455dc68c238cd1e122f7c5fe6fae98706596fa6
75,108
def distance(xyz, lattice, PBC=[1,1,1]): """ Returns the Euclidean distance from the origin for a fractional displacement vector. Takes into account the lattice metric and periodic boundary conditions, including up to one non-periodic axis. Args: xyz: a fractional 3d displacement vector...
589d6162006e1a7a0f2a431224e2cd10c5ebed3c
75,109
def attr_strict_float_on_setattr( instance: ParameterGroup, # pylint: disable=unused-argument attribute: Attribute, value: float, ) -> float: """ Validate that the value set for an attribute is a float, or a number that can be converted to a float :param instance: ParameterGroup to which t...
a50ac749e148dee0948ee316ab3151256d176522
75,110
def univcrest(): """Returns a constant, the University College Crest number (1249 digits long - year of founding)""" crest = """11111111111111111111111188111111111111111111111111 11111111111111111111881888818811111111111111111111 11111111111111111111118888881111111111111111111111 1111188...
9c397c666b211fcfd741bc1df49cc9c0726da2e9
75,111
def residual_unit_v3(data, num_filter, stride, dim_match, name, **kwargs): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filt...
5756a05e51fb16f52572701cc8de6d313559af7b
75,112
def get_open_descriptions(get_open, initial_state, current_state): """ Get all 'open' descriptions from the current state (if any). Parameters ---------- get_open: function Function that gets the drawer or the door which is opened. initial_state: nd.array Initial state of the env...
cc4abab0cbfc8cb38db7cb46003ec6e80b1df634
75,113
from typing import Optional import logging import requests def get_historical_options( ticker: str, expiry: str, strike: float, put: bool, chain_id: Optional[str] ) -> pd.DataFrame: """ Gets historical option pricing. This inputs either ticker, expiration, strike or the OCC chain ID and processes the...
8f9a8e42c0f3026d0ace088b99a9ce54fce05c52
75,114
def parse_extended_entities(extended_entities_dict): """Parse media file URL:s form tweet data :extended_entities_dict: :returns: list of media file urls """ urls = [] if "media" in extended_entities_dict.keys(): for item in extended_entities_dict["media"]: # add static i...
9fc1ccdf57ac236f6fbca219bb74c96026dac0c2
75,115
def get_cycle_stats(data_list): """ Calculates cycle statistics for test run. Returns min, max, avg cycle count. """ cycles = [data[0] for data in data_list] min_cycles = min(cycles) max_cycles = max(cycles) avg_cycles = sum(cycles) / len(cycles) return min_cycles, max_cycles, avg_cy...
e8fc1a7b3619ed0f9b63995ded217a4037bdf618
75,116
import scipy def apply_window(image, window_function="tukey", **kwargs): """ Apply window function to image. Parameters ---------- image : numpy.ndarray Image window_function : str Window function to apply. One of 'tukey', 'hann' or any other in `scipy.signal.windows`. kwa...
b5b76c7b3e7d548fead388d3ae44e96095c7515a
75,117
def PCA(eig_val, scaled_data, raster): """Calculate PCA """ pca = decomposition.PCA(n_components=len(eig_val)) dataset = pca.fit_transform(scaled_data) glcm_reshape = dataset.reshape( raster.shape[1], raster.shape[2], dataset.shape[1]) # move the number of bands at the front of the 3d ar...
c0398330b4c65d58832d9c93a41df9da3e8093bf
75,118
def ns_has_i_umlaut(ns: str, gs: str, np: str): """ Checks if the nominative singular has an i-umlaut # >>> ns_has_i_umlaut("ketill", "ketils", "katlar") # True >>> ns_has_i_umlaut("armr", "arms", "armar") False >>> ns_has_i_umlaut("mór", "mós", "móar") False >>> ns_has_i_umlaut("...
3d1e1f00e6f305103b1c32a0f84ab9bc9faee66f
75,120
def name_scope(target): """A decorator to add a tf name scope for a function.""" name = target.__name__ def wrapper(*args, **kwargs): with tf.name_scope(name): return target(*args, **kwargs) return wrapper
aab1b182460b48f32795248e916748e8d4d3e1f4
75,121
import urllib from bs4 import BeautifulSoup def crawl(url): """ Does not execute Javascript which is faster and yields more video_urls per unit of time, and since there are unlimited URL's it makes more sense this way. :param url: :return: BeautifulSoup of the page source """ req = urllib....
89cadfbd9088f2b98cdfdade48c95dd450e19ab5
75,122
def get_int(question): """makes sure user input is an int. quit if "q" """ while True: answer = input_py_2_and_3(question + '\n>>> ') if answer == 'q': raise SystemExit try: output = int(answer) return output except ValueError: prin...
1bbf2f5f22fc3df0d1bbfc168f60aac369546e14
75,123
import requests from datetime import datetime def team_statistics(tbl_name): """Build a URL for the specified year and return team statistics for the specified table on that page. Performance not guaranteed for tables that are not "misc_stats" Args: tbl_name: The name of the table to be returned...
e5b8e10c1d40b124f778f3784ea749a6e69d987f
75,124
def from_hex(h): """ Return the nearest xterm 256 color code from hex input. """ return from_rgb(__hex2rgb(h))
42cdae06fd974f5786baece75f8b52a82e40c9ab
75,125
def should_domain_substitute(path, relative_path, search_regex, unused_patterns): """ Returns True if a path should be domain substituted in the source tree; False otherwise path is the pathlib.Path to the file from the current working directory. relative_path is the pathlib.Path to the file from the s...
c8bd0e2927922a95cf585bb70b70ecf5aec0e6ce
75,126
def is_registry_match(item, pattern): """returns True if the registry matches the given whitelist pattern Unlike in OpenShift, the comparison is done solely on hostname part (excluding the port part) since the latter is much more difficult due to vague definition of port defaulting based on insecure fl...
857d51ef92a40b479c6082236c7e15fea29c490c
75,127
def list_registries(): """ GET /registries :return: """ request_inputs = anchore_engine.apis.do_request_prep(request, default_params={}) user_auth = request_inputs["auth"] method = request_inputs["method"] bodycontent = request_inputs["bodycontent"] params = request_inputs["params"]...
ab0c72fa69ef9332200f886948a8e9fbd78d9b34
75,128
def plot_img( img, *args, fields=("temperature", "pressure1", "energy", "fov"), **kwargs ): """See uspy.plotting.plot_img""" img = imgify(img) return uspy.plotting.plot_img(img, fields=fields, *args, **kwargs)
a8b7ca1668347d9f6d001b3b293a3fafd75b4720
75,129
def LBtoKG(mlb): """ Convertie une masse en lb vers kg note: 1 kg = 2.20462 lb :param mlb: masse [lb] :return mkg: masse [kg] """ mkg = mlb / 2.20462 return mkg
41c4a4a38f4f10b8b1a006ef6da8f9d5f76934fc
75,130
import itertools def expand_alt_section(alt_section, max_expansions=None): """Helper function for refilter_ctm.""" spans = [['']] alt_separator_line = '' for line in alt_section.strip().split('\n'): if '<ALT_BEGIN>' in line: spans.append(['']) elif '<ALT_END>' in line: ...
77ec3e274d5b435994cce2e9e9c289a09c336cc8
75,131
def get_value_from_aligned_membuf(buf, valtype): """Returns the value held in a __gnu_cxx::__aligned_membuf.""" return buf['_M_storage'].address.cast(valtype.pointer()).dereference()
09ff1861e1c6c0a5b484be59572ff12cea01878b
75,132
def rename_columns(df: pd.DataFrame, service: str, config_df: pd.DataFrame) -> pd.DataFrame: """Rename the columns of the dataframe according to the config file Keyword arguments df -- pd.DataFrame of the data set service -- "wf" or "cl" config_df -- mapping of original and new column names ...
82ad87f60d46f2b8f9e9d1a7d9230c3c1f974b5e
75,133
import multiprocessing def model_parallelized(obs, param, ncore=12): """ Compute model for each data points in obs tuple (multiprocess version). """ pool = multiprocessing.Pool(ncore) b = np.array([param] * len(obs)) c = b.reshape(len(obs), 1) d = np.append(obs, c, axis=1) res = pool...
4c65a047181cf9056c681df0eb32ecb11a033d74
75,134
from typing import Concatenate def create_srcnn(wt=None, ht=None, scale=None, c_in = 1, c_out = 1, c_aux=0, f_1 = 64, f_2 = 32, kernels=(9,1,5), output_activity='linear', hidden_activity='elu', loss='mse', optimizer='adam', alpha = 1.0E-5, beta=0.9, dropout_rate=0.1, metrics=[], run_...
ebfd8764c4686cb6375e871c956d6b4fce9bb308
75,135
def compute_mask(cpu): """ Given a CPU number, return a bitmask that can be used in /proc/irq to set the processor affinity for an interrupt. """ return 1<<cpu
a393c663e5426ecde752aa107c97c7c429aa589a
75,136
def admin_update(): """ **Update a User record** """ id = request.form["id"] name = request.form["name"] password = request.form["password"] admin_user = request.form.get("admin_user") if admin_user == "True": admin_user = True else: admin_user = False...
eb7a31f26642edd65ceabbe19e8ad2134deb979f
75,137
import locale def get_os_language(): """Returns the ISO language code of the OS.""" lang, _ = locale.getlocale() return lang[0:2]
be1093e50fb7d6e8672659b5abda5073f07bc285
75,138
import struct def read_bstr(f, encoding=DEFAULT_ENCODING): """ Read byte-prefixed string """ size = struct.unpack("B", f.read(1))[0] if size == 0: return "" bstring = f.read(size) return bstring.decode(encoding)
8ed9178d20f1f8a095a8d342a7dd4194d75198ab
75,139
def get_bpe(model, words): """ Get BPE embeddings. It only works word by word!! Will be slow :param model: bpe model :param words: words :param batch_size: batch size :return: """ # Make batches of words # check word by word first_word = words[0] batch_word_embed = np.mean(mo...
549d5c4dff945d853d8bd7b8ea2f961ac5e694e7
75,140
def _prefix_linear(s, op, false, true): """Apply associative binary operator linearly. @param s: container @param op: operator @param false, true: values if treating `op` as disjunction """ if not s: return false u = s[0] for v in s[1:]: # controlling value ? if ...
85f799e826297c8478bb03c2d4dd26643247a9e1
75,141
def add_modulo(image1, image2): """Add two videos, without clipping the result. At least one of the videos must have mode "1". .. code-block:: python out = ((image1 + image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1...
f32ff151ad1d7322417f9edbee5933d219c7c9ac
75,142
import math def hav(angle:float) -> float: """Return the haversine of an angle (input in radians)""" try: float(angle) except TypeError: raise Exception("Input to hav must be numeric, received " + angle) else: return math.sin(angle/2)**2
e6d4f5d0d791209cdb8f02a1f0f6ce1f90557fee
75,143
import six def get_display(spec): """Convert a display specification (such as :0) into an actual Display object. Pyglet only supports multiple Displays on Linux. """ if spec is None: return None elif isinstance(spec, six.string_types): return pyglet.canvas.Display(spec) els...
57a244abdb7ba86ee609056691610da0c5017317
75,144
def decode_string(val: bytes) -> str: """Decodes a possibly null terminated byte sequence to a string using ASCII and strips whitespace.""" return val.partition(b'\x00')[0].decode('ascii').strip()
1e963040a41ae16ba1bb7750ecf17b5e5cdb680f
75,146
import avalon.schema from avalon.maya.pipeline import parse_container def get_contained_containers(container): """Get the Avalon containers in this container Args: container (dict): The container dict. Returns: list: A list of member container dictionaries. """ # Get avalon co...
ac19c12de8d25a8a057aadd3e49bb3081f8caf29
75,147
def product_id_attrs(obj): """A ``choice_attrs`` function to label each item with its product ID.""" return {"data-product-id": obj.product.id}
89a710104bdc907fcfecfc6359469986a7649989
75,148
def hkl2twotheta(hkl, UVstar, energy_kev=17.794): """ Calcualte d-spacing from hkl reflection :param hkl: [nx3] array of reflections :param UV: [3x3] array of unit cell vectors :param energy_kev: float energy in keV :return: [nx1] array of d-spacing in A """ q = np.dot(hkl, UVstar) q...
25ff35ada49569ad99f3984c8c999d313882a89c
75,149
def get_url(username, group, email): """ Create presigned URL to allow job to upload output data """ app.logger.info('%s GetJobUploadURL user:%s group:%s' % (get_remote_addr(request), username, group)) if app.config['ENABLE_DATA'] != 'True': return func_disabled() backend = ProminenceB...
42bc8fe4798c1fbdf6e9d16a5df9f85770f7d249
75,151
import logging def setup_platform(hass, config, add_devices, discovery_info=None): """Store add_devices for the light components.""" if discovery_info is None or 'qsusb_id' not in discovery_info: logging.getLogger(__name__).error( 'Configure main Qwikswitch component') return False...
ae69c8d34624932dfff652c3238b2dcb48f5c921
75,152
import re def bqtk_default_context(request) -> str: """Generate unique id by using pytest nodeid. Args: request: pytest fixture which provide tests context info. Returns: str: unique id matching big query name constraints """ invalid_bq_chars = re.compile('([^a-zA-Z0-9_]+)') ...
5f486f625ae0ff2670dd457a25043ad61193af90
75,153
def profile_memory(run_metadata, prefix_name="", visualize=True): """Return dictionary of memory usage (bytes) for each device.""" dev_stats = run_metadata.step_stats.dev_stats results = [] for dev_stat in dev_stats: res = _peak_from_nodestats(dev_stat.node_stats, dev_stat.dev...
f38b68f15baa2fe536fb99193b22e89adea3573d
75,154
def outputs_or_raise(element: Element) -> Outputs: """Get outputs from xml element.""" return Outputs( output1=element_text_or_raise(element, "output1").lower() == "on", output2=element_text_or_raise(element, "output2").lower() == "on", output3=element_text_or_raise(element, "output3").l...
0f2139543c9fc94f1ce9e98bd23001dc83d088de
75,155
def add(a,b,c): """ Through introspection add two vsipl objects. add(a,b,c) adds a to b elementwise returning the answer in c. Unlike VSIPL this add will return c as a convenience. note not every combination is supported. Currently supported are vsip_vadd_f, vsip_vadd_d, vsip...
346dafb921ca6d02ed474192f54d7a241523d596
75,156
def extractPositionsFromOEMol(oemol): """Get the positions from an OEMol and return in a position array with units via simtk.unit, i.e. foramtted for OpenMM. Adapted from choderalab/openmoltools test function extractPositionsFromOEMOL Arguments: ---------- oemol : OEMol OpenEye molecule ...
92122b2065b4a27fb38367e17c2fb1e55d122f00
75,157
from pathlib import Path import gzip import pickle def load_bandit_data(fp=Path('./data/'), fn='Bandit_1.pickle'): """" Returns: x(np.ndarray): context like sequence of images, shape would be (#samples, #timesteps, #features) y(np.ndarray): ground-truth label for the context x, one-hot encode...
745440842666072dab6f4365d7b44603d3675f00
75,158
def power(x, p): """ Return x to the power p, (x**p). If `x` contains negative values, the output is converted to the complex domain. Parameters ---------- x : array_like The input value(s). p : array_like of ints The power(s) to which `x` is raised. If `x` contains mul...
4ff96e69c520ddb1576437a73bba44c42110b448
75,159
def post_augment_chunk(data_list): """ perform fast augmentation that can be applied directly to the chunks in realtime. """ chunk_size = data_list[0].shape[0] rotations = np.random.randint(0, 4, chunk_size) flip_h = np.random.randint(0, 2, chunk_size).astype('bool') flip_v = np.random.rand...
e3af6ff807b4e073ec74a62a60d277a9258fbdc9
75,160
def make_sed_fast(sfh_tuple, metval, dustval, zval, filcurves, igmval = True, return_lam = False, sp = mocksp, cosmology = cosmo): """Generate and multiply a spectrum with previously generated filter transmission curves to get SED. ---WARNING: assumes filcurves have been generated at the correct zv...
ae769c3ca115f2d790dd091022d76768bb97dc33
75,161
def generateMS_by_score_file(score_info_object): """ every object has an mz array every object has an diff array """ ms = MasterSpectrum() delta_func = calculate_Delta_by_ppm(20) dPeaks_matched = 0 for m, diff in zip(score_info_object['mz'], score_info_object['diff']): p = Peak(...
716487545a99e5ad2e7f5db7a293fb5512b1f5fc
75,162
def sort_list(this_list): """ Lamda Function sorts pairs in list by 2nd-part (Shannon Entropy). """ # Sort the domain tuples (Entropy, FQDN) pairs high entropy items. # Return SORTED LIST return sorted(this_list, key = lambda pairs: pairs[0])
75f4def632b330c392f7a4f4db416262585c432b
75,163
def logprob_alpha(alpha,counts): """ beta assumed = 0 """ assert alpha > 0 K, T = len(counts), sum(counts) # tables, customers logP = gammaln(alpha) + K*np.log(alpha) - gammaln(alpha+T) \ + sum(gammaln(counts)) return logP
81ba987f96e26f0c0e97ef3fd3df9bc75f1b7991
75,165