content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def process(command, outfile=None, appendfile=None, dequote=False, shell=False, dependency=None, cwd=None): """Spawns a new process Runs command provided as a new process and returns process info Args: command (str): Command t...
ba1408357ebc82a62fcfe440af9fffb75a0b5832
54,900
from typing import Iterator import types from typing import Callable def pure_functions() -> Iterator[None]: """ Context manager to resolve all ``Callable`` as pure functions. It is not a default in ``hypothesis``. """ def factory(thing) -> st.SearchStrategy: like = (lambda: None) if len(...
f34a42762caae8d0d88c99c4810bdd125077f1a6
54,901
import statistics def ft_compute_median_pmi(path, dropdown_topic_list, n_topic_pmi): """ Computes the pmi score for topics in dropdown list. Takes the stored pmi scores and computes their median. Return a dict with {<topicnbr>: <pmiscore>...} """ dict_pmi = dict() for i in dropdown_topic_l...
b9a9a24aceb07c37c8d30fbe4c1e4461d9a347e4
54,902
import sys def parseTestCases(el): """ Iterates over the children in @p el which is expected to have the name 'TestCases', and for each child element named 'EntityTest' is parseTestCase() called. @param el a TestCases element """ if not el.tagName == "TestCases": sys.stderr.write(...
030c2691b88f21559dad4bd453c1639140512a49
54,903
def build_next_gen_network_flow_environment( environment_config, episode_length, order_gen: str, reward_function_name: str ): """ Second generation of shipping point assignment environment. Args: environment_config: A dictionary with the config to build the environment, see any PTL run for an ex...
3964a82ecb1e4ad80eeb7d6a0694f6b080fed3dc
54,904
def not_found_or_method_not_allowed(request): """ Overrides the default is HTTPNotFound [404] by appropriate HTTPMethodNotAllowed [405] when applicable. Not found response can correspond to underlying process operation not finding a required item, or a completely unknown route (path did not match any e...
699c573874056639b37492acad0ac2d0c3b0bcbf
54,905
def get_dot_file_path(gname): """ For a graph named gname, this method returns the path to its dot file in the dot_atlas directory. Parameters ---------- gname : str Returns ------- str """ return "dot_atlas/good_bad_trols_" + gname + ".dot"
4ead9a2c3656718a8c088e879742962a9782ef02
54,906
def template(str, template_context, strict_undefined=False): """ Return the value of string templated through the dictionary 'template_context' """ if strict_undefined: env = Environment(undefined=StrictUndefined) else: env = Environment() t = env.from_string(str) result = t....
9f3abe599cbabc676781d096e4609c06fa92f3ea
54,907
def get_dataset(bridge, num_classes): """ Create a tf.data dataset which yields batches of samples for training. Args: bridge: the isaac sample accumulator node which we will acquire samples from Returns: A tf.data dataset which yields batches of training examples. """ dataset = tf.data.D...
9d432f5c7bcbbc7992d03a4cf3e0477940ac3a10
54,908
import numpy import math def monteCarlo(temp, size, trials): """ Calculate the energy and magnetization (\"straight\" and squared) for a given temperature Input: - temp: Temperature to calculate for - size: dimension of square matrix - trials: Monte-carlo trials (how many times do we ...
4221e656dc9bc094b6bde9a6a2a7c629009bd1a9
54,909
def test_api(request, n): """ The API test request handler :param request: the request itself :param n: request path parameter :return: the HTTP response """ if "exception" in request.GET.keys(): try: exception = import_string(request.GET['exception']) raise ...
586c6db94be9b1d294a5f83437aca68f636c28cc
54,910
def parse_sample(sample_text, genotypic): """Parse a single Sample.""" d = {} d['SampleName'] = clean_up(RE_SAMPLENAME.search(sample_text).group(1)) d['SampleSize'] = int(RE_SAMPLESIZE.search(sample_text).group(1)) d['SampleData'] = parse_sampledata(RE_SAMPLEDATA.search(sample_text).group(1), genoty...
6147c11cb78e6ae22ab3cf40537a1d6770edcff5
54,911
def login(): """ Allows user to login to their user account """ if request.method == "POST": # check if username exists in db existing_user = mongo.db.users.find_one( {"username": request.form.get("username").lower()}) if existing_user: # ensure hashed password m...
71cc495eb107e1749737d0757d88a87b4872a6a3
54,912
def rgbi3d(include_top=True, weights=None, input_tensor=None, input_shape=(64, 112, 112, 3), dropout_prob=0.5, channel_axis=4, endpoint_logit=True, classes=10): """ RGB Iception 3D model for video action recognition :param include_...
e9813a1f21c5ebfd1cfdf3db8173964d5d5e0975
54,913
def demand_r2_score(regr, X, y, sample_weight=None): """ Return r2 score of the predicted demand X is a matrix of features with X[:, 0] being the M1 time y is the observed M3 time """ y_true, y_pred = predict_demand(regr, X, y) return r2_score(y_true, y_pred, sample_weight)
0915b0fcd3cf46b5089871960e39d174767dca98
54,914
def widgets_match_pixel_mapping( pixel_mapping: PixelMapping, pixel_options: PixelOptions ) -> bool: """ Checks that the contents of the pixel mapping widgets match the contents of a PixelMapping object. :param pixel_mapping: The Pixel Mapping object that is being edited via the PixelOptions interface. ...
787dcee1cb27ef1bb50abc5f3eb00ee12e426b01
54,915
import json def listExportFilesJson(request): """ Generates a JSON file containing a list of exportfiles and their properties. """ data_header = [ "format", "datatype", "year", "status", "approved", "export_name", "export_file_name", "generated_d...
6a8ad0bee34584c9c05e586c25042e3bd374538d
54,916
import requests import time import json def retrieve_regional_weather_data(box, start_date, end_date, regional_output=RegionalOutput.AVERAGE, output_format=OutputFormat.DATAFRAME, data_request_delay=10): """ This function is useful to retrieve weather data on a rectangle...
6de07b0a379fc9d07e6466bb94b13fcc89a84cc2
54,917
def learn_loop(dataset, answers, target): ### Just the digits from main dataset """Takes a dataset with expected values returns proper weights for each element of the vector space """ # set initial guess, initial weights, threshold, and learning rate binary_dataset = convert_dataset(dataset) [vector.append(1) f...
323626d79a7cc2dd234519eaf2c5417b83124044
54,918
def _invert_signs(signs): """ Shall we invert signs? Invert if first (most probable) term is negative. """ return signs[0] < 0
4135340cfbeb4fce67513a160b63304a3199cf1a
54,919
def cms_open_profile_from_bytes(profile_bytes: bytes) -> qc3const.PyCapsule: """Returns a handle to lcms profile wrapped as a Python object. The handle doesn't require to be closed after usage because on object delete operation Python calls native cms_close_profile() function automatically. :param ...
e6d499a74c57990db925851093fb51455f74d72f
54,920
def main(): """Simple wrapper to call absltest.main().""" return absltest.main()
ad58d4411c2b2dc8ea054dfb9532893b46e8a055
54,921
import requests def get_http_codes_to_retry(): """ :return: set of http codes that should be retried """ return set(x for x in requests.status_codes._codes if should_retry_http_code(x))
ade17904a68d1d5381803909074fc7f63da00c06
54,922
def is_within_r_periodic(structure, central_pos, neighbor_pos, radius): """ :param structure: :param central_pos: :param neighbor_pos: :param radius: :return: """ images = structure.get_periodic_images(neighbor_pos, super_check=2) # Check to see if images are within the radius f...
a536354649ff24de72535170c4cea87a2ac8266f
54,923
import numpy import math import itertools def balanced_synthetic_dataset_uniform(D, N, B, within_noise = 0.5, between_noise = 0.1, cluster_percentage = 1, association_type = 'parabola', number_of_cat = None ): """ D: int number of features N: int number of samples ...
e0b72fac790e597cf21444cd8da0868a4c61328e
54,924
import watchlists def CMDupload(change_info, args): """Uploads the changelist to the server for review. This does not submit a try job; use gcl try to submit a try job. """ if '-s' in args or '--server' in args: ErrorExit('Don\'t use the -s flag, fix codereview.settings instead') if not change_info.Get...
b186efd15cdf1b3410a70b8622fc0b427fecc7bf
54,925
def GetListArgParser(subparser): """Return the list arg parser. Args: subparser: argparse.ArgumentParser that is attached to main acloud cmd. Returns: argparse.ArgumentParser with list options defined. """ list_parser = subparser.add_parser(CMD_LIST) list_parser.required = False...
90ad014be9eab058712a1702b0d16b4517169868
54,926
import math def calculateAllImpactsUsing(treesMap, traversals): """ tressMap - obvious traversals - A list of tuples with right, down traversal steps """ impactsList = [calculateImpactsFrom(treesMap, traversal[0], traversal[1]) for traversal in traversals] return math.prod(impactsList)
435f5e69b1f788edbcf7d86ff4633bcc6d0d7f60
54,927
import importlib def _import_class(module_and_class_name: str) -> type: """Import class from a module, e.g. 'text_recognizer.models.MLP'""" module_name, class_name = module_and_class_name.rsplit(".", 1) module = importlib.import_module(module_name) class_ = getattr(module, class_name) return clas...
0943f237dd8a3e22611c45ac4e640af18a86b90e
54,928
def detail(): """ Serve up details of a specific exploitdb item """ if request.args(0) is None: redirect(URL('index')) record = db(db.t_exploitdb.f_eid == request.args(0)).select(cacheable=True).first() if not record: redirect(URL('default', 'error', vars={'msg': T('Exploit DB r...
849ab44edfc8e1165afbd0b2c7fedb49161f7c34
54,929
import os import logging def split_dataset(root_dir, filename, split_dir_name, train_size=0.8): """ :param str root_dir: The path of the root directory containing the Dataset file. :param str filename: The plain name of the file inside the root directory. :param str split_dir_name: The ...
31d88d6323d85dc1906e61b160d3ddb8ded7eb61
54,930
def maxnonsat(array, saturated): """ .. todo:: Document this! """ minimum = np.amin(np.clip(array, None, saturated), axis=2) _array = np.ma.MaskedArray(array, mask=np.invert((array > 0.0) & (array<saturated))) maximum = np.ma.amax(_array, axis=2) maximum[maximum.mask] = minimum[maxim...
80b946454db7c52ed644d37e544cc720789a7d72
54,931
import json import subprocess def get_pub_addr(controller: str): """Gets the hostname that Ambassador will respond to.""" # Check if we've manually set a hostname on the ingress try: output = get_output('juju', 'kubectl', 'get', 'ingress/ambassador', '-ojson') return json.loads(output)['s...
3c050ab2389df953f9225f1c885222e38fba1cd6
54,932
def parse_directive(source_text, directive): """ <Purpose> Given the file source, 'source-text', this function will search for the given directive. <Arguments> source_text: The source in which we are searching for a pragma directive. directive: The pragma directive we are searching for. <Excep...
1fb538a75a530ff5c9d368dcc3601be0419fc150
54,933
def minimum_filter(input, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional minimum filter. Either a size or a footprint with the filter must be provided. An output array can optionally be provided. The origin parameter ...
a907b7dc75f4e31af76bf211ec7342582d0490a4
54,934
import os def verify_format(file_path, verification_format): """Verify if a file contains annotations in a specific format. Parameters ---------- file_path : str Path of the file. verification_format : enum (FileFormat) Format of the file. Returns ------- bool ...
317a6c7b4e462de65515a9ce8d867b47c04fbaf3
54,935
def and_operation(entites , set): """ Helper function.. Reduces the set on every iteration. """ for elem in entites: r = find(elem[1] , set) set = r return set
5db8976d94baed3d99de54c08b45e916164d0712
54,936
def get_projection_matrix(w, centroid, centroid_vec): """ Output: projection matrix P that projects a vector onto the subspace spanned by w, centroid, and centroid_vec P is 3 x num_features """ subspace = np.concatenate(( w.reshape(1, -1), centroid.reshape(1, -1), ...
565c78eaa02e7c09bd08d957b7a7a62cd83e574c
54,937
def safe_xml_tag_name( name: str, numeric_prefix: str = "tag-", empty_fallback: str = "empty-tag" ) -> str: """ Returns a safe xml tag name by replacing invalid characters with a dash. :param name: The name that must be converted to a safe xml tag name. :param numeric_prefix: An xml tag name can't ...
fea34367fbc7f2a4b9dbe23d11c70ecb75dad3da
54,938
def channel(target, pem=None, opts=None): """Construct a grpc channel. Args: target: url of target include host:port pem: ssl/tls pem location opts: grpc channel options grpc.default_authority: default authority grpc.ssl_target_name_override: ssl target n...
7c8880c79662bab3a6d92f1acc12bf31b0456945
54,939
def get_diagnostics(obsname, beamnum, obstype, versionnum, directory): """Get diagnostic to common DB. Inputs: obsname: Observation name in the format: {Project ID}.{Source name}.{MJD}.{Sequence number} beamnum: ALFA beam number (an integer between 0 ...
fc1c863c401af4265ec96ae871013a6917e8345d
54,940
def override_dataframe(dataframe1, dataframe2, index_cols): """override data from dataframe2 in dataframe1 using index_cols as a key to compare. """ dx = dataframe1.to_dict(orient="records") dy = dataframe2.to_dict(orient="records") ddx = {tuple(r[c] for c in index_cols): r for r in dx} ddy...
5daa8b33c98ddb230f13ddf5fe22f3d7e982b9a0
54,941
def create_list(user): """ @api {post} /user/list Create a reading list @apiName Create a reading list @apiGroup List @apiUse AuthorizationTokenHeader @apiParam {String} name List name. @apiParamExample {json} Request (Example) { "name": "CMPUT495 Seminar" } ...
4750f8acd1e6a94a51fb4462c23c8c00cd16582c
54,942
def _opstr_to_meas_circ(op_strings): """Constructs circuits with the correct post-rotations for measurements. Parameters ---------- op_strings : list of str List of strings representing the operators needed for measurements. Returns ------- circs : list of qiskit.QuantumCircuit ...
28fae80f5c874132646101d4620fd622ebd177bb
54,943
import pathlib from typing import Optional def _local_sync_map(local_path: pathlib.Path) -> Optional[_SyncMap]: """ List all the files and directories beneath the ``local_path``. All paths are given as relative paths to the ``local_path``. :param local_path: path to a local directory :return: co...
68dcde7ba2486865ecad7de90a89afa01643ab7b
54,944
def short_long_peak_detector(t_stats, thresholds, window_lengths, peak_height): """Peak detector for two signals. Signal derived from shorter window length takes precedence. Transcribed from find_events_single_scale in wavelet_util.cpp. Equivalent to the MinKNOW implementation as of 25/06/2014. :p...
849d74057b774c42fd233363140770b27e450021
54,945
from sys import flags def hermitian(cls): """ Decorator for hermitian operators, i.e. operators that are equal to their adjoint. It sets the 'linear' and 'hermitian' flags. Note that implicit shape hermitian operators do not have to be square. """ return flags(cls, 'hermitian')
474c16a715c20607b9166c73e67e7b215c1fb6d7
54,946
import sys import binascii def x(h): """Convert a hex string to bytes""" if sys.version > '3': return binascii.unhexlify(h.encode('utf8')) else: return binascii.unhexlify(h)
3e22bddbadf356e8a97c8c2da3406680a4b79e38
54,947
def ATOL(*new_atol): """Alias for `cfdm.atol`.""" return atol(*new_atol)
6f0cf612ce30af83fdb846ceb3a9cd45417bb647
54,948
def pos_extractor(sentence): """ extract Noun, Adjective, Verb only """ tokens = [] pos = tw.pos(sentence, norm=True, stem=True) for token, p in pos: if p == 'Noun' or p == 'Adjective' or p == 'Verb': tokens.append(token) return tokens
ee2b47e94395b554740bfa286ade5871b1d94dc6
54,949
def pkg_info(): """Return project information for setuptools.""" try: doc = __doc__.decode("UTF-8") except (AttributeError, UnicodeError): doc = __doc__ # Python3, or some strangeness return dict( # project data & layout name = __name__.split('.')[0], ## TODO: ve...
789149ecc3ebd711c7a9ec472077cde30319c807
54,950
import numpy def _plot_composite( composite_file_name, composite_name_abbrev, composite_name_verbose, plot_saliency, output_dir_name): """Plots one composite. :param composite_file_name: Path to input file. Will be read by `_read_composite`. :param composite_name_abbrev: Abbrevia...
e115f9bc5158c8aad25688a533ab59131373c8d4
54,951
import logging import json def open_json(filename): """ Given a filename unpacks a json object into an annotation list """ logging.info('Opening json file {}'.format(filename)) with open(filename) as infile: try: logging.info('Decoding .json into annotations'.format(filename)) ...
693b1d07f98e658d004459337da7b97c0405c906
54,952
def lensing_efficiency(x, zx, nz): """Lensing efficiency. This function computes the general form of the lensing efficiency function given in [1]_. Parameters ---------- x: (nx,) array_like Array of comoving distances at which evaluate the lensing efficiency function. zx: ar...
0a775747aa4a3912ef972ce507e92b3d797828d8
54,953
from typing import List from typing import Dict def get_columns_from_tables(tables: List[Table]) -> List[Column]: """ Return the superset of columns from a list of tables. """ columns: Dict[str, Column] = {} for table in tables: for column in table.columns: name = column.name ...
685664217040256f0ad420aafd44a5384af19354
54,954
def build_model(input_size: int, output_size: int, hidden_sizes: list) -> nn.Sequential: """Create the neural network model""" return nn.Sequential( nn.Linear(input_size, hidden_sizes[0]), nn.Tanh(), nn.Linear(hidd...
77970c09cd2553ae64e6da8b3cc9a3dfe1b28871
54,955
import os def get_attachment(host, oec_id, job): """ 发送结果附件 :param host: :param oec_id: :param job: :return: """ dir_job = os.path.join(dir_results, host, oec_id, job) attachment = dir_job + '.tar.gz' filedir = os.path.dirname(attachment) filename = os.path.basename(attachm...
6e9c6965dbe7deeef68efb569904d1d28f4a2c31
54,956
def list_multipart_upload(resource, bucket_name, prefix=""): """List in-progress multipart uploads""" client = resource.meta.client mpupload = client.list_multipart_uploads(Bucket=bucket_name, Prefix=prefix) return { "Uploads": mpupload.get("Uploads"), "CommonPrefixes": mpupload.get("Co...
669b852a8c38acc58f1a4dad833a03d011bb4e14
54,957
from re import A def sbox(x): """AES S-Box.""" y = mpc.to_bits(x**254) z = mpc.matrix_prod([y], A, True)[0] w = mpc.vector_add(z, B) v = mpc.from_bits(w) return v
ff201bbdc1982f5c4ec92ecaaf07c8893839a98f
54,958
import scipy def makePermutationMatrix(permList): """ Takes a list defining the permutation and makes the appropriate matrix. """ permList = scipy.array(permList) n = len(permList) if 0 not in permList: permList = permList - 1 permMat = scipy.zeros((n,n),'d') for ii, jj in enum...
bdd04dc4deb15aa69228f0d3004c299dcf1a55a8
54,959
from typing import Tuple def compute_daily_change(series: pd.Series) -> Tuple[Tuple[pd.Series, str], Tuple[pd.Series, str], Tuple[pd.Series, str]]: """returns (change, smooth, smooth2) where 'change' is ...
2867e27344410f9e80dcc1c5c633a91a14aaae9c
54,960
def tcl_prep_otaver(ota=None): """ Prepare variables for OTA versus full check. :param ota: The starting version if OTA, None if not. Default is None. :type ota: str """ if ota is not None: mode = 2 fvver = ota else: mode = 4 fvver = "AAA000" return mode,...
b42c9af8abd9b6c2b361d906737429acf967182b
54,961
def aboutme_view(request): """About me static page""" cl = CategoryLister(request.LANGUAGE_CODE) t = loader.get_template('blog/aboutme.html') c = RequestContext(request, { 'cat_list': cl.get_categories(), 'link_list': Link.objects.all().order_by('order'), 'about_text': AboutMe....
1ce2b147b11cc672d753caa9546ef9e3abc6a55b
54,962
def test4(dims,fout): """ Cylinder defined as a dataset in an otherwise empty box. As per test 3, but the cylinder is along the third dimension instead, to be able to store it more efficiently """ def circle(idx1,idx2,cd1,cd2,r) : d = np.sqrt(abs(idx2-cd2)**2 + abs(idx1-cd1)**2) ...
d00a8365a16eaa6225595b52b95bbfd8dc7bacbb
54,963
import os import copy def get_data(file_path, dest): """ # [input parameters] - file_path: The root path of the dataset returned by the ready_data() function. - dest: 'train' or 'test' -> This is the choice of what metadata to read. It also creates that folder as a result. # Separate the e...
62d93e32af3cf922588a064d873cd6614714ebd8
54,964
def view_specific_post(post_id: int): """...""" form = forms.NewReplyForm() post = models.db.session.query(models.Post).get(post_id) replies = models.db.session.query(models.Post).filter(models.Post.reply_to == post_id) return render_template( 'post.html', form=form, post=po...
75e3fa5afb26d4b07ee8dc04916699ef892d55d5
54,965
from datetime import datetime def child_elem_as_datetime(elem,qname,format): """Returns the content of the child element as datetime.""" child = elem.find_child_element(qname) if child: return datetime.datetime.strptime(str(child.schema_actual_value),format) return None
5cb025448c96a3ed336f7403be622f161bf9d8c3
54,966
def count_large_cell_angle_regions(field, /, min_angle, direction=None, units='rad'): """Count regions with large angles between neighbouring cells. This method counts regions, where the angle between neighbouring cells is above the given threshold. If ``direction`` is no...
2a636d0574ef36d37efc93e29de2e190d4555dc5
54,967
def get_location_count(): """ Get the total number of locations. Returns ------- count : int The total number of locations. """ count = Location.query.count() return count
562d7b6c762ca77d13f74413bb0089db739ca580
54,968
def delete_keyword_metadata(request, hs_file_type, file_type_id, **kwargs): """deletes a keyword for a given logical file The keyword to be deleted is expected as part of the request.POST NOTE: This view function must be called via ajax call """ logical_file, json_response = _get_logical_file(hs_fi...
c1068ab70706b459a38388ed572a7c7c3c270a34
54,969
import numpy def nc_read_var(ncFile,ThisOne): """ Reads a variable from a netCDF file and returns the data, the QC flag and the variable attribute dictionary. """ # check the number of dimensions nDims = len(ncFile.variables[ThisOne].shape) if nDims not in [1,3]: msg = "nc_read_var...
bdd59a3314a44f5cd8d82a36101e16c15d5ba64b
54,970
def whereis_file(self, path): """Same as `whereis_file_()`, but for a single path and return-dict""" #return list(self.whereis_file_([path]))[0] return list(whereis_file_(self, [path]))[0]
d921a2370eaa4369bd0afa589e1b4e12443570e8
54,971
def _build_doxygen_main(args, env): """Customize the doxygen input file. Run the doxygen command, copy in any images, and put the output in the right place.""" if isinstance(args, list): if len(args) < 2: base.die("Need subs dictionary and dummy file arg for the doxygen command " + ...
52ded17816f96e427f3a7b7aaf345dd6065b4aac
54,972
import math def cov(x, y, mean_x=None, mean_y=None, return_gram=False, return_mean=False): """ Computes a covariance between two matrices using the form Cov(X, Y) = E(XY) - E(X)E(Y) This function prevents the need to explicitly compute the outer product E(X)E(Y) by taking advantage of...
d0346d76baf32c30d23df7b6622c904efb340443
54,973
def evaluation(logits, labels): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number ...
d4106c57be1a27758cf51fbfc0774ed337ecc5e2
54,974
def pessoa(texto): """ :param texto: :return: """ while True: p = input(texto).strip().upper() if p.isdigit() or p == '': print('Erro, digite um nome válido por favor.') else: return p
e07755638c291a726b7681dbc013a43b21a3890b
54,975
def get_r_intmit(q_HPU_ave, q_HPU_min): """1時間平均のヒートポンプユニットの断続運転率 (5) Args: q_HPU_ave(ndarray): 1時間平均のヒートポンプユニットの平均暖房出力 (W) q_HPU_min(ndarray): 1時間平均のヒートポンプユニットの最小暖房出力 (W) Returns: ndarray: 1時間平均のヒートポンプユニットの断続運転率 (5) """ r_intmit = np.clip(q_HPU_ave / q_HPU_min, None, 1.0) r...
8598d5f325f90c722b83bcd784a2151f3318299c
54,976
def parse_and_import_eri_2g(parent_dag_name, child_dag_name, start_date, schedule_interval): """Parse and import Ericsson GSM CM data""" dag = DAG( '%s.%s' % (parent_dag_name, child_dag_name), schedule_interval=schedule_interval, start_date=start_date, ) t22 = BashOperator( ...
b07f078463e29767ca0d9f28725c1ba58b38521a
54,977
def np_uncertainty(obs_name, wc_obj, *args, N=100, threads=1, **kwargs): """Get the uncertainty of the prediction of an observable in the presence of new physics. Parameters ---------- - `obs_name`: name of the observable as a string - `wc_obj`: an instance of `flavio.WilsonCoefficients` -...
d8c339a9899506178732f688e7bf6cc19cb99d42
54,978
import re import os def obtain_template(engine_dir, template): """Given a directory with engines and a template downloads an engine if neccessary Args: engine_dir (str): directory where engines are stored template (str): either the name of an engine from the engines directory or a link to reposi...
909a45666c4c7a149b1a265350f32ad5195cd338
54,979
def setup(app): """ Sets up the Sphinx extension for the `problog` directive. """ # register two Sphinx config values used for the extension app.add_config_value('sphinx_problog_code_directory', None, 'env') app.add_config_value('sphinx_problog_execution_server_url', '', 'env') # register t...
c890431df4d7b66b38106696b855d00772bdc2e0
54,980
import numpy def calculate_weighted_statistics(values, weights, statistics): """ Calculates weighted statistics :param values: pixel values :params weights: weight of each pixel, where 0 > weight >= 1 (areas of 0 weight should be masked out first). Weights can be thought of as the proportion of...
502869b5719aa0db59f16f61ab0eaa1c21a7128a
54,981
from typing import Optional from typing import Tuple from typing import List def get_center_location(db: Session, user: Optional[User]) -> Tuple[float, float]: """ Find the center position between all assets. If user is passed and not admin then we only consider assets owned by the user. TODO: if ...
5d90aff0aea56761155d271dc5f5ef2bb04201a5
54,982
def check_sup_x(supp, row_num, z, c): """ delete unusable numbers from rows """ for x in range(3): for y in range(3): for k in row_num: supp[x+z*3][y+c*3][k] = 0 return supp
f776dd426a11ac806a7c025dd6e88c244f988208
54,983
def _get_session_id(config, url): """Retrieve session id associated with url. :param url: HTTP endpoint (including protocol, port and optional user). """ try: return config.parser.get('session_id', url) except NoSectionError: config.parser.add_section('session_id') except NoOptionError: pass
fc787c0ae95a3554991a825ba73bfad46de4db6d
54,984
def average_precision_recall_fscore(results, micro=True): """Return average precision, recall and f-score for list of BinaryClassificationMetrics. """ if micro: total = BinaryClassificationMetrics(*tuple(np.sum(results, axis=0))) return precision_recall_fscore(total.tp, total.fp, total.f...
a18cd518d6cbb71b1716d1c03c2c0a4d0f2e9f46
54,985
def unstratified_pooled_hessian(X, delta, beta): """unstratified_pooled's hessian.""" score_numer, score_denom = collect(unstratified_pooled_score, ["xebx", "ebx"])(X, delta, beta) score_numer_cs = cumsum(score_numer, name="xebx_cs") score_denom_cs = cumsum(score_denom, nam...
869a1bc8a9f96498d89be2fc79d594a237aa57fa
54,986
def get_name_from_key(key) -> str: """Given a dask collection's key, extract the collection name. Parameters ---------- key: string or tuple Dask collection's key, which must be either a single string or a tuple whose first element is a string (commonly referred to as a collection's 'na...
8a5b46a85000325932c043eb4a94864fef2d6dd4
54,987
def cornersphere(x): """Sphere (squared norm) test objective function constraint to the corner""" nconstr = len(x) - 0 if any(x[:nconstr] < 1): return np.NaN return sum(x**2) - nconstr
39e18fdbf69573d19a47537d4faa8a08f3504d79
54,988
from typing import Union def convert_cells_to_percentages(dimensions: Union[CoordinateType, ExtentType], cell_resolution: CellResolutionType) -> Union[ CoordinateType, ExtentType]: """Converts dimensions from cell units to percentage units""" if isinstance(dimensions, CoordinateType): if dimensions.x.units ...
7b9830d392d04f102999154e3364c245e6760cea
54,989
from typing import List def get_gene(entrez_gene_id: str, gene_list: List[GeneInfo], genes: dict): """ Find GeneInfo with a given entrez gene id or create a new GeneInfo """ gene_id = 'NCBIGene:'+str(entrez_gene_id) if gene_id in genes: return genes[gene_id] gene = GeneInfo(gene_id...
eb307f5c36a69ee3e2df600eedc99e6c14a4cec0
54,990
def get_auto_flow(novaclient, process_what): """Constructs and returns the engine entrypoint flow. This flow will do the following: 1. Disable compute service on source host 2. Get all HA_Enabled instances. 3. Evacuate all the HA_Enabled instances. 4. Confirm evacuation of instances. """ ...
3c3813cc56d598e79f91a70a211bbd43e7d1fe10
54,991
def get_percentiles(latency_list, percentages): """ Get the percentiles of the given latency list Arguments: latency_list: The list with latencies as elements p: List of percentiles to plot """ latency_np = np.array(latency_list) # Convert to numpy array sorted_np = np.sort(late...
a229b09bb0fba697ce3da6e3e60409f9c8c28399
54,992
from typing import Optional def make_identifier( signature: InstrSignature, dockerfile: Optional[Dockerfile] = None ) -> str: """ Create an URL friendly identifier string from a signature. This notion of identifier string does not exist in Docker per se, since we do factor in the definituon's mod...
c394e46d6a01e6d7622742efc4529666e308c030
54,993
def configure_mafdf(mafdf, keep_samples): """Configures a maf dataframe Args: mafdf: Chunk of maf dataframe keep_samples: Samples to keep in the maf file Returns: Configured maf dataframe """ keep_mafdf = mafdf[ mafdf['Tumor_Sample_Barcode'].isin(keep_samples.toli...
73a8be59eed431185ddcfaa1ea655ff554f61072
54,994
def yices_function_type2(tau1, tau2, ran): """For convenience: returns the function type tau1, tau2 -> ran, tau1, tau2, ran must be a valid types.""" return libyices.yices_function_type2(tau1, tau2, ran)
8b4e260a97d36c986e5fbabc20c896202255d7aa
54,995
def search(connection, preferred_hosts, ignore_hosts, facets): """Search for files on ESGF. Parameters ---------- connection : pyesgf.search.SearchConnection Search connection preferred_hosts : :obj:`list` of :obj:`str` List of preferred hosts. ignore_hosts : :obj:`list` of :obj...
3baef2b9cd8949b86d48c2a28d5ddf85c27f24a9
54,996
def _gaussian(x,mu,sig,height): """ helper function which computes a guassian """ return height*np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
9fa89b56dfd80ef0365194970415a57e36b0dc8b
54,997
def powers_and_coefs(order): """For a `order`-way FM returns the powers and their coefficients needed to compute model equation efficiently """ decompositions, _ = get_shorter_decompositions(np.ones(order)) graph = defaultdict(lambda: list()) graph_reversed = defaultdict(lambda: list()) for ...
cef362a32422844a919835ee8365d977b05ea95b
54,998
import sqlite3 from typing import Optional def get_account_id_for_api_key(db: sqlite3.Connection, api_key: str) \ -> tuple[Optional[int], AccountFlag]: """ This is not indicative of whether there is an account or not as disabled accounts will not be matched. If the account is valid, then and only ...
9cfaf458da4c132894e9faad041265e9ea648c74
54,999