content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def jump_instruction(args: list, register_copy: dict): """ "jnz x y" - Jumps to an instruction y steps away (positive means forward, negative means backward), but only if x (a constant or a register) is not zero :param args: Array of arguments passed into this command. :param register_copy: Dict wit...
32e855bedc59cd7dbc3bc9de1be6ebfa979abc24
3,605,827
def pop(the_stack): """ Returns top of stack if stack not empty. Otherwise, returns None """ if is_empty(the_stack): return None else: item = the_stack[len(the_stack) - 1] del the_stack[len(the_stack) - 1] return item
e64b274e7f828e88eb852e96ba8ec29ae8351767
3,605,828
def build_weighted_graph(G, alpha=0.9, p_null=None): """using log-odds ratio probability weighting to model graph edges. when [p_null] is missing, using a default null model for the weighting: random degree-preserving rewiring approximation.""" W = G > 0 deg = W.sum(axis=1).reshape((1, -1)) M = ...
b51e5aeb6c8214d609b4ffc119394bb1c763e02d
3,605,829
def get_badge(total, colour=DEFAULT_COLOUR): """update total and return shields.io URL Args: total: total coverage (str). colour: badge colour (str). """ percent = quote("%") shields_badge = ( f"https://img.shields.io/badge/Coverage-{total}{percent}-{c...
1f872a12ff3d60847ca9c94248aa8478b12dbefc
3,605,830
import torch def perm(N, seed: int = None): """Generate a tensor with the numbers 0 through N-1 ordered randomly.""" gen = torch.Generator() if seed is not None: gen.manual_seed(seed) perm = torch.normal(torch.zeros(N), torch.ones(N), generator=gen) return torch.argsort(perm)
da12d8783e0aec0bea1d3841c30c554dbaaf3a77
3,605,832
from typing import Union from typing import Callable import torch def pytorch_load( torch_object: Union[Callable, TORCH_RECOVERABLE], path: str, device: torch.device = torch.device("cuda" if torch.cuda.is_available() else "cpu"), ) -> TORCH_RECOVERABLE: """Can instantiate or load on an existing instan...
4e05323192eb15bbf41b8023a986a5ff41814ee0
3,605,833
def lowercase(df): """ lowercase things """ return pd.DataFrame({ "sentence": df.sentence.apply(lambda x: " ".join([i.lower() for i in x.split(" ")])), "label": df.label })
59dfd02de57f57b1272761bd83d5c6971ded0fc9
3,605,834
def summarise_tenant(instance_states): """ Summaries usage of Nova tenant """ core_usages = {} calculator = InstanceScore() for state in instance_states: if state["tenant"] not in core_usages: core_usages[state["tenant"]] = 0 core_usages[state["tenant"]] += calculator.get_sc...
df9a043b5df6cce81eb73d19b42e63e802f4b508
3,605,835
import string def decode(digits, base): """Decode given digits in given base to number in base 10. digits: str -- string representation of number (in given base) base: int -- base of given number return: int -- integer representation of number (in base 10)""" # Handle up to base 36 [0-9a-z] as...
febdf9973a73de5b3686a20b8c2a5738391a815e
3,605,836
import tempfile import codecs def check_vocab(vocab_file, special_vocabs, pad_to_eight): """Check if vocab_file doesn't exist, create from corpus_file.""" global UNK, SOS, EOS, UNK_ID if tf.gfile.Exists(vocab_file): tf.logging.info("# Vocab file %s exists\n" % vocab_file) vocab = [] vocab_size = 0 ...
f2ba4eb1f16097a4e040b9ec232339262895dd66
3,605,837
def sub2ind(subs, shape): """Convert sub indices (i, j, k) into linear indices. Parameters ---------- subs : iterable of array_like List of sub-indices. Its length is the number of dimension. Each element should have the same number of elements and shape. shape : iterable Si...
3f729716361c4b44cfde362536320c7e1894ebbc
3,605,839
from typing import Literal def Tokenize(string, separators): """Tokenizes the given string based on a list of separator strings. This is similar to splitting the string based on separators, except that this function retains the separators. The separators are wrapped in Separator objects and everything else i...
f1a2c2a6f7174024350c64da9e493bda2e52ca15
3,605,840
from apysc._file import module_util from typing import Callable from typing import Any def _get_callable_from_package_path_and_callable_name( *, module_or_class_package_path: str, callable_name: str) -> Callable: """ Get a callable object from a specified package path and callable name. ...
263cc2f677f402889f5878cfdb51100b6f021a10
3,605,841
def interseccion_todas_capas(c, f, lc, l_index, args): """ Return true if exist intesection with other layers, false otherwise. """ uri2 = QgsDataSourceUri() uri2.setConnection(args.server, str(args.port), args.dbname, args.user, args.password) geom = f.geometry() bbox_geom = geom.boundingBox() ...
1f06f60fd33748f254c80e9ce709f0032825f80b
3,605,842
def validinstruction(instruction): """ Check whether the given instruction is valid :param instruction: a cardinal point :return: If the instruction is a valid input """ if instruction in CARDINAL_POINTS: return True return False
4c9668615992a479e6c029fc73360cd4a206d0cd
3,605,843
def read_file(fn, guess_product = True): """ Reads a file with the ICARTT format. https://www-air.larc.nasa.gov/missions/intexna/DataManagement_plan.htm Parameters ---------- fn : TYPE DESCRIPTION. guess_product : TYPE, optional DESCRIPTION. The default is True. Returns...
4fde6bd665093bf4e4f698811fa64018a799fdcc
3,605,844
def generate_phone_numbers(): """Returns example phone numbers.""" return [PhoneNumber(number="0123456789", location="Mobile"), PhoneNumber(number="+490", location="Work"), PhoneNumber(number="", location="")]
733106d534bed56c456c4cc7853472c4fd13bccc
3,605,846
from numpy import linspace def gbox_boundary(gbox, pts_per_side=16): """Return points in pixel space along the perimeter of a GeoBox, or a 2d array. """ H, W = gbox.shape[:2] xx = linspace(0, W, pts_per_side, dtype='float32') yy = linspace(0, H, pts_per_side, dtype='float32') return polygon...
e06176435163694da539cc2f354f64deb8c04734
3,605,847
def get_model_fields(model): """ For a given model, returns all fields with their names """ _fields = [] for key, val in dict(model.__dict__).iteritems(): if issubclass(val.__class__, ModelAttribute): _fields.append((key, val.__class__)) return _fields
e9ce1ab931a5e59624a29f4ef6662c832343a9e5
3,605,848
def map_pixels_to_ascii_chars(image, range_width=25): """Maps each pixel to an ascii char based on the range in which it lies. 0-255 is divided into 11 ranges of 25 pixels each. """ pixels_in_image = list(image.getdata()) pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value...
31d31ecdda9d1479bbe4c4c9091c4c21e60812ee
3,605,849
import re def is_good_photo(photo): """Return True if photo is usable; False if it is a bad photo.""" return all([re.search(pat, photo['img_src']) is None for pat in BAD_PATS])
f5163769483ee0e266fedd730fd9c487b92a6315
3,605,850
def descent_set(t): """ Return the descent set of a standard tableau ``t`` (encoded as a sorted list). The *descent set* of a standard tableau `t` is defined as the set of all entries `i` of `t` such that the number `i+1` appears in a row below `i` in `t`. EXAMPLES:: sage: from sa...
01d91600ab23646ebb471a1b65c137a6e8287183
3,605,851
def softmax_with_cross_entropy(preds, target_index): """ Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output target_index: np array of int, shape is (1) or ...
946c2fa76d6bbab53be311b6062b44a1fdef5810
3,605,852
def evaluate(inputs): """ Evaluates a weighted sum function. $sum = \Sigma_{i=0} (i+1)*x_{i}$ min with replacement = n*(n-1)/2*lb occurs at x_{i} = lb (i.e., lower bound of the discrete variables) max with replacement = n*(n-1)/2*ub occurs at x_{i} = ub (i.e., upper bound of the discrete variables) ...
c09e4c8973d069e46e981a02d09f8754f893f95d
3,605,853
def _boot_time_amiga() -> "float|None": """Returns uptime in seconds or None, on AmigaOS.""" try: return os.stat("RAM:").st_ctime except (NameError, OSError): return None
45ab403609f18321c039f1e112f433fa6366ba8e
3,605,854
from sklearn.ensemble import IsolationForest def run_iforest(X): """ Predict the anomaly score with iForest """ clf = IsolationForest() clf.fit(X) scores = clf.decision_function(X) return scores
56b2ebcd300faca8ef0224f7aacb150e0bf2c133
3,605,856
def get_A1_hom(s, scalarKP=False): """ Builds A1 for the spatial error GM estimation with homoscedasticity as in Drukker et al. [Drukker2011]_ (p. 9). .. math:: A_1 = \{1 + [n^{-1} tr(W'W)]^2\}^{-1} \[W'W - n^{-1} tr(W'W) I\] ... Parameters ---------- s : csr_m...
7c90fde361ceb2fc7349812b8743264e486c7e01
3,605,857
import ctypes def register_node(type_key=None): """register node type Parameters ---------- type_key : str or cls The type key of the node """ node_name = type_key if isinstance(type_key, str) else type_key.__name__ def register(cls): """internal register function""" ...
8105395cc7c19677a04612a3702c6ed1806ca35d
3,605,858
def sort_url_by_query_keys(url): """A helper function which sorts the keys of the query string of a url. For example, an input of '/v2/tasks?sort_key=id&sort_dir=asc&limit=10' returns '/v2/tasks?limit=10&sort_dir=asc&sort_key=id'. This is to prevent non-deterministic ordering of the query stri...
694201c1dc6c5d30df6d589e338e325f538fff47
3,605,859
import pandas def add_measured_to_input(time_df, input_df, measured_df): """adds info of measurement dataframe to time and layer execution dataframe Args: time_df: DataFrame with input layer names as columns, stores runtime input_df: DataFrame with input layes names as columns, stores executi...
e6871ea8693726ffc33f4e52d0875b6489e672ae
3,605,860
def conditional_lateness_plots(rows=None, degrees_sep=1, conds=(0,60,300,600,1200)): """ Plots the (weighted) conditional lateness distribution as F( lateness at stop | lateness at Dth stop previous ) where D = degrees_sep. This is plotted ...
1c434458cbaf61ff83e2117f17898e63a9401271
3,605,861
def sample_rois(rois, gt_boxes, num_classes, rois_per_image, fg_rois_per_image, fg_overlap, box_stds, seg, im_info): """ generate random sample of ROIs comprising foreground and background examples :param rois: [n, 5] (batch_index, x1, y1, x2, y2) :param gt_boxes: [n, 5] (x1, y1, x2, y2, cls) :param...
42920de5251879da80346c603a1690f95c2453c8
3,605,862
import requests from bs4 import BeautifulSoup def get_departures(vazi_od, dan_u_nedelji, linija): """dan_u_nedelji: R - radni, S - subota, N - nedelja""" URL = f'http://gspns.co.rs/red-voznje/ispis-polazaka?rv=rvp&vaziod={vazi_od}&dan={dan_u_nedelji}&linija[]={linija}' r = requests.get(URL) soup = Bea...
986d5c175e5d27896cf68c096f2e7201c2dfa778
3,605,863
def getaccesskeys(show): """ This function is used to get the list of all accesskeys """ try: accesskeys=iam.list_access_keys() except botocore.exceptions.ClientError as e: coloredtext("There was an error while getting access key data: \n\n\n") print(...
52c907385e628638c524ac33f83e38986b081648
3,605,864
def convert_categorical_column(col : ColumnObject) -> pd.Series: """ Convert a categorical column to a Series instance """ ordered, is_dict, mapping = col.describe_categorical if not is_dict: raise NotImplementedError('Non-dictionary categoricals not supported yet') # If you want to che...
30c99adacc32ed8f51b85055494817ae1b58529c
3,605,865
from .RNN.values_arrangement import get_outputs_by_neuron from typing import Union from typing import List def autocorrelation_periodicity(audio_path: Union[str, List[str]], downbeat_model: bool = True) -> float: """ Autocorrelation periodicity pulse clarity metric Args: audio_path: string or lis...
80c4d2203d6261599673a4bff0e851225e906e16
3,605,866
def random_ddm(drift, threshold, ndt, rel_sp=.5, noise_constant=1, dt=0.001, max_rt=10): """Simulates behavior (rt and accuracy) according to the diffusion decision model. In this parametrization, it is assumed that 0 is the lower threshold, and, when rel_sp=1/2, the diffusion process starts halfway throug...
8a3df7d78a617d7ed397810b65522eaf0f5a7681
3,605,867
def flow_camera_motion_loss(gt_masks, camera_motion, depth, flow, camera_intrinsics): """Supervise camera_motion with optical flow. Args: gt_masks: tensor of shape [batch_size, num_boxes, image_height, image_width] camera_motion: tensor of shape [batch_size, 7] depth: tensor of shape [batch_size, image_...
6a3d2eebd2f96fea2025bd6a02fd4dbe6adcf479
3,605,868
import random import string def user_generate_key(id): """Generate new key for user""" user = User.query.get(id) key = Key() key.key = ''.join(random.sample( string.ascii_letters + string.digits, 32 )) key.user_id = user.id db.session.add(key) db.session.commit() flash('Suc...
d20024c036f678cdafe18d27c2437556fe49c8d3
3,605,870
def interp2dxy(field3d, xy, meta=True): """Return a cross section for a three-dimensional field. The returned array will hold the vertical cross section data along the line described by *xy*. This method differs from :meth:`wrf.vertcross` in that it will return all vertical levels found ...
1cda7b44055a61efdcb5a824256e57071d01460a
3,605,871
def calc_prestress(params, calc_eta_func, coords): """Calculate the prestress Calculate -h(eta) * [ C_ijkl(eta) * epsilonT_kl ] Note that C_1211, C_1222, C_2111 and C_2122 are zero. Args: calc_eta_func: function to calculate the phase field coords: the Sfepy coordinate array epsilon...
782ad01fbb1bdba8c399a6543f01481b172516e2
3,605,872
def pass_args(args): """Possible argument to attr_handler()""" return args
5681a5f80c1f01bcae099d4baaf7fb07785c5983
3,605,873
def post_detail(request, id): """ Create a view that return a single Post object based on the post ID and and render it to the 'postdetail.html' template. Or return a 404 error if the post is not found """ post = get_object_or_404(Post, pk=id) post.views += 1 # clock up the number o...
ed806e3061a4fbb9ab28068678341d96b4406b4b
3,605,875
def bin_ip_2_ip(bin_ip): """ convert a binary string of IP to decimal IP in a numpy array :param bin_ip: binary string of an IP :type bin_ip: string :return: a decimal IP address in numpy array :rtype: np.array """ length = int(len(bin_ip) / 8) ip = np.zeros(length, dtype=np.uint8)...
cf9e3543335503ec559426f11ddbd8ce52823201
3,605,876
def gen_rand_params(include=(), cond_dict=None, seed=None): """Returns a dict of DDM parameters with random values. :Optional: include : tuple Which optional parameters include. Can be any combination of: * 'z' (bias, default=0.5) ...
0a044a4b79a452e6d6bb54f3a8765f864a3fe217
3,605,877
def resnet18_ibn_b(**kwargs): """ Constructs a ResNet-18-IBN-b model. """ model = ResNet_IBN(block=BasicBlock_IBN, layers=[2, 2, 2, 2], ibn_cfg=('b', 'b', None, None), **kwargs) return model
3338e7a48fb27e5baca16e750c46f245e062ae4f
3,605,878
def dict_to_tfexample(mol_dict): """Convert dictionary of molecular info to tfExample. Args: mol_dict : dictionary containing molecule info. Returns: example : tf.example containing mol_dict info. """ example = tf.train.Example() feature_map = example.features.feature feature_map[fmap_constants....
e3eb8335b4e5ea12b378b978c941fd960ed334c1
3,605,879
def normalize_pygcn(a): """ normalize adjacency matrix with normalization-trick. This variant is proposed in https://github.com/tkipf/pygcn . Refer https://github.com/tkipf/pygcn/issues/11 for the author's comment. Arguments: a (scipy.sparse.coo_matrix): Unnormalied adjacency matrix Return...
48ab37ae1b5acb8fce97a61449277966dc3d3545
3,605,880
def least_significan_bit(n): """Least significant bit of a number num AND -num = LSB Args: n ([type]): [description] Raises: TypeError: [description] Returns: [type]: [description] """ if type(n) != int: raise TypeError("Number must be Integer.") if...
5fcde70104f885eeb753697fb74d8ec2e7156eae
3,605,881
def filter_contigs(assembler): """Remove junk from the assembled contigs.""" log.info('Saving assembled contigs: iteration {}'.format( assembler.state['iteration'])) blast_db = blast.temp_db_name( assembler.iter_dir(), assembler.state['blast_db']) hits_file = blast.output_file_name( ...
7c7394a093502d0a62aa8f3a7f5925e0e3c5376e
3,605,882
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def moon_agent_filter(app): return MoonAgentKeystoneMiddleware(app, conf) return moon_agent_filter
5abf18ddcb13f54a5872e7596edcf25878670a17
3,605,883
def add(T, w, i=0): """ :param T: trie :param string w: word to be added to T :returns: new trie consisting of w added into T :complexity: O(len(w)) """ if T is None: T = TrieNode() if i == len(w): # 叶子节点 T.isWord = True else: T.s[w[i]] = add(T.s[w[i]], w, i...
c8977bd383572b1accb671199589fc519e3805d1
3,605,884
def make_polar_stereo(attrs_dict, globe): """Handle polar stereographic projection.""" attr_mapping = [('central_longitude', 'straight_vertical_longitude_from_pole'), ('true_scale_latitude', 'standard_parallel'), ('scale_factor', 'scale_factor_at_projection_origin')] ...
dcbb25c24c705c7c9503bcb605a2b74f097613a8
3,605,885
def is_k_anonymous(df,partition,sensitive_column,k =3): """ params df: The dataframe on which to check the partition. partition: The partition of the dataframe to check. sensitive_column: The name of the sensitive column k: The desired k returns True if the partition...
e58ae8f65524c8a9f7b404d391c2b1d3d0b188c2
3,605,886
def normalize_variant(variant: str) -> str: """ Normalize variant. Reformat variant replace colons as separators to underscore. chromosome:position:reference:alternative to chromosome_position_reference_alternative :param variant: string representation of variant :return: reformat...
2dc97b7f7b09add6a8062db94376c1ab030ff07c
3,605,887
from typing import Union from typing import Any from typing import Callable import warnings def add_deactivated_after_edit_handler(parent : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True) -> Union[int, str...
dfc362c55448f7a21df79ab51d944334a0505931
3,605,888
from typing import Tuple def compute_limits( numdata: int, numblocks: int, blocksize: int, blockn: int ) -> Tuple[int, ...]: """Generates the limit of indices corresponding to a specific block. It takes into account the non-exact divisibility of numdata into numblocks letting the last block to take th...
748344d60baa8f2ecd31ce822c0e33aca981bc13
3,605,889
from astropy.utils.data import download_file from astropy.utils.data import download_file def initialise_ephemeris( ephem="DE405", units="TCB", earthfile=None, sunfile=None, timefile=None, ssonly=False, timeonly=False, filenames=False, ): """ Download/read and return solar syst...
5161f22ad433b901ca0c35cadc90288e5e30c7b1
3,605,890
def eval_en_performance(representations: np.array, ): """ entropy of probe representations at output layer and at origin. """ res = drv.entropy_pmf(representations).mean() return res
d940d83d8c2eae0115c0f3300ea3582f85b13d59
3,605,891
def binarized_loss(x, l): """Cross-entropy loss Args: x: B x 1 x H x W floating point ground truth image, [-1, 1] scale l: B x 2 x H x W output of neural network Returns: loss: 0-dimensional NLL loss tensor """ assert l.size(1) == 2 x = _binarized_label(x) # cross_e...
599e830165b8bb6b70725e664f5d5d0586a5554e
3,605,892
import json def getToken(response): """ Get the tokenised card reference from the API response :param response: Response object in JSON :return: String - token """ resp_dict = json.loads(response.text) try: token = resp_dict["token"] except KeyError: print('Retrieval ...
b849f3b021b995b164b99690a82ecabf881bb18b
3,605,893
def _read_transition_statistics_from_files(model, verbose): """Parses the transitions statistics from the simulation output files for later analysis Parameters ------- model : obj object containing all anchor and milestone information Returns --------- total_steps : int total number ...
1a4f326bd628e6ddd9475c9610b92cb2ba564bba
3,605,894
def _extend_to_nparray(item, n): """If item is already list/array return np.array, otherwise extend to length n.""" data = item if isinstance(item, (list, np.ndarray)) else [item for _ in range(n)] return np.asarray(data)
69a344c9df8e8b8dd079e7b72c7cf911e5c7ed6a
3,605,895
def maskData(data): """ - Occasionally, the simulation may crash due to a Riemann solver failure - This is typically fixed by a restart from a checkpoint with a lower courant number - However, the data is still there in the history file - This function masks out incorrect data, by finding areas where "time tr...
2321555a87a959fca63c44cc18be1362e1ddb491
3,605,896
import re def read_urls(filename): """Returns a list of the puzzle urls from the given log file, extracting the hostname from the filename itself. Screens out duplicate urls and returns the urls sorted into increasing order.""" # +++your code here+++ f = open(filename, 'r') paths = re.findall(r'GET (.*...
ff2b9be867c75fd5b5d4e419a58818a319246d21
3,605,897
from typing import List import ipaddress import json def k8s_resolve( runner: Runner, remote_info: RemoteInfo, hosts_or_ips: List[str] ) -> List[str]: """ Resolve a list of host and/or ip addresses inside the cluster using the context, namespace, and remote_info supplied. Note that if any hostname...
545412ef7807a57cc46a4a5403681c7047f9c8a1
3,605,898
def createSubsetGafDict(subset, gafDict): """ Generates a dictionary that maps the subset's Uniprot ACs to the GO IDs, based on the provided gene subset and the gaf dictionary. Parameters ---------- subset : set of str A subset of Uniprot ACs of interest. gafDict : dict of str mappi...
76e69cd79c984a19254df171403c008405276408
3,605,899
def eperm_crim(por, eperm1, eperm2, eperm3=None, sw=None): """Effective electric permittivity after CRIM. Markov et al., 2012, Journal of Applied Geophysics, Eq. 7. Parameters ---------- por: float or array Concentration of constituent 1 (host, wetting phase). eperm1, eperm2, eperm3 :...
4daa8528b8e91ff315ee1ecf49f0f88d219cbb87
3,605,900
def shortest_paths(graph, vertex_key): """Uses Dijkstra's algorithm to find the shortest path from `vertex_key` to all other vertices. If we have no lengths, then each edge has length 1. :return: `(lengths, prevs)` where `lengths` is a dictionary from key to length. A length of -1 means t...
f2ac9abf9292364099748475988d4ee1dbeb4b23
3,605,901
def process_overall_mode_choice(mode_choice_data): """Processing and reorganizing the data in a dataframe ready for plotting Parameters ---------- mode_choice_data: pandas DataFrame From the `modeChoice.csv` input file (located in the output directory of the simulation) Returns ------...
870685017d223f8a277265f80eea56e50eedec90
3,605,902
def loadtemplater(ui, spec, defaults=None, resources=None, cache=None): """Create a templater from either a literal template or loading from a map file""" assert not (spec.tmpl and spec.mapfile) if spec.mapfile: frommapfile = templater.templater.frommapfile return frommapfile(spec.mapfil...
fffc64d1a41486c20c4e61aa4281787730c93cb4
3,605,904
def vgg16(inputs, batch_size=100, num_classes=12, is_training=True, dropout=0.5, weight_decay=0.005, spatial_squeeze=True, scope='vgg_16'): """Oxford Net VGG 16-Layers version D Example. Note: All the fully_connected layers have been transfo...
e70abe98dc581c42526a95deb9f03126b7c3a37f
3,605,905
def print_movie_rating_results(genre_to_rating_map): """Given a dictionary, prints the average IMBD ratings for each year for each genre formatted as: *genre* *space* *release years* : *average IMBD rating* Parameters: genre_to_rating_map: a dictionary that maps genres to r...
d045cce8a6fe2f73ce27327a6f6aabb97473a5d9
3,605,906
def flatten_datasets(rel_datasets): """Take a dictionary of relations, and returns them in tuple format.""" flattened_datasets = [[], [], []] for kind in rel_datasets.keys(): for i in range(0, 3): for rel in rel_datasets[kind][i]: flattened_datasets[i].append([*rel, kind]...
70affa370a98c8328effed0bdb015999c5874913
3,605,907
from typing import Callable def requires_token(func: Callable): """ This annotation protects API calls that require authentication. It will cause them to raise NoAcccessTokenException if the token is not set in the client. :return: Function decorated with the protection """ def wrapper(self...
368b223bc824c394072f1f99a7bb33d19015a545
3,605,908
import torch def log_sum_exp(x, dim=None): """Log-sum-exp trick implementation""" x_max, _ = torch.max(x, dim=dim, keepdim=True) x_log = torch.log(torch.sum(torch.exp(x - x_max), dim=dim, keepdim=True)) return x_log+x_max
45b1f6d198569567d3284bab4116a4703b0589a3
3,605,909
import hashlib def feature(self, node="clickhouse1"): """Check alter user query syntax. ```sql ALTER USER [IF EXISTS] name [ON CLUSTER cluster_name] [RENAME TO new_name] [IDENTIFIED [WITH {PLAINTEXT_PASSWORD|SHA256_PASSWORD|DOUBLE_SHA1_PASSWORD}] BY {'password'|'hash'}] [[ADD|DROP] HOST {LOCA...
d9cde1936c78d9d61ca9a446d5018e51c74c221f
3,605,910
def nb_year(p0, percent, aug, p): """ Finds the amount of years required for the population to reach a desired amount. :param p0: integer of starting population. :param percent: float of percent increase per year. :param aug: integer of new inhabitants. :param p: integer of desired population. ...
054496347fc8bedca3424143d48d122712dd1363
3,605,911
def find_largest_digit(n): """ :param n: the number to be processed and compared with :return: the largest digit in the number """ num = abs(n) initial_largest_digit = num % 10 # set largest digit to the last digit of the number return helper(num, initial_largest_digit)
3f9324ab3676bb29b1d81b2eea13c43fc0d338c0
3,605,912
def compute_overlaps(boxes1, boxes2): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. For better performance, pass the largest set first and the smaller second. """ # Areas of anchors and GT boxes area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - ...
f224ee968a824984e8463ab43e346e6396cf4325
3,605,913
def search_master(request): """Method to query existing customers.""" try: results = [] query_id = int(request.GET.get('id')) query = request.GET.get('q') school_level = request.GET.get('level') # Filters for external ids if query_id == 1: agents = OVCFacility.objects.filter(facility_name__icontains=qu...
30ce02b79a05ec5d37c08f36ea25836fc3ba2b5d
3,605,914
def generate_importance_map(map_size): """ This function generates a weighted map of "where we want the brain to be". It is thus 1 at the center and 0 at the edges. """ importance_map = np.zeros(map_size) for i in range(map_size[0]): for j in range(map_size[1]): for k in rang...
4931dd522cbf8e6cec53edd13a6814d47a5ba8f3
3,605,915
from typing import Optional def change_email_address( user_id: UserID, new_email_address: Optional[str], verified: bool, initiator_id: UserID, *, reason: Optional[str] = None, ) -> UserEmailAddressChanged: """Change the user's e-mail address.""" user = _get_user(user_id) initiator ...
baae07a39055b302bdabaae0df65f0136da6303f
3,605,917
def write_walks_to_disk(args): """ Write random walk into file :param args: arguments for random walk write Returns ------- the name of file containing random walks """ num_walks, walk_length, window_size, num_pairs_required, subsample, file_name, iter_function, seed, __current_graph, __vertex2str =...
dcec7907a8c7986fff6f71469ffdd3b629980138
3,605,918
def tshark_read( device, capture_file, packet_details=False, filter_str=None, timeout=60, rm_file=True, ): """Read the packets via tshark :param device: lan or wan... :type device: Object :param capture_file: Filename in which the packets were captured :type capture_file: St...
8fc31098e750691a1aa7c27a868abf0d6254adec
3,605,919
def light_similarity(conn, entry_ids_1, entry_ids_2, metric, cpu_cores): """ main function :param conn: db_connection :param entry_ids_1: list of entries 1 :param entry_ids_2: list of entries 2 :param cpu_cores: number of cores to be used :param metric: 'lin', 'resnick', 'jc' or 'all' :r...
f5684a3cc96a456cffd18393f760d740c2d394b6
3,605,920
def prepare_window(ds_length, window_name, window_kwargs): """Window needs special preparation as the parameters can be dependent on dataset length. Args: ds_length (int): Length of the dataset. window_name (str): Name of the window module. window_kwargs (dit): Key word arguments from t...
9607cc89227e54b8b477d5fab05ec85d1e3925d1
3,605,921
def resize_image(img): """resize images prior to utilizing in trianing model""" width, height = img.size ratio = width/height new_height = 100 new_width = int(new_height*ratio) img = img.resize((new_width, new_height)) return img
1aa0164e1e25ef0f22e55a15a654fda2dfef5b12
3,605,922
def _filter_calibration(time_field, items, start, stop): """filter calibration data based on time stamp range [ns]""" if len(items) == 0: return [] def timestamp(x): return x[time_field] items = sorted(items, key=timestamp) calibration_items = [x for x in items if start < timestam...
c7575ec85c7da9f1872150a1da3d7b02718df8a0
3,605,923
import torch def phi_inv(D): """ Inverse of the reallification phi""" AB,_ = torch.chunk(D,2,dim=0) A,B = torch.chunk(AB,2,dim=1) return torch.stack([A,B],dim=len(D.shape))
b8198764b89f3f1261e96014697cf1346e1c7d43
3,605,924
def activate_wps(wps, endpoint, name): """ Activate a WebProcessingService object by calling getcapabilities() on it and handle errors appropriately. Args: wps (owslib.wps.WebProcessingService): A owslib.wps.WebProcessingService object. Returns: (owslib.wps.WebProcessingService): Returns a...
d146f22db9d13db17e688bfb404366b9e236dc8c
3,605,927
def make_low_freq(xx, halfperiod=10, halfamplitude=1.): """ make low frequncy signals """ omega = np.pi / halfperiod return halfamplitude * np.sin(omega * xx + np.random.uniform(0, 2*np.pi))
f3ca7ab174f8e9d3b7f06251009820c753622f15
3,605,929
from re import T def tree_weight(pytree: T, weight: float) -> T: """Weights tree leaves by weight.""" return jax.tree_map(lambda l: l * weight, pytree)
b6da802e783632fc3986fa5547fad8ca5994e3a7
3,605,930
def get_sigma_clip(img,sigma=3,iters=100): """ Do sigma clipping on the raw images to improve constrast of target regions. Reference ========= [1] sigma clip http://docs.astropy.org/en/stable/api/astropy.stats.sigma_clip.html """ img_clip = sigma_clip(img, sigma=sigma, iters=ite...
a426fea3caafcb382fb0547145eadbeef0f9d7c8
3,605,931
def Get_foregroundapp(device): """Return the foreground app""" return device.shell("dumpsys activity recents | grep 'Recent #0' | cut -d= -f2 | sed 's| .*||' | cut -d '/' -f1").strip()
236986e3d08f6a4c7dd4cd8c8441806d25e76654
3,605,932
def chunk_size(request): """ Set the chunk size for the source (or None to use the default). """ return request.param
c57269f434790953d475a2791c862d70d204ed86
3,605,934
def finite_diff_hessian_diag(x, grad, epsilon=FINITE_DIFF_EPSILON): """ Approximate the diagonal of the Hessian of a function using finite difference in the partial gradient. :param np.ndarray x: point at which to evaluate derivative :param function grad: function that returns the gradient """ f...
c1670919376ab554d02f4e954c0e6775328bf469
3,605,936
import json def get_new_username(): """Prompt for a new username.""" username = input("What is your name? ") filename = 'Excercise_10_13.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username
e25546247a849aca6dae94728c4318ff10a43434
3,605,937
def densify(*args): """ Make the matrix dense and assign nonzeros to a value. densify(IM x) -> IM densify(DM x) -> DM densify(SX x) -> SX densify(MX x) -> MX """ return _casadi.densify(*args)
122c0f4710ca8b4e6b3274a665caab1ffc568acf
3,605,938
def t0(S, t_r, n): """ t0 = t_r - M_r / n :param S: S angle :type S: float :param t_r: reference time :type t_r: float :param n: mean movement :type n: float :return: t0 :rtype: float """ return t_r - 2 / 3 * np.sqrt(2) / n / np.tan(S)
7534034e64476fcdec3a2585f7716bd8daa26f08
3,605,939