content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def warn(string: str) -> str: """Add warn colour codes to string Args: string (str): Input string Returns: str: Warn string """ return "\033[93m" + string + "\033[0m"
0bdbe5e7052e1994d978e45273baef75a1b72d89
6,200
def normalized_mean_square_error(logits, labels, axis = [0,1,2,3]): """ logits : [batch_size, w, h, num_classes] labels : [batch_size, w, h, 1] """ with tf.name_scope("normalized_mean_square_error"): nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(logits, labels), axis=[1,2,3])) ...
0aee175ed0be3132d02018961265461e4880221b
6,201
from sys import path def load_glove_data(): """ Loads Stanford's dictionary of word embeddings created by using corpus of Twitter posts. Word embeddings are vectors of 200 components. OUTPUT: dictionary containing tweet word embeddings """ glove_path = path.join('..', 'data', 'glove', ...
e78010f80ee7dd54c11a0b2bd293025ff2f90d70
6,202
def get_partition_to_num_rows( namespace, tablename, partition_column, partition_column_values ): """ Helper function to get total num_rows in hive for given partition_column_values. """ partitions = { "{0}={1}".format(partition_column, partition_column_value) for partition_colum...
305d40fd326bc45e906925b94077182584ffe3be
6,203
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = initialize_game() card_title = "Welcome" speech_output = "Hello! I am Cookoo. Let's play a game. " \ "Are you ready to play?" ...
9c28194575013e98d1d6130a956714f65ebe3764
6,204
def kl_divergence_with_logits(logits_a, logits_b): """ Compute the per-element KL-divergence of a batch. Args: logits_a: tensor, model outputs of input a logits_b: tensor, model outputs of input b Returns: Tensor of per-element KL-divergence of model outputs a and b """...
7df5976287edf5de37291db653a4334ed046a2f3
6,205
import csv def load_labels(abs_path): """ loads relative path file as dictionary Args: abs_path: absolute path Returns dictionary of mappings """ label_tsv = open(abs_path, encoding="utf-8") labels = list(csv.reader(label_tsv, delimiter="\t")) return labels
8ded58965dcc98b7a0aaa6614cbe4b66722dc76b
6,206
def cut_tree_balanced(linkage_matrix_Z, max_cluster_size, verbose=False): """This function performs a balanced cut tree of a SciPy linkage matrix built using any linkage method (e.g. 'ward'). It builds upon the SciPy and Numpy libraries. The function looks recursively along the hierarchical ...
53290f432b9ad7404760e124ffe6d03e95e5d529
6,207
from typing import Callable def len_smaller(length: int) -> Callable: """Measures if the length of a sequence is smaller than a given length. >>> len_smaller(2)([0, 1, 2]) False """ def len_smaller(seq): return count(seq) < length return len_smaller
a43f1344a46a57d443d267de99ba7db08b9bf911
6,208
def e_2e_fun(theta, e_init=e_1f): """ Electron energy after Compton scattering, (using energy e_1f) :param theta: angle for scattered photon :param e_init: initial photon energy :return: """ return e_init / (((m_e * c ** 2) / e_init) * (1 / (1 - np.cos(theta))) + 1)
8785f6dfbb4226df88e6ab2b883a989ff799d240
6,209
from typing import AbstractSet from pathlib import Path from typing import Optional from typing import Set from typing import Tuple from typing import Mapping from typing import Sequence from typing import Dict from typing import List import csv import shutil def tag_images_for_google_drive( input_files: Abst...
93750786413455b7baa74bce9764fdcfddc665f2
6,210
import os def xml_reader(filename): """ A method using iterparse as above would be preferable, since we just want to collect the first few tags. Unfortunately, so far iterparse does not work with html (aka broken xml). """ name = os.path.basename(filename) with open(filename, "rb") as file...
70cc9420155d5a0cf15a68ada1a428f66ac6ba9f
6,211
from typing import List def interval_list_intersection(A: List[List], B: List[List], visualization: bool = True) -> List[List]: """ LeteCode 986: Interval List Intersections Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersectio...
722902e4c4c076a1dc25d07cc3253b2ec9f3d110
6,212
import os def get(environ: OsEnvironLike = None) -> str: """Get the application ID from the environment. Args: environ: Environment dictionary. Uses os.environ if `None`. Returns: Default application ID as a string. We read from the environment APPLICATION_ID (deprecated) or else GAE_APPLICATION....
112d816eb0cf4582694222d63561e909444d3e5d
6,213
def tokenize_query(query): """ Tokenize a query """ tokenized_query = tokenizer.tokenize(query) stop_words = set(nltk.corpus.stopwords.words("english")) tokenized_query = [ word for word in tokenized_query if word not in stop_words] tokenized_query = [stemmer.stem(word) for word in tokenized...
422d59dc95661496dcfac83f142190a94127ae68
6,214
def rewrite_return(func): """Rewrite ret ops to assign to a variable instead, which is returned""" ret_normalization.run(func) [ret] = findallops(func, 'ret') [value] = ret.args ret.delete() return value
d141ae9d2f36f4f3e41da626ed43a3902e43c267
6,215
def get_loss_fn(loss_factor=1.0): """Gets a loss function for squad task.""" def _loss_fn(labels, model_outputs): start_positions = labels['start_positions'] end_positions = labels['end_positions'] start_logits, end_logits = model_outputs return squad_loss_fn( start_positions, end_p...
ad07afbd39aa1338a0aeb3c1398aefacebceffa3
6,216
import asyncio async def run_command(*args): """ https://asyncio.readthedocs.io/en/latest/subprocess.html """ # Create subprocess process = await asyncio.create_subprocess_exec( *args, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE) ...
a0071a1bb8ba169179c67d22f5c8caca717697b3
6,217
def get_variants_in_region(db, chrom, start, stop): """ Variants that overlap a region Unclear if this will include CNVs """ xstart = get_xpos(chrom, start) xstop = get_xpos(chrom, stop) variants = list(db.variants.find({ 'xpos': {'$lte': xstop, '$gte': xstart} }, projection={'_id': Fals...
5665f4ff65832449c2dd7edb182fc3bd0707d189
6,218
def get_business(bearer_token, business_id): """Query the Business API by a business ID. Args: business_id (str): The ID of the business to query. Returns: dict: The JSON response from the request. """ business_path = BUSINESS_PATH + business_id #4 return request(API_HOST, b...
982eb518b7d9f94b7208fb68ddbc9f6607d9be9a
6,219
from keras.layers import Conv2D, Input, MaxPooling2D, ZeroPadding2D from keras.layers.normalization import BatchNormalization from keras.layers.merge import concatenate from keras.models import Model from keras.regularizers import l2 def AlexNet_modified(input_shape=None, regularize_weight=0.0001): """ Alexn...
b4bf37200a2bf429fe09eb9893b673e381ce0b36
6,220
import re def readblock(fileObj): """ parse the block of data like below ORDINATE ERROR ABSCISSA 2.930E-06 1.8D-07 5.00E+02 X. 8.066E-06 4.8D-07 6.80E+02 .X. 1.468E-05 8.3D-07 9.24E+02 ..X. 2.204E-05 1.2D-06 1.26E+03 ...
838adc5e4efc4f97c255917e8d51b5da398718bd
6,221
def as_scalar(scalar): """Check and return the input if it is a scalar. If it is not scalar, raise a ValueError. Parameters ---------- scalar : Any the object to check Returns ------- float the scalar if x is a scalar """ if isinstance(scalar, np.ndarray): ...
ca5dd15eb2672ec61785dd2a36495d61ad4a3f9f
6,222
import itertools def evaluate_dnf( # pylint: disable=too-many-arguments,too-many-locals num_objects: int, num_vars: int, nullary: np.ndarray, unary: np.ndarray, binary: np.ndarray, and_kernel: np.ndarray, or_kernel: np.ndarray, target_arity: int, ) -> np.ndarray: """Evaluate given...
2a73f917594361ba4837e7e1d5f45398b3b0eb8d
6,223
def black_color_func(word, font_size, position, orientation, random_state=None, **kwargs): """Make word cloud black and white.""" return("hsl(0,100%, 1%)")
d5e874a4f62d30abcba29476d0ba7fc3a31b0ca6
6,224
import re def setup(hass, config): """ Setup history hooks. """ hass.http.register_path( 'GET', re.compile( r'/api/history/entity/(?P<entity_id>[a-zA-Z\._0-9]+)/' r'recent_states'), _api_last_5_states) hass.http.register_path('GET', URL_HISTORY_PERIOD, _api...
c87ddf7d7473d49b142a866043c0adee216aed39
6,225
import os def shuffle_file(filename): """Shuffle lines in file. """ sp = filename.split('/') shuffled_filename = '/'.join(sp[:-1] + ['shuffled_{}'.format(sp[-1])]) logger.info(shuffled_filename) os.system('shuf {} > {}'.format(filename, shuffled_filename)) return shuffled_filename
a2105af5b049df9da0f96f91d4a5e4515d0d978c
6,226
import itertools def fitallseq(digitslist, list): """if there is repeating digits, itertools.permutations() is still usable if fail, still print some print, if i >= threshold, served as start point for new searching """ for p in itertools.permutations(digitslist): #print "".join(pw) i=0 ...
069c9a2038593e7146558a53ac86c8fe877b44d3
6,227
def adduser(args): """Add or update a user to the database: <username> <password> [[role] [role] ...]""" try: username, password = args[0:2] except (IndexError, ValueError), exc: print >> sys.stderr, "you must include at least a username and password: %s" % exc usage() try: ...
7522753dff0647ac0764078902bf87c888f5a817
6,228
def check_linear_dependence(matrix: np.ndarray) -> bool: """ Functions checks by Cauchy-Schwartz inqeuality whether two matrices are linear dependent or not. :param matrix: 2x2 matrix to be processed. :return: Boolean. """ for i in range(matrix.shape[0]): for j in range(matrix.shape[0]):...
1b962afc16c135c49409a1cfb1f4c2b6a5695c75
6,229
import json def cors_400(details: str = None) -> cors_response: """ Return 400 - Bad Request """ errors = Model400BadRequestErrors() errors.details = details error_object = Model400BadRequest([errors]) return cors_response( req=request, status_code=400, body=json.du...
1f775db943ed0989da49d1b7a6952d7614ace982
6,230
def detect_label_column(column_names): """ Detect the label column - which we display as the label for a joined column. If a table has two columns, one of which is ID, then label_column is the other one. """ if (column_names and len(column_names) == 2 and "id" in column_names): return [c fo...
40524e7ed0878316564ad8fd66a2c09fc892e979
6,231
import subprocess import re def get_date(): """ get the date """ date = subprocess.check_output(["date"]) date = date.decode("utf-8") date = re.search(r"\w{3} \d{1,2} \w{3} \d{4}", date) date = date.group(0) return date
d8d69805a42f18e7cb793f6695146ea3dfb8251c
6,232
import glob def sorted_files(pattern): """Return files matching glob pattern, *effectively* sorted by date """ return sort_files(glob.glob(pattern))
4fb2ad9f6396cb844320e4e3aeb2941567d8af4a
6,233
import torch def random_float_tensor(seed, size, a=22695477, c=1, m=2 ** 32, requires_grad=False): """ Generates random tensors given a seed and size https://en.wikipedia.org/wiki/Linear_congruential_generator X_{n + 1} = (a * X_n + c) % m Using Borland C/C++ values The tensor will have values be...
c6c8ce42b2774204c3156bdd7b545b08315d1606
6,234
def derivable_rng(spec, *, legacy=False): """ Get a derivable RNG, for use cases where the code needs to be able to reproducibly derive sub-RNGs for different keys, such as user IDs. Args: spec: Any value supported by the `seed` parameter of :func:`seedbank.numpy_rng`, in addition ...
0772c9d27ba166f0981b3eb1da359a3ebb973322
6,235
def table(custom_headings, col_headings_formatted, rows, spec): """ Create a LaTeX table Parameters ---------- custom_headings : None, dict optional dictionary of custom table headings col_headings_formatted : list formatted column headings rows : list of lists of cell-str...
0ca28fce26fc7476aa5b88a621c5476ae8d381ce
6,236
from optparse import OptionParser import textDisplay import textDisplay import graphicsDisplay import pickle import random import sys def readCommand( argv ): """ Processes the command used to run pacman from the command line. """ usageStr = """ USAGE: python pacman.py <options> EXAMPLES:...
07cfc3b70e867a7656b642ad8d4bc0740a58c126
6,237
def skipIfNoDB(test): """Decorate a test to skip if DB ``session`` is ``None``.""" @wraps(test) def wrapper(self, db, *args, **kwargs): if db.session is None: pytest.skip('Skip because no DB.') else: return test(self, db, *args, **kwargs) return wrapper
a75cc067679aaab3fec78c2310cbc2e34a19cee7
6,238
def rboxes2quads_numpy(rboxes): """ :param rboxes: ndarray, shape = (*, h, w, 5=(4=(t,r,b,l) + 1=angle)) Note that angle is between [-pi/4, pi/4) :return: quads: ndarray, shape = (*, h, w, 8=(x1, y1,... clockwise order from top-left)) """ # dists, shape = (*, h, w, 4=(t,r,b,l)) # angles,...
a5c48d48444f3c063fe912e2c6e76de373f7a1fc
6,239
from typing import Callable from typing import Optional from typing import Mapping from typing import Any import reprlib from typing import List import inspect from typing import cast from typing import MutableMapping def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspectio...
d7218029fd387bae108eedf49c9eef14d98e3c70
6,240
def human_permissions(permissions, short=False): """Get permissions in readable form. """ try: permissions = int(permissions) except ValueError: return None if permissions > sum(PERMISSIONS.values()) or permissions < min( PERMISSIONS.values() ): return "" ...
0d9c15659c93833042f44a0a96746e2f1dd9d307
6,241
def predict(): """ Prediction end point Post a JSON holding the features and expect a prediction Returns ------- JSON The field `predictions` will hold a list of 0 and 1's corresponding to the predictions. """ logger.info('Starting prediction') json_ = request.get_j...
6899725edff8d2536c4a97018a5c6c7a4e0d416e
6,242
from unittest.mock import call def run_program(program, cmdargs, stdin_f, stdout_f, stderr_f, run=True, cmd_prepend="", run_from_cmd=True, **kwargs): """Runs `program` with `cmdargs` using `subprocess.call`. :param str stdin_f: File from which to take standard input :param ...
aea74ec8ac296567b16e6f76eed1360e8bc76f69
6,243
def second_step_red(x: np.array, y: np.array, z: np.array, px: np.array, py: np.array, pz: np.array, Fx: np.array, Fy: np.array, Fz: np.array, z_start: float, z_stop: float) -> (np.array, np.array, np.array, ...
909f16a51074ca0c52641d3539509e513ca4ac80
6,244
def drop_tabu_points(xf, tabulist, tabulistsize, tabustrategy): """Drop a point from the tabu search list.""" if len(tabulist) < tabulistsize: return tabulist if tabustrategy == 'oldest': tabulist.pop(0) else: distance = np.sqrt(np.sum((tabulist - xf)**2, axis=1)) index ...
4cd8887bdd77bb001635f0fba57f5908f3451642
6,245
def get_atom_feature_dims(list_acquired_feature_names): """ tbd """ return list(map(len, [CompoundKit.atom_vocab_dict[name] for name in list_acquired_feature_names]))
575de38dc0fdd198f6a6eb5cbb972063260bc4d4
6,246
def parse_selector(selector): """Parses a block of selectors like div .name #tag to class=.name, selector=div and id=#tag. Returns (selector, id, class[]) """ m_class, m_id, m_selector, m_attr = [], None, None, {} if selector is not None and type(selector) == str: selector_labels = selector.spli...
eadaa4cd79ed933325b0058e752a7187d5a09085
6,247
def is_batch_enabled(release_id): """ Check whether batching is enabled for a release. """ details = get_release_details_by_id(release_id) return details['data']['attributes']['enable_batching']
e22965166b35584e172e775b16a9d84affe5868f
6,248
import contextlib def create(tiles): """Handler.""" with futures.ThreadPoolExecutor(max_workers=8) as executor: responses = executor.map(worker, tiles) with contextlib.ExitStack() as stack: sources = [ stack.enter_context(rasterio.open(tile)) for tile in responses if tile ...
cd080b0df34b12f8045420ac076f8e9ee6bc7c15
6,249
import os import math import sys def write_rxn_rates(path, lang, specs, reacs, fwd_rxn_mapping): """Write reaction rate subroutine. Includes conditionals for reversible reactions. Parameters ---------- path : str Path to build directory for file. lang : {'c', 'cuda', 'fortran', 'matl...
110074159d07bbca9837dafc560cadbbc2780689
6,250
def _rfftn_empty_aligned(shape, axes, dtype, order='C', n=None): """Patched version of :func:`sporco.fft.rfftn_empty_aligned`. """ ashp = list(shape) raxis = axes[-1] ashp[raxis] = ashp[raxis] // 2 + 1 cdtype = _complex_dtype(dtype) return cp.empty(ashp, cdtype, order)
a85ab3a938694a82d186b968a2d7d4c710f1ecde
6,251
def get_test_config(): """ Returns a basic FedexConfig to test with. """ # Test server (Enter your credentials here) return FedexConfig(key='xxxxxxxxxxxxxxxxx', password='xxxxxxxxxxxxxxxxxxxxxxxxx', account_number='xxxxxxxxx', mete...
81b29fbb135b30f24aa1fe7cb32844970617f0ee
6,252
from datetime import datetime import itertools import json import logging import csv def write_data(movies, user, data_format='json'): """ """ assert movies, 'no data to write' date = datetime.now().strftime('%Y%m%d') movies_clean = itertools.chain.from_iterable((json.loads(el) for el in movies)) ...
704ebf1aa1b45855b8fade61cdf6a9bb12e44c83
6,253
import json import tempfile def get_genotypes( single_end: list, paired_end: list, metadata: str, bam_dir: str, intermediate_dir: str, reference_genome_path: str, mapping_quality: int, blacklist_path: str, snps_path: str, processes: int, memory: int, skip_preprocessing:...
7ee61a9b8dfbbedf7d595034a40ae9084e1fa69f
6,254
def async_handle_google_actions(hass, cloud, payload): """Handle an incoming IoT message for Google Actions.""" result = yield from ga.async_handle_message( hass, cloud.gactions_config, payload) return result
1c9ec2e37a1c752abb59301f546db4e14fdf57d8
6,255
def get_picture_landmarks(filepath, predictor, logs=True): """ Do the doc! """ if logs: print("Processing file: {}".format(filepath)) frame = cv2.imread(filepath) lm = FLandmarks() lm.extract_points(frame, predictor) return lm if logs: print('\n')
02b92c663c9efe3fad18b35b3808e0b004b1a8c0
6,256
def conflict(next_x: int, s: tuple) -> bool: """Return a boolean that defines the conflict condition of the next queen's position""" next_i = len(s) for i in range(next_i): if abs(s[i] - next_x) in (0, next_i - i): return True else: return False
cc29b142e1cc799c0a305523b713c5085af25fd0
6,257
async def main_page(): """Main page. Just for example.""" return APIResponse(message="ok")
f1a2022df08725388c02dabe77bc4ee29eb5f968
6,258
from typing import List def split_to_sublists(initial_list:list, n:int, strict:bool=True) -> List[list]: """Takes a list and splits it into sublists of size n Parameters ---------- initial_list : list The initial list to split into sublists n : int The size of each sublist s...
fcca74f9814020c99aaf8b31f092ca3ca9533216
6,259
import os import re def get_matched_files(dirPath=".", regex=None): """Get the abspath of the files whose name matches a regex Only files will be returned, and directories are excluded. Args: dirPath (str): the directory to search regex (regex): the regular expression to match the filena...
118cf628b54f50b2c41c1885bcf000a741966086
6,260
from pathlib import Path def get_sha1(req_path: Path) -> str: """ For larger files sha1 algorithm is significantly faster than sha256 """ return get_hash(req_path, sha1)
768f101fe4ad57eaea9ccd68d247e6a85b1cebaa
6,261
import mimetypes import os import requests def upload_attachment(page_id, file, comment, confluence_api_url, username, password, raw = None): """ Upload an attachement :param page_id: confluence page id :param file: attachment file :param comment: attachment comment :return: boolean """ ...
563ea4b033a733c479d1e58b2c7fc3e661052021
6,262
def _make_note(nl_transcript: str, tl_audio_file: str) -> Note: """ Creates an Anki note from a native langauge transcript and a target language audio file. """ return Note(model=_MODEL, fields=[f"[sound:{tl_audio_file}]", nl_transcript])
4765e39b2c3a7794fb973de2b9424bad361cbe4c
6,263
from datetime import datetime def bed2beddb_status(connection, **kwargs): """Searches for small bed files uploaded by user in certain types Keyword arguments: lab_title -- limit search with a lab i.e. Bing+Ren, UCSD start_date -- limit search to files generated since a date formatted YYYY-MM-DD ru...
2fb1f67cc256bc1ff04c4a5e8c1fa61f43f69d30
6,264
def parse_urdf_file(package_name, work_name): """ Convert urdf file (xml) to python dict. Using the urdfpy package for now. Using the xml package from the standard library could be easier to understand. We can change this in the future if it becomes a mess. """ rospack = rospkg.RosPack() ...
7b209216d9f65303441e5e9f761119bfa9fc5810
6,265
def _get_mgmtif_mo_dn(handle): """ Internal method to get the mgmt_if dn based on the type of platform """ if handle.platform == IMC_PLATFORM.TYPE_CLASSIC: return("sys/rack-unit-1/mgmt/if-1") elif handle.platform == IMC_PLATFORM.TYPE_MODULAR: return("sys/chassis-1/if-1") else: ...
455c5baf0f659b98c78bfcc386bd03e0850df267
6,266
import scipy def measure_cv_performance(gene_by_latent_train, data_test): """ Measure NMF model performance on held out data. Performance is evaluated based on the model's ability to reconstuct held out samples. \hat{u} := arg min_{u} || x - uV^T || s.t. u >= 0 \hat{x} := \hat{u} V^T error = || x - ...
a16b66d9604b3921a7288dcb06b43a51c987d5cd
6,267
def sectionize(parts, first_is_heading=False): """Join parts of the text after splitting into sections with headings. This function assumes that a text was splitted at section headings, so every two list elements after the first one is a heading-section pair. This assumption is used to join sections wi...
402832d55268dc808888f94b95e3a1c991394041
6,268
def byte_compare(stream_a, stream_b): """Byte compare two files (early out on first difference). Returns: (bool, int): offset of first mismatch or 0 if equal """ bufsize = 16 * 1024 equal = True ofs = 0 while True: b1 = stream_a.read(bufsize) b2 = stream_b.read(bufsi...
59adfe50fefdb79edd082a35437018d4b954ec75
6,269
from re import A def get_resize_augmentation(image_size, keep_ratio=False, box_transforms=False): """ Resize an image, support multi-scaling :param image_size: shape of image to resize :param keep_ratio: whether to keep image ratio :param box_transforms: whether to augment boxes :return: album...
62affae338e16cb0e7fc609d0ee995c728d6ec47
6,270
def extract_question(metric): """Extracts the name and question from the given metric""" with open(metric) as f: data = f.readlines() data = [x.strip() for x in data] # filter out empty strings data = list(filter(None, data)) # data[0] = '# Technical Fork' metric_name = data[0].sp...
27ddc25c489d19e1ca17ae80774e20c14208b653
6,271
def get_side(node, vowels, matcher, r): """Get side to which char should be added. r means round (or repeat). Return 0 or plus int to add char to right, minus int to left, None if char node should be avoided. """ # check if node has both char neighbours if node.next is None: if node...
b7a34982bed475cacef08faf8f4d6155fc4147fb
6,272
def gap_perform_pruning(model_path, pruned_save_path=None, mode='gap', slim_ratio=0.5, mask_len=False, full_save=False, full_save_path=None, var_scope='', ver=1): """ Interface for GAP pruning step (step2). Args: model_path: path to the saved checkpoint, ...
b49b7f5d61113990746ef37d03267805424f10be
6,273
def html_wrap(ptext, owrapper, attribute=''): """ Wrap text with html tags. Input: ptext -- text to be wrapped owrapper -- tag to wrap ptext with attribute -- if set, attribute to add to ptext If owrapper ends with a newline, then the newline will appear after the bracket c...
3a9d6fcf165ce6ad46ecc2ab7437b794d03449d9
6,274
import socket import subprocess def start_vsfm(port=None, vsfm_binary_path=default_path): """ Starts VSFM, binds it to a socket, opens the socket interface, sets up a logger and waits. :param port: Port number to open, defaults to a random one :param vsfm_binary_path: the path to VSFM.exe, defaults fr...
2d92fe432053ee846757a4de759ab0d158f3d5dd
6,275
def names(namespace): """Return extension names without loading the extensions.""" if _PLUGINS: return _PLUGINS[namespace].keys() else: return _pkg_resources_names(namespace)
de772f9c671b92f9707e333006354d89ba166ae2
6,276
def cfq_lstm_attention_multi(): """LSTM+attention hyperparameters tuned for CFQ.""" hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 1024 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.initializer = 'uniform_unit_scaling' hparams.initia...
7f982aff67a58200c7a297a5cfbfee6cc3c33173
6,277
def create_modeling_tables(spi_historical, spi_fixtures, fd_historical, fd_fixtures, names_mapping): """Create tables for machine learning modeling.""" # Rename teams for col in ['team1', 'team2']: spi_historical = pd.merge(spi_historical, names_mapping, left_on=col, right_on='left_team', how='left...
bfaab71b64979859b7ec474dbf1805e117d9730d
6,278
import math import random def daily_selection(): """ Select a random piece of material from what is available. A piece is defined by a newline; every line is a new piece of content. """ logger.log("Selecting today's material") with open(settings.CONTENT, "r") as file: content = file.re...
2b16be5e02273e539e7f0417ef72d28de91624cb
6,279
import shlex import subprocess import re def get_browser_version(): """ obtain the firefox browser version, this is necessary because zeus can only handle certain versions. """ logger.info(set_color( "attempting to get firefox browser version" )) try: firefox_version_command = ...
bc170316136b89281076495a534208f36749847d
6,280
def is_checkpointing() -> bool: """Whether the current forward propagation is under checkpointing. Returns: bool: :data:`True` if it's under checkpointing. """ return thread_local.is_checkpointing
2779c059622bfe15586f69e4c0cfeb3bbf16a754
6,281
import json def create_tile_assets_profile(iam, profile_name, locations): """ Creates a profile (and corresponding role) with read and write access to the tile assets bucket. """ profile = iam.create_instance_profile( InstanceProfileName=profile_name, Path='/', ) iam.crea...
e1e9bfb9405b4558fbf9972dfab67bd22a9f0189
6,282
import scipy def noise_filter(rgb_array, coef=8, read_noise=2, shot_noise=246): """ Apply bilateral noise filter to RGB image""" h, w, _ = rgb_array.shape luma_img = rgb_array[:, :, 0] + rgb_array[:, :, 1] + rgb_array[:, :, 2] average = scipy.ndimage.filters.uniform_filter(luma_img, 5, mode='mirror') ...
6178429e237a56081696696c4d35f9fea5459065
6,283
import json def drop_entity(p_json: json): """ Удаляет сущность :param p_json: json с указанием id сущности, которую нужно удалить """ try: l_model=Model(p_json=p_json) l_model.drop_entity() return _JsonOutput(p_json_object=None, p_message="Entity has dropped successfully"...
1bec1f8f42d6aea39e25078383b018c2a651e5e5
6,284
from typing import Optional from typing import Sequence def get_ssl_vpn_client_certs(ids: Optional[Sequence[str]] = None, name_regex: Optional[str] = None, output_file: Optional[str] = None, ssl_vpn_server_id: Optional[str] = None,...
3d3bb6664aff7468c684a6e2e16a887fbbc3f425
6,285
from typing import Optional def quantile(h: Distogram, value: float) -> Optional[float]: """ Returns a quantile of the distribution Args: h: A Distogram object. value: The quantile to compute. Must be between 0 and 1 Returns: An estimation of the quantile. Returns None if the Dis...
76f2a9b33d2e3e6a4a419a9f32cff591e191a145
6,286
def arachni_del_vuln(request): """ The function Delete the Arachni Vulnerability. :param request: :return: """ if request.method == 'POST': vuln_id = request.POST.get("del_vuln", ) un_scanid = request.POST.get("scan_id", ) scan_item = str(vuln_id) value = scan_it...
3be794525025fec019a5f76e0d885519077bc72a
6,287
import subprocess def pipe(*args, encoding="utf-8", print_output=False, raise_exception=False): """Every arg should be a subprocess command string which will be run and piped to any subsequent args in a linear process chain. Each arg will be split into command words based on whitespace so whitespace embe...
6ee3f95a86bd0c8d30d912e691738b5fbd846919
6,288
def construct_imports(variables, imports): """Construct the list of imports by expanding all command line arguments.""" result = {} for i in imports: kv = i.split('=', 1) if len(kv) != 2: print 'Invalid value for --imports: %s. See --help.' % i sys.exit(1) result[kv[0]] = expand_template(k...
2e26b3496dff96fa713e2388af415cadf831d032
6,289
import re def is_regex(param): """ 判断参数是否是合法正则表达式字符串 :param param: {String} 参数 :return: {Boolean} 是否是合法正则表达式 """ try: re.compile(param) return True except re.error: return False
6a3ee33e68e33d3557db546beadc005235360080
6,290
def NetCDF_SHP_lat_lon(name_of_nc, box_values, name_of_lat_var, name_of_lon_var, correct_360): """ @ author: Shervan Gharari @ Github: https://github.com/ShervanGharari/candex @ author's email id: sh.gharari@gmail.com @license: Apache2 Th...
dc214f4449193f0daef0327df596c3109837a16e
6,291
from datetime import datetime import logging def format_issues( input_issues: list, developer_ids: list, start_date: datetime.datetime, end_date: datetime.datetime, end_date_buffer: int = 0, ) -> list: """extract and formats key fields into an output list Args: input_issues: issues ...
98af172b329c8887666d2ba430ad6e3bda00fe3d
6,292
import torch def train_transforms(image_size, train_img_scale=(0.35, 1), normalize: bool = True, mean=torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225])): """Transforms for train augmentation with Kornia.""" transforms =...
957aaf01edf64589d5bd846cac9895077ba43fd0
6,293
def get_spans_bio(tags,id2label=None): """Gets entities from sequence. Args: tags (list): sequence of labels. Returns: list: list of (chunk_type, chunk_start, chunk_end). Example: >>> tags = ['B-PER', 'I-PER', 'O', 'B-LOC'] >>> get_spans_bio(tags) # output [['PER'...
9a9e45eedaf7c8700b72af9649cf80b13e276fc8
6,294
def min_count1(lst): """ Get minimal value of list, version 1 :param lst: Numbers list :return: Minimal value and its count on the list """ if len(lst) == 0: return [] count = 0 min_value = lst[0] for num in lst: if num == min_value: count += 1 el...
b441d0a37534909e9a990b91a953d4022698c04b
6,295
import os def create_build_from_docker_image( image_name, install_package, namespace, source_image="quay.io/ocsci/fedora", source_image_label="latest", ): """ Allows to create a build config using a Dockerfile specified as an argument, eg.:: $ oc new-build -D $'FROM centos:7\\...
ac615fae1643c37a2ce86a7579605e48b585d338
6,296
def exactly_one_topping(ketchup, mustard, onion): """Return whether the customer wants exactly one of the three available toppings on their hot dog. """ return True if int(ketchup) + int(mustard) + int(onion) == 1 else False
214c95d35c116993dc78740d5d16b874122960ed
6,297
def strip_line_endings(data: list) -> list: """Removes line endings(\n). Removes item if only contains \n.""" return [i.rstrip("\n") for i in data if i != "\n"]
5383b1bc3884395459ca63b6f15c0a1091eaaaf0
6,298
def calculate_afqt_scores(df): """This function calculates the AFQT scores. See information at https://www.nlsinfo.org/content/cohorts/nlsy79/topical-guide/education/aptitude-achievement-intelligence-scores for more details. In addition, we adjust the Numerical Operations score along the lines des...
ba6573e40115d766b2c0aebb78a3beb2881fbb4c
6,299