content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import tempfile import shlex import subprocess import shutil def RunRevision(context, revision, zip_file, profile, num_runs, command, args): """Given a zipped revision, unzip it and run the test.""" print('Trying revision %s...' % str(revision)) # Create a temp directory and unzip the revision into i...
81b1af05af9d29386e60f155315438f97a68941d
45,300
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('items', metavar='str', nargs='+',...
9d6708b9fcdfe2ade4e0a975b0cc618c5f0590b2
45,301
def formatted_loss_components_string(components: dict) -> str: """ Formats the components returned by calc_LV_Lbeta """ total_loss = components['L_V']+components['L_beta'] fractions = { k : v/total_loss for k, v in components.items() } fkey = lambda key: f'{components[key]:+.4f} ({100.*fractions...
717419a5ddccc0c3b020b6412cd497e5d67c8602
45,302
from typing import Union def teardown_cluster(cluster_config: Union[dict, str]) -> None: """Destroys all nodes of a Ray cluster described by a config json. Args: cluster_config (Union[str, dict]): Either the config dict of the cluster, or a path pointing to a file containing the config. ...
8cf2a3ab7f576980a3122b6d62f9c826b90158f1
45,303
def _get_placeholders(): """Returns placeholders for the image and segmentation.""" img = tf.placeholder(dtype=tf.float32, shape=_IMAGE_SHAPE) seg = tf.placeholder(dtype=tf.float32, shape=_SEGMENTATION_SHAPE) return img, seg
31652c8aef5d295295b14713485b0d6311973ccc
45,304
def _get_mult_function(mt: sparse.COO): """ Get a function similar to `` lambda a, b: np.einsum('i,ijk,k->j', a, mt, b)`` Returns ------- func : function (array_like (n_dims,), array_like (n_dims,)) -> array_like (n_dims,) A function that computes the appropriate multiplication """ ...
36b5a3bc177b857f443eea45530ae03bfe5f7afa
45,305
def add_sb_to_sb(G, make_clique = False): """Assigns track drivers to the SB muxes. Each mux gets driven from all the tracks entering the same BLE section, apart from those coming from the direction of the wire it drives. This creates a reasonably flexible and very straight-forward to implement switch, ...
3b394ea76f5fa2dcf0de11e0256dbbf6e9ad1c36
45,306
from saq.analysis import _JSONEncoder import json def submission_target_buffer(self, description, analysis_mode, tool, tool_instance, type, eve...
662fd20700547673ea9da6d01659e56e0fe26a6d
45,307
def autoreturn(tree, *, syntax, **kw): """[syntax, block] Implicit "return" in tail position, like in Lisps. Each ``def`` function definition lexically within the ``with autoreturn`` block is examined, and if the last item within the body is an expression ``expr``, it is transformed into ``return expr`...
8bc197d55699c1b948891ef48454e2f3c812405e
45,308
def filter_ignore(annotations, filter_fns): """ Set the ``ignore`` attribute of the annotations to **True** when they do not pass the provided filter functions. Args: annotations (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of annotations ...
f59e6c481eb744245ae9503ae07ed88d1f3f8253
45,309
def load_image_stack(topdir, filename): """ Load ome.tif image stack of either 1,2,3 images Differenciates layers of images as either "left" or "right" image Rotates images 90 degrees and stiches left and right side together Returns the loaded left, right and stiched images. """ fulldatap...
d6a56b4b16b9eb8b67707016213b23e6b3af7460
45,310
def update_dict_params_for_calibration(params): """ Update some specific parameters that are stored in a dictionary but are updated during calibration. For example, we may want to update params['default']['compartment_periods']['incubation'] using the parameter ['default']['compartment_periods_incubatio...
8aaf9cb030076adfddb7c8d5740a2c8cc5c21c06
45,311
def mk_lt(ctx, x, y): """ mk_lt(Int_ctx ctx, Int_net x, Int_net y) -> Int_net Parameters ---------- ctx: Int_ctx x: Int_net y: Int_net """ return _api.mk_lt(ctx, x, y)
8d3f48a64cc96b7df5943e0fe560f707fbdb8644
45,312
def webServerDetection(): """ webServerDetection works like this: -First, program asks user to give IP addresses of web servers ten times. -Then,it scans them via nmap. -It writes details of each web server to a file called web.dat """ web = [] try: # Take 10 input...
9dde346ab5204ea5110ecc6e87174177ad9a5e6b
45,313
def counting_sort(numbers): """Sort given numbers (integers) by counting occurrences of each number, then looping over counts and copying that many numbers into output list. Running time: O(n + k) where k is the range of numbers, because if k is really high then affects the run time significantly. Memo...
7123a215f685ff251c13cfd5210fe1887fe3795f
45,314
def get_payment_balance() -> float: """ Payment balance """ output = 0 payment_dicts = get_payments() for payment_dict in payment_dicts["payments"]: payment = Payment(payment_dict) direction = payment.direction if direction == DIRECTION_TRANSFER: continue op...
b1df2943f333937fdb5d9de2fb98fa67f7fe2ebd
45,315
def round_to(value: float, target: float): """ Round price to price tick value. """ rounded = int(round(value / target)) * target return rounded
74a417e951be6921cb9208144834132b09607a15
45,316
def g_data(rgb_data, dim=ArrayDim.TWO): """ 功能:获取一个 RGB 图像的 G 分量\n 参数:\n rgb_data:一个图像的 rgb 数据(3维数组)\n dim:指明返回值是2维数组还是3维数组\n 返回值:图像的 R 分量数组(是一个2维数组 or 3维数组)\n """ return _rgb_component_data(rgb_data, RGBComponent.G, dim)
d594b6121f436dbc395dcc8a44aca8d3f6372128
45,317
def self_replicator(params, time, gamma_max, nu_max, omega, phi_Rb, phi_Mb, Kd_cpc=0.025, Kd_cnt=5E-4, phi_O = 0, dil_ap...
72009fb3a59cce7786f4830c22a00bf4edd6def9
45,318
def imei_get_subscribers_api(imei, **kwargs): """IMEI Subscribers API (version 2.0) GET route.""" return ImeiApi().get_subscribers(imei, **kwargs)
c29c5d4db0368f8de8e3636220ed6d6f3c795b65
45,319
def AvailableAccounts(): """Get all accounts that have credentials stored for the CloudSDK. This function will also ping the GCE metadata server to see if GCE credentials are available. Returns: [str], List of the accounts. """ store = c_creds.GetCredentialStore() accounts = store.GetAccounts() | S...
c2aa8463bb99295518943537abfeb9e53d968cfe
45,320
def open(format, **kwargs): """ writer.open('.eps') will create a sl.writer instance """ if format not in known_formats: raise WriterFormatError(format, known_formats) return known_formats[format].open(kwargs)
4637c2cbf360e88ad315880bc2cc854e2f3075e8
45,321
def smart_post_expression(): """ This is the function to be called as the first argument for the AddKnobChanged callback later on. Sets its context to nuke.thisNode() and picks up the changing knob by the nuke.thisKnob() command. @return: None """ n = nuke.thisNode() k = nuke.thisKnob() ...
88931a0aac2518df45c3224c94c6b2ac454d7b13
45,322
def bspline_to_bezier(ctrl_points, degree, knot_vector=None): """Extraction of the Constituent Bezier Curves using Boehm's Algorithm. This implementation only works for cubic B-Splines. Derivation is based on the algorithm described in Sederberg's "Computer Aided Geometric Design", on "Extracting Bezie...
f421ad287316f79bca7d1ad1bac9834dcf52e97c
45,323
from dallinger import logger import os import tempfile def find_experiment_export(app_id): """Attempt to find a zipped export of an experiment with the ID provided and return its path. Returns None if not found. Search order: 1. local "data" subdirectory 2. user S3 bucket 3. Dalli...
77ebedd4694b123f83f7a21edae8d3a3ee26ba31
45,324
import argparse def get_cmd_line_args(): """ Parse the command line arguments and return a dict mapping <argument name> -> <value>. """ parser = argparse.ArgumentParser(description=DOC) dhelp = ("Path to directory where to download and convert the 1000 " "Genomes phase3 referenc...
ed0edc1bec8d4de9b7f699d0a4b37b79607ea53f
45,325
def is_private(prefix, base): """prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (a...
fc68641c1483132c2b15af57f3cc11c8062df318
45,326
def probability_move(M, current_vertex): """get moving probabilities for current vertex""" # get current vertex id v_idx = ext.get_python_idx(current_vertex) n = len(M[v_idx]) prob_move = [] my_vertices = [] for col in range(0, n): prob_v = M[v_idx][col] # if target can move...
d6bb1c9f8289475b86d90ccf502c8579116f38f5
45,327
def SqrtISwapXEBOptions(*args, **kwargs): """Options for calibrating a sqrt(ISWAP) gate using XEB.""" return XEBPhasedFSimCharacterizationOptions(*args, **kwargs).with_defaults_from_gate(SQRT_ISWAP)
0362c685e5b8a594d36d4b7a30a651d7656b1c87
45,328
def _set_location(hass, data, location_name): """Fire HA event to set location.""" device = _device_name(data) async_dispatcher_send( hass, TRACKER_UPDATE, device, (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), location_name, data) return web.Response( text="Setting location for ...
cb415b25aae45aca42ed0aa36f8fbc62ac293c88
45,329
import scipy def create_decision_per_leafs(tree): """ Create a decision path matrix for leaf nodes - relative to all nodes of single tree Argument: --------- tree : sklearn style tree object (has attribute .tree_) generated tree to create decision path matricies from Returns: ...
9a0d82c85a4827a194a8d6b7fad28a11e055522e
45,330
from typing import TextIO def load_genre(fhandle: TextIO) -> str: """Load genre data from a file Args: path (str): path to metadata annotation file Returns: str: loaded genre data """ annotation = jams.load(fhandle) return annotation.search(namespace="tag_open")[0]["data"][0]...
2cf9fe938dca3d5bedf1eb80a7adec3fbe02dac3
45,331
import collections def _find_resources(graph, types): """Build up cache of type=>[resource=>localname]]""" resources=collections.defaultdict(dict) for t in types: resources[t]={} for x in graph.subjects(RDF.type, t): resources[t][x]=_quote(localname(x)) resources[RDFS.C...
410324b343c5987cb335aa2cd891ed1e08fddd62
45,332
def vocab_parallel_KLDivLoss(vocab_parallel_s_logits, vocab_parallel_t_logits, epsilon=1e-12): """Helper function for the cross entropy.""" return _VocabParallelKLDivLoss.apply(vocab_parallel_s_logits, vocab_parallel_t_logits, epsilon)
b52610049f45972a43a9617b4b2908991f53530f
45,333
def get_email_list(): """ Returns an array of files parsed into an actual array (as opposed to an object) :return: array of strings """ email_file_list = [] pending_email_list = aws_list_files() for email_file in pending_email_list: email_file_list.append(email_file) # Remove th...
4ce4e77c1217b7b19b7bf0c2a67e6c766932eda8
45,334
def mu_central(components, observation=None, method='centroid', zeropoint=27.0, pixel_scale=0.168, weight_order=0): """ Determine the central surface brightness, by calculating the average of 9 pixels around the centroid Parameters ---------- components: a list of `scarlet.Component` or `scarlet.Co...
673d0cb5eaa43c61552def552f5861916fb4d4fa
45,335
from typing import Optional import uuid import asyncio def num_available_gpus() -> int: """Returns the number of available GPUs, 0 if not a gpu node""" async def async_num_available_gpus() -> int: num_gpus = 0 container: Optional[DockerContainer] = None async with aiodocker.Docker() a...
f55828e8638809d5c2fe9ee011b5d43e9d80c9c7
45,336
def cli(text="", items=None, wraplen=80, header=None, border=None, hchar="/"): """ Provide a standardized look to the SeisFlows command line interface messages The look we are after is something like: $ seisflows cmd ======================= HEADER ////// ...
e945af2767e66170560d9b9be32aecf9c0918397
45,337
def resnext56_8x8d_cifar10(classes=10, **kwargs): """ ResNeXt-56 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrai...
e42420ef73495c6966af0b1033daa8be44e74e6f
45,338
def _unit_fun(x): """unit function""" return x
236dfe5d50b76549e601ef5c65c6a04cf8fcbeb8
45,339
import nose import os.path from datetime import datetime def get_nose_runner(report_folder, parallel=True, process_timeout=600, process_restart=True, xunit_report=False, exclude_integration=True, code_coverage=False): """Create a nose execution method""" def _run_nose(name, working_dir): ...
4729f754aea075a15b5f903946da5713d648958d
45,340
def get_roi_scores(img, d, params): """Return array of all scores for each possible ROI of given dimension.""" shape = [img.shape[i]-d[i]+1 for i in range(3)] + [len(params)] scores = np.empty(shape, dtype=np.float32) for z, y, x, i in np.ndindex(scores.shape): roi = img[z:z+d[0], y:y+d[1], x:x+...
237a11274d9bf01a5aa08989ff84ca45d720c113
45,341
import json def dump_grid(grid: Grid) -> str: """ Dump a grid to JSON Args: grid: The grid. Returns: A json string """ return json.dumps(_dump_grid_to_hayson(grid))
5b0a5c98ba9f0ffbf0b4ea7156b8837a442a0315
45,342
def abstract_connected_regions(sample_list, aspect='rim', show=False, batch_size_cpu=32, batch_size_gpu=64, outer=False): """ :param sample_list: each sample should be a 2d binary numpy array with one semantic, 0 indicate not this semantic and 1 means positive. If a sample has many semantics, you should sli...
774b1d045ccf4f4353c05f1815eb45b4e1f7e405
45,343
def simple_collectd_alarm_generators(update_vals=None): """A function for returning Collectd alarm event generators. Returns generators for a given number of Collectd alarms. :param update_vals: preset values for ALL update events :return: generators for alarms as specified """ test_entity_sp...
09f9a97a49647a7de30abee434a6ee11ba4fa486
45,344
def sample_distribution( p: np.ndarray, random: np.random.RandomState, ) -> int: """Samples an integer with probabilities given by p.""" return random.choice(np.arange(len(p)), p=p)
56cb38fd1c9ff328eeb31e0e692845035a775d42
45,345
def update_confusion_matrix_training_dash(n_clicks, value, n_intervals): """ Function that just calls the update_confusion_matrix_training function. This function is decorated by the Dash Application decorator. Such an arrangement is used as unit testing decorated functions is complex. """ fi...
e0e742d2676bc838e83ca1767ee9af867c325578
45,346
import math import statistics def _get_average_da(streams_da: dict) -> dict: """Calculate average data availability among all data streams""" total_results = {} for k, v in streams_da.items(): for i, j in v.items(): if i not in total_results: total_results[i] = [] ...
db2fde9e13b4cbb5ce43d5f3c2d2ff2abd30f487
45,347
def preview_string(graved): """ Creates preview string of the given graved content. Parameters ---------- graved : `None` or `list` of (`str`, ``Grave``) elements Returns ------ content : `None` or `str` """ if graved is None: return None words = [] for element...
382a9dd339e51d90ba6ba42ee9b45173b5c4c8ec
45,348
import get_text_content_from_text_refs from indra.literature.adeft_tools import universal_extract_text from indra.literature import pubmed_client def _get_text_for_grounding(stmt, agent_text): """Get text context for Adeft disambiguation If the INDRA database is available, attempts to get the fulltext from ...
56905dfd7e446e9ecc2ea8dd6d601763dbae9a0b
45,349
import re def get_pycon_speaker_first_names(soup=None): """Parse the PYCON_HTML using BeautifulSoup, extracting all speakers (class "speaker"). Note that some items contain multiple speakers so you need to extract them. Return a list of first names """ if soup is None: soup = ...
3b1545732f36a611d7f9ec5b7db81e994884a03c
45,350
def read_trec_res_file(file_name): """ Assuming data is in trec format results file with 6 columns, 'Qid entropy cross_entropy Score '""" data_df = pd.read_csv(file_name, delim_whitespace=True, header=None, index_col=0, names=['qid', 'Q0', 'docNo', 'docRank', 'docScore', 'ind']...
47feaa2abe11bc7ccf2ea7555482394f2219ed93
45,351
def bboxes_iou(boxes1, boxes2): """ boxes: [xmin, ymin, xmax, ymax, score, class] format coordinates. """ boxes1 = np.array(boxes1) boxes2 = np.array(boxes2) boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1]) boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) *...
a5fab20307ea3903328ee468cce8e668d8b03f20
45,352
import torch def loss_fn(outputs, labels): """ Compute the binary cross entropy loss given outputs and labels. Args: outputs: (Tensor) dimension batch_size x 1 - output of the model labels: (Tensor) dimension batch_size, where each element is a value in [0, 1] Returns: loss (...
4190c20ccee794f68af5697a7556ac616dde9724
45,353
def find_index(text, pattern): """Return the starting index of the first occurrence of pattern in text, or None if not found. o(n) runtime, based off the length of the text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a st...
b13ce4571f562a95625cc223818c3d11f5e5aa3b
45,354
from typing import Dict def _candidate_to_package_info_artefact(candidate: InstallationCandidate) -> Dict[str, str]: """ Provide artifact metadata """ loc = candidate.link artefact = { 'filename': loc.filename, 'hash': '{}:{}'.format(loc.hash_name, loc.hash), 'url': loc.url, } ...
d6d72a496f7181fa8343dbca0f379f687a86b08d
45,355
import importlib import pkgutil def get_namespace_pkg_types(ns_pkg_name, preferred='egg', print_msg=True, use_env=None): """Determine how namespace packages are installed. Parameters: ns_pkg_name (string): The name of the namespace package to inspect. preferred='eg...
f59cad9ea13cb5f3531719f73d38ca9aea69c636
45,356
def compute_boundary(cpumap, cpulist): """ I think the name is misleading... """ bound = np.searchsorted(cpumap, cpulist) return np.concatenate([bound, [cpumap.size]])
6ac999f361815161399a95488a59a926e3aa4c8a
45,357
import os def basename(fullname): """os.path.basename""" return os.path.basename(fullname)
316d7da5ed346b5923ee053b578be673f13f6c21
45,358
def _compute_element_mse(data_a, data_b): """Compute MSE (Mean Squared Error). :param data_a: Data for element a :param data_b: Data for element b :returns: The MSE value """ return np.mean(np.square(np.subtract(data_a, data_b, dtype=np.double)))
b3679153681ef1843cdf724601a6f35fc654a277
45,359
def sg(P): """ Specific entropy [kJ / kg K] of saturated vapor""" return region4.sg(P)
a1600840f8fc70444e883cfcf2538b1a501a35c4
45,360
def example(request): """ Returns a finished home page to the user """ return render(request, 'page_gen/example.html')
aa1772e31c39d6d68ce8919b86b69db841f2d603
45,361
import re def initial_data_processor(Irwin_FP, pretraining=True, from_disk=True): """ "Simple" utility function to clean the Irwin fire data """ if from_disk: file = gpd.GeoDataFrame( pd.read_pickle( "/home/connor/Desktop/MassCrop/OutputFolder/tabular/tabular_fix...
620166ff4f8453ebcb508df3b4c21d7b532938fa
45,362
def cached(method=None, name=None, ignore_args=False): """A decorator allowing for specifying the name of a cache, allowing it to be modified elsewhere.""" if ignore_args: return _cached_ignore_args(method=method, name=name) else: return _cached(method=method, name=name)
de0757f446d492ccadff024b68fe0c4b52049e16
45,363
import os def example_audio_file(index=0): """ Get path to an example audio file Parameters ---------- index : int, default=0 Index of the audio file Returns ------- path : str Path to the example audio file """ data_path = os.path.dirname(__file__) data_path...
4c0e81ec6e77d48e0d93421d6a851541e84d357d
45,364
def bias_reduced_delta(Y, Ygrid, X, m, num_resamples, conf_level, fy=None, xr=None): """Plischke et al. 2013 bias reduction technique (eqn 30)""" d_hat = calc_delta(Y, Ygrid, X, m, fy=fy, xr=xr) if num_resamples > 0: d = np.zeros(num_resamples) N = len(Y) r = np.random.randint(N, s...
7e32bf57b6e1ba8b343b5e8e66343d2603ff781e
45,365
def _CreateRecipe(messages, agent_rule, os_type, prev_recipes): """Create a recipe for one agent rule in guest policy. Args: messages: os config guest policy api messages. agent_rule: ops agent policy agent rule. os_type: ops agent policy os type. prev_recipes: a list of original SoftwareRecipe. ...
ddd70f25e86d9d77178c99bdbb3f7a0a6dc8d942
45,366
def fixture_extended(): """Return a /forecast/extended/pollen/<ZIP> response.""" return { "Type": "pollen", "ForecastDate": "2018-06-12T00:00:00-04:00", "Location": { "ZIP": "80238", "City": "DENVER", "State": "CO", "periods": [ ...
eff02c6271bc985473c86203cb7a69f4e673c827
45,367
def is_sequencing(lane_info): """ Determine if we are just sequencing and not doing any follow-up analysis """ if lane_info['experiment_type'] in ('De Novo','Whole Genome'): return True else: return False
822125f8603969a4624e07188874aae40f8752d3
45,368
from matplotlib.colors import LinearSegmentedColormap def parula_map(): """Generate a color map similar to Matlab's Parula for use in NeXpy. The color map data are from the 'fake_parula' function provided by Ander Biguri, "Perceptually uniform colormaps" MATLAB Central File Exchange (2020). """ ...
0f0b1d3fa2cd202940d2be9e40aa80028880716b
45,369
def frame_data_to_non_herm_hoff(fname, channel, start=None, stop=None, TDlen=0, window_shape=0., verbose=True,deltaT=None): """ Function to read in data in the frame format and convert it to a COMPLEX16FrequencySeries h(f) = FFT[ h(t) ] Create complex FD data that does not assume Hermitiani...
6d71f3aa0f10eeb4779bea470299426149c470af
45,370
import os def concat_data(years): """ Convert to long format, add 'Year' and concatenate into one DataFrame """ lookup = pd.read_csv("lookup.csv", index_col=0) data = [] for year in years: filename = lookup.loc["Filename", str(year)] sheet_name = lookup.loc["Institutional", str...
d545a5bc6a7f24c80fa770cde6064849b5044c81
45,371
import random def get_session_data(transaction, session_id): """ Looks up (or creates) the session with the given session_id. Creates a random session_id if none is provided. Increments the number of views in this session. Updates are done in a transaction to make sure no saved increments ...
e19423c6ab360ce3ed135227fe18452621ece0d4
45,372
import os def list_examples(): """Return names of all the local examples""" for __, __, file_names in os.walk(example_file()): return [os.path.splitext(f)[0] for f in file_names]
a3e086a4cbb273083feb974764084135f5df942e
45,373
import os def default_executor(**kwargs): """ Initialize and return an executor object. :param config: Settings passed in here will override those in `pywren_config`. Default None. :param job_max_runtime: Max time per lambda. Default 200 :return `executor` object. Usage >>> import pywr...
a6f9d90d73193e58d831ebe9ec9036cec40ae0af
45,374
import string def _split_punc(source): """Split leading or trailing punctuation.""" tokens = source.split(" ") new_tokens = [] for token in tokens: if all(char in string.punctuation for char in token): new_tokens.append(token) continue leading_punc = None for punc in string.punctuatio...
79f49cdfe0663b19f634c749c4bb5d515568fc05
45,375
import six def _ValidateDurationUs(arg_internal_name, arg_value): """Validates an argument which should have Duration value in microseconds.""" try: if isinstance(arg_value, six.string_types): return TIMEOUT_PARSER_US(arg_value) elif isinstance(arg_value, int): return TIMEOUT_PARSER_US(str(arg...
82c938c3957653c983f8dba9a1beef740d72a2e8
45,376
def get_saved_cities(uid): """ Gets the weather information for all the locations listed in the Places List of the user's database record. Args: uid (string) -- the user's key Returns: None if the user doesn't exist in the database. List of weather information (see get_weather()) ...
675c0e3203aa35a49ee189a8f623aa20540b5247
45,377
def shr2shc(omega_real): """ Convert from real to complex spherical harmonics. (See https://en.wikipedia.org/wiki/Spherical_harmonics#Real_form) Parameters ---------- omega_real: ndarray(shape=(N**2,), dtype=float) Returns ------- omega_complex: ndarray(shape=(N**2,), dtype=complex...
cc7f60a3b6559a856d38676b48d7778f16a3860b
45,378
def get_cluster_name(tags): """ Get the cluster name from the list of specified tags :param tags: tags :type tags: [str] :returns: cluster name :rtype: str """ for tag in tags: if tag.startswith("storm.cluster.name:"): return tag.replace("storm.cluster.name:", "") ...
2b811f32d5c61bb093d6a68fcaecddbdce3be057
45,379
from typing import BinaryIO import io import wave import struct def fixture_two_chunk_plain_wav() -> BinaryIO: """Creates a fixture WAVE file with two distinct sections. The audio is 100Hz mono. Each section 10 samples long. Samples in the first alternate between +/-(1 << 5) and in the second between +/-(1 << ...
3c6d06409b40228348c3e5697b8fdc1b9bc73c90
45,380
def convert_hash(fp, hash_func=md5_hash): """ into metadata [byte-read][bytes] format. Args: fp: str filepath hash_func: function for calculating hash of file Returns: tuple (int, hash) int: byte length of the hash """ fn_hash = hash_func(fp) return util.byte_l...
48933b2c5ca19bc6c767adb36589c2f30a8aaaed
45,381
def staircase(A, B, C, compute_T=False, form='c', invert=False, block_indices=False): """ Given a state model data A, B, C, Returns the so-called staircase form State realization to assess the controllability/observability properties. If observer-form is requested, internally the system i...
19b5f76100f3548fe8e5a92416dc1c944a487cfa
45,382
def adjacency_dict(graph): """ Returns the adjacency list representation of the graph. """ adj = {node: [] for node in graph.nodes} for edge in graph.edges: node1, node2 = edge[0], edge[1] adj[node1].append(node2) if not graph.is_directed: adj[node2].append(no...
d7ce44b6106b2b6a6e88f4ced23ec0faa722d80f
45,383
def _detailed_parse_choice(choice): """Return Selected Choice's Full Name string as per its codename. Choices are based as per our server. :param choice: str The code name of the choice :return: str Return Selected Choice's Full Name string as per its codename """ ...
3b7fe18c322426e478b5243ec75e3881d1bd690e
45,384
def np_exponential_moving_average(source: np.ndarray, window_size: int): """ Compute an exponential moving average from a source list. Arguments: source: The source list of data from which to compute the moving average. window_size: The size of the moving average to compute. Ret...
24add1b9e0eceffa7850b914d3bdf0064c2f5690
45,385
def get_body(content_dict): """ Get the content item body or caption, whatever it's called """ content_item = find_content_item(content_dict) if content_item.get('body', False): body = content_item['body'] or '' elif content_item.get('caption', False): body = content_item['capti...
31d128c002eb43cb83bdbef0d6bbaceff52a9313
45,386
def compute_mass_list(dialog_idx, sen_idx): """ Most confusing step... dialog_idx = [41, 81, 134, ...] means the first dialogue of the subtitle is plain_text[0:41] the second dialogue of the subtitle is plain_text[41:81] the third dialogue of the subtitle is plain_text[81:134] ...
9745fbebde8302a1fa3b4fb4d94cc19eb3316458
45,387
def svn_node_kind_from_word(*args): """svn_node_kind_from_word(char word) -> svn_node_kind_t""" return _core.svn_node_kind_from_word(*args)
6c52da476e7801a55392dcfcb82f1a738d98ad79
45,388
def rotate(th): """Return the matrix to rotate a 2-D point about the origin by ``angle``. The angle is measured in radians. To Point a point about a point other then the origin, translate the Point, do the rotation, and translate it back: >>> from sympy.geometry.entity import rotate, translate ...
ad30c797f739bfe6b91354b5802e9aaaede9d8e4
45,389
import os import csv def get_table_unique_keys(table): """Get columns that correspond to jointly unique keys""" # Read rows and append column name and data type to main container template_path = os.path.join(os.environ['MYSQL_TABLE_TEMPLATES_DIR'], f'{table}.csv') with open(template_path, newline=''...
5e345fef6afff8f3d3268d0b75ae557d499a4928
45,390
def autocor(y): """Autocorrelation of array y""" #Formula from: https://www.itl.nist.gov/div898/handbook/eda/section3/eda35c.htm autocorarr = [] counter = 0 denom = sumdenomeq(y) for i in range (len(y)-1): autocorarr.append((sumnomeq(y,i)/denom)) counter += 1 print(f"Progress...
ecf2715cc0786ba29bf1a3414bb69d936efaf0b6
45,391
import shlex import subprocess def run(command: str, timeout: int = 1) -> RunResult: """Run the command and record the result. :param str command: :param int timeout: # timeout :returns: result of the run :rtype: tuple(int, str, str, str) """ cmd = shlex.split(command) try: o...
18d5864b88ece744d890f91a36440056fc807efe
45,392
def get_jenkins_auth_handler(jenkinsuser, jenkinspass, jenkinsurl): """ Get a basic authentification handler for jenkins :param jenkinsuser: jenkins username, str :param jenkinspass: jenkins password, str :param jenkinsurl: jenkins base url, str :return: a list of handlers """ for param ...
e672334c40b3005b553c17a09f4dc7742adef689
45,393
import numpy as np import astropy.io.fits as pyfits import astropy.wcs as pywcs def wfc3ir_header(ra=53.1592277508136, dec=-27.782056346146, pa_aper=128.589, flt='ibhj34h6q_flt.fits', filter='G141'): """Make HST/WFC3-IR image header Parameters ---------- ra, dec: float, float ...
e5b4bfe866e14b294baf84acf63b8fd02941b5b4
45,394
def get_base_graph() -> GeNeG: """ Retrieves the base graph created from the news dataset. """ utils.get_logger().info('GeNeG: Loading base knowledge graph into memory..') global __BASE_GRAPH__ if '__BASE_GRAPH__' not in globals(): initializer = lambda: GeNeG.build_base_graph() __BASE_GR...
c56d40dbb053d22317e055f084de4d9e190ae9a6
45,395
import re def do_parse_pod_name(text): """Find the pod name from the failure and return the pod name.""" p = re.search(r' pod (\S+)', text) if p: return re.sub(r'[\'"\\:]', '', p.group(1)) else: return ""
01c5999a4b735973ef25fc9c0e563cfbd5e70610
45,396
def needle_statistics_alignio(infile): """Reads in a needle alignment file and returns an AlignIO object with annotations Args: infile (str): Alignment file name Returns: AlignIO: annotated AlignIO object """ alignments = list(AlignIO.parse(infile, "emboss")) if len(alignmen...
07eabb4cfae4db60101830dac73c2ccc4c6cb7eb
45,397
def _testProduct_to_dict(product_obj, ctx): """ Returns testProduct instance in dict format. Args: product_obj (_TestProduct): testProduct instance. ctx (SerializationContext): Metadata pertaining to the serialization operation. Returns: dict: product_obj as a ...
7db80ae68cb6966273e53a4f0fb2d9aad52fa119
45,398
def get_phi(struct,obser='ones',rmax=15,delta=0.05,sigma=0.075,kernsize=10,tol=0.1): """ Get the fingerprint phi for a given structure :param struct: The pymatgen structure you want to use :param rmax: The maximum r in Angstroms you want to create the fingerprint for :param obser: The observable yo...
619fba4ac5ea9a0754e32095e2eb566d0f78022e
45,399