content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def deliver_hybrid(): """ Endpoint for submissions intended for dap and legacy systems. POST request requires the submission JSON to be uploaded as "submission", the zipped transformed artifact as "transformed", and the filename passed in the query parameters. """ logger.info('Proc...
87bb05f376c1791668bd5e160cc5940377363f64
3,644,125
def midi_to_chroma(pitch): """Given a midi pitch (e.g. 60 == C), returns its corresponding chroma class value. A == 0, A# == 1, ..., G# == 11 """ return ((pitch % 12) + 3) % 12
25ef72f78269c3f494ca7431f1291891ddea594a
3,644,127
import re def _snippet_items(snippet): """Return all markdown items in the snippet text. For this we expect it the snippet to contain *nothing* but a markdown list. We do not support "indented" list style, only one item per linebreak. Raises SyntaxError if snippet not in proper format (e.g. contains...
bdeb5b5c5e97ef3a8082b7131d46990de02a59af
3,644,128
def get_collection(*args, **kwargs): """ Returns event collection schema :param event_collection: string, the event collection from which schema is to be returned, if left blank will return schema for all collections """ _initialize_client_from_environment() return _client.get_collection(*args,...
95698a5c750b2d40caad0f0ddfe9e17a8354be03
3,644,129
def get_tf_generator(data_source: extr.PymiaDatasource): """Returns a generator that wraps :class:`.PymiaDatasource` for the tensorflow data handling. The returned generator can be used with `tf.data.Dataset.from_generator <https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator>`_ in or...
2b786b111c2e2b17c3ee2887f93aff02de63f369
3,644,130
def is_mechanical_ventilation_heat_recovery_active(bpr, tsd, t): """ Control of activity of heat exchanger of mechanical ventilation system Author: Gabriel Happle Date: APR 2017 :param bpr: Building Properties :type bpr: BuildingPropertiesRow :param tsd: Time series data of buildin...
626e24da9f0676be27e15a4422676034a94e1702
3,644,131
import aiohttp async def fetch_user(user_id): """ Asynchronous function which performs an API call to retrieve a user from their ID """ session = aiohttp.ClientSession() res = await session.get(url=str(f'{MAIN_URL}/api/user/{user_id}'), headers=headers) await sessio...
725c4f7f89efc242948799c48541a25a2bd17d8c
3,644,132
from typing import List import requests from bs4 import BeautifulSoup def category(category: str) -> List[str]: """Get list of emojis in the given category""" emoji_url = f"https://emojipedia.org/{category}" page = requests.get(emoji_url) soup = BeautifulSoup(page.content, 'lxml') symbols: List...
61eaff867e9d9c75582f31435a6c22f3b92fd85a
3,644,133
from typing import Optional def calc_cumulative_bin_metrics( labels: np.ndarray, probability_predictions: np.ndarray, number_bins: int = 10, decimal_points: Optional[int] = 4) -> pd.DataFrame: """Calculates performance metrics for cumulative bins of the predictions. Args: labels: An array of ...
c3574c8e74d5c6fd649ea4258b9a8518811210f6
3,644,134
def rootbeta_cdf(x, alpha, beta_, a, b, bounds=(), root=2.): """ Calculates the cumulative density function of the log-beta distribution, i.e.:: F(z; a, b) = I_z(a, b) where ``z=(ln(x)-ln(a))/(ln(b)-ln(a))`` and ``I_z(a, b)`` is the regularized incomplete beta function. Parameters -------...
e0b951c177f288bc89536494485904e1839af7de
3,644,135
def get_scores(treatment, outcome, prediction, p, scoring_range=(0,1), plot_type='all'): """Calculate AUC scoring metrics. Parameters ---------- treatment : array-like outcome : array-like prediction : array-like p : array-like Treatment policy (probability of treatment for each row...
c59cc98e08cfff6b01eff5c3ff4f74973ababf34
3,644,136
def get_arima_nemo_pipeline(): """ Function return complex pipeline with the following structure arima \ linear nemo | """ node_arima = PrimaryNode('arima') node_nemo = PrimaryNode('exog_ts') node_final = SecondaryNode('linear', nodes_from=[node_arima, node_nemo]) ...
1ae171d29624ecc615f213f343c4a88c733d3554
3,644,137
from typing import Counter import math def conditional_entropy(x, y, nan_strategy=REPLACE, nan_replace_value=DEFAULT_REPLACE_VALUE): """ Calculates the conditional entropy of x given y: S(x|y) Wikipedia: https://en.wikipedia.org/wiki/...
c0a9c943efdd4da1ad2f248ef7eaa2e4b1b7be06
3,644,138
def peaks_in_time(dat, troughs=False): """Find indices of peaks or troughs in data. Parameters ---------- dat : ndarray (dtype='float') vector with the data troughs : bool if True, will return indices of troughs instead of peaks Returns ------- nadarray of i...
acafee26ac6bc236aa68f48fbea5953020faa471
3,644,139
def read_submod_def(line): """Attempt to read SUBMODULE definition line""" submod_match = SUBMOD_REGEX.match(line) if submod_match is None: return None else: parent_name = None name = None trailing_line = line[submod_match.end(0):].split('!')[0] trailing_line = tr...
27ed8d88fdb8fd112b072f50dba00bad783eb9f3
3,644,140
def predict(model, images, labels=None): """Predict. Parameters ---------- model : tf.keras.Model Model used to predict labels. images : List(np.ndarray) Images to classify. labels : List(str) Labels to return. """ if type(images) == list: i...
a6c2261e7fea262fb1372f870ba3096a9faf2a68
3,644,141
import codecs import re def process_span_file(doc, filename): """Reads event annotation from filename, and add to doc :type filename: str :type doc: nlplingo.text.text_theory.Document <Event type="CloseAccount"> CloseAccount 0 230 anchor 181 187 CloseAccount/Source 165 170 CloseAccou...
e2ae8f32947a6c99dfba69b0da06adcfffa3fc3c
3,644,142
from typing import Tuple def mask_frame_around_position( frame: np.ndarray, position: Tuple[float, float], radius: float = 5, ) -> np.ndarray: """ Create a circular mask with the given ``radius`` at the given position and set the frame outside this mask to zero. This is sometimes required ...
cf616a0193cf9150821ed00c8e20c61a88b64d9e
3,644,143
import numpy as np def apogeeid_digit(arr): """ NAME: apogeeid_digit PURPOSE: Extract digits from apogeeid because its too painful to deal with APOGEE ID in h5py INPUT: arr (ndarray): apogee_id OUTPUT: apogee_id with digits only (ndarray) HISTORY: 2017-O...
48e21ab69c9f733dbf7b612994bfed35b8980424
3,644,144
def transform_user_weekly_artist_chart(chart): """Converts lastfm api weekly artist chart data into neo4j friendly weekly artist chart data Args: chart (dict): lastfm api weekly artist chart Returns: list - neo4j friendly artist data """ chart = chart['weeklyartistchart'] a...
1034211f6c21774044d767aeb7861b6aa80b4023
3,644,145
def plotter(fdict): """ Go """ pgconn = get_dbconn('isuag') ctx = get_autoplot_context(fdict, get_description()) threshold = 50 threshold_c = temperature(threshold, 'F').value('C') hours1 = ctx['hours1'] hours2 = ctx['hours2'] station = ctx['station'] oldstation = XREF[station] ...
f8a412065700ab111f5bf846938721aa397803b3
3,644,146
def config_namespace(config_file=None, auto_find=False, verify=True, **cfg_options): """ Return configuration options as a Namespace. .. code:: python reusables.config_namespace(os.path.join("test", "data", "test_config.ini")) ...
c3293fa36e32d2ebea610a88a6e29ba47906ab7b
3,644,147
import pandas import numpy import tqdm import torch def extract_peaks(peaks, sequences, signals, controls=None, chroms=None, in_window=2114, out_window=1000, max_jitter=128, min_counts=None, max_counts=None, verbose=False): """Extract sequences and signals at coordinates from a peak file. This function will tak...
f3a3696f2e31b7b91384df50dd0374c2e4e46443
3,644,148
def map_feature(value, f_type): """ Builds the Tensorflow feature for the given feature information """ if f_type == np.dtype('object'): return bytes_feature(value) elif f_type == np.dtype('int'): return int64_feature(value) elif f_type == np.dtype('float'): return float64_featur...
26416b27737542c8ac6100168775f47b271206a3
3,644,150
def is_text_area(input): """ Template tag to check if input is file :param input: Input field :return: True if is file, False if not """ return input.field.widget.__class__.__name__ == "Textarea"
4657a93809e123aaa27ee0a202b33e0383ac23cc
3,644,151
def print_album_list(album_list): """Print album list and return the album name choice. If return is all then all photos on page will be download.""" for i in range(len(album_list)): print("{}. {} ({} photo(s))".format( i + 1, album_list[i]['name'], album_list[i]['count'])) choice...
2a3c4fde9fc56da179ea43c88f966735fc5c7beb
3,644,152
import struct def read_bool(data): """ Read 1 byte of data as `bool` type. Parameters ---------- data : io.BufferedReader File open to read in binary mode Returns ------- bool True or False """ s_type = "=%s" % get_type("bool") return struct.unpack(s_type,...
9302a3f4831143c44b0a67cfe0f146463e8ba27e
3,644,156
def sectorize(position): """ Returns a tuple representing the sector for the given `position`. Parameters ---------- position : tuple of len 3 Returns ------- sector : tuple of len 3 """ x, y, z = normalize(position) x, y, z = x // GameSettings.SECTOR_SIZE, y // GameSettings.S...
689fc3ee350e5493d037df290c5df05d50621b7e
3,644,157
import random def add_random_phase_shift(hkl, phases, fshifts=None): """ Introduce a random phase shift, at most one unit cell length along each axis. Parameters ---------- hkl : numpy.ndarray, shape (n_refls, 3) Miller indices phases : numpy.ndarray, shape (n_refls,) phas...
7739d99b58bec80283a5e49fc2e6eaa6161286ae
3,644,158
import itertools import re def parse_cluster_file(filename): """ Parse the output of the CD-HIT clustering and return a dictionnary of clusters. In order to parse the list of cluster and sequences, we have to parse the CD-HIT output file. Following solution is adapted from a small wrapper script ...
d50eaeb926be3a7b8d1139c82142e4a1b595c1a0
3,644,162
def app(par=None): """ Return the Miniweb object instance. :param par: Dictionary with configuration parameters. (optional parameter) :return: Miniweb object instance. """ return Miniweb.get_instance(par)
3d2b0d1a9fd87e9e5c26ea9a141e40fbe342b764
3,644,163
def openTopics(): """Opens topics file :return: list of topics """ topicsFile = 'topics' with open(topicsFile) as f: topics = f.read().split() return topics
e6d43ff6717122532a71355b71134d6f78f9db85
3,644,164
from django.forms.boundfield import BoundField from django.utils.inspect import func_supports_parameter, func_accepts_kwargs def fix_behaviour_widget_render_forced_renderer(utils): """ Restore the behaviour where the "renderer" parameter of Widget.render() may not be supported by subclasses. """ orig...
7d55ecc18fae91af221b806448fa30203fdd9cd4
3,644,165
from typing import List def split_blocks(blocks:List[Block], ncells_per_block:int,direction:Direction=None): """Split blocks is used to divide an array of blocks based on number of cells per block. This code maintains the greatest common denominator of the parent block. Number of cells per block is simply an esti...
e7ebf6189b3f140b006d74846c4979058023784a
3,644,166
def get_entry_details(db_path, entry_id): """Get all information about an entry in database. Args: db_path: path to database file entry_id: string Return: out: dictionary """ s = connect_database(db_path) # find entry try: sim = s.query(Main).filter(Main....
7a4023fa32a0e41cf3440bcd8fd2140ce88b8c33
3,644,167
import bisect def pose_interp(poses, timestamps_in, timestamps_out, r_interp='slerp'): """ :param poses: N x 7, (t,q) :param timestamps: (N,) :param t: (K,) :return: (K,) """ # assert t_interp in ['linear', 'spline'] assert r_interp in ['slerp', 'squad'] assert len(pos...
cc8e49b6bab918c6887e37973d09469fcddc298d
3,644,168
from datetime import datetime def checklist_saved_action(report_id): """ View saved report """ report = Report.query.filter_by(id=report_id).first() return render_template( 'checklist_saved.html', uid=str(report.id), save_date=datetime.now(), report=report, ...
302bc174ffe0ed7d3180b2a59c5212b3a38e7eaf
3,644,169
def trilinear_memory_efficient(a, b, d, use_activation=False): """W1a + W2b + aW3b.""" n = tf.shape(a)[0] len_a = tf.shape(a)[1] len_b = tf.shape(b)[1] w1 = tf.get_variable('w1', shape=[d, 1], dtype=tf.float32) w2 = tf.get_variable('w2', shape=[d, 1], dtype=tf.float32) w3 = tf.get_variable('w3', shape=[...
d6ed8cc216019987674b86ef36377a6af45a6702
3,644,170
def private_questions_get_unique_code(assignment_id: str): """ Get all questions for the given assignment. :param assignment_id: :return: """ # Try to find assignment assignment: Assignment = Assignment.query.filter( Assignment.id == assignment_id ).first() # Verify that t...
1c94404168ac659e9ee3c45b3ecf7c2c398d1cca
3,644,171
def make_ngram(tokenised_corpus, n_gram=2, threshold=10): """Extract bigrams from tokenised corpus Args: tokenised_corpus (list): List of tokenised corpus n_gram (int): maximum length of n-grams. Defaults to 2 (bigrams) threshold (int): min number of n-gram occurrences before inclusion ...
8897456e9da4cd3c0f1c3f055b43e7d27c7261d8
3,644,172
def bw_estimate(samples): """Computes Abraham's bandwidth heuristic.""" sigma = np.std(samples) cand = ((4 * sigma**5.0) / (3.0 * len(samples)))**(1.0 / 5.0) if cand < 1e-7: return 1.0 return cand
44629f9e774d07f7c55a5a77dcb7b06ae38a964b
3,644,173
def process_coins(): """calculate the amount of money paid based on the coins entered""" number_of_quarters = int(input("How many quarters? ")) number_of_dimes = int(input("How many dimes? ")) number_of_nickels = int(input("How many nickels? ")) number_of_pennies = int(input("How many pennies? ")) ...
6a26ad161720554079a76f6bdadbbf9555d6b82d
3,644,174
def getLastSegyTraceHeader(SH,THN='cdp',data='none', bheadSize = 3600, endian='>'): # added by A Squelch """ getLastSegyTraceHeader(SH,TraceHeaderName) """ bps=getBytePerSample(SH) if (data=='none'): data = open(SH["filename"]).read() #...
19de6339bcc3ec63b0e33007f51fa50ddb619449
3,644,175
def get_data_url(data_type): """Gets the latest url from the kff's github data repo for the given data type data_type: string value representing which url to get from the github api; must be either 'pct_total' or 'pct_share' """ data_types_to_strings = { 'pct_total': 'Percent of Total Populatio...
f92520243ee7f952ff69c7c62c315225982a24fe
3,644,176
def kl(p, q): """Kullback-Leibler divergence D(P || Q) for discrete distributions Parameters ---------- p, q : array-like, dtype=float, shape=n Discrete probability distributions. """ p = np.asarray(p, dtype=np.float) q = np.asarray(q, dtype=np.float) return np.sum(np.where(p != 0, ...
06b6283ea83a729f9c374dabbe1c1a94a8ed8480
3,644,177
import torch def get_loaders(opt): """ Make dataloaders for train and validation sets """ # train loader opt.mean = get_mean(opt.norm_value, dataset=opt.mean_dataset) # opt.std = get_std() if opt.no_mean_norm and not opt.std_norm: norm_method = transforms.Normalize([0, 0, 0], [1, 1, 1]) elif not opt.std_norm...
d7a166a477c535a60846e05598dd19bbe84062be
3,644,178
def trapezoidal(f, a, b, n): """Trapezoidal integration via iteration.""" h = (b-a)/float(n) I = f(a) + f(b) for k in xrange(1, n, 1): x = a + k*h I += 2*f(x) I *= h/2 return I
f2887a3b0d1732f322dca52d0d869c1063e08c22
3,644,179
def writetree(tree, sent, key, fmt, comment=None, morphology=None, sentid=False): """Convert a tree to a string representation in the given treebank format. :param tree: should have indices as terminals :param sent: contains the words corresponding to the indices in ``tree`` :param key: an identifier for this tr...
cf8181596a4882ae18a8adcd0411e1c4e2ee8a33
3,644,180
import struct def xor_string(hash1, hash2, hash_size): """Encrypt/Decrypt function used for password encryption in authentication, using a simple XOR. Args: hash1 (str): The first hash. hash2 (str): The second hash. Returns: str: A string with the xor applied. """ xor...
4efc263a0ff9fb05b0ee7cb7b7b3fdd4c8c0c2ec
3,644,181
def create_secret_key(string): """ :param string: A string that will be returned as a md5 hash/hexdigest. :return: the hexdigest (hash) of the string. """ h = md5() h.update(string.encode('utf-8')) return h.hexdigest()
eb31e149684074b18fdbc1989ecfc14f21756dea
3,644,182
import base64 def decode_password(base64_string: str) -> str: """ Decode a base64 encoded string. Args: base64_string: str The base64 encoded string. Returns: str The decoded string. """ base64_bytes = base64_string.encode("ascii") sample_st...
0f04617c239fbc740a9b4c9c2d1ae867a52e0c74
3,644,183
def _generate_overpass_api(endpoint=None): """ Create and initialise the Overpass API object. Passing the endpoint argument will override the default endpoint URL. """ # Create API object with default settings api = overpass.API() # Change endpoint if desired if endpoint is not None: ...
9b8016035e87428286f68622e9a6129bcf818c4a
3,644,184
def to_pascal_case(value): """ Converts the value string to PascalCase. :param value: The value that needs to be converted. :type value: str :return: The value in PascalCase. :rtype: str """ return "".join(character for character in value.title() if not character.isspace())
138ab9ddf7ca814b50bf8ff0618de03b236535c7
3,644,185
from typing import Iterable from typing import Any from typing import List def drop(n: int, it: Iterable[Any]) -> List[Any]: """ Return a list of N elements drop from the iterable object Args: n: Number to drop from the top it: Iterable object Examples: >>> fpsm.drop(3, [1, 2...
0732bd560f0da0a43f65ee3b5ed46fd3a05e26f5
3,644,186
def generate_classification_style_dataset(classification='multiclass'): """ Dummy data to test models """ x_data = np.array([ [1,1,1,0,0,0], [1,0,1,0,0,0], [1,1,1,0,0,0], [0,0,1,1,1,0], [0,0,1,1,0,0], [0,0,1,1,1,0]]) if classification=='multiclass': y_data = np.array([ [1, 0, 0], [1, 0, 0], ...
77a65bb3445216a9a21aa30a7c7201983328efce
3,644,187
def getSupportedDatatypes(): """ Gets the datatypes that are supported by the framework Returns: a list of strings of supported datatypes """ return router.getSupportedDatatypes()
635612975c271bdbe22b622787a2d7f823277baa
3,644,189
def run_stacking(named_data, subjects_data, cv=10, alphas=None, train_sizes=None, n_jobs=None): """Run stacking. Parameters ---------- named_data : list(tuple(str, pandas.DataFrame)) List of tuples (name, data) with name and corresponding features to be used for predict...
75b97509097652fdccc444cfd3731ce68b49e992
3,644,190
def add_random_shadow(img, w_low=0.6, w_high=0.85): """ Overlays supplied image with a random shadow poligon The weight range (i.e. darkness) of the shadow can be configured via the interval [w_low, w_high) """ cols, rows = (img.shape[0], img.shape[1]) top_y = np.random.random_sample() * rows ...
3b520312941ffc4b125ce0a777aeb76fecd6b263
3,644,191
def csv_args(value): """Parse a CSV string into a Python list of strings. Used in command line parsing.""" return map(str, value.split(","))
b2596180054f835bfe70e3f900caa5b56a7856a6
3,644,192
def get_tokens(): """ Returns a tuple of tokens in the format {{site/property}} that will be used to build the dictionary passed into execute """ return (HAWQMASTER_PORT, HAWQSTANDBY_ADDRESS)
4664feb568a3a5599b9da64594d09a034e9aaebb
3,644,193
def projl1_epigraph(center): """ Project center=proxq.true_center onto the l1 epigraph. The bound term is center[0], the coef term is center[1:] The l1 epigraph is the collection of points $(u,v): \|v\|_1 \leq u$ np.fabs(coef).sum() <= bound. """ norm = center[0] coef = center[1:] ...
d7b8c70f45853eef61322fdb9583c8279780982f
3,644,194
import requests from datetime import datetime def crypto_command(text): """ <ticker> -- Returns current value of a cryptocurrency """ try: encoded = quote_plus(text) request = requests.get(API_URL.format(encoded)) request.raise_for_status() except (requests.exceptions.HTTPError, re...
0b0757a8b657791204d74b8536be3b6cb5af2ff5
3,644,195
import torch def byol_loss_multi_views_func(p: torch.Tensor, z: torch.Tensor,p1: torch.Tensor, z1: torch.Tensor, simplified: bool = True) -> torch.Tensor: """Computes BYOL's loss given batch of predicted features p and projected momentum features z. Args: p, p1 (torch.Tensor): NxD Tensor containing p...
705cbe9e62fa1e58da0a1f4087e6090d7b8002b8
3,644,196
def a_test_model(n_classes=2): """ recover model and test data from disk, and test the model """ images_test, labels_test, data_num_test = load_test_data_full() model = load_model(BASE_PATH + 'models/Inception_hemorrhage_model.hdf5') adam_optimizer = keras.optimizers.Adam( lr=0.0001, ...
d060f79a149d7659d74ffac316f71d7ef7b63368
3,644,197
def generate_synchronous_trajectory(initial_state): """ Simulate the network starting from a given initial state in the synchronous strategy :param initial_state: initial state of the network :return: a trajectory in matrix from, where each row denotes a state """ trajectory = [initial_state] ...
85f452f7665028e29085296820f67cf2e5cdb8bf
3,644,198
import inspect from textwrap import dedent import ast def arg_names(level=2): """Try to determine names of the variables given as arguments to the caller of the caller. This works only for trivial function invocations. Otherwise either results may be corrupted or exception will be raised. level: 0 is...
ce5b26747404442bfd017827435e9515c60aace0
3,644,199
import jinja2 def render_template(path, ctx): """Render a Jinja2 template""" with path.open() as f: content = f.read() tmpl = jinja2.Template(content) return html_minify(tmpl.render(**ctx))
0eb4b2a73a645283998260cdadbab37da32d6784
3,644,200
def reverse( sequence ): """Return the reverse of any sequence """ return sequence[::-1]
f08ae428844347e52d8dbf1cd8ad07cfbf4ef597
3,644,202
def createOutputBuffer(file, encoding): """Create a libxml2 output buffer from a Python file """ ret = libxml2mod.xmlCreateOutputBuffer(file, encoding) if ret is None:raise treeError('xmlCreateOutputBuffer() failed') return outputBuffer(_obj=ret)
28ece9b710362d710ff6df25f426d91a0b318ebf
3,644,203
def wait_for_proof(node, proofid_hex, timeout=60, expect_orphan=None): """ Wait for the proof to be known by the node. If expect_orphan is set, the proof should match the orphan state, otherwise it's a don't care parameter. """ def proof_found(): try: wait_for_proof.is_orphan = n...
f8f390424fe084bf8bf62bf1d16ac780d5c5df69
3,644,205
def check(verbose=1): """ Runs a couple of functions to check the module is working. :param verbose: 0 to hide the standout output :return: list of dictionaries, result of each test """ return []
4ecf144fc64a165b5b0f9766b76eb6b703eba130
3,644,206
def cylinder_sideways(): """ sideways cylinder for poster """ call_separator('cylinder sidweays') T1 = .1 #gs = gridspec.GridSpec(nrows=2,ncols=3,wspace=-.1,hspace=.5) fig = plt.figure(figsize=(5,4)) ax11 = fig.add_subplot(111,projection='3d') #ax12 = fig.add_subplot(...
98c0ed70c11ffe619d28623a5c5f4c4e2be40889
3,644,207
def get_generic_or_msg(intent, result): """ The master method. This method takes in the intent and the result dict structure and calls the proper interface method. """ return Msg_Fn_Dict[intent](result)
00853e2e74892a6d01ba1c6986e72f6436c88a92
3,644,208
def s3_example_tile(gtiff_s3): """Example tile for fixture.""" return (5, 15, 32)
a4b7e35fc6f7bf51a551ac8cb18003c23ff35a01
3,644,209
def execute_list_of_commands(command_list): """ INPUT: - ``command_list`` -- a list of strings or pairs OUTPUT: For each entry in command_list, we attempt to run the command. If it is a string, we call ``os.system()``. If it is a pair [f, v], we call f(v). If the environment variable...
79247f8dc15cc790b6f1811e3cb79de47c514bc4
3,644,210
import requests def get_transceiver_diagnostics(baseurl, cookie_header, transceiver): """ Get the diagnostics of a given transceivers in the switch :param baseurl: imported baseurl variable :param cookie_header: Parse cookie resulting from successful loginOS.login_os(baseurl) :param transceiver: d...
c2863b54b03ae3bdcf779fbd18a50e2bcdb2edd7
3,644,211
def mask_valid_boxes(boxes, return_mask=False): """ :param boxes: (cx, cy, w, h,*_) :return: mask """ w = boxes[:,2] h = boxes[:,3] ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16)) mask = (w > 2) & (h > 2) & (ar < 30) if return_mask: return mask else: return...
3a3c00f934dabce78ee8a28f0ece2105d79f9f3f
3,644,213
import tokenize def import_buffer_to_hst(buf): """Import content from buf and return an Hy AST.""" return tokenize(buf + "\n")
4571bac8987911bf9b9a277590be6204be6120ab
3,644,214
def preprocess_input(x, **kwargs): """Preprocesses a numpy array encoding a batch of images. # Arguments x: a 4D numpy array consists of RGB values within [0, 255]. # Returns Preprocessed array. """ return imagenet_utils.preprocess_input(x, mode='tf', **kwargs)
ca81dff57f51184042899849dff6623d32e475c0
3,644,217
def build_gauss_kernel(sigma_x, sigma_y, angle): """ Build the rotated anisotropic gaussian filter kernel Parameters ---------- sigma_x : numpy.float64 sigma in x-direction sigma_y: numpy.float64 sigma in y-direction angle: int angle in degrees of the needle holder ...
14dd4143ad94bcdfa3298b4acf9b2d4c2bd0b7e6
3,644,218
def kwargs_to_flags(**kwargs): """Convert `kwargs` to flags to pass on to CLI.""" flag_strings = [] for (key, val) in kwargs.items(): if isinstance(val, bool): if val: flag_strings.append(f"--{key}") else: flag_strings.append(f"--{key}={val}") retu...
aa672fe26c81e7aaf8a6e7c38354d1649495b8df
3,644,219
def extractBananas(item): """ Parser for 'Bananas' """ badwords = [ 'iya na kao manga chapters', ] if any([bad in item['tags'] for bad in badwords]): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): r...
f06167a0d379ec3b1921bb7ad8146b0bca9fd8aa
3,644,220
def get_template_parameters_s3(template_key, s3_resource): """ Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found Args: template_key: S3 key for template file. omit bucket. s3_resource: a boto3 s3 resource Returns: filename of paramete...
3b68dc9c1fa8636bd0d066780aab43a6e55ecf2f
3,644,222
def cell_from_system(sdict): """ Function to obtain cell from namelist SYSTEM read from PW input. Args: sdict (dict): Dictinary generated from namelist SYSTEM of PW input. Returns: ndarray with shape (3,3): Cell is 3x3 matrix with entries:: [[a_x b_x c_x] ...
fbd6e034f738f42be45d7e5304892a9e69a8493b
3,644,223
def A12_6_3_2(FAxial, eta, Pp, Pu, Muey , Muez, Muay, Muaz, Ppls, Mby, Mbz, GammaRPa, GammaRPb): """ A.12.6.3.2 Interaction equation approach where : Pu is the applied axial force in a member due to factored actions, determined in an analysis that includes Pu effects (see A.12.4); ...
7a36ec489681100f99563f9c336df1306363851d
3,644,224
def gain_deploy_data(): """ @api {get} /v1/deploy/new_data 获取当前deploy_id 的信息 @apiName deployNew_data @apiGroup Deploy @apiDescription 获取当前deploy_id 的信息 @apiParam {int} project_id 项目id @apiParam {int} flow_id 流程id @apiParam {int} deploy_id 部署id @apiParamExample {json} Request-Example:...
9dc5e5faa53235ac6c5d8f0d37a2989b15ead477
3,644,225
def topk_mask(score, k): """Efficient implementation of topk_mask for TPUs. This is a more efficient implementation of the following snippet with support for higher rank tensors. It has the limitation that it only supports float32 as element type. The mask only contains k elements even if other elements have...
0a33dc6d5b9c621ab3fbd86c54c9ec90ac00f21f
3,644,226
import calendar def valueSearch(stat_type,op,value,**kwargs): """Quick function to designate a value, and the days or months where the attribute of interest exceeded, equalled, or was less than the passed value valueSearch("attribute","operator",value,**{sortmonth=False}) * "attribute" must ...
94b55a362d179f6acce705b002eb99f330a5427b
3,644,228
import requests def get_gnid(rec): """ Use geonames API (slow and quota limit for free accounts) """ if not any("http://www.geonames.org" in s for s in rec.get("sameAs")) and rec["geo"].get("latitude") and rec["geo"].get("longitude"): changed = False r = requests.get("http://api.geonam...
ab9d5e50e45217e3742f1d1ca7f58326ed3bf6f6
3,644,229
def allowed_file(filename): """ Is file extension allowed for upload""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
3d0a3a15eecf8f6b0d76b52935a14628f1655328
3,644,231
import re def parse_tsv(filename, name_dict): """ """ output_matrix = [] with open(filename, 'rU') as handle: curr_protein = [] for line in handle: if line[0] == "#" or line[0] == "-" or len(line.strip('\n')) < 1: continue if re.match("Protein",...
12aa31ab3ff033ecc514518700c22ea467f01ef6
3,644,232
def get_orlist(site=DEFAULT_SITE, namespace="0|6|10|14|100|828", redirects="nonredirects"): """Get list of oldreviewed pages.""" request = Request(site=site, action="query", list="oldreviewedpages", ornamespace=namespace, or...
8253b2ac8ea72690086fa7864e5ca4ffcc33de50
3,644,233
def meshVolume(verts, norm, tri): """Compute the Volume of a mesh specified by vertices, their normals, and indices of triangular faces """ # TEST zeronorms = [] for i, n in enumerate(norm): #if n == [0., 0., 0.] or n == (0., 0., 0.): if n[0] == 0 and n[1] == 0 and n[2] == 0: #print "norma...
018818ab558b64b9699250bf6f45f0a1c47f92c8
3,644,234
def _groupby_clause(uuid=None, owner=None, human_name=None, processing_name=None): """ Build the groupby clause. Simply detect which fields are set, and group by those. Args: uuid: owner: human_name: processing_name: Returns: (str): "field, ..., field" """...
21546efa19e841661ed3a7ad8a84cf9a9a76d416
3,644,235
def _coeff_mod_wfe_drift(self, wfe_drift, key='wfe_drift'): """ Modify PSF polynomial coefficients as a function of WFE drift. """ # Modify PSF coefficients based on WFE drift if wfe_drift==0: cf_mod = 0 # Don't modify coefficients elif (self._psf_coeff_mod[key] is None): _log.w...
345d07a8850ec702d42f5c527fae0311f50a69b1
3,644,236
def get_transformed_webhook_payload(gh_payload, default_branch=None, lookup_user=None): """ Returns the GitHub webhook JSON payload transformed into our own payload format. If the gh_payload is not valid, returns None. """ try: validate(gh_payload, GITHUB_WEBHOOK_PAYLOAD_SCHEMA) except Exception as ex...
26e645219b816405521ddb6033a0a44c2ab7bba5
3,644,237
def get_retweeted_tweet(tweet): """ Get the retweeted Tweet and return it as a dictionary If the Tweet is not a Retweet, return None Args: tweet (Tweet or dict): A Tweet object or a dictionary Returns: dict: A dictionary representing the retweeted status or None if there is...
f852d45deadb1622687d097f2c724bdaef72ccc9
3,644,238
def listminus(c1, c2): """Return a list of all elements of C1 that are not in C2.""" s2 = {} for delta in c2: s2[delta] = 1 c = [] for delta in c1: if not s2.has_key(delta): c.append(delta) return c
829c347343d6a305fef2ad2f71539d7267b5a973
3,644,239
import random import torch def distribute_quantity_skew(batch_size, grouped_data, distributed_dataset, groupings, p=0.5, scalar=1.5): """ Adds quantity skew to the data distribution. If p=0. or scalar=1., no skew is applied and the data are divided evenly among the workers in each label group. :pa...
b4ebd1d6058550d2e32cedd62a56b50441d93b4c
3,644,240
def get_dtype(names, array_dtype=DEFAULT_FLOAT_DTYPE): """ Get a list of tuples containing the dtypes for the structured array Parameters ---------- names : list of str Names of parameters array_dtype : optional dtype to use Returns ------- list of tuple Dty...
9f29dae78b3839429f13b8513293e9ce4c240e2f
3,644,243