content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_wolfe_gap(point_x, objective_function, feasible_region): """Compute the Wolfe gap given a point.""" grad = objective_function.evaluate_grad(point_x.cartesian_coordinates) v = feasible_region.lp_oracle(grad) wolfe_gap = grad.dot(point_x.cartesian_coordinates - v) return wolfe_gap
f2b09a232063599aa7525a70e6d3a0d8bafb57e7
3,646,300
async def get(ip, community, oid, port=161, timeout=DEFAULT_TIMEOUT): # type: (str, str, str, int, int) -> PyType """ Delegates to :py:func:`~puresnmp.aio.api.raw.get` but returns simple Python types. See the "raw" equivalent for detailed documentation & examples. """ raw_value = await raw....
6682d9877ac4d5b287088fd17d626011b95b6c31
3,646,301
def preprocess_image(image, params): """Preprocess image tensor. Args: image: tensor, input image with shape [cur_batch_size, height, width, depth]. params: dict, user passed parameters. Returns: Preprocessed image tensor with shape [cur_batch_size, height, ...
4e5a563610c2ecdcd29fa5c077025100625b767b
3,646,302
def get_vlim(xarr: xr.DataArray, alpha: float) -> dict: """Get vmin, vmax using mean and std.""" mean = xarr.mean() std = xarr.std() return {"vmin": max(0., mean - alpha * std), "vmax": mean + alpha * std}
4f6c87f290ab23db56fe67f700136a49e2b52363
3,646,303
def count_consumed_symbols(e): """Count how many symbols are consumed from each sequence by a single sequence diff entry.""" op = e.op if op == DiffOp.ADDRANGE: return (0, len(e.valuelist)) elif op == DiffOp.REMOVERANGE: return (e.length, 0) elif op == DiffOp.PATCH: return (1...
63a3d97840fae49a7ff3279e10e553d82dfcf801
3,646,304
def maha_dist_sq(cols, center, cov): """Calculate squared Mahalanobis distance of all observations (rows in the vectors contained in the list cols) from the center vector with respect to the covariance matrix cov""" n = len(cols[0]) p = len(cols) assert len(center) == p # observation matri...
9e54a7f49ed3b977b351007991f3fe263306a20a
3,646,305
def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return urlresolvers.reverse("comments.view...
d7e6ad126a35109d589d7f2734a4bd3e56df748f
3,646,306
def secret_page(username=None, password=None): """ Returns the HTML for the page visited after the user has logged-in. """ if username is None or password is None: raise ValueError("You need to pass both username and password!") return _wrapper(""" <h1> Welcome, {username}! </h1> <...
3bd81f30f0bf63290c6ee24cf3bccb7090fd406c
3,646,307
import collections def user(username): """ displays a single user """ all_badgers = loads(r_server.get('all_badgers')) this_badger = all_badgers[username] this_badger_sorted = collections.OrderedDict(sorted(this_badger.items(), reverse=True)) days = days_in_a_row(this_badger) kwargs = {'badger...
27cf03175184cc839a64d931aa3477a0196c24aa
3,646,308
import numpy def ifft(a, axis): """ Fourier transformation from grid to image space, along a given axis. (inverse Fourier transform) :param a: numpy array, 1D or 2D (`uv` grid to transform) :param axis: int; axes over which to calculate :return: numpy array (an image in `lm` coordinate space...
3a96d6b615c8da63deaeca5e98a4f82f18fec8dd
3,646,309
import random def transitions_and_masks_to_proposals(t1, t2, m1, m2, max_samples=10, max_ccs=6): """ assumes set-based...
146b937e7a46d6d051b10f900574378874535932
3,646,310
import os from pathlib import Path import logging def make_manifest(root: AnyPath) -> FileManifest: """ Returns the file manifest for the given directory. """ manifest = {} for (dirpath, dirnames, filenames) in os.walk(root): dirnames[:] = sorted(dirnames) for filename in sorted(...
8bd85903615f6da14686599425ea824ae9846955
3,646,311
import requests import re def exists(url): """Check based on protocol if url exists.""" parsed_url = urlparse(url) if parsed_url.scheme == "": raise RuntimeError("Invalid url: %s" % url) if parsed_url.scheme in ('http', 'https'): r = requests.head(url, verify=False) if r.statu...
bb91fd5fb93ec6441125a1aa4874ad6d7f103535
3,646,312
def inverse_chirality_symbol(symbol): """ Inverses a chirality symbol, e.g., the 'R' character to 'S', or 'NS' to 'NR'. Note that chiral double bonds ('E' and 'Z') must not be inversed (they are not mirror images of each other). Args: symbol (str): The chirality symbol. Returns: st...
e87fae6ad9169efac0b3c95f53dfb92e0c450909
3,646,313
def simplify_columns(df): """ Simplify column labels for use as snake_case database fields. All columns will be re-labeled by: * Replacing all non-alphanumeric characters with spaces. * Forcing all letters to be lower case. * Compacting internal whitespace to a single " ". * Stripping leadi...
9ee85c1a9f4aa97f1e3760db8a7dccf32c288802
3,646,314
from typing import Optional def delete( request: HttpRequest, wid: Optional[int] = None, workflow: Optional[Workflow] = None, ) -> JsonResponse: """Delete a workflow.""" if request.method == 'POST': # Log the event Log.objects.register( request.user, Log.WOR...
07b6de0d66a5101660f1bf4aa37abe4be71568ff
3,646,315
def at_threshold(FPR, TPR, parameter, threshold): """ False positive rate (FPR) and True positive rate (TPR) at the selected threshold. :param FPR: False positive rates of given receiver operating characteristic (ROC) curve :param TPR: True positive rate of given receiver operating characteristic (ROC) ...
d66edc0e43a18a5fdf8b6d216e4130aef8a7b17b
3,646,316
def _check_kl_estimator(estimator_fn, distribution_fn, num_samples=10000, rtol=1e-1, atol=1e-3, grad_rtol=2e-1, grad_atol=1e-1): """Compares the estimator_fn output and gradient to exact KL.""" rng_key = jax.random.PRNGKey(0) def expected_kl(params): distribution_a = distribution_fn(*...
b4e34f35f6531f795c8621fee2082993c3b518bd
3,646,317
def relative_bias(simu, reco, relative_scaling_method='s1'): """ Compute the relative bias of a reconstructed variable as `median(reco-simu)/relative_scaling(simu, reco)` Parameters ---------- simu: `numpy.ndarray` reco: `numpy.ndarray` relative_scaling_method: str see `ctaplot....
1bc611b1ea135d593bc9b8c83a02a50eeaf18a7e
3,646,318
from typing import Dict from typing import Any def addon_config() -> Dict[str, Any]: """Sample addon config.""" return { "package-name": "djangocms-blog", "installed-apps": [ "filer", "easy_thumbnails", "aldryn_apphooks_config", "parler", ...
f4266735ef2f0809e5802abed54dfde4c1cbd708
3,646,319
def join_mutations_regions( out_path: str, sample1_id: int, sample2_id: int, mutations_file: File, regions_file: File ) -> File: """ Join mutations and regions together to compute an allele frequence. """ def iter_mut_points(muts): for pos, count in muts: yield pos, "mut", count...
4d712a914e2f4c221df982fbd3352eb4f572ad11
3,646,320
def credibility_interval(post, alpha=1.): """Calculate bayesian credibility interval. Parameters: ----------- post : array_like The posterior sample over which to calculate the bayesian credibility interval. alpha : float, optional Confidence level. Returns: -------- ...
b31009918324980ba2ffc53a1f29af1f4e421f95
3,646,321
def svn_ra_invoke_replay_revstart_callback(*args): """ svn_ra_invoke_replay_revstart_callback(svn_ra_replay_revstart_callback_t _obj, svn_revnum_t revision, void replay_baton, svn_delta_editor_t editor, void edit_baton, apr_hash_t rev_props, apr_pool_t pool) -> svn_error_t """ ret...
4c792a16d6dcdbb588062f1f47b3caed84bbd610
3,646,322
import click def tree(ctx, rootpage): """Export metadata of a page tree.""" if not rootpage: click.serror("No root page selected via --entity!") return 1 outname = getattr(ctx.obj.outfile, 'name', None) with api.context() as cf: results = [] try: #page = c...
d055d8dc5fc5a3a267500362ca89b6e895d9d50f
3,646,323
import math def to_half_life(days): """ Return the constant [1/s] from the half life length [day] """ s= days * 3600*24 return -math.log(1/2)/s
af7724dfb9442bf1f5e931df5dd39b31d0e78091
3,646,324
import struct def Send (dst_ip, data, sequence=0, spoof_source=False, dst_port=MDNS_PORT, src_port=MDNS_PORT, dns_name=TEST_QUERY): """ Send one packet of MDNS with data. :param dst_ip: IP as string. :param data: Data as bytes/string. :param sequence: Number to use for sequence. Int. :param spoof_source: Defaul...
9541c71d52dcbaa09ffba1aa1bf4d4d422d66ed6
3,646,325
from units.models import Unit def accreds_logs_list(request): """Display the list of accreds""" main_unit = Unit.objects.get(pk=settings.ROOT_UNIT_PK) main_unit.set_rights_can_select(lambda unit: Accreditation.static_rights_can('LIST', request.user, unit)) main_unit.set_rights_can_edit(lambda unit:...
41961a3cd4f351d13ae5132cfb37e83be7050cc5
3,646,326
from typing import Counter def build_dict(file_name, max_vocab_size): """ reads a list of sentences from a file and returns - a dictionary which maps the most frequent words to indices and - a table which maps indices to the most frequent words """ word_freq = Counter() with open(file_name) ...
ec2067e1fbf8d0f6845024ae69f8531c1f776348
3,646,327
import functools import logging def from_net(func): """ 为进行相似度数据收集的函数装饰,作用是忽略env中的数据获取模式,改变数据获取模式, 只使用网络数据模式进行数据收集,完成整个任务后,再恢复之前的数据获取模式 :param func: 进行相似度应用且有数据收集行为的函数 """ @functools.wraps(func) def wrapper(*args, **kwargs): # 临时保存env设置中的g_data_fetch_mode fetch_mode = ABuE...
68c3a9302d83cf0e02a74c104fd2b5894b85020a
3,646,328
def create_index(connection, table_name, index): """Create index. Args: connection: pyodbc.connect() object, Connection to use when running Sql table_name: string, Table name including db schema (ex: my_schema.my_table) index: string, Column name of index...
e52ccedda6dc097f58a2d0c826ea2e6010623c4e
3,646,329
def embedding_lookup(ids, params): """ Returns the embeddings lookups. The difference of this function to TensorFlow's function is that this function expects the ids as the first argument and the parameters as the second; while, in TensorFlow, is the other way around. :param ids: the ids :...
ef85f95cfa5d2a426616ee9203707877ae202051
3,646,330
def in_auto_mode(conx: Connection) -> bool: """Determine whether the controller is in AUTO or one of the MANUAL modes. Wraps the Karel IN_AUTO_MODE routine. NOTE: this method is moderately expensive, as it executes a Karel program on the controller. :returns: True if the controller is in AUTO...
c2819344130a1562fab5a9ece177f8b400a15fbc
3,646,331
def pref(pref_name, default=None): """Return a preference value. Since this uses CFPreferencesCopyAppValue, Preferences can be defined several places. Precedence is: - MCX - /var/root/Library/Preferences/com.github.salopensource.sal.plist - /Library/Preferences/com.github.salopensou...
10102f3dde316e473d5943fee059f729d6e9454c
3,646,332
def tRange(tStart, tStop, *, timedelta=300): """ Generate datetime list between tStart and tStop with fixed timedelta. Parameters ---------- tStart: datetime start time. tStop: datetime stop time. Keywords -------- timedelta: int time delta in seconds (defaul...
4dec7a624bcd2b349d361831993b8108e99725a8
3,646,333
import numpy def TransformInversePoints(T,points): """Transforms a Nxk array of points by the inverse of an affine matrix""" kminus = T.shape[1]-1 return numpy.dot(points-numpy.tile(T[0:kminus,kminus],(len(points),1)),T[0:kminus,0:kminus])
7e04a741c6ad0ec08e40ab393a703a1878ef784a
3,646,334
def act_func(act): """function that can choose activation function Args: act: (str) activation function name Returns: corresponding Pytorch activation function """ return nn.ModuleDict([ ['relu', nn.ReLU(inplace=True)], ['leaky_relu', nn.LeakyReLU(negative_slope=0.01...
ffd0e6f2ec3ea419c4c3fbb618e4734d59420826
3,646,335
def ajax_get_hashtags(): """Flask Ajax Get Hashtag Route.""" f = request.args.get('f', 0, type=int) t = request.args.get('t', 0, type=int) hashtags_list = get_hashtags() try: if t == 0: return jsonify(dict(hashtags_list[f:])) elif t > len(hashtags_list): ret...
3c9249a5fefb93d422c6e2c4be56394711bf1d7a
3,646,336
def extract_pdf_information(pdf_path): """ Print and return pdf information """ # read binary with open(pdf_path, 'rb') as f: pdf = PdfFileReader(f) information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f""" Information about {pdf_path}: Aut...
bec3667aba872f8e7bf53da09a9fb1905bcf5eec
3,646,337
def normalize_string(subject: str) -> str: """Deprecated function alias""" logger.warn("normalize_string is deprecated") return string_to_title(subject)
6531a6e7211c61d8439bfa8ddc0e609c35b8b6f3
3,646,338
import inspect def get_default_args(func): """ Return dict for parameter name and default value. Parameters ---------- func : Callable A function to get parameter name and default value. Returns ------- Dict Parameter name and default value. Examples --------...
dcc75dceae1385868866d668aa021584547190df
3,646,339
def sec_to_time(seconds): """Transform seconds into a formatted time string. Parameters ----------- seconds : int Seconds to be transformed. Returns ----------- time : string A well formatted time string. """ m, s = divmod(seconds, 60) h, m = divmod(m, 60) r...
59fcfe2f53d11ea7daac736b59b5eaeb72172dba
3,646,340
def power_oos(dmap_object, Y): """ Performs out-of-sample extension to calculate the values of the diffusion coordinates at each given point using the power-like method. Parameters ---------- dmap_object : DiffusionMap object Diffusion map upon which to perform the out-of-sample extension. ...
4de7d75324cd05a7d1ada0e8f6e724ecd551930c
3,646,341
def detect_face_landmarks(image, face_rect=None): """ detect face landmarks, if face_rect is None, the face_rect is the same size as image -> object :param image: :param face_rect: where the face is """ if(face_rect == None): face_rect = dlib.rectangle(0, 0, image.sh...
70c299ae2ce98409e2359e11fa9def0d35e7554f
3,646,342
from typing import Iterable from typing import Mapping def ensure_iterable(obj): """Ensure ``obj`` is either a sequential iterable object that is not a string type. 1. If ``obj`` is :const:`None` return an empty :class:`tuple`. 2. If ``obj`` is an instance of :class:`str`, :class:`bytes`, or ...
56c2db3d87c5927b1f2dbb51b64e7be73956d2b8
3,646,343
def test_dist(**kwargs): """ Test Distance """ a = np.random.random((2, 3)) d = ahrs.utils.metrics.euclidean(a[0], a[1]) result = np.allclose(d, np.linalg.norm(a[0] - a[1])) return result
46a9343fda3445fe0f07bfbb41fc321e6572e4a7
3,646,344
def get_pca(coords): """ Parameters ----------- coords : 2D np.array of points Returns --------- new_coords : 2D np.array of points keeps original number of dimension as input coords variance_ratio : tuple """ pca = PCA(n_components=3) # pca.fit(coords) # ...
a0bce6a7c4b50139502cbdedc6f0f456f21d26b6
3,646,345
def get_form_info(email): """Gets all existing application form info from the database.""" user_id = get_user_id(email) if not user_id: return (False, "Invalid user ID. Please contact the organizers.") query = """ SELECT * FROM applications WHERE user_id = %s AND application_year = %s ""...
f612b83aeb63ff138cc637dc04446ce59f6ecc6b
3,646,346
import logging def getLog(): """simple wrapper around basic logger""" return logging
b51942d2ed02f9ea7faf0a626715ec07e1677c88
3,646,347
from datetime import datetime def _date(defval, t): """ 支持的格式: unix 时间戳 yyyy-mm-dd 格式的日期字符串 yyyy/mm/dd 格式的日期字符串 yyyymmdd 格式的日期字符串 如果年月日其中有一项是0,将被转换成 1 """ if t is None: return defval if isinstance(t, (int, float)): return datetime.fromtimes...
e8a1121da89d9dc46bdce5d1b8c70ec973909abb
3,646,348
import math def compute_lat_long_distance(point1, point2): """ Compute the distance between two records that have fields 'lat' and 'lon'. See details and reference implementation at http://andrew.hedges.name/experiments/haversine/ :param point1: a record with { 'lat', 'lon' } :param point2: a rec...
8058df18106636a0bc6c1f7471f912e07e61ae21
3,646,349
import logging def entropy_analysis(data_df): """ Masked Shannon entropy analysis for sequences Parameters ---------- data_df: pandas.DataFrame merged Pandas dataframe Returns ------- H_list: list entropy values for all positions null_freq_list: list masked ...
8b1d887f2c39b39a833c13780864bd47d0d8d648
3,646,350
import re def get_requirements(filename): """ Helper function to read the list of requirements from a file """ dependency_links = [] with open(filename) as requirements_file: requirements = requirements_file.read().strip('\n').splitlines() requirements = [req for req in requirements if...
292d45ab8e7f8523734326869bb1dd05c6f395f1
3,646,351
def nigam_and_jennings_response(acc, dt, periods, xi): """ Implementation of the response spectrum calculation from Nigam and Jennings (1968). Ref: Nigam, N. C., Jennings, P. C. (1968) Digital calculation of response spectra from strong-motion earthquake records. National Science Foundation. :para...
4e9853b660d85d12701bafe9e328bc91499df73a
3,646,352
def binary_hamiltonian(op, nqubits, qubits1, qubits2, weights, device=None): """Generates tt-tensor classical Ising model Hamiltonian (two-qubit interaction terms in a single basis). Hamiltonian of the form: H = sum_i omega_i sigma_ind1(i) sigma_ind2(i) where omega_i are the Hamiltonian weights, s...
50360d50123c44719a8875a59d02e913cd95f2ad
3,646,353
def map_entry(entry, fields): """ Retrieve the entry from the given fields and replace it if it should have a different name within the database. :param entry: is one of the followings: - invalid field name - command (i.g. $eq) - valid field with no attribute name - vali...
05d392f3ab387381b0f114db05834d642350d817
3,646,354
def seqlogo_hairpin(N, target='none', ligand='theo', pam=None): """ Randomize the stem linking the aptamer to the sgRNA and the parts of the sgRNA that were the most conserved after being randomized in previous screens. Specifically, I identified these conserved positions by looking at a sequenc...
a6be46325d80a23e5afa820b042fa4c878370e45
3,646,355
from typing import Dict from typing import Any def azure_firewall_ip_group_list_command(client: AzureFirewallClient, args: Dict[str, Any]) -> CommandResults: """ List IP groups in resource group or subscription. Args: client (AzureFirewallClient): Azure Firewall API client. args (dict): Co...
c52108af9903f952adf316b11098f726d7280153
3,646,356
def plot_heatmap(df, title=""): """ Plotly heatmap wrapper :param df: pd.DataFrame :param title: str """ fig = go.Figure( data=go.Heatmap(z=df.values, x=df.columns, y=df.index, colorscale="RdBu") ) fig.update_layout(template=_TEMPLATE, title=title, legend_orientation="h") ret...
46c3d362bdbe742b54ad09a56f4638ef1497bcc2
3,646,357
import os def normalise_dir_pattern(repo_dir, d): """ if d is a relative path, prepend the repo_dir to it """ if not d.startswith(repo_dir): return os.path.join(repo_dir, d) else: return d
ea240eda35f7c85e652f78f5e80eb3ac16ce4e98
3,646,358
import tempfile import os import subprocess import shutil def patch(diff, orig_file, filename, request=None): """Apply a diff to a file. This delegates out to ``patch`` because noone except Larry Wall knows how to patch. Args: diff (bytes): The contents of the diff to apply. ...
2d2481fec0151c74ad8c7993fb21bfeef60ee30b
3,646,359
def shift_transactions_forward(index, tindex, file, pos, opos): """Copy transactions forward in the data file This might be done as part of a recovery effort """ # Cache a bunch of methods seek=file.seek read=file.read write=file.write index_get=index.get # Initialize, pv=z64...
c19009c15a04b4a55389b584fad1744ebde03187
3,646,360
def draw_disturbances(seed, shocks_cov, num_periods, num_draws): """Creates desired number of draws of a multivariate standard normal distribution.""" # Set seed np.random.seed(seed) # Input parameters of the distribution mean = [0, 0, 0] shocks_cov_matrix = np.zeros((3, 3), float) np.fill...
d467a1d5fde3eb32debca2711597ef24dc117aaa
3,646,361
import argparse from datetime import datetime import asyncio def main(): """Entrypoint function.""" parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', help='Hydro Quebec username') parser.add_argument('-p', '--password', help='Pas...
9a50f0944688236cd8786896b9c41c012ef3dca9
3,646,362
def wheel(pos): """Generate rainbow colors across 0-255 positions.""" if pos>1280: pos = 1280 if pos <= 255: r = 255-pos g = 0 b = 255 else: pos = pos-256 if pos <= 255: r = 0 g = pos b = 255 else: p...
765df4262ce3b04fb8b06f9256ca51670e2f5bfb
3,646,363
def get_physical_connectivity(port): """Get local_link_information from specified port. @param port a port object @return lli a list of following dict {"switch_id": "MAC_of_switch", "port_id": "1/1/0/1", "switch_info": "switch_name"} """ # TODO(yushiro) replace fol...
cddd8c1191d9e73c55bdd5eecb6086773c3d1a86
3,646,364
def optimize_profile(diff_matrix, x_points, dc_init, exp_norm_profiles, display_result=True, labels=None): """ Fit the diffusion matrix Parameters ---------- diff_matrix : tuple tuple of (eigenvalues, eigenvectors) in reduced basis (dim n-1) x_points : 1-D array_li...
f2550f6fe4cb267559676d30ef0156ce528178cf
3,646,365
def getargsfromdoc(obj): """Get arguments from object doc""" if obj.__doc__ is not None: return getargsfromtext(obj.__doc__, obj.__name__)
d49510388be36a60259683f4560b1d01fe9f9bf6
3,646,366
def nms(dets, thresh): """Dispatch to either CPU or GPU NMS implementations.\ Accept dets as tensor""" return pth_nms(dets, thresh)
e6dbe7b44e1975c080e58d02d6e07ef22b2d3711
3,646,367
import subprocess def get_disk_usage(): """ Handle determining disk usage on this VM """ disk = {} # Get the amount of general disk space used cmd_out = subprocess.getstatusoutput('df -h | grep "/dev/xvda1"')[1] cmd_parts = cmd_out.split() disk["gen_disk_used"] = cmd_parts[2] disk...
e4f65e1c652a74086c111a3c80d5f6c9db94a66e
3,646,368
import argparse def generate_arg_parser(): """ this function receives input arguments for various functions. :return: """ project_path = get_project_path() # load data default_db_path = "".join([project_path, "/data/DisasterResponseDataBase.db"]) default_model_path = "".join([str(proje...
c8e654da2edcd241e5d9e2c2414909ffd0e40f0c
3,646,369
def QFont_from_Font(font): """ Convert the given Enaml Font into a QFont. Parameters ---------- font : Font The Enaml Font object. Returns ------- result : QFont The QFont instance for the given Enaml font. """ qfont = QFont(font.family, font.pointsize, font.weight...
bb62daf4d46315a7a55135894dc78e1d2898fee2
3,646,370
from typing import OrderedDict def _find_in_iterable_case_insensitive(iterable, name): """ Return the value matching ``name``, case insensitive, from an iterable. """ iterable = list(OrderedDict.fromkeys([k for k in iterable])) iterupper = [k.upper() for k in iterable] try: match = ite...
548c951b08fb07251fda1b8918282462c8d0351a
3,646,371
import os import logging def RunInSeparateProcess(fn, *args): """Runs a function in a separate process. Note: Only boolean return values are supported. @type fn: callable @param fn: Function to be called @rtype: bool @return: Function's result """ pid = os.fork() if pid == 0: # Child process ...
4770f6091d7eb6d96b5fdb2bb983da7be68b7e59
3,646,372
def predict_all_points(data, order, coefficients): """ :param data: input data to create least squares prediction of order(order) of :param order: order for least squares prediction :param coefficients: coefficients of LPC :return: returns estimation of entire data set. Will be of length (len(data) ...
4725c735241f439bf986743cafdee0e995373966
3,646,373
def _unpack(msg, decode=True): """Unpack and decode a FETCHed message dictionary.""" if 'UID' in msg and 'BODY[]' in msg: uid = msg['UID'] body = msg['BODY[]'] if decode: idate = msg.get('INTERNALDATE', None) flags = msg.get('FLAGS', ()) return (uid, IMAP4Message(body, uid, idate, flags)) else: r...
5c027dcd54d29f6d95647b66ad2d28998866dc3c
3,646,374
import logging def video_in(filename=INPUTPATH): """reads (max.20sec!) video file and stores every frame as PNG image for processing returns image name and image files (as np array?)""" #create video capture object cap = cv2.VideoCapture(filename) name = filename.split('/')[-1].split('.')[0] i...
cb82d7c6865c3bfe5f3f52f9cb7adc55a8d2e002
3,646,375
from typing import List def convert_all_timestamps(results: List[ResponseResult]) -> List[ResponseResult]: """Replace all date/time info with datetime objects, where possible""" results = [convert_generic_timestamps(result) for result in results] results = [convert_observation_timestamps(result) for resul...
f81121fcd387626a2baa0ecfb342d3381f6def7f
3,646,376
def convert(s): """ Take full markdown string and swap all math spans with img. """ matches = find_inline_equations(s) + find_display_equations(s) for match in matches: full = match[0] latex = match[1] img = makeimg(latex) s = s.replace(full, img) ...
684a6be3812aad8b602631c45af407ca878f9453
3,646,377
from sys import path from sys import prefix def file_parser(input_file: str = 'stocks.json') -> dict: """Reads the input file and loads the file as dictionary. Args: input_file: Takes the input file name as an argument. Returns: dict: Returns a json blurb. """ if path.isf...
c4383ab4037595aeaa2aca2bc9ab77de1777a4fe
3,646,378
def _amplify_ep(text): """ check for added emphasis resulting from exclamation points (up to 4 of them) """ ep_count = text.count("!") if ep_count > 4: ep_count = 4 # (empirically derived mean sentiment intensity rating increase for # exclamation points) ep_amplifier = ep...
8f78a5f24aa22b5f2b4927131bfccf22ccc69ff3
3,646,379
def inline_singleton_lists(dsk): """ Inline lists that are only used once >>> d = {'b': (list, 'a'), ... 'c': (f, 'b', 1)} # doctest: +SKIP >>> inline_singleton_lists(d) # doctest: +SKIP {'c': (f, (list, 'a'), 1)} Pairs nicely with lazify afterwards """ dependencies = dict((...
a4c2a8b6d96d0bfac8e9ba88a4bed301c3054f0a
3,646,380
def vegasflowplus_sampler(*args, **kwargs): """Convenience wrapper for sampling random numbers Parameters ---------- `integrand`: tf.function `n_dim`: number of dimensions `n_events`: number of events per iteration `training_steps`: number of training_iterations Returns...
1b53d83bd010a8113640858d46d66c9c0ef76ff8
3,646,381
def remove_recalculated_sectors(df, prefix='', suffix=''): """Return df with Total gas (sum of all sectors) removed """ idx = recalculated_row_idx(df, prefix='', suffix='') return df[~idx]
54272933f72d45cf555f76086c809eba14713242
3,646,382
def unparse_headers(hdrs): """Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST. """ return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n"
7c06127752d0c6be19894703ba95f2e827e89b8f
3,646,383
def modify_natoms(row, BBTs, fg): """This function takes a row of a pandas data frame and calculates the new number of atoms based on the atom difference indicated in itw functional groups BBTs : list of instances of BBT class fg : instance of the Parameters class (fg parameters) returns : n_atoms (...
2c2df3d2859d33128f982b936011c73bafb723bc
3,646,384
def recreate_cursor(collection, cursor_id, retrieved, batch_size): """ Creates and returns a Cursor object based on an existing cursor in the in the server. If cursor_id is invalid, the returned cursor will raise OperationFailure on read. If batch_size is -1, then all remaining documents on the curs...
1a4987715e35f1cf09ac3046c36c752289797ee6
3,646,385
def nut00b(date1, date2): """ Wrapper for ERFA function ``eraNut00b``. Parameters ---------- date1 : double array date2 : double array Returns ------- dpsi : double array deps : double array Notes ----- The ERFA documentation is below. - - - - - - - - - - ...
a5235543aca0d6de6e79878ac3db1d208d237a0d
3,646,386
def Join_Factors(*factor_data, merge_names=None, new_name=None, weight=None, style='SAST'): """合并因子,按照权重进行加总。只将非缺失的因子的权重重新归一合成。 Parameters: =========== factor_data: dataframe or tuple of dataframes merge_names: list 待合并因子名称,必须是data_frame中列的子集 new_name: str 合成因子名称 weight: lis...
95db1eda297cb8cb05a1db9b1fae9c25a034685f
3,646,387
from pathlib import Path def _check_for_file_changes(filepath: Path, config: Config) -> bool: """Returns True if a file was modified in a working dir.""" # Run 'git add' to avoid false negatives, as 'git diff --staged' is used for # detection. This is important when there are external factors that impact ...
c99da7e993e74f7dbe5789c48832afc59638762c
3,646,388
import time def wait_or_cancel(proc, title, message): """ Display status dialog while process is running and allow user to cancel :param proc: subprocess object :param title: title for status dialog :param message: message for status dialog :return: (process exit code, stdout output or None) ...
8b60e459523933ee205210d4761b6b7d9d8acbfb
3,646,389
def getg_PyInteractiveBody_one_in_two_out(): """Return a graph that has a PyInteractiveBody with one input and two outputs. """ @dl.Interactive( [("num", dl.Int(dl.Size(32)))], [('num_out', dl.Int(dl.Size(32))), ('val_out', dl.Bool())] ) def interactive_func(node: dl.PythonNode):...
31af32a5ece2f4c76635a8f37a0ac644c5f0e364
3,646,390
def batch_norm_relu(inputs, is_training): """Performs a batch normalization followed by a ReLU.""" # We set fused=True for a performance boost. inputs = tf.layers.batch_normalization( inputs=inputs, axis=FLAGS.input_layout.find('C'), momentum=FLAGS.batch_norm_decay, epsilon=FLAGS.batch_nor...
ab771b9d8747bc27d747dd9dce42a6bc9a1d59d3
3,646,391
def knn(points, p, k): """ Calculates the k nearest neighbours of a point. :param points: list of points :param p: reference point :param k: amount of neighbours :return: list of k neighbours """ return sorted(points, key=lambda x: distance(p, x))[:k]
e1a806cd4c16b5ecbf66301406dafeb2b12c46db
3,646,392
def ruleset_detail(request, slug): """ View for return the specific ruleset that user pass by using its slug in JSON format. :param request: WSGI request from user :return: Specific ruleset metadata in JSON format. """ # try to fetch ruleset from database try: ruleset = Ruleset.obje...
a122a2e20641a13d6a934c0261f199ff304ae622
3,646,393
import requests import json def send_slack_notification(message): """ Send slack notification Arguments: message {string} -- Slack notification message Returns: response {Response} -- Http response object """ response = requests.post( SLACK_WEBHOOK, data=json.d...
6c5f0e51c1bfce19ff9a4aec77c1e4c98cd359fa
3,646,394
import argparse def options_handler(): """Validates and parses script arguments. Returns: Namespace: Parsed arguments object. """ parser = argparse.ArgumentParser(description="Downloads XSOAR packs as zip and their latest docker images as tar.") parser.add_argument('-p', '--packs', ...
d3a650d58d0444981b010e230cb5111245a00bc7
3,646,395
def method_detect(method: str): """Detects which method to use and returns its object""" if method in POSTPROCESS_METHODS: if method == "rtb-bnb": return RemovingTooTransparentBordersHardAndBlurringHardBorders() elif method == "rtb-bnb2": return RemovingTooTransparentBord...
cb1dafba5a7c225c093ab602c6e383cb7f499bba
3,646,396
def approve_pipelines_for_publishing(pipeline_ids): # noqa: E501 """approve_pipelines_for_publishing # noqa: E501 :param pipeline_ids: Array of pipeline IDs to be approved for publishing. :type pipeline_ids: List[] :rtype: None """ return util.invoke_controller_impl()
585d4972955e240f146c3d06d5a181dcad36d111
3,646,397
def get_x(document_id, word2wid, corpus_termfrequency_vector): """ Get the feature vector of a document. Parameters ---------- document_id : int word2wid : dict corpus_termfrequency_vector : list of int Returns ------- list of int """ word_list = list(reuters.words(docu...
fca6e5a6071a6b48b83effb37d3b77a88ddf4046
3,646,398
def process_chain_of_trust(host: str, image: Image, req_delegations: list): """ Processes the whole chain of trust, provided by the notary server (`host`) for any given `image`. The 'root', 'snapshot', 'timestamp', 'targets' and potentially 'targets/releases' are requested in this order and afterwards ...
391024aeaa814f3159c8f45a925afce105b7b339
3,646,399