content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def jitterer(out, z): """This function jitters the x axis 1: matrix of layer activations of the form: 2. which layer number to do outputs a transposed matrix of no of neurons rows and no of data columns""" Jx=np.ones(out[z].T.shape) for i in range(out[z].T.shape[0]): 'this is the number...
65b1337e42dab802a0c91bc27d93249171569281
25,100
from typing import Tuple def deconstruct_full_path(filename: str) -> Tuple[str, str]: """ Returns a tuple with the parent folder of the file and the file's name. Parameters ---------- filename : str The path (with filename) that will be deconstructed. Returns ------- Tupl...
d33a8fc71beb39d56dc0aa9bf94264164e8bf1a9
25,101
def bbx_to_world(cords, vehicle): """ Convert bounding box coordinate at vehicle reference to world reference. Parameters ---------- cords : np.ndarray Bounding box coordinates with 8 vertices, shape (8, 4) vehicle : opencda object Opencda ObstacleVehicle. Returns -----...
3d7438beccca9635fc15b266d2e8ada6bbc053c7
25,102
def load_data(): """ Loading data and padding """ training_set, testing_set = imdb.load_data(num_words = 10000) x_train, y_train = training_set x_test, y_test = testing_set x_train_padded = sequence.pad_sequences(x_train, maxlen = 100) x_test_padded = sequence.pad_sequences(x_test, maxlen = 100)...
ca52118f7038a70386e9ca552faf24dac6be9faf
25,103
def rotate_to_calibrated_axis( data: np.ndarray, ref_val_0: complex, ref_val_1: complex ) -> np.ndarray: """ Rotates, normalizes and offsets complex valued data based on calibration points. Parameters ---------- data An array of complex valued data points. ref_val_0 The refe...
82adf83c9565ec56ae6f13e1eec15c1be90f5dc4
25,104
from typing import Optional from typing import Tuple from typing import List def filter_graph_data(df: pd.DataFrame, x_col: str, x_range: Optional[Tuple[int, int]], file_cols: List[str], file_tuple: FileTuple) -> Optional[pd.DataFrame]: """ Filter data relevant for the graph from the dat...
200e19d73ae04c4ceabae6d0d65ccd034f368e15
25,105
def get_question_summary_from_model(question_summary_model): """Returns a domain object for an Oppia question summary given a question summary model. Args: question_summary_model: QuestionSummaryModel. The QuestionSummary model object to fetch corresponding QuestionSummary domain object...
65cce3d4440ebea81f5a777dcdec80c61b06e83b
25,106
from collections import defaultdict def processLine(line): """Process a single line of input, returning a single line of output as a string. Input on stdin is <input path>\t<output fmt>\t<aligner>\t<fiducials>\t<output parameters> where: - <input path> is a local path of the input image to a...
32fbdccf76f43943475551d9bd4816ea851da1f7
25,107
def refraction(alt_degrees, temperature_C, pressure_mbar): """Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon. """ r = 0.016667 / tan((alt_degrees + ...
d413aba8e238b81c5a8076460cc35ae56617f148
25,108
def reduce_mem_usage(df): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024**2 logger.info('Memory usage of dataframe is {:.2f} MB'.format(start_mem)) for col in df.columns: col...
d78e0de83c85bc7495141be428bd54a0b86a2564
25,109
def retry_pattern(): """Retry pattern decorator used when connecting to snowflake """ return backoff.on_exception(backoff.expo, snowflake.connector.errors.OperationalError, max_tries=5, on_backoff=log_backoff_att...
78375f5f634f2826edd9c72fa20e2bb2d760b534
25,110
def get_vrf_route_targets( device, address_family, rt_type, vrf=None, route_distinguisher=None ): """ Get route target value from a device Args: address_family ('str'): address family value rt_type ('str'): route target type ex.) rt_type = 'import' OR ...
d06b40220c8cc5c44c5ef4ab1e7a60057791dda5
25,111
def privGetElevationLocs(locs, dataProvider, dataProviderArgs): """ FIXME """ try: dataProvider = dataProvider.lower() except: pass # NOTE: Neither mapquest, pgRouting, nor OSRM are supported. # FIXME -- None is not allowed if (elevDataProviderDictionary[dataProvider] == 'ors-online'): locsWithA...
43ca4639e1f504d76c65340910ae6b953d9c0d11
25,112
def _format_field(value, parts, conv, spec, want_bytes=False): """Format a replacement field.""" for k, part, _ in parts: if k: if part.isdigit(): value = value[int(part)] else: value = value[part] else: value = getattr(value, p...
d7c7bdf86b3b09800a4147d166584e81d7300c4f
25,113
def mixed_string_list_one_valid(): """Return mixed strings.""" return _MIXED_STRING_LISTS_ONE_VALID_
c1f0ae91f761213a6d7674ec80e24befc0b959a4
25,114
def make_parser(): """Create the argument parser, derived from the general scripts parser.""" parser = get_parser( __doc__, ('A file containing a list of files/file paths to be read. These ' 'should be nxml or txt files.') ) parser.add_argument( dest='output_name', ...
4bb2320708728bbf277bd9de380bdf6b1ead5a8b
25,115
import pathlib def script_names(): """Returns the sequence of example script names.""" result = [str(pathlib.Path(s).with_suffix('.py')) for s in _stem_names()] return result
cdb4ab63718135fa98adbfbe8a1a237f6f5ad031
25,116
def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted).float().cumsum(0) jaccard = 1. - intersection ...
5226660a77d5753346bedaecf786644eda296b74
25,117
def expand_image(_img, block, stride, deform=True): """ Args: _img: numpy array block: size of the blocks required stride: step size Returns: array of blocks """ if deform: _img=_img.astype('float32') ims_Z=np.zeros([_img.shape[0],block[1],block[0]...
0ffbbfe2691be69980a334d1d32f4743dfd79de0
25,118
def disabled(reason='No reason given'): """Decorator that disables a command.""" # pylint:disable=missing-docstring,unused-argument def actual_decorator(func): @wraps(func) def wrapper(*args, **kwargs): raise DisabledCommandException('This command is disabled: %s' % reason) ...
32753d4d58ee11f12eb32acabdb692640b93bab7
25,119
def get_tensor_model_parallel_group(): """Get the tensor model parallel group the caller rank belongs to.""" assert _TENSOR_MODEL_PARALLEL_GROUP is not None, \ 'intra_layer_model parallel group is not initialized' return _TENSOR_MODEL_PARALLEL_GROUP
ecf9e212995f09fe9d6a5482213dba3d1071ba80
25,120
import re import string def normalize(data): """Normalizes the values of incoming data Args: data (dict): Dictionary of response data Returns: dict """ normalized_data = {} for key in data: value = str(data[key]) key = key.lower() # Strip all fields...
ed88050001e6ea65b77d8381b2fd247918ed8f37
25,121
def five_fold(data_set): """[summary] Args: data_set (List of Sample objects): The Samples to be partitioned Returns: fold: where fold is list of len n in n-fold of (train,test) where train and test are lists of Samples """ partition_index = int( len(data_set) / 5 ) s = 0 fol...
d4179c238da3e9ebe05ab3513b80bcce982c8728
25,122
from typing import List import os import requests def _query_trembl(accessions: List[str], format: str) -> str: """Searches TrEMBL server for UniProt entries based on accession. The server to use is set as an environment variable 'TREMBL_SERVER'. Normally this would be the internal TrEMBL server which co...
625f2fdc2054a1ed864e6a3258d00fe33f43787e
25,123
import re def get_english_info(content_section): """ The english source section can have multiple publishers and volume counts. The criteria is that the publisher with the largest volume count is most likely the one we want so sort the lines in the section and grab data from the first line. """ ...
c71751d863a4407fa409b18d7cced44c6044cb10
25,124
import numpy def load_factual_vec(fname, vocab, k): """ Loads 300x1 word vecs from FACTBANK compiled word embeddings """ word_vecs = {} with open(fname, "rb") as f: header = f.readline() vocab_size, layer1_size = map(int, header.split()) binary_len = numpy.dtype('float32'...
f37e030b4b8412a96652e67a673204e13c3cb3dc
25,125
from datetime import datetime def vaccine(date): """ Auxiliary function. Download data about vaccination in Cantabria from the Ministry of Health, Consumer Affairs and Social Welfare. https://www.mscbs.gob.es Args: date(str): Date in format %Y%m%d Returns: DataFrame with vaccination d...
5e3f9ffc3106b76ab637ab23fb6e8e6f487a48f1
25,126
def cache(f): """A decorator to cache results for a given function call. Note: The caching is only done on the first argument, usually "self". """ ret = {} def _Wrapper(*args, **kwargs): self = args[0] if self not in ret: ret[self] = f(*args, **kwargs) return ret...
786218b8c248bcb7c9d519a843dd4542a9b612b0
25,127
def home(): """Return the home page.""" response = flask.render_template( 'index.html', metrics=SUPPORTED_METRICS.keys()) return response, 200
aeb98484b580ceab6f45d7f52e05dda0b97ddb2b
25,128
def data_to_segments_uniform(x, n_segments, segment_ranges=True): """ Split data into segments of equal size (number of observations).""" return split_equal_bins(x, n_segments)
d787bdad8604f4dbf327576f655a9e408b314766
25,129
from pathlib import Path def load_all_sheets(file_name): """ Load from a xls(x) file all its sheets to a pandas.DataFrame as values to sheet_names as keys in a dictionary Parameters ---------- file_name : str, Path file_name to load from Returns ------- dict dictionary...
84452af6d81c7b44c0669af637950e8b1c1dbda8
25,130
from datetime import datetime def rate_limit(limit=1000, interval=60): """Rate limit for API endpoints. If the user has exceeded the limit, then return the response 429. """ def rate_limit_decorator(func): @wraps(func) def wrapper(*args, **kwargs): key: str = f"Limit::{req...
3f609d2bfe4a90fcf822df50e6c81032ad7d0d03
25,131
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 auth_filter(filteredapp): return AuthProtocol(filteredapp, conf) return auth_filter
b4b3b64093998865cf6a1846935c1a10db37b0ea
25,132
def parse(stylesheet): """Parse a stylesheet using tinycss2 and return a StyleSheet instance. :param stylesheet: A string of an existing stylesheet. """ parsed_stylesheet = tinycss2.parse_stylesheet( stylesheet, skip_comments=True, skip_whitespace=True ) css = qstylizer.style.StyleShee...
3df3901c06e861b03746c21a056bae51bb93ebd6
25,133
import unittest def test_suite(): """Returns a test suite of all the tests in this module.""" test_classes = [TestNetCDFPointUtilsConstructor, TestNetCDFPointUtilsFunctions1, TestNetCDFPointUtilsGridFunctions ] suite_list = map(unittest.default...
ebe3b28968def1131be19aedc963263f3277a5fb
25,134
from typing import List def compute_max_cut(n: int, nodes: List[int]) -> int: """Compute (inefficiently) the max cut, exhaustively.""" max_cut = -1000 for bits in helper.bitprod(n): # Collect in/out sets. iset = [] oset = [] for idx, val in enumerate(bits): ise...
30acd71267cd213e559bf43b8296333530736624
25,135
def get_capacity_potential_from_enspreso(tech: str) -> pd.Series: """ Return capacity potential (in GW) per NUTS2 region for a given technology, based on the ENSPRESO dataset. Parameters ---------- tech : str Technology name among 'wind_onshore', 'wind_offshore', 'wind_floating', 'pv_utilit...
4daaf38ca9f54aa162b79682ed981d3ba3ab3167
25,136
import time import urllib import json def use_nearby_search(url, next_page=False, request_count=0): """Call nearby search API request. Parameters ---------- url: str URL to use to send a Nearby Search Request in Google Maps Place Search API next_page: boolean, optional(default=False) ...
f579288356c4330a3af5ec2ac94cf31242669ba8
25,137
import urllib def _GetGoogleAuthtoken(account_type, user, password, service, source): """This function authenticates the user in the specified service using the provided authentication data. Args: account_type: Type of the account to login, could be GOOGLE or any other string if the account is exte...
9852968100d116e27cf50f4b047661ef3135074d
25,138
def trim_filters(response): """Trim the leading and trailing zeros from a 1-D array or sequence, leaving one zero on each side. This is a modified version of numpy.trim_zeros. Parameters ---------- response : 1-D array or sequence Input array. Returns ------- first : int ...
2582c5821bd5c8487c0f9d2f55d2d982767d2669
25,139
def is_spanning(graph, subgraph): """ Return True or False by passing graph and subgraph through function V to check if the subgraph uses all verticies of the original graph Parameters ---------- graph = A networkx graph. subgraph = A networkx subgraph of 'graph'. ...
371388bd6657165451216c4c65c5ea43ef19fed5
25,140
import subprocess def get_commit_msg() -> str: """ Return the last commit message. """ result = subprocess.run( 'git show -s --format=%s'.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) if result.stderr: # no commit yet ret...
aaaf8ff98e7d633cb6b9c116191d1ff9f7b5d754
25,141
from pathlib import Path from typing import List import os def relative_paths(root: Path, paths: list) -> List[str]: """ Normalises paths from incoming configuration and ensures they are all strings relative to root """ result = [] for path in paths: # more hacks for exclusions I'm not...
8193669491bc33b3014f1b44ca7ef4157e760af0
25,142
from re import DEBUG import torch def domain_loss_roi(pred, domain_label): """ ROI-level domain adversarial loss """ if DEBUG: print('\tDA-ROI loss') device_id = pred.get_device() target_label = Variable( torch.FloatTensor(pred.data.size()).fill_(float(domain_l...
fd7cb841840d023b4e86ca2e9daf79fb9c4dc760
25,143
from bs4 import BeautifulSoup import re def clean_text(text): """ A function to pre-process text Parameters ---------- text : string the string to be processed Returns ------- text : string a clean string """ tok = WordPunctTokenizer() pat1 = r'@[A-Za-z0-9]...
dc9d243d4c57ec1ea1af20325be57db536ec4286
25,144
import tqdm import torch def train_one_epoch(dataloader, model, optimizer, device, writer, epoch, cfg): """ Trains the model for one epoch. """ model.train() optimizer.zero_grad() metrics = [] n_batches = len(dataloader) progress = tqdm(dataloader, desc='TRAIN', leave=False) for i, sample...
9bccf2edfa3f87db60c30bfb785ed25d89c6577c
25,145
def test_alias_function(): """Test 4: Generate markup based on an element using an (alias w/function) parameter to explicitly correlate data and elements""" template = get_template('contacts-alias') def alias_name(p, e, k, v): eq_(k, 'name') return 'foo' weld(template('.contact')[0], d...
69275c3e6676ac7b0473676fc7fe65d387edfecd
25,146
def baseurl(request): """ Return a BASE_URL template context for the current request. """ if request.is_secure(): scheme = 'https://' else: scheme = 'http://' return {'BASE_URL': scheme + request.get_host(), }
76f3d75008eb996d1da226dbb4a7bd6e228fbcd1
25,147
import requests def geolocate(address, bounds=None, country=None, administrative_area=None, sensor=False): """ Resolves address using Google Maps API, and performs some massaging to the output result. Provided for convenience, as Uber relies on this heavily, and the desire to give a simple 'batteries incl...
71edf37429aa10420e070d0cacf4e9ade1e6a75f
25,148
def _cmdy_hook_class(cls): """Put hooks into the original class for extending""" # store the functions with the same name # that defined by different plugins # Note that current (most recently added) is not in the stack cls._plugin_stacks = {} def _original(self, fname): """Get the orig...
5653a71aeafc184751edcb8fddecd503c4aa2ee9
25,149
def pair_verify( credentials: HapCredentials, connection: HttpConnection ) -> PairVerifyProcedure: """Return procedure object used for Pair-Verify.""" _LOGGER.debug( "Setting up new AirPlay Pair-Verify procedure with type %s", credentials.type ) if credentials.type == AuthenticationType.Nul...
6269a3f2e14a860cdba15be9e21d3718ceebfe94
25,150
import os def get_file_type_and_ext(filename): """ Return file type and extension if the file can be previewd online, otherwise, return unknown type. """ fileExt = os.path.splitext(filename)[1][1:].lower() if fileExt in get_conf_text_ext(): return (TEXT, fileExt) filetype = FILEEX...
a3e5835ee49c8f8bb966ff26363e4d7ea64ab363
25,151
def load_data( datapath=None, minstorms=3, minbmps=3, combine_nox=True, combine_WB_RP=True, remove_grabs=True, grab_ok_bmps="default", balanced_only=True, fix_PFCs=True, excluded_bmps=None, excluded_params=None, as_dataframe=False, **dc_kwargs ): """Prepare data f...
72c7e6be0eabddeba79c681c5da30e0b855b6496
25,152
import requests import json def sign(request): """ Returns a signed URL (for file upload) and an OTP """ credentials, project_id = auth.default() if credentials.token is None: # Perform a refresh request to populate the access token of the # current credentials. credentials...
8ead2fb48821d7869c42f0173b83358b80e6e712
25,153
def _parse_squeue_state(squeue_out, job_id): """Parse "state" column from squeue output for given job_id Returns state for the *first* job matching job_id. Returns 'u' if `squeue` output is empty or job_id is not found. """ invalid_job_str = "Invalid job id specified" if invalid_job_str in sq...
c3bdb8fa296f670d3f302d9ef9441262ca0da105
25,154
def parser_IBP_Descriptor(data,i,length,end): """\ parser_IBP_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "IBP", "contents" : unparsed_descriptor_contents } (Defined in ISO 13818-1 specif...
12379af2260dd461751c59e2023b7e5e9d68b979
25,155
import logging def build_county_list(state): """ Build the and return the fips list """ state_obj = us.states.lookup(state) logging.info(f"Get fips list for state {state_obj.name}") df_whitelist = load_data.load_whitelist() df_whitelist = df_whitelist[df_whitelist["inference_ok"] == True]...
b11a0b831b7b89d04896ed1914acf993ef1d48ba
25,156
import bs4 def is_comment(obj): """Is comment.""" return isinstance(obj, bs4.Comment)
e56749b3d5f95754a031cc7286229d942333a22e
25,157
from typing import Tuple import sqlite3 def insert_user(username: str) -> Tuple[int, str]: """ Inserts a new user. If the desired username is already taken, appends integers incrementally until an open name is found. :param username: The desired username for the new user. :return A tuple contai...
9eeeb6755251183de5ad775acfceef17c9f582a3
25,158
def get_gateway(ctx, name): """Get the sdk's gateway resource. It will restore sessions if expired. It will read the client and vdc from context and make get_gateway call to VDC for gateway object. """ restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['pr...
998f1a6a600797164c3e053eed206d99d20b338c
25,159
def fn_getdatetime(fn): """Extract datetime from input filename """ dt_list = fn_getdatetime_list(fn) if dt_list: return dt_list[0] else: return None
efea54154d318e0e5ef71c6147057b461696c677
25,160
def greenplum_kill_process(process_id): """ :param process_id: int :return: None """ query = """ select pg_cancel_backend({0}); select pg_terminate_backend({0}); """.format(process_id) return greenplum_read(query)
1bcd362bf2ed3d4cb5773c5539d0e9bb43bc96ab
25,161
import base64 import re def check_app_auth(headers): """Authenticate an application from Authorization HTTP header""" try: auth_header = headers["Authorization"] except KeyError: return False # Only handle HTTP Basic authentication m = re.match("Basic (\w+==)", auth_header) i...
5378f70041294fdad591ffbb941991cb03a7fb3d
25,162
def setupConnection(): """ Create connection to database, to be shared by table classes. The file will be created if it does not exist. """ dbPath = conf.get('db', 'path') conn = builder()(dbPath) return conn
3437cf04622acf32b974b1ecc406daa594d30650
25,163
def max_pool(ip): """does a 2x2 max pool, crops off ends if not divisible by 2 ip is DxHxW op is DxH/2xW/2 """ height = ip.shape[1] - ip.shape[1]%2 width = ip.shape[2] - ip.shape[2]%2 h_max = np.maximum(ip[:,:height:2,:], ip[:,1:height:2,:]) op = np.maximum(h_max[:,:,:width:2], h_max[:,...
c270c4128842e33e69e0861f0010b0903c9728d3
25,164
import torch def get_bin_vals(global_config): """ Creates bin values for grasping widths according to bounds defined in config Arguments: global_config {dict} -- config Returns: tf.constant -- bin value tensor """ bins_bounds = np.array(global_config['DATA']['labels']['offset...
07acdcb0329c1002983ca021fbc84c60f7474758
25,165
def dphi_dop(t, profile, r0_vec, v_vec, d_hat, use_form=False, form_fun=None, interp_table=None): """ Returns the phase shift due to the Doppler delay for subhalos of mass, mass TODO: add use_closest option """ v_mag = np.linalg.norm(v_vec, axis=1) r0_v = np.einsum("ij, ij -> i...
2dfe7fa2257591f60ce5b9041cb3bae85bb69abd
25,166
def calculate_Hubble_flow_velocity_from_cMpc(cMpc, cosmology="Planck15"): """ Calculates the Hubble flow recession velocity from comoving distance Parameters ---------- cMpc : array-like, shape (N, ) The distance in units of comoving megaparsecs. Must be 1D or scalar. cosmology : strin...
823d94faa682f3b5fb123ad00fe2a7d02eedd355
25,167
import itertools def CollapseDictionary(mapping): """ Takes a dictionary mapping prefixes to URIs and removes prefix mappings that begin with _ and there is already a map to their value >>> from rdflib import URIRef >>> a = {'ex': URIRef('http://example.com/')} >>> a['_1'] = a['ex'] ...
9f2befbd52b75b75aa15cadf9e68d5f9eebcae71
25,168
def do_pre_context(PreContextSmToBeReversedList, PreContextSmIdList, dial_db): """Pre-context detecting state machine (backward). --------------------------------------------------------------------------- Micro actions are: pre-context fullfilled_f DropOut --> Begin of 'main' state machine...
d211cf1aac7e103b6d1efe25bfde964578b81950
25,169
from datetime import datetime async def check_user_cooldown(ctx: Context, config: Config, cooldown: dict): """Check if command is on cooldown.""" command = ctx.command.qualified_name last = cooldown[command]["last"] rate = cooldown[command]["rate"] per = cooldown[command]["per"] uses = coold...
649b108def51c9029b17fa6e14eada141d7c5239
25,170
def round_robin(units, sets=None): """ Generates a schedule of "fair" pairings from a list of units """ if len(units) % 2: units.append(None) count = len(units) sets = sets or (count - 1) half = count / 2 schedule = [] for turn in range(sets): pairings = [] ...
f736fe4ce1f0b407f55d4627a7ecc8396943cdd0
25,171
def filter_df(p_df:pd.DataFrame, col_name:str, value, keep:bool=True, period=None): """ Filter a dataframe based on a specific date Parameters : p_df : pandas.DataFrame The original dataframe col_name : str The dataframe column name where the ...
f866ac1df9c436dc65e6a3d1b7eeb02487bba100
25,172
import logging def _VerifyOptions(options): """Verify the passed-in options. Args: options: The parsed options to verify. Returns: Boolean, True if verification passes, False otherwise. """ if options.endpoints_service and not options.openapi_template: logging.error('Please specify openAPI tem...
872feb5ac314ed2ef28ddbfaeff1b5dafc5e9ed8
25,173
def force_delegate(func: _F) -> _F: """ A decorator to allow delegation for the specified method even if cls.delegate = False """ func._force_delegate = True # type: ignore[attr-defined] return func
771159f2baafce044f480ce138596e4a07e89a97
25,174
import binascii def create_signature(key_dict, data): """ <Purpose> Return a signature dictionary of the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': '...'}. The signing process will use the private key in key_dict['keyval']['private'] and 'data' to generate the signa...
1a1e37838679a6912c8dc3d482a8092b1e75056c
25,175
def parse_line(line): """ Parse a queue trace line into a dict """ line = line.split() result = {} if len(line) < 12: return result result["event"] = line[0] result["time"] = float(line[1]) result["from"] = int(line[2]) result["to"] = int(line[3]) result["type"] = line[4]...
432e6a624626e89d27fe6d3d9ed7c4230d97c0a6
25,176
from typing import Dict def gaussian_linear_combination(distributions_and_weights: Dict): """ Computes the PDF of the weighted average of two Gaussian variables. """ assert isinstance(distributions_and_weights, dict) assert all( isinstance(dist, MultivariateNormal) for dist in distribution...
704a1f22392819075e3d9ba0c243c7364baab827
25,177
def check_pattern_startswith_slash(pattern): """ Check that the pattern does not begin with a forward slash. """ regex_pattern = pattern.regex.pattern if regex_pattern.startswith('/') or regex_pattern.startswith('^/'): warning = Warning( "Your URL pattern {} has a regex beginning...
9015f1f8d17297ace5fcef2e2cf0fe2c6dd6e76c
25,178
import subprocess def attack_images(cores, prob_cutoff): """ :param cores: how many cores to use for multiprocessing :param prob_cutoff: user's image belongs to a certain category if the output of the last FC layer of the resnet model for the category > prob_cutoff :return: """ mediaFile =...
609072c6e2deb03207008a4a1e79dfedf50f197d
25,179
def ht(x): """ht(x) Evaluates the heaviside function Args: x: Domain points Returns: ht(x): Heaviside function evaluated over the domain x """ g = np.ones_like(x) for i in range(np.size(x)-1): if x[i] < 0: g[i] = 0 elif x[i] > 0: g[i] =...
b109a72a6fd57e088327cc1fa1d9d70950b1860a
25,180
def xoGkuXokhXpZ(): """Package link to class.""" pkg = Package("pkg") return pkg.circles.simple_class.Foo
500832ece1987a726812350faf72130de65f37a0
25,181
def create_all_pts_within_observation_window(observation_window_hours) -> str: """ create a view of all patients within observation window return the view name """ view_name = f"default.all_pts_{observation_window_hours}_hours" query = f""" CREATE OR REPLACE VIEW {view_name} AS ...
f711ac343815b9adc3b07e833ae8ee31cd07a125
25,182
def get_signature(data, raw_labels): """ Should return a 4 x z* matrix, where z* is the number of classes in the labels matrix. """ labels = raw_labels.reset_index() pca = decomposition.PCA(n_components=2) lle = manifold.LocallyLinearEmbedding(n_components=2) X_pca = pd.DataFr...
eefd7f5e682ad25bb31989d118747691f4cc64f0
25,183
def get_xyz_where(Z, Cond): """ Z and Cond are MxN matrices. Z are data and Cond is a boolean matrix where some condition is satisfied. Return value is x,y,z where x and y are the indices into Z and z are the values of Z at those indices. x,y,z are 1D arrays """ X,Y = np.indices(Z.shape) ...
b1e1b2144e44f292dc6e2c5e917cb7511bdbf288
25,184
def retrieve_seq_length(data): """compute the length of a sequence. 0 are masked. Args: data: input sequence Returns: a `int`, length of the sequence """ with tf.name_scope('GetLength'): used = tf.sign(tf.reduce_max(tf.abs(data), axis=2)) length = tf.reduce_sum(used, axis=1) length = ...
ba6cb7ac9e9cc63311a6194e55b30ffa02fb3bc7
25,185
def get_census_params(variable_ids, county_level=False): """Gets census url params to make an API call. variable_ids: The ids of the variables to request. Automatically includes NAME. county_level: Whether to request at the county level, or the state level.""" keys = variable_ids.copy() key...
b24204c8e9ef82575b54151bdc0ac98de0fb7fc0
25,186
def lookupName(n, names): """Check if name is in list of names Parameters ---------- n : str Name to check names : list List of names to check in Returns ------- bool Flag denoting if name has been found in list (True) or not (False) """ if n in names:...
0fbb97e252f5daf9de52a946c206fa74395b01c6
25,187
def calculate_appointments(new_set, old_set): """ Calculate different appointment types. Used for making useful distinctions in the email message. new_set will be the fresh set of all available appointments at a given interval old_set will the previous appointments variable getting passed in. ...
b54735293ba910e2b310e55e263e2611863d088a
25,188
from typing import Callable import logging def log(func: Callable[..., RT]) -> Callable[..., RT]: """logs entering and exiting functions for debugging.""" logger = logging.getLogger(func.__module__) @wraps(func) def wrapper(*args, **kwargs) -> RT: logger.debug("Entering: %s", func.__name__) ...
a83d691c86f92231bb78affe0e383535f4c3dd95
25,189
def transaksi_hari_ini(): """ used in: app_kasir/statistik.html """ return Transaksi.objects.filter( tanggal_transaksi__year=timezone.now().year, tanggal_transaksi__month=timezone.now().month, tanggal_transaksi__day=timezone.now().day ).count()
a04e835be4cc495b09e1d7ae93ed141315168a81
25,190
def extractWindows(signal, window_size=10, return_window_indices=False): """ Reshape a signal into a series of non-overlapping windows. Parameters ---------- signal : numpy array, shape (num_samples,) window_size : int, optional return_window_indices : bool, optional Returns ------- ...
2d9b319325dc1be9a92766c093db12c2e1f24123
25,191
def add(left: int, right: int): """ add up two numbers. """ print(left + right) return 0
75d7bd10cfdfb38211f6faf838b5e200e8593693
25,192
import argparse def parse_args(): """ Parse command-line arguments """ parser = argparse.ArgumentParser(description='Move retrieval to a ' 'different directory.') parser.add_argument('retrieval_id', help='the id of the retrieval ' 'to move',...
a7f536db32f4bbe8270af976b3e1e058d880a705
25,193
import random def rand_x_digit_num(x): """Return an X digit number, leading_zeroes returns a string, otherwise int.""" return '{0:0{x}d}'.format(random.randint(0, 10**x-1), x=x)
b46864143ca6186ebeede6c687a85d1b585e70db
25,194
def gen_workflow_steps(step_list): """Generates a table of steps for a workflow Assumes step_list is a list of dictionaries with 'task_id' and 'state' """ steps = format_utils.table_factory(field_names=['Steps', 'State']) if step_list: for step in step_list: steps.add_row([step....
d01dc1937dc17e3d8b30390ccd1ea460391a7492
25,195
import os def commonprefix(items): """Get common prefix for completions Return the longest common prefix of a list of strings, but with special treatment of escape characters that might precede commands in IPython, such as %magic functions. Used in tab completion. For a more general function, se...
4a93798b417487ac30dd1ee11936963f538f2d08
25,196
from typing import Union from typing import Any def sround(x: Union[np.ndarray, float, list, tuple], digits: int=1) -> Any: """ 'smart' round to largest `digits` + 1 Args x (float, list, tuple, ndarray) digits (int [1]) number of digits beyond highest Examples >>> sround(0.02123...
a695546c46d4bbd41b481d7b58d879bcd4d53247
25,197
def element_png_display(element, max_frames): """ Used to render elements to PNG if requested in the display formats. """ if 'png' not in Store.display_formats: return None info = process_object(element) if info: IPython.display.display(IPython.display.HTML(info)) return ...
273d19194c467d5596f99626bbe01e53005bee17
25,198
def list_documents(connection, name: str = None, to_dictionary: bool = False, to_dataframe: bool = False, limit: int = None, **filters): """Get all Documents available in the project specified within the `connection` object. Args: connection(object): MicroStrategy connection obje...
383e74177fcc7eefb03ac3aa96ceb232685bb9ac
25,199