content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def load_config(config_file): """ 加载配置文件 :param config_file: :return: """ with open(config_file, encoding='UTF-8') as f: return json.load(f)
85bab8a60e3abb8af56b0ae7483f2afe992d84b4
26,334
def decode(var, encoding): """ If not already unicode, decode it. """ if PY2: if isinstance(var, unicode): ret = var elif isinstance(var, str): if encoding: ret = var.decode(encoding) else: ret = unicode(var) els...
da59232e9e7715c5c1e87fde99f19997c8e1e890
26,335
def vehicle_emoji(veh): """Maps a vehicle type id to an emoji :param veh: vehicle type id :return: vehicle type emoji """ if veh == 2: return u"\U0001F68B" elif veh == 6: return u"\U0001f687" elif veh == 7: return u"\U000026F4" elif veh == 12: return u"\U0...
8068ce68e0cdf7f220c37247ba2d03c6505a00fe
26,337
import functools def np_function(func=None, output_dtypes=None): """Decorator that allow a numpy function to be used in Eager and Graph modes. Similar to `tf.py_func` and `tf.py_function` but it doesn't require defining the inputs or the dtypes of the outputs a priori. In Eager mode it would convert the tf....
5ed18b1575ec88fe96c27e7de38b00c5a734ee91
26,338
from typing import List from typing import Dict def constituency_parse(doc: List[str]) -> List[Dict]: """ parameter: List[str] for each doc return: List[Dict] for each doc """ predictor = get_con_predictor() results = [] for sent in doc: result = predictor.predict(sentence=sent) ...
30dd8eca61412083f1f11db6dc8aeb27bc171de9
26,339
def extract_results(filename): """ Extract intensity data from a FLIMfit results file. Converts any fraction data (e.g. beta, gamma) to contributions Required arguments: filename - the name of the file to load """ file = h5py.File(filename,'r') results = file['results'] keys = sorted_nicely(...
c4a9f4f66a53050ea55cb1bd266edfa285000717
26,341
async def bundle_status(args: Namespace) -> ExitCode: """Query the status of a Bundle in the LTA DB.""" response = await args.di["lta_rc"].request("GET", f"/Bundles/{args.uuid}") if args.json: print_dict_as_pretty_json(response) else: # display information about the core fields p...
2efb12b4bba3d9e920c199ad1e7262a24220d603
26,342
def determine_step_size(mode, i, threshold=20): """ A helper function that determines the next action to take based on the designated mode. Parameters ---------- mode (int) Determines which option to choose. i (int) the current step number. threshold (float) The ...
9b59ebe5eeac13f06662e715328d2d9a3ea0e9a2
26,343
def scroll_down(driver): """ This function will simulate the scroll down of the webpage :param driver: webdriver :type driver: webdriver :return: webdriver """ # Selenium supports execute JavaScript commands in current window / frame # get scroll height last_height = driver.execut...
7d68201f3a49950e509a7e389394915475ed8c94
26,344
from datetime import datetime def processing(): """Renders the khan projects page.""" return render_template('stem/tech/processing/gettingStarted.html', title="Processing - Getting Started", year=datetime.now().year)
53f6c69692591601dcb41c7efccad60bbfaf4cf7
26,345
def conv_unit(input_tensor, nb_filters, mp=False, dropout=0.1): """ one conv-relu-bn unit """ x = ZeroPadding2D()(input_tensor) x = Conv2D(nb_filters, (3, 3))(x) x = relu()(x) x = BatchNormalization(axis=3, momentum=0.66)(x) if mp: x = MaxPooling2D(pool_size=(3, 3), strides=(2, ...
7c24dae045c38c073431e4fab20687439601b141
26,346
import torch def combine_vectors(x, y): """ Function for combining two vectors with shapes (n_samples, ?) and (n_samples, ?). Parameters: x: (n_samples, ?) the first vector. In this assignment, this will be the noise vector of shape (n_samples, z_dim), but you shouldn't need to know ...
700ea418c6244dc745bf6add89ad786c4444d2fe
26,347
def expandMacros(context, template, outputFile, outputEncoding="utf-8"): """ This function can be used to expand a template which contains METAL macros, while leaving in place all the TAL and METAL commands. Doing this makes editing a template which uses METAL macros easier, becau...
04aad464f975c5ee216e17f93167be51eea8f6e6
26,348
def graph_papers(path="papers.csv"): """ Spit out the connections between people by papers """ data = defaultdict(dict) jkey = u'Paper' for gkey, group in groupby(read_csv(path, key=jkey), itemgetter(jkey)): for pair in combinations(group, 2): for idx,row in enumerate(pair...
43cae08f303707b75da2b225112fa0bc448306d9
26,349
def tariterator1(fileobj, check_sorted=False, keys=base_plus_ext, decode=True): """Alternative (new) implementation of tariterator.""" content = tardata(fileobj) samples = group_by_keys(keys=keys)(content) decoded = decoder(decode=decode)(samples) return decoded
8ea80d266dfe9c63336664aaf0fcac520e620382
26,350
def juego_nuevo(): """Pide al jugador la cantidad de filas/columnas, cantidad de palabras y las palabras.""" show_title("Crear sopa de NxN letras") nxn = pedir_entero("Ingrese un numero entero de la cantidad de\nfilas y columnas que desea (Entre 10 y 20):\n",10,20) n_palabras = pedir_entero("I...
ec42615c3934fd98ca5975f99d215f597f353842
26,351
def mk_sd_graph(pvalmat, thresh=0.05): """ Make a graph with edges as signifcant differences between treatments. """ digraph = DiGraph() for idx in range(len(pvalmat)): digraph.add_node(idx) for idx_a, idx_b, b_bigger, p_val in iter_all_pairs_cmp(pvalmat): if p_val > thresh: ...
f219d964ec90d58162db5e72d272ec8138f8991e
26,352
def body2hor(body_coords, theta, phi, psi): """Transforms the vector coordinates in body frame of reference to local horizon frame of reference. Parameters ---------- body_coords : array_like 3 dimensional vector with (x,y,z) coordinates in body axes. theta : float Pitch (or ele...
2e0e8f6bf3432a944a350fb7df5bdfa067074448
26,353
def negloglikelihoodZTNB(args, x): """Negative log likelihood for zero truncated negative binomial.""" a, m = args denom = 1 - NegBinom(a, m).pmf(0) return len(x) * np.log(denom) + negloglikelihoodNB(args, x)
8458cbc02a00fd2bc37d661a7e34a61afccb6124
26,354
def combine(m1, m2): """ Returns transform that combines two other transforms. """ return np.dot(m1, m2)
083de20237f484806c356c0b29c42ff28aa801f6
26,355
import torch def _acg_bound(nsim, k1, k2, lam, mtop = 1000): # John T Kent, Asaad M Ganeiber, and Kanti V Mardia. # A new unified approach forthe simulation of a wide class of directional distributions. # Journal of Computational andGraphical Statistics, 27(2):291–301, 2018. """ ...
45d96fee1b61d5c020e355df76d77c78483a3a0b
26,356
def melspecgrams_to_specgrams(logmelmag2 = None, mel_p = None, mel_downscale=1): """Converts melspecgrams to specgrams. Args: melspecgrams: Tensor of log magnitudes and instantaneous frequencies, shape [freq, time], mel scaling of frequencies. Returns: specgrams: Tensor of log magnitudes...
34090358eff2bf803af9b56c210d5e093b1f2900
26,358
from scipy.stats.mstats import gmean import numpy as np def ligandScore(ligand, genes): """calculate ligand score for given ligand and gene set""" if ligand.ligand_type == "peptide" and isinstance(ligand.preprogene, str): # check if multiple genes needs to be accounted for if isinstance(eval...
68141e9a837619b087cf132c6ba593ba5b1ef43d
26,359
def eval(x): """Evaluates the value of a variable. # Arguments x: A variable. # Returns A Numpy array. # Examples ```python >>> from keras import backend as K >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32') >>> K.eval(kvar) array(...
a9b5473cc71cd999d6e85fd760018d454c194c04
26,360
from typing import Optional def triple_in_shape(expr: ShExJ.shapeExpr, label: ShExJ.tripleExprLabel, cntxt: Context) \ -> Optional[ShExJ.tripleExpr]: """ Search for the label in a shape expression """ te = None if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)): for expr2 in expr.shapeEx...
a1e9ba9e7c282475c775c17f52b51a78c3dcfd71
26,361
def poly_learning_rate(base_lr, curr_iter, max_iter, power=0.9): """poly learning rate policy""" lr = base_lr * (1 - float(curr_iter) / max_iter) ** power return lr
fdb2b6ed3784deb3fbf55f6b23f6bd32dac6a988
26,362
def parent_path(xpath): """ Removes the last element in an xpath, effectively yielding the xpath to the parent element :param xpath: An xpath with at least one '/' """ return xpath[:xpath.rfind('/')]
b435375b9d5e57c6668536ab819f40ae7e169b8e
26,363
from datetime import datetime def change_project_description(project_id): """For backwards compatibility: Change the description of a project.""" description = read_request() assert isinstance(description, (str,)) orig = get_project(project_id) orig.description = description orig.lastUpdated =...
c6b59cfbbffb353943a0a7ba4160ffb0e2382a51
26,364
import unittest def run_all(examples_main_path): """ Helper function to run all the test cases :arg: examples_main_path: the path to main examples directory """ # test cases to run test_cases = [TestExample1, TestExample2, TestExample3, Tes...
9a5176bff4e2c82561e3b0dbee467cd1dec0e63e
26,365
def get_queue(queue): """ :param queue: Queue Name or Queue ID or Queue Redis Key or Queue Instance :return: Queue instance """ if isinstance(queue, Queue): return queue if isinstance(queue, str): if queue.startswith(Queue.redis_queue_namespace_prefix): return Queue....
159860f2efa5c7a2643d4ed8b316e8abca85e67f
26,366
def ptttl_to_samples(ptttl_data, amplitude=0.5, wavetype=SINE_WAVE): """ Convert a PTTTLData object to a list of audio samples. :param PTTTLData ptttl_data: PTTTL/RTTTL source text :param float amplitude: Output signal amplitude, between 0.0 and 1.0. :param int wavetype: Waveform type for output si...
f4be93a315ff177cbdf69249f7efece55561b431
26,367
from typing import Union from pathlib import Path from typing import Tuple import numpy import pandas def read_output_ascii( path: Union[Path, str] ) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]: """Read an output file (raw ASCII format) Args: path (str): path to the file ...
ef3008f6cf988f7bd42ccb75bfd6cfd1a58e28ae
26,368
def AliasPrefix(funcname): """Return the prefix of the function the named function is an alias of.""" alias = __aliases[funcname][0] return alias.prefix
771c0f665ddad2427759a5592608e5467005c26d
26,369
from typing import Optional from typing import Tuple from typing import Callable def connect( sender: QWidget, signal: str, receiver: QObject, slot: str, caller: Optional[FormDBWidget] = None, ) -> Optional[Tuple[pyqtSignal, Callable]]: """Connect signal to slot for QSA.""" # Parameters e...
2ebeca355e721c5fad5ec6aac24a59587e4e86bd
26,371
import torch def get_detection_input(batch_size=1): """ Sample input for detection models, usable for tracing or testing """ return ( torch.rand(batch_size, 3, 224, 224), torch.full((batch_size,), 0).long(), torch.Tensor([1, 1, 200, 200]).repeat((batch_size, 1)), ...
710a5ed2f89610555d347af568647a8768f1ddb4
26,372
def build_tables(ch_groups, buffer_size, init_obj=None): """ build tables and associated I/O info for the channel groups. Parameters ---------- ch_groups : dict buffer_size : int init_obj : object with initialize_lh5_table() function Returns ------- ch_to_tbls : dict or Table ...
964bc6a817688eb8426976cec2b0053f43c6ed79
26,373
def segmentspan(revlog, revs): """Get the byte span of a segment of revisions revs is a sorted array of revision numbers >>> revlog = _testrevlog([ ... 5, #0 ... 10, #1 ... 12, #2 ... 12, #3 (empty) ... 17, #4 ... ]) >>> segmentspan(revlog, [0, 1, 2, 3, 4]) 17 >>...
51624b3eac7bba128a2e702c3387bbaab4974143
26,374
def is_stateful(change, stateful_resources): """ Boolean check if current change references a stateful resource """ return change['ResourceType'] in stateful_resources
055465870f9118945a9e5f2ff39be08cdcf35d31
26,375
def get_session_from_webdriver(driver: WebDriver, registry: Registry) -> RedisSession: """Extract session cookie from a Selenium driver and fetch a matching pyramid_redis_sesssion data. Example:: def test_newsletter_referral(dbsession, web_server, browser, init): '''Referral is tracker for...
0faaa394c065344117cec67ec824ec5186252ee2
26,377
from typing import Tuple def paper() -> Tuple[str]: """ Use my paper figure style. Returns ------- Tuple[str] Colors in the color palette. """ sns.set_context("paper") style = { "axes.spines.bottom": True, "axes.spines.left": True, "axes.spines.righ...
6e53247c666db62be1d5bf5ad5d77288af277d2d
26,379
import difflib def _get_diff_text(old, new): """ Returns the diff of two text blobs. """ diff = difflib.unified_diff(old.splitlines(1), new.splitlines(1)) return "".join([x.replace("\r", "") for x in diff])
bd8a3d49ccf7b6c18e6cd617e6ad2ad8324de1cc
26,380
def GetStatus(operation): """Returns string status for given operation. Args: operation: A messages.Operation instance. Returns: The status of the operation in string form. """ if not operation.done: return Status.PENDING.name elif operation.error: return Status.ERROR.name else: retu...
c9630528dd9b2e331a9d387cac0798bf07646603
26,382
def ft2m(ft): """ Converts feet to meters. """ if ft == None: return None return ft * 0.3048
ca2b4649b136c9128b5b3ae57dd00c6cedd0f383
26,384
def show_colors(*, nhues=17, minsat=10, unknown='User', include=None, ignore=None): """ Generate tables of the registered color names. Adapted from `this example <https://matplotlib.org/examples/color/named_colors.html>`__. Parameters ---------- nhues : int, optional The number of break...
34b45185af96f3ce6111989f83d584006ebceb49
26,385
def get_all_lights(scene, include_light_filters=True): """Return a list of all lights in the scene, including mesh lights Args: scene (byp.types.Scene) - scene file to look for lights include_light_filters (bool) - whether or not light filters should be included in the list Returns: (list)...
4570f36bdfbef287f38a250cddcdc7f8c8d8665d
26,386
def get_df(path): """Load raw dataframe from JSON data.""" with open(path) as reader: df = pd.DataFrame(load(reader)) df['rate'] = 1e3 / df['ms_per_record'] return df
0e94506fcaa4bd64388eb2def4f9a66c19bd9b32
26,387
def _format_distribution_details(details, color=False): """Format distribution details for printing later.""" def _y_v(value): """Print value in distribution details.""" if color: return colored.yellow(value) else: return value # Maps keys in configuration to...
ccfa7d9b35b17ba9889f5012d1ae5aa1612d33b1
26,388
async def async_get_relation_id(application_name, remote_application_name, model_name=None, remote_interface_name=None): """ Get relation id of relation from model. :param model_name: Name of model to operate on :type model_name: str :...
2447c08c57d2ed4548db547fb4c347987f0ac88b
26,389
from operator import or_ def get_timeseries_references(session_id, search_value, length, offset, column, order): """ Gets a filtered list of timeseries references. This function will generate a filtered list of timeseries references belonging to a session given a search value. The length, offset, and...
67011d7d1956259c383cd2722ae4035c28e6a5f3
26,390
def mxprv_from_bip39_mnemonic( mnemonic: Mnemonic, passphrase: str = "", network: str = "mainnet" ) -> bytes: """Return BIP32 root master extended private key from BIP39 mnemonic.""" seed = bip39.seed_from_mnemonic(mnemonic, passphrase) version = NETWORKS[network].bip32_prv return rootxprv_from_see...
ceb5f5e853f7964015a2a69ea2fdb26680acf2b3
26,392
def translate_text( text: str, source_language: str, target_language: str ) -> str: """Translates text into the target language. This method uses ISO 639-1 compliant language codes to specify languages. To learn more about ISO 639-1, see: https://www.w3schools.com/tags/ref_language_codes.as...
ed82dbb2fd89398340ed6ff39132f95758bfab97
26,394
def evt_cache_staged_t(ticket): """ create event EvtCacheStaged from ticket ticket """ fc_keys = ['bfid' ] ev = _get_proto(ticket, fc_keys = fc_keys) ev['cache']['en'] = _set_cache_en(ticket) return EvtCacheStaged(ev)
86543ca98257cab28e4bfccef229c8d8e5b6893b
26,395
from typing import Dict def _get_setup_keywords(pkg_data: dict, keywords: dict) -> Dict: """Gather all setuptools.setup() keyword args.""" options_keywords = dict( packages=list(pkg_data), package_data={pkg: list(files) for pkg, files in pkg_data.items()}, ) keyw...
34f2d52c484fc4e49ccaca574639929756cfa4dc
26,396
import six def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,...
041807c1622f644c062a5adb0404d14589cc543b
26,397
from clawpack.visclaw import colormaps, geoplot from numpy import linspace from clawpack.visclaw.data import ClawPlotData from clawpack.visclaw import gaugetools import pylab import pylab from numpy import ma from numpy import ma import pylab import pylab from pylab import plot, xticks, floor, xlabel def setplot(plot...
a777686f5b8fafe8c2a109e486242a16d25a463b
26,398
from typing import Dict import json def load_spider_tables(filenames: str) -> Dict[str, Schema]: """Loads database schemas from the specified filenames.""" examples = {} for filename in filenames.split(","): with open(filename) as training_file: examples.update(process_dbs(json.load(tr...
1575d0afd4efbe5f53d12be1c7dd3537e54fc46c
26,399
from typing import Dict import array def extract_float_arrays(blockids: str, data: bytes) -> Dict[str, array]: """Extracts float arrays from raw scope, background trace, and recorder zoom binary data (block ids a, A, b, B, x, y, Y in the DLC pro 'Scope, Lock, and Recorder Binary Data' format). Args: ...
8789f73d175b9d0f244b33b61d0fe1effa702ded
26,400
def rotate_image(path): """Rotate the image from path and return wx.Image.""" img = Image.open(path) try: exif = img._getexif() if exif[ORIENTATION_TAG] == 3: img = img.rotate(180, expand=True) elif exif[ORIENTATION_TAG] == 6: img = img.rotate(270, expand=True...
b4f450a3f6cb01a4d9c8e6c384edeabd0366ac63
26,401
def predict(): """Predict endpoint. Chooses model for prediction and predcits bitcoin price for the given time period. @author: Andrii Koval, Yulia Khlyaka, Pavlo Mospan """ data = request.json if data: predict = bool(data["predict"]) if predict: if predictor.p...
90fbc72e3a57ad7dae3617bec20268c87a0c158a
26,402
def splice_imgs(img_list, vis_path): """Splice pictures horizontally """ IMAGE_WIDTH, IMAGE_HEIGHT = img_list[0].size padding_width = 20 img_num = len(img_list) to_image = Image.new('RGB', (img_num * IMAGE_WIDTH + (img_num - 1) * padding_width, ...
97d4ab32f1a734fbd04e7c558062867c2e6bd3b4
26,403
def create_segmented_colormap(cmap, values, increment): """Create colormap with discretized colormap. This was created mainly to plot a colorbar that has discretized values. Args: cmap: matplotlib colormap values: A list of the quantities being plotted increment: The increment used...
9ab8a0a95896e1ae0f8777b705f920196afc6627
26,404
from io import StringIO def division_series_logs(): """ Pull Retrosheet Division Series Game Logs """ s = get_text_file(gamelog_url.format('DV')) data = pd.read_csv(StringIO(s), header=None, sep=',', quotechar='"') data.columns = gamelog_columns return data
414de8e0409bba9651bef81bbdc811e105d1d11f
26,405
def release_date(json): """ Returns the date from the json content in argument """ return json['updated']
635efd7140860c8f0897e90433a539c8bd585945
26,406
def init_embedding_from_graph( _raw_data, graph, n_components, random_state, metric, _metric_kwds, init="spectral" ): """Initialize embedding using graph. This is for direct embeddings. Parameters ---------- init : str, optional Type of initialization to use. Either random, or spectral, by ...
22c2d939a47932b625491a1e685b055214753010
26,407
def basic_hash_table(): """Not empty hash table.""" return HashTable(1)
b06e59c2a6767309e5394df6e51bdaf12c58d073
26,408
def scan_by_key(key, a, dim=0, op=BINARYOP.ADD, inclusive_scan=True): """ Generalized scan by key of an array. Parameters ---------- key : af.Array key array. a : af.Array Multi dimensional arrayfire array. dim : optional: int. default: 0 Dimension along which th...
ea9556b3e2a87a08cca62d03da41edf5985d4156
26,409
def local_luminance_subtraction(image, filter_sigma, return_subtractor=False): """ Computes an estimate of the local luminance and removes this from an image Parameters ---------- image : ndarray(float32 or uint8, size=(h, w, c)) An image of height h and width w, with c color channels filter_sigma : ...
d9cc46a205f495c0107211d7222be27f40d6896b
26,410
def createBank(): """Create the bank. Returns: Bank: The bank. """ return Bank( 123456, 'My Piggy Bank', 'Tunja Downtown' )
676f0d6cf330e7832064393b543a5ffd1f1068d1
26,411
def str_to_bool(param): """ Convert string value to boolean Attributes: param -- inout query parameter """ if param.upper() == 'TRUE': return True elif param.upper() in ['FALSE', None]: return False else: raise InputValidationError( 'Invalid query...
ef860e2b2e623d98576c04ef1e397604576d8d48
26,412
from typing import Optional from typing import List from typing import Dict from datetime import datetime def fetch_log_messages(attempt_id: Optional[int] = None, task_id: Optional[int] = None, min_severity: Optional[int] = None): """ Fetch log messages from the d...
10e78d0ee14647cf7a390287208a28aa957551a4
26,415
def part_1_solution_2(lines): """Shorter, but not very readable. A good example of "clever programming" that saves a few lines of code, while making it unbearably ugly. Counts the number of times a depth measurement increases.""" return len([i for i in range(1, len(lines)) if lines[i] > lines[i - 1]...
d393f0385a1afbea4c2f3b4d3f51d8e7d0ade204
26,417
def get_lifecycle_configuration(bucket_name): """ Get the lifecycle configuration of the specified bucket. Usage is shown in usage_demo at the end of this module. :param bucket_name: The name of the bucket to retrieve. :return: The lifecycle rules of the specified bucket. """ s3 = get_s3()...
380c884afddbf72db6474e60480bf75ebe67309e
26,418
def compute_reward(ori, new, target_ids): """ Compute the reward for each target item """ reward = {} PE_dict = {} ori_RI, ori_ERI, ori_Revenue = ori new_RI, new_ERI, new_Revenue = new max_PE, min_PE, total_PE = 0, 0, 0 for item in target_ids: PE = new_Revenue[item] - ori_Revenue[item] # Eq. (3) in paper...
a64a1c47089924d373c7435c5018c63fd4edbe74
26,419
from typing import Any import torch import tqdm def _compute_aspect_ratios_slow(dataset: Any, indices: Any = None) -> Any: """Compute the aspect ratios.""" print( "Your dataset doesn't support the fast path for " "computing the aspect ratios, so will iterate over " "the full dataset an...
8fd183a5c353503067666526bdf6722bb53a4317
26,420
import getopt def parse_args(input_args): """ Parse the supplied command-line arguments and return the input file glob and metric spec strings. :param input_args: Command line arguments. :return: A triplet, the first element of which is the input file glob, the second element is the ...
a15327a3aa2aae86ef8ad14ebcae46b6f3593503
26,421
def _diffuse(field: jnp.ndarray, diffusion_coeff: float, delta_t: float) -> jnp.ndarray: """ Average each value in a vector field closer to its neighbors to simulate diffusion and viscosity. Parameters ---------- field The vector field to diffuse. *Shape: [y, x, any].* diffusion_coe...
e05763df93164bd7b4baa778720dbecc32fea228
26,422
def dAdzmm_ron_s0(u0, M, n2, lamda, tsh, dt, hf, w_tiled): """ calculates the nonlinear operator for a given field u0 use: dA = dAdzmm(u0) """ print(u0.real.flags) print(u0.imag.flags) M3 = uabs(np.ascontiguousarray(u0.real), np.ascontiguousarray(u0.imag)) temp = fftshift(ifft(f...
57c958bca07b77eaa406cb6b95bf5719af34075b
26,423
def create_support_bag_of_embeddings_reader(reference_data, **options): """ A reader that creates sequence representations of the input reading instance, and then models each question and candidate as the sum of the embeddings of their tokens. :param reference_data: the reference training set that deter...
0b09423e9d62d1e5c7c99bd1ebede22ca490797a
26,424
def get_hosts_cpu_frequency(ceilo, hosts): """Get cpu frequency for each host in hosts. :param ceilo: A Ceilometer client. :type ceilo: * :param hosts: A set of hosts :type hosts: list(str) :return: A dictionary of (host, cpu_frequency) :rtype: dict(str: *) """ hosts_cpu_total ...
aa6049b9d011d187e1a246a413835aafdbb5c6dc
26,425
def _cloture(exc): """ Return a function which will accept any arguments but raise the exception when called. Parameters ------------ exc : Exception Will be raised later Returns ------------- failed : function When called will raise `exc` """ # scoping will sav...
b2e22f5b4bd267d1945b7f759f5ddfb1ee8c44e5
26,426
from typing import Dict import json def _with_environment_variables(cmd: str, environment_variables: Dict[str, object]): """Prepend environment variables to a shell command. Args: cmd (str): The base command. environment_variables (Dict[str, object]): The set of environment variab...
ae27d9e7a62f49e836f1c1b116205f318d9d0dd3
26,427
def update_spam_assets(db: 'DBHandler') -> int: """ Update the list of ignored assets using query_token_spam_list and avoiding the addition of duplicates. It returns the amount of assets that were added to the ignore list """ spam_tokens = query_token_spam_list(db) # order maters here. Make ...
4e7f4e5ae8a6b92ebd5a60a34d9330330690b663
26,428
import png def png_info(path): """Returns a dict with info about the png""" r = png.Reader(filename=path) x, y, frames, info = r.read() return info
97b9df7dd7800f350695e8d678d25154c7a4b2b8
26,430
def _(data: ndarray, outliers: ndarray, show_report: bool = True) -> ndarray: """Process ndarrays""" if type(data) != type(outliers): raise TypeError("`data` and `outliers` must be same type") # convert to DataFrame or Series data = DataFrame(data).squeeze() outliers = DataFrame(outliers).sq...
1c478af8a6fffcf6240b2547782ee3fc256fdd0c
26,431
import six def bool_from_string(subject, strict=False, default=False): """ 将字符串转换为bool值 :param subject: 待转换对象 :type subject: str :param strict: 是否只转换指定列表中的值 :type strict: bool :param default: 转换失败时的默认返回值 :type default: bool :returns: 转换结果 :rtype: bool """ TRUE_STRINGS ...
3c6efa416471da391e60b82aec3753d823ee2878
26,432
def prot_to_vector(seq: str) -> np.ndarray: """Concatenate the amino acid features for each position of the sequence. Args: seq: A string representing an amino acid sequence. Returns: A numpy array of features, shape (len(seq), features)""" # convert to uppercase seq = seq.upper() ...
ac5293ee67698243e4910c87944133f9697d8646
26,433
def set_partition(num, par): """ A function returns question for partitions of a generated set. :param num: number of questions. :param par: type of items in the set based on documentation. :return: questions in JSON format. """ output = question_list_maker(num, par, 'set-par...
71540d753020e5333558098b7edf96c4318fb316
26,435
def meanS_heteroscedastic_metric(nout): """This function computes the mean log of the variance (log S) for the heteroscedastic model. The mean log is computed over the standard deviation prediction and the mean prediction is not taken into account. Parameters ---------- nout : int Number of out...
75bc5ddb482cc0e99bb4f5f9b0d557321b57cf06
26,436
def ec2_connect(module): """ Return an ec2 connection""" region, ec2_url, boto_params = get_aws_connection_info(module) # If we have a region specified, connect to its endpoint. if region: try: ec2 = connect_to_aws(boto.ec2, region, **boto_params) except (boto.exception.No...
d94b5a1359a31657aa2dffd1f0c11d9cd06493dd
26,437
import glob def read_lris(raw_file, det=None, TRIM=False): """ Read a raw LRIS data frame (one or more detectors) Packed in a multi-extension HDU Based on readmhdufits.pro Parameters ---------- raw_file : str Filename det : int, optional Detector number; Default = both ...
98351f63a78a37ac8cbb3282e71903ee6dd6bbb1
26,438
def mu(n: int) -> int: """Return the value of the Moebius function on n. Examples: >>> mu(3*5*2) -1 >>> mu(3*5*2*17) 1 >>> mu(3*3*5*2) 0 >>> mu(1) 1 >>> mu(5) -1 >>> mu(2**10-1) -1 """ if n == 1: re...
b8347480041de2dc9dfc469096293e3815eebbcd
26,439
def find_last(arr, val, mask=None, compare="eq"): """ Returns the index of the last occurrence of *val* in *arr*. Or the last occurrence of *arr* *compare* *val*, if *compare* is not eq Otherwise, returns -1. Parameters ---------- arr : device array val : scalar mask : mask of the a...
376a21174bc26ca332768aadf96b84b06e7f55f5
26,440
def find_orphans(input_fits, header_ihdus_keys): """Return a dictionary with keys=(ihdu, key) and values='label' for missing cards in 'header_ihdus_keys' Parameters: ----------- input_fits: astropy.io.fits.HDUList instance FITS file where to find orphan header cards header_ihdus_keys: l...
bcc98722ba43450ff68367f776a84c0e193447d9
26,441
def Rotation_multiplyByBodyXYZ_NInv_P(cosxy, sinxy, qdot): """ Rotation_multiplyByBodyXYZ_NInv_P(Vec2 cosxy, Vec2 sinxy, Vec3 qdot) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & qdot: SimTK::Vec3 const & """ return _simbody.Rotation_multiplyByB...
93303a83224b29d9dddf09a64f36d7004ae2ace0
26,443
def sqrt(x: float): """ Take the square root of a positive number Arguments: x (int): Returns: (float): √x Raises: (ValueError): If the number is negative """ if x < 0: raise ValueError('Cannot square-root a negative number with this ' ...
ab43573010044ffa3861f6a13a58135be52c02b4
26,444
def get_tree_type(tree): """Return the (sub)tree type: 'root', 'nucleus', 'satellite', 'text' or 'leaf' Parameters ---------- tree : nltk.tree.ParentedTree a tree representing a rhetorical structure (or a part of it) """ if is_leaf_node(tree): return SubtreeType.leaf tree_t...
15d292ab1f756594add92a6999c7874f6d7fc45b
26,445
def intersection(ls1, ls2): """ This function returns the intersection of two lists without repetition. This function uses built in Python function set() to get rid of repeated values so inputs must be cast to list first. Parameters: ----------- ls1 : Python list The first list. Cannot be array. ls2 : Pyt...
fb3bda67d8040da5f4f570e8ff10a8503e153f36
26,446
def params_count(model): """ Computes the number of parameters. Args: model (model): model to count the number of parameters. """ return np.sum([p.numel() for p in model.parameters()]).item()
12bb8463f6eb722a5cb7e7adfdf869764be67944
26,448
from pathlib import Path import platform import shutil def open_cmd_in_path(file_path: Path) -> int: """ Open a terminal in the selected folder. """ if platform.system() == "Linux": return execute_cmd(["x-terminal-emulator", "-e", "cd", f"{str(file_path)}", "bash"], True) elif platform.system() ==...
899424cd8ab2d76a5ca47d7219a7057d29bb5abe
26,449
def get_f(user_id, ftype): """Get one's follower/following :param str user_id: target's user id :param str ftype: follower or following :return: a mapping from follower/following id to screen name :rtype: Dict """ p = dict(user_id=user_id, count=200, stringify_ids=True, include...
31371d823509c8051660ca0869556253af6b99cc
26,450