content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cases_list(request): """List caseversions.""" return TemplateResponse( request, "manage/case/cases.html", { "caseversions": model.CaseVersion.objects.select_related( "case", "productversion", "productversion__product", ...
f159de0330cc66155056101604400c424c510391
3,608,372
import functools import errno def wrap_exceptions(fun): """Decorator which translates bare OSError and WindowsError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) exce...
f2ce0079b193065bae725b144cdd1d759af50c9c
3,608,373
import random def draw_box(pred, orig_img, cls, colors): """ draw the predicted bounding boxes on a given image. designed for single images. For multi batch support, supply singular image iteratively """ coords1 = tuple(pred[1:3].int()) coords2 = tuple(pred[3:5].int()) label = "{0}"....
d04494b8736f76f94ab69d491ba71b17dc40665f
3,608,374
from typing import Tuple def compute_climatology( data: xr.DataArray, base_period: Tuple = (None, None), ) -> xr.DataArray: """ Computes the seasonal mean of a DataArray that has a time dimension Parameters ---------- data base_period """ _check_dimensions(data) return...
e211800d0b7a0c4127e369a4c7132b3e8d0a5f64
3,608,375
def name_by_arg(sex: str, name: str = None, id: int = None): """Get name object by passed `name` or `id` argument. Args: sex (str): male/female/all Returns: dict: Name object if successful, otherwise error. If no argument passed, return all names. """ if sex == "male": ...
61a7db60c5360ece9f1457947ed027ba507f8d56
3,608,376
def plugin_info(): """ Returns information about the plugin Args: Returns: dict: plugin information Raises: """ return { 'name': 'ds18b20 Plugin', 'version': '1.0', 'mode': 'poll', '' 'type': 'south', 'interface': '1.0', 'config': _DEFAUL...
97ce0e5b7e1f7cdd1eaa72b0258cd394ded65366
3,608,377
def LP(): """ load prototype """ return builder.lp()
124c3034fecbd7e3abf9186e1749bfa970668408
3,608,378
def maxkcolor_edges(num_vertices: int, num_edges: int): """Generates edges for MaxKColor problems randomly Args: num_vertices: Number of vertices num_edges: Number of edges Returns: List of randomly generated undirected edges `[..., (v1, v2) ,...]`. Note that (v1, v2) and ...
1febf58f50102fb95317fc8b3680b555a6b442fc
3,608,379
def _standard_normalize(values, axes=(0,)): """Standard normalizes values `values`. Args: values: Tensor with values to be standardized. axes: Axes used to compute mean and variances. Returns: Standardized values (values - mean(values[axes])) / std(values[axes]). """ values_mean, values_var = tf...
d1103b725c462c01e37d503dfdcb68c936fea505
3,608,380
import array def dimcollapse_csr(v, indexes=(), normalize=True): """dimensional collapse of a vector :param v: csr vector :param indexes: allowed dimensional indexes :param normalize: logical, set True to rescale values to unit norm :return: new csr vector, values outside indexes reset to zero ...
a12d065190c47728755e40c0ce5ac3fb53d77ac3
3,608,381
import requests def openei_api_request(data, pause_duration=None, timeout=180, error_pause_duration=None): """ Args: data (dict or OrderedDict): key-value pairs of parameters to post to the API pause_duration: timeout (int): how long to pause in seco...
ad228a80bd7d4c7d2ffe8db148a4ebd48fa4aa23
3,608,384
def downside_risk_nb(returns, ann_factor, required_return_arr): """2-dim version of `downside_risk_1d_nb`. `required_return_arr` should be an array of shape `returns.shape[1]`.""" result = np.empty(returns.shape[1], dtype=np.float_) for col in range(returns.shape[1]): result[col] = downside_ris...
4a56b95824dc9d13d6cd401b86d7eb700942309d
3,608,385
import json def shorten(): """ Input a youtube id from the client and we will return a jsonified array of subclips. [(s1, e1), (s2, e2)] We cache all extracted yt hot clips with their respective yt id's. We maintain the 10 most recent hot clips per yt id. """ yt_id = request.form['yt_id']...
76dc5f137957d7dbe8052eb6ce6c0823af620f3d
3,608,386
import random def generate_masked_image(image, boxes, masks, class_ids, class_names, scores=None, show_mask=True, show_bbox=True, show_score=True, colors=None, captions=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coord...
5155f9d0226f47fb6dc7e47435994f57da5ecc55
3,608,387
def msbe(P, R, Γ, v): """Mean squared Bellman error (MSBE).""" assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) return np.sum(d_pi * bellman_error(P, R, Γ, v) ** 2)
2905987f5dcf83499d96c29a77c191d9da9ed683
3,608,388
def new_indicator_request(category): """ Create a new indicator """ url = '{}/indicators/{}'.format(BASE_PATH, category) response = http_request( 'POST', url, headers=GET_HEADERS ) try: return response.json().get('data') except Exception as e: LO...
3419b0e108d095799a9301ee521ebd8d5c4f96cf
3,608,389
def parse_default( filename, data=None, metadata=None, read_write='r'): """ Default parser for data. Assumes there is a single line of metadata at the top line in the form of a dictionary and the remainder is tabular and can be imported as a pandas DataFrame :param filename: Name of the file to be ...
839a845af95622a908f0c4f8958a72747b7bdbf3
3,608,390
from typing import Counter def filter_adjoined_candidates(candidates, min_freq): """ Funcao que filtra apenas os candidatos proximos que aparecem com certa frequencia """ candidates_freq = Counter(candidates) filtered_candidates = [] for candidate in candidates: freq = candidates_freq[...
be9c8618dc9e8efd086cc3c8cc51d5ffdb5d8254
3,608,391
def tune_model(X_train, y_train, X_test, y_test, model, space, metric, n_calls=25, minimize=True, min_func=gp_minimize): """ :param X_train: array-like, shape = [n_samples, n_features] The input samples. :param y_train: array of shape = [n_samples] The training values. :param X_train: arr...
79d8f0f689e2d1d52b4346c5fc29a0f1e1eee074
3,608,392
def gcd(a, b): """Find the greatest common denominator of two integers. Using Euclid's algorithm. """ b = abs(b) while b != 0: a, b = (b, a % b) return a
3c636a00c73fbc26a2dbcf5d3a99bc1ca26c887e
3,608,393
from typing import Iterable def load_data(pairs_db_obj): """ Load currency pair's data """ data = _schema.dump(pairs_db_obj, many=isinstance(pairs_db_obj, Iterable)) return data
c8b7ffeffe6ccc45a3f61307e3f02347e9426bb0
3,608,394
def logout_view(request): """ logout """ logout(request) return redirect('/')
6a2a2dcbd904b19ccff6ffbc9cad3997439f78be
3,608,396
def a2tf(ndp, angle): """ Wrapper for ERFA function ``eraA2tf``. Parameters ---------- ndp : int array angle : double array Returns ------- sign : char array ihmsf : int array Notes ----- The ERFA documentation is below. - - - - - - - - e r a A 2 t f ...
04070aef38a558146d7e3c68fc5769e28ebbd91e
3,608,397
def calc_distance_matrix(all_seqs: list): """ Uses BLAST to calculate pairwise distances between sequences :param all_seqs: A list of sequences to write to file :return: a symmatrical matrix of distances and a list of the row/colnames """ # align_output, header = blast_seqs(all_seqs, all_seqs, b...
8dd7f224a7bce14cd420892bfc51f7ea23f197c9
3,608,398
def getCache(request): """ 测试方法 :param request: :return: """ dict = settings.ZK_HARPC.get_resource() return JsonResponse({'test': dict}, safe=False)
145f25bba8625a61d67e8ae295c602e1886dc333
3,608,399
def create_tdm_tree(): """Create tdm tree info""" tree_info = [ [0, 0, 0, 1, 2], [0, 1, 0, 3, 4], [0, 1, 0, 5, 6], [0, 2, 1, 7, 8], [0, 2, 1, 9, 10], [0, 2, 2, 11, 12], [0, 2, 2, 13, 0], [0, 3, 3, 14, 15], [0, 3, 3, 16, 17], [0, 3, ...
03a44baa724135b07b88f8f5bec4834262498320
3,608,400
def find_all_key_entities(text): """ Find all key entity mentions in text, including locations, persons, and other types """ all_entities = [] try: doc = Doc(text) doc.segment(segmenter) doc.tag_morph(morph_tagger) doc.parse_syntax(syntax_parser) doc.tag_ner(n...
7efa5e9c2431638f158d1639adefb6376be7e467
3,608,402
def selftest_function(opts): """ Placeholder for selftest function. An example use would be to test package api connectivity. Suggested return values are be unimplemented, success, or failure. """ app_configs = opts.get("fn_create_zoom_meeting", {}) zoom = ZoomCommon(opts, app_configs) requ...
d18cdce7aebbf51ffc21aac988c8669f41c7c80d
3,608,403
def conv_F2C(value): """Converts degree Fahrenheit to degree Celsius. Input parameter: scalar or array """ value_c = (value-32)*(5/9) if(hasattr(value_c, 'units')): value_c.attrs.update(units='degC') return(value_c)
1f3ac169942c51b363a7ae7977890be237b95390
3,608,404
def get_db_tables_with_data() -> list: """Gets database tables. If table is empty pass""" full_dbs = [] get_tables = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") for table in get_tables: check_table_rows = cursor_2.execute(F'SELECT count(*) FROM {table[0]}') for ...
afd26c9a68c18ea547984d9b7812600e99231ff8
3,608,405
import time def inner_loop(repo, cref, clock=time): """Fetches the config ref and runs single iteration of processing. Returns: tuple (bool success status, list of synthesized commits). """ repo.fetch() cref.evaluate() return process_repo(repo, cref, clock)
2dd90ef7cdb84c3a032ba762027b42c7b4a316b1
3,608,406
def extract_yyyy_mm_dd_hh_mm_ss_from_datetime64(dt64): """ Extract separate fields for year, monday, day, hour, min, sec from a datetime64 object, or an array-like object of datetime64 objects Parameters ---------- dt64 : xarray DataArray, np.ndarray, list of, or single numpy.datetime64 ...
d41719fe92444bc4fff42c9cc496935e019409c7
3,608,407
import warnings def postelToDirCos(u, v): """Convert Postel azimuthal equidistant tangent plane projection u,v to direction cosines. Parameters ---------- u, v : float Postel tangent plane coordinates in radians. Returns ------- alpha, beta, gamma : float Direction co...
51819ce5b7d467acaf74bbb1f21895353fb46f42
3,608,408
import pandas def protocol_df_chunk_to_pandas(df): """ Convert exchange protocol chunk to ``pandas.DataFrame``. Parameters ---------- df : ProtocolDataframe Returns ------- pandas.DataFrame """ # We need a dict of columns here, with each column being a NumPy array (at # l...
99afa0e9a680da790c628d8770d1f71cf96f9828
3,608,409
def parse_dtype(s): """ Parse text as numpy dtype >>> parse_dtype('i4') dtype('int32') >>> parse_dtype("[('a', 'i4')]") dtype([('a', '<i4')]) """ if s.startswith(b'['): return np.dtype(eval(s)) # Dangerous! else: return np.dtype(s)
65dfe2331ea020a2860468029ef6318b618700d4
3,608,410
import re def test_custom_s3_decorator(): """Example of creating a custom decorator""" bucket = "my-bucket" prefix = "all-exceptions/" httpretty.register_uri(httpretty.PUT, re.compile(r".*amazonaws\..*"), body="") def my_exception_report(f): storage_backend = S3ErrorStorage(access_key="a...
17d8061cab2ca0b1cba50b00c8e93e4ce7b2545c
3,608,413
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username"...
9ddd7b76481f94239dee979cec44956db5aaf6cc
3,608,414
def get_cutoff(obj, r_max=units.length(1, 'nm'), r_min=0, hyperparam='default', return_mask=False, reverse=False): """get cutoff""" if obj is None or isinstance(obj, Cutoff): return obj if isinstance(obj, str): if obj not in _CUTOFF_ALIAS.keys(): raise ValueError( ...
8b1a0a104758ab9c60200cea1aad0f66b9d3283d
3,608,417
def AggFormula(formula, formulaParam, *matchPairs): """ Create a formula aggregation. :param formula: (java.lang.String) - the formula to apply to each group :param formulaParam: (java.lang.String) - the parameter name within the formula :param matchPairs: (java.lang.String...) - the columns to...
8ef974d0e1e7c0e5df8cd58a947766feb7a472b6
3,608,418
def status_in_range(value: int, lower: int = 100, upper: int = 600) -> bool: """ Validates the status code of a HTTP call is within the given boundary, inclusive. """ return value in range(lower, upper+1)
43bb6f4824b7e42b6620e3ddff853aa65713f145
3,608,419
def combine_dicts(*args, exclude=(), deep_copy=False): """Returns a new dict with entries from all dicts passed, with later dicts overriding earlier ones. :param exclude: Remove these keys from the result. :param deepcopy: Perform a deepcopy of the dicts before combining them. """ if not len(args): ...
49627b9f37c08be7f7d3f51f8a47ddb316c545d4
3,608,420
def get_FR_dev(start_time,end_time,sim_dt,spikemon,n): """ get firing rate given spikemonitor and time interval. quantify deviation as well. start_time: time of input start end_time: time of input end sim_dt: simulation time step spikemon_t: time array from spike monitor n: total number...
579ba454cdbc924cca5b4789fcc6e57cd81c977c
3,608,421
def _convert_from_roi(fname): """Convert a roi file to a numpy array [x, y, h, w]. Parameters ---------- fname : string If ends with `.roi`, we assume a full path is given """ if not fname.endswith('.roi'): fname = '%s.roi' % join(IJ_ROI_DIR, fname) with open(fname, 'rb') ...
80cc53ed8ac576100974e9d7843751fed0173141
3,608,422
def init_grid (mins=0, limits=np.array([-180, 180, -90, 90])): """ Initiates the grid variables based on the number of points wanted within the given limits gris step is in minutes, 60 min = 1 degree """ dim = limits * pi/180 if ( (mins < 1) or (mins > 600) ): size_long = 5 ...
5aaf240aa4a958e9fa6df2de5abb545647b761c4
3,608,423
def author(request, author): """ View function for author """ return render(request, 'author.html', {})
a1b713d8919d16728322dc478c1d46abb7f22ca9
3,608,424
def import_feed_from_text(text, filename=None) -> [str]: """ >>> text = "<opml> https://blog.guyskk.com/blog/1 https://blog.anyant.com" >>> expect = set(['https://blog.guyskk.com/blog/1', 'https://blog.anyant.com']) >>> set(import_feed_from_text(text)) == expect True >>> set(import_feed_from_tex...
197f3551b90f328025b46d4c0a75d3fca0028ee6
3,608,425
def create_attachment(b64_data, name): """Create a Salesforce attachment object from a jpeg.""" attachment = Attachment() attachment.update_fields({ "Body": b64_data, "Name": name, }) return attachment
a8aa9537535430a2237e569d24a28f70a710fd96
3,608,426
def getSteamAppDir(appid: int) -> str: """ A function that retrieves the folder of an app by searching in all possible libraries \t :param appid: The app's id to search for :return: path to app's folder :raises RuntimeError: raised when the app is not found """ for path in libraryFolders(): try: logger.inf...
c93736aafa5440f530a3d025cf8e92313dcb2bf0
3,608,427
def lyapunov(A, Q=None): """ Solve the equation :math:`A^T X + X A = -Q`. default Q is set to I :param A: system matrix :type A: np.ndarray | np.matrix | List[List] :param Q: matrix :type Q: np.ndarray | np.matrix :return: the matrix X if there is a solution :rtype: np.ndarray | No...
bfc65d7966e12b640b2e52e0bee28c1f23d95000
3,608,428
def _resize_cropped(image, image_size, thumbnail_display_size, thumbnail_image_size): """ Resizes the image to fit the desired size, preserving aspect ratio by cropping, if required. """ # Resize with nice filter. image_aspect = image_size.aspect if image_aspect > thumbnail_image_size.aspect...
7067c2348e6bcb35f3e6e33d2e7fe16a6b9e8855
3,608,429
def nodeOrdering(criteria = "const FieldList<%(Dimension)s, %(DataType)s>&"): """Compute the order that a given set of nodes should be stepped through given a FieldList of things to sort them by. The FieldList returned is the one to N indexing corresponding to sorting the input in increasing order.""" return "...
70af2ca0549a03e3e6bf9cfd08b6d831770c4a31
3,608,430
def xtile(lst, lo=0, hi=1, width=50, chops=[0.1, 0.3, 0.5, 0.7, 0.9], marks=[" ", ".", ".", " ", " "], bar="", star="o", show=" %5.3f"): """ Pretty print a large list of numbers. Take a list of numbers, sort them, then print them as a horizontal xt...
e9c548a3d9bdf1fd015f9e11b692afa1e35a509d
3,608,431
import six def format_decimal(decimal): """ Formats a decimal number using the same precision as Excel :param decimal: the decimal value :return: the formatted string value """ getcontext().rounding = ROUND_HALF_UP # strip trailing zeros normalized = decimal.normalize() sign, digi...
e4907e613832856802de7a2fa933877012aaaec2
3,608,432
def avg_Nc(log10mhalo,z,log10mstellar_thresh,sig_log_mstellar): """<Nc(m)>""" log10mstar = Mstellar_halo(z,log10mhalo) num = log10mstellar_thresh - log10mstar denom = np.sqrt(2.) * sig_log_mstellar return 0.5*(1. - erf(num/denom))
9575d43ba1477e697937916094345020380cbab3
3,608,433
def get_hiragana(word: str) -> str: """文字列をひらがなに変換します。 Args: word (str): 変換する文字列 Returns: str: ひらがな文字列 """ converted_word = jaconv.kata2hira(word) return converted_word
de2597a1846e8da038bcb8108fe7ca0357af3f9e
3,608,434
def get_activity_polylines(before=None, after=None, limit=None): """Gets activity polylines for user. Args: before (datetime or str): Optional. Retrieve activities before this date. Format YYYY-MM-DD. after (datetime or str): Optional. Retrieve activities after this date...
4ee542936b4dad7bca0702c1f7ea11a13fd1a125
3,608,435
import ast def processLambda(arg, exp, fail=ast.FAIL): """Destructure lambda arguments. f(λa1 a2 ... an.body) → f(λa1.f(λa2. ... f(λan.body))) f(λ[x . y].body) → λv.if pair? v then (f(λx y.body)) (head v) (tail v) else FAIL → λv.if pair? v then (λx.λy.body) (head v) (tail v) else FAIL...
c29a7a88885e4abada9c1e1ec4358875ac7b4cd7
3,608,436
def tails_concentration(): """Calculate the possible enrichment given tails U234 concentrations """ # Split product in two parts to have a higher granularity in the # first part. size = 50 xp = np.concatenate((np.linspace(1, 20, size, endpoint=False), np.linspace(20, 9...
00463b6cc6a470ebce87e55da7cc70316071162a
3,608,438
async def crime_plot(current_city:City): """ Visualize crime information for city - see overall crime breakdown - visualize breakdown of violent crime and property crime ### Query Parameters - city ### Response JSON string to render with react-plotly.js """ city = validate_city...
477aa54ff87a6470757636a5ea3d7b2acd4f6df1
3,608,439
def _float_to_str(x): """ Converts a float to str making. For most numbers this results in a decimal representation (for xs:decimal) while for very large or very small numbers this results in an exponential representation suitable for xs:float and xs:double. """ return "%s" % x
cb795b9c4778b9a3fda7398024166d86d8458bd3
3,608,440
def create_ips(file1_content, file2_content): """ Creates a new Patch object based on the differences between file1 and file2 :Parameters: file1_content : bytearray Contents of the first file file2_content : bytearray Contents of the second file rtype: Patch return: The newly created Pat...
cff7e01025b93057cc952d23629f81a63ed3adc2
3,608,442
def unique_cluster_indices(cluster_indx): """ Return a unique list of cluster indices :param cluster_indx: Cluster index list of ClusterExpansionSetting """ unique_indx = [] for symmgroup in cluster_indx: for sizegroup in symmgroup: for cluster in sizegroup: ...
36bc5a287d49c6abbd552b9edc0e72675ba82eca
3,608,443
from datetime import datetime def get_slmtag_str(dbpath, timestamp=None): """Read the database and return an SLMTag string. dbpath - the path to the sqlite database. timestamp - to be used for testing only, where we want to ensure that log times are always the same. """ (authva...
5165ffc51a782b76e69a8575fc902101b0753b21
3,608,444
def makeExternalLink(url, anchor): """Function applied to wikiLinks""" if options.keepLinks: return '<a href="%s">%s</a>' % (quote(url.encode('utf-8')), anchor) else: return anchor
cf7d4895b2ca40ea780e18b95fd2aa28787ecee6
3,608,445
def _calculate_atr(atr_length, highs, lows, closes): """Calculate the average true range atr_length : time period to calculate over all_highs : list of highs all_lows : list of lows all_closes : list of closes """ if atr_length < 1: raise ValueError("Specified atr_length may not be l...
f5878eda22c09fa8c428122bd013f9c6088ea0f8
3,608,446
def combine_cdd_path(*, resp, **_): """Call function to generate combined dataframe from csv file and excel dataset, bringing only those flows from the excel file that are not in the csv file """ df_csv = write_cdd_path_from_csv() df_excel = epa_cddpath_call(resp=resp) df_excel = df_excel[~d...
752ad0305cc34b07789a019b1939726eeadb7f2f
3,608,447
def generate_handles(labels, colors, edge='k', alpha=1): """ Generate handles for the legend map :param labels: name of legend entry :param colors: color of legend box :param edge: edge colour, default is black :param alpha: transparency of legend, default is not transparent :return: handles...
0a97ec997bb0ea03b412eebedadb1617cadbb90d
3,608,448
def get_reviewers(request): """ All assigned reviewers, staff or admin """ return User.objects.filter(Q(submissions_reviewer__isnull=False) | Q(groups__name=STAFF_GROUP_NAME) | Q(is_superuser=True)).distinct()
fb0e7a7a34643ebbe02be5c5b61e01e585aaa2b9
3,608,449
import io def _load_data(fov_data, exp): """ Load a field of view dataset Parameters ---------- fov_data : pd.DataFrame Table of file locations for the spot results and mask label image corresponding to the dataset to be viewed exp : Experiment Experiment ...
95f95f9d6e9e28cec138757714d4686205f024cc
3,608,450
from typing import Any def move_file(client: Any, team_drive_id: str, file_id: str): """Moves a file from one team drive to another""" f = make_call(client.files(), "get", fileId=file_id, fields="parents", supportsTeamDrives=True) previous_parents = ",".join(f.get("parents")) return make_call( ...
6cbdd56b2898bf0c972413110cf2bd229504101e
3,608,451
def requested() -> bool: """Return whether listeners should shut down.""" return _flag.is_set()
b95736b7c1f31999c6e34828cf5d8d23fa4d16a2
3,608,453
import sh def extract_sac(data, ctable, processes): """ extract the downloaded data to the sac and pz format. """ # * get dirname thedir = dirname(data) # * mkdir for the sac and pz files sh.mkdir("-p", join(thedir, "SAC")) sh.mkdir("-p", join(thedir, "PZ")) # * extract sac win...
e58dab1eb747b9f6f727584f53598cf8f1e54b18
3,608,454
def _spin_echo_gates(idx: int) -> cirq.ops: """Outputs one of 4 single-qubit pi rotations which is used for spin echoes.""" pi_pulses = [ cirq.PhasedXPowGate(phase_exponent=0.0, exponent=1.0), cirq.PhasedXPowGate(phase_exponent=0.5, exponent=1.0), cirq.PhasedXPowGate(phase_exponent=1.0, ...
bf780d3c1de3caee4543e2eb4e5c5dfd7aaa3e08
3,608,455
def peak_normalization(spectrum, peak_range=[3.05, 4.05], verbose=False): """ Each spectrum is divided by its mean so that its median becomes 1 :param spectrum: dataframe of the spectrun values index are the cases and columns are the ppm value ...
475c4df7bc12ff6e7d32318cda104c42f66b3226
3,608,456
def get_node_text_tags_preserved(xml_node): """Get the body of an XML node as a string, avoiding a specific blacklist of bad tags.""" xml_node = deepcopy(xml_node) etree.strip_tags(xml_node, *_tag_black_list) # Remove the wrapping tag node_text = xml_node.text or '' node_text += ''.join(etr...
2611eea7e5fc484d9750cd420361e9ce8335c0db
3,608,458
def _getopt_size(py_obj, option): """Gets the specified size option""" i = pynng.ffi.new('size_t []', 1) opt_as_char = pynng.nng.to_char(option) # attempt to accept floats that are exactly int obj, lib_func = _get_inst_and_func(py_obj, 'size', 'get') ret = lib_func(obj, opt_as_char, i) pynng...
90a99ec0edbbfbac7f90e65b531382756ad3761f
3,608,460
def fileFromItem(item): """ Return the file contained in an item. Raise an exception if the item doesn't contain exactly one file. """ files = Item().childFiles(item, limit=2) if files.count() != 1: raise DanesfieldWorkflowException( "Item must contain %d files, but should co...
16a86fe51f67b5df44370b247d5d7f777b2f53d9
3,608,461
def capacity_factor(pudl_out, min_cap_fact=0, max_cap_fact=1.5): """Calculate the capacity factor for each generator. Capacity Factor is calculated by using the net generation from eia923 and the nameplate capacity from eia860. The net gen and capacity are pulled into one dataframe and then run through...
87cf99cb19795e718d3cd43b76a858f27b13c61a
3,608,462
import json def get_minister_positions(minister, lang_code): """ Return all positions for the minister """ file_name = settings.MINISTER_JSON_FILE if lang_code == 'fr': status_prefix = 'Précédent ' else: status_prefix = 'Former ' positions = [] with open(file_name, 'r'...
2979ff7a59b9f47cd93fc6caa9cf5591c20e7d49
3,608,463
def home(): """Home page.""" current_app.logger.info("Hello from the home page!") return render_template("index.html")
3f9054e945eae7f377c3e3edc0fbe820aa021f59
3,608,464
def compare_interior_kaplan(obs, var_pair, rescale_kaplan=False, rescale_interior=False): """ Interior vs kaplan est for `multi_locus_analysis.finite_window.ab_window`. Compare the Kaplan-Meier estimator to the empirical distribution function (eCDF) of interior times of data...
9c53818c5fc873ae53b7a33cc57c2535898f6fbf
3,608,465
def all_intervals(text, elements, config): """From the slices of elements and units create an intervaltree. time consuming and may unnessesary to search the whole txt 1. search all elements in text 2. search all elements in paragraph! 3. links > 40: search with aho-coressio search algo for speed ...
06f4e764c74984ab71667417033331688ff5090f
3,608,466
def multigauss(x, mu, cov, norm=True): """ Evaluates multivariate Gaussian distributions, each at different data points. This code is optimised to evaluate M Gaussians of dimension N at M points. The distribution is normalised by default but there is an option to turn off normalisation. ...
036f4f7104b65a8b049839457bc43bf9b9720c97
3,608,467
import torch def preprocess(camera_value): # Preprocessing for camera format --> Network input format """ Preprocessing function for camera format --> network input format param camera_value: input from Camera type camera_value: np.ndarray """ global device, normalize x = camera_value ...
29d9ebe362172be617f609d2707daaee4abdaf69
3,608,468
def number_of_pending_jobs(): """Return the number of jobs in the slurm queue.""" cmd = ["squeue", "-u", "lstanalyzer", "-h", "-t", "pending", "-r"] output = sp.check_output(cmd) return output.count(b"\n")
054e77f553746f37d02eeeb8ed05771b263f5bb6
3,608,469
def copy_weights(model, source, target, num_layers, shared=False): """Copies the weight values of mixture weights and head from source to target domain. Arguments: model: a tf.keras.Model object. source: source domain name. target: target domain name. shared: whether the model is shared. num_layers: nu...
227ea9a45a3c9af2086ded56ce5f9a6c6780d2c9
3,608,473
def load_csv(file_name): """ Load a csv-file generated by Audio2LED. PARAMETER --------- file_name: str the path to the csv file RETURNS ------- led_time: ndarray the time in seconds from the start led_channel_levels: ndarray 2D array for the LED channels and fra...
f7985d6c00f7bdb8d381dcfe468f4b9e4bd39aa9
3,608,474
def error_in_assigned_energy(predictions, ground_truth): """Compute error in assigned energy. .. math:: error^{(n)} = \\left | \\sum_t y^{(n)}_t - \\sum_t \\hat{y}^{(n)}_t \\right | Parameters ---------- predictions, ground_truth : nilmtk.MeterGroup Returns ------- er...
92891991241bfbd5d583b11e8583ac59204b4af0
3,608,476
import torch from typing import Tuple def get_tot_objf_and_finite_mask(tot_scores: torch.Tensor, reduction: str) -> Tuple[torch.Tensor, torch.Tensor]: """Figures out the total score(log-prob) over all successful supervision segments (i.e. those for which the total score wasn't -infinity). Args: ...
d09b95056c2635be22a7db1baaa64b6667955007
3,608,478
def dct2d(a): """ Computes the 2D Normalized DCT-II. Arguments --------- X: (m, n) numpy array 2D image. Returns ------- (m, n) numpy array DCT coefficient matrix. """ return fp.dctn(a, norm='ortho')
c16c04687b060485e1a4314daae8972da86cd40f
3,608,479
def generate_embedding_mat(dict_size, emb_len, init_mat=None, extra_symbol=None, scope=None, reuse=None, trainable=False): """ generate embedding matrix for looking up :param dict_size: indices 0 and 1 corresponding to empty and unknown token :param emb_len: :param init_mat: init mat matching for [di...
c29efb8be60cb1153aa80774abf0283cd0304526
3,608,480
def user_settings(request): """ Let a user change its settings, like email preferences. :param request: :return: """ try: meta = request.user.usermeta except UserMeta.DoesNotExist: meta = UserMeta() request.user.usermeta = meta meta.save() request.use...
0233c57baf6e07d46a0214964746fb6e38b2e641
3,608,481
import graphviz # noqa: F401 def render_graph(graph_specification, render_distributions=False): """ Create a graphviz object given a graph specification. :param bool render_distributions: Show distribution of each RV in plot. """ try: except ImportError as e: raise ImportError( ...
8fd01c67423e7303e11cac613e8265e75c7cc1c2
3,608,483
import dateutil from operator import sub def donationParser(inLoc, header=True): """Takes a donation csv formatted from twitch alerts. Returns a list of lists for each entry. 0-Date (datetime object) 1-Name 2-Email 3-Amount (Decimal type) 4-Comment """ donations=[] file =open(inLoc...
59f318c4570b0ebf06102bc99b4dc37889847a75
3,608,484
def VaporPressure(tempc, phase="liquid"): """Water vapor pressure over liquid water or ice. INPUTS: tempc: (C) OR dwpt (C), if SATURATION vapour pressure is desired. phase: ['liquid'],'ice'. If 'liquid', do simple dew point. If 'ice', return saturation vapour pressure as follows: Tc>=0: es = ...
058caabe6db9c6506daa6e1fa0071c3903a2ca9a
3,608,485
def fft_detect(resultImage, hostImage, alpha): """Starting from a watermarked image, detects the watermark image embedded into the host image by using the Fast Fourier Transform.\n Arguments: resultImage (NumPy array) -- the watermarked image hostImage (NumPy array) -- the original im...
9a45d7bf0af3278071d71bda79e005ab834bc9d9
3,608,486
def get_auth_twitter() -> tweepy.OAuthHandler: """auth twitter with saved tokens. Returns: tweepy.OAuthHandler: """ return tweepy.OAuthHandler(SETTINGS['TWITTER_API_KEY'], SETTINGS['TWITTER_API_SECRET_KEY'])
2e9911a3d6f3aaf9e08a33ca7e4caff592494b01
3,608,487
def post_statistics(): """ get the data of posts """ post_statistic = dict() post_statistic['total_posts'] = len(Post.query.filter_by(post_type='post').all()) post_statistic['total_comments'] = len(Comment.query.filter_by(user_id=0).all()) post_statistic['total_pages'] = len(Post.query.filter_by(pos...
a2c125b725c5361739a6f05957a92918e6ba2911
3,608,488
import pandas def get_variant_ann_by_chrom_pos(db, chrom, start, ref, alt): """ e.g., UI: https://biobankengine.stanford.edu/variant/1-39381448 MongoDB: db.variants.find({'xpos': '1039381448'}, fields={'_id': False}) SciDB: between(vairant, 1, 39381448, 1...
19397af50d0c0ea2b871069959066c8b7e20aa83
3,608,489
def get_answers(candidate_tokens,predict_set,predict_result,dictionary): """ Build the dictionary of the selected answer for a QA-based network. :param candidate_tokens: the dictionary of the documents and their candidate KPs :param predict_set: the input of the network :param predict_result: the o...
3a6e82c34bb398c9ede673ad2e9a3c6fb672a8f3
3,608,490