content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def extract_keys(keys, dic, drop=True): """ Extract keys from dictionary and return a dictionary with the extracted values. If key is not included in the dictionary, it will also be absent from the output. """ out = {} for k in keys: try: if drop: ou...
15a66fff5207df18d8ece4959e485068f1bd3c9c
21,466
from flask import current_app def jsonresolver_loader(url_map): """Resolve the referred EItems for a Document record.""" def eitems_resolver(document_pid): """Search and return the EItems that reference this Document.""" eitems = [] eitem_search = current_app_ils.eitem_search_cls() ...
9da05e92850cbdbedb8d49cdf2cdf3763d0b1ab6
21,467
import sqlite3 def getStations(options, type): """Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN') """ conn = sqlite3.connect(options.database) c = conn.cursor() if type == "ALL": c.execute("select rowid, id, name, lat, lon from stations") else: c.execute(...
59d45a79542e68cd691cf848f3d4fe250389732c
21,468
def test_name(request): """Returns (module_name, function_name[args]) for a given test""" return ( request.module.__name__, request._parent_request._pyfuncitem.name, # pylint: disable=protected-access )
4ef40de8a2c917c0b12cb83db9fd39f6b59777a0
21,469
import textwrap def inputwrap(x, ARG_indented: bool=False, ARG_end_with: str=" "): """Textwrapping for regular 'input' commands. Parameters ---------- x The text to be wrapped. ARG_indented : bool (default is 'False') Whether or not the textwrapped string should be indented. A...
af0ab3b69205965b40d3e03bdcfe3148889f7080
21,470
from .utils import phys_size def SBP_single(ell_fix, redshift, pixel_scale, zeropoint, ax=None, offset=0.0, x_min=1.0, x_max=4.0, alpha=1, physical_unit=False, show_dots=False, show_grid=False, show_banner=True, vertical_line=None, linecolor='firebrick', linestyle='-', linewidth=3, labelsize=25, ticksi...
5aab69adfc38afad84b6f45972ffb7ce05d547ac
21,471
def min_conflicts_value(csp, var, current): """Return the value that will give var the least number of conflicts. If there is a tie, choose at random.""" return argmin_random_tie(csp.domains[var], key=lambda val: csp.nconflicts(var, val, current))
ab338ce8b0abd7a77078193fcac3041155ed3e78
21,472
from app.model import TokenRepository def init(jwt): """Initialize the JWTManager. Parameters: jwt (JWTManager): an instance of the jwt manager. """ @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decoded_token): """Callback to check if a token is in the bl...
406ff6e8ce6169dff6559b141f5c4453cce68f1e
21,473
from typing import Callable import inspect def get_component_rst_string(module: ModuleType, component: Callable, level: int) -> str: """Get a rst string, to autogenerate documentation for a component (class or function) :param module: the module containing the component :param component: the component (c...
511c718610456b4c5df5df2bc9e0ae5e7ac6823c
21,474
def log_mse_loss(source, separated, max_snr=1e6, bias_ref_signal=None): """Negative log MSE loss, the negated log of SNR denominator.""" err_pow = tf.math.reduce_sum(tf.math.square(source - separated), axis=-1) snrfactor = 10.**(-max_snr / 10.) if bias_ref_signal is None: ref_pow = tf.math.reduc...
46203582f0d0ec2a98248ec000805c9e43f54091
21,475
from typing import Union def crack(password: str) -> Union[str, None]: """ Crack the given password """ # found 96% by caesar return caesar(password)
058779267c400501eecac2d3e43d691e2152ef8d
21,476
def fetchOne(query): """ Returns a dict result from the fetch of one query row """ return sqliteRowToDict(query.fetchone())
5be4753ea541a6e27ece16fb375c8a0664487a71
21,477
def _get_class_rgb(num_classes, predicted_class): """Map from class to RGB value for a specific colormap. Args: num_classes: Integer, the total number of classes. predicted_class: Integer, the predicted class, in [0, num_classes). Returns: Tuple of 3 floats in [0.0, 1.0] representing an RGB color....
914824eef57a829a7d67e74f45f56088d73ea34e
21,478
from datetime import datetime def PUT(request): """Update a project's name.""" request.check_required_parameters(body={'project': {'name': 'name'}}, path={'projectId': 'string'}) project = Project.from_id(request.params_path['projectId']) project.check_exists() project.check_user_access(request...
ab5cc9bea5f5a933293761a852532f2c7c6004ec
21,479
def load_book_details(file_path): """ Read book details from a csv file into a pandas DataFrame. """ books_df = pd.read_csv(file_path, index_col='book_id') return books_df
9240efd9778198e34464fe6f95d312a82fd3894e
21,480
import random import string def random_string_fx() -> str: """ Creates a 16 digit alphanumeric string. For use with logging tests. Returns: 16 digit alphanumeric string. """ result = "".join(random.sample(string.ascii_letters, 16)) return result
835c2dc2716c6ef0ad37f5ae03cfc9dbe2e16725
21,481
from typing import Dict from typing import List import logging def parse_scheduler_nodes( pbscmd: PBSCMD, resource_definitions: Dict[str, PBSProResourceDefinition] ) -> List[Node]: """ Gets the current state of the nodes as the scheduler sees them, including resources, assigned resources, jobs current...
bceec54b302b0b70e77181d3940fd6e41b8922c4
21,482
def GaugeSet(prefix, *, name, index, **kwargs): """ Factory function for Gauge Set. Parameters ---------- prefix : str Gauge base PV (up to 'GCC'/'GPI'). name : str Name to refer to the gauge set. index : str or int Index for gauge (e.g. '02' or 3). prefix_con...
ef856c77e414d8bc4532483e5b65aa3ebb0cc132
21,483
def user_rating(user, object, category=""): """ Usage: {% user_rating user obj [category] as var %} """ return user_rating_value(user, object, category)
09ac3ea8d1efcc3dc70d82bf5266f3e768a35c3b
21,484
import numpy def weighted_mean( x: NumericOrIter, w: NumericOrIter = None, na_rm: bool = False, ) -> NumericType: """Calculate weighted mean""" if is_scalar(x): x = [x] # type: ignore if w is not None and is_scalar(w): w = [w] # type: ignore x = Array(x) if w is not N...
4034d642629696f1be73c62384bf6633ccb6efe1
21,485
import socket def internet(host="8.8.8.8", port=53, timeout=10): """ Check Internet Connections. :param host: the host that check connection to :param port: port that check connection with :param timeout: times that check the connnection :type host:str :type port:int :type timeout:i...
c0ee11cf7aa9699a077e238d993136aeb4efcead
21,486
def parse_date(td): """helper function to parse time""" resYear = float(td.days)/364.0 # get the number of years including the the numbers after the dot resMonth = int((resYear - int(resYear))*364/30) # get the number of months, by multiply the number after the dot by 364 and divide by 30...
bda78b0968b59c13f763e51f5f15340a377eeb35
21,487
import math def hue_angle(a, b): """ Returns the *hue* angle :math:`h` in degrees. Parameters ---------- a : numeric Opponent colour dimension :math:`a`. b : numeric Opponent colour dimension :math:`b`. Returns ------- numeric *Hue* angle :math:`h` in degr...
2f508be9ed0cdcb0e8b193eefb441a6281a464c7
21,488
def perform_similarity_checks(post, name): """ Performs 4 tests to determine similarity between links in the post and the user name :param post: Test of the post :param name: Username to compare against :return: Float ratio of similarity """ max_similarity, similar_links = 0.0, [] # Kee...
78813c3b2223072a4a5b15a5a71837424a648470
21,489
def create_getters(tuples): """Create a series of itemgetters that return tuples :param tuples: a list of tuples :type tuples: collections.Iterable :returns: a generator of item getters :rtype: generator :: >>> gs = list(create_getters([(0, 2), (), (1,)])) >>> d = ['a', 'b', '...
43d6fed8233ee56b91a52c024c533ae72c8e6890
21,490
def report_cots_cv2x_bsm(bsm: dict) -> str: """A function to report the BSM information contained in an SPDU from a COTS C-V2X device :param bsm: a dictionary containing BSM fields from a C-V2X SPDU :type bsm: dict :return: a string representation of the BSM fields :rtype: str """ report =...
df0aa5ae4b50980088fe69cb0b776abbf0b0998d
21,491
import logging def get_level_matrix(matrix, level): """Returns a binary matrix with positions exceeding a threshold. matrix = numpy array object level = floating number The matrix it returns has 1 in the positions where matrix has values above level and 0 elsewhere.""" logging.info("Selectin...
1516f14970471c4f9402fcbf2cfb2a0d017e754e
21,492
def bookmark(repo, subset, x): """``bookmark([name])`` The named bookmark or all bookmarks. If `name` starts with `re:`, the remainder of the name is treated as a regular expression. To match a bookmark that actually starts with `re:`, use the prefix `literal:`. """ # i18n: "bookmark" is a ...
71fd382ad0710e2e54a80b0b739d04c6d5410719
21,493
def indel_protein_processor(df, refgene, proteincdd=None): """Calculate protein features Features not used in the final model are commented out Args: df (pandas.DataFrame) refgene (str): path to refCodingExon.bed.gz proteincdd (str): optional, path to proteinConservedDomains.t...
721b4b19838ac2d6cd21f471d647c34c3586ebb2
21,494
def perdict_raw(model, *args, **kwargs): """ Tries to call model.predict(*args, **kwargs, prediction_type="RawFormulaVal"). If that fail, calls model.predict(*args, **kwargs) """ try: return model.predict(*args, **kwargs, prediction_type="RawFormulaVal") except TypeError: return ...
2ab7790c0cd48cc9b26f6e7888dd61436cb728b4
21,495
def login_required(arg): """ Decorator to check if a user is logged in""" @wraps(arg) def wrap(*args, **kwargs): """Checking if token exists in the request header""" if request.headers.get('Authorization'): auth_token = request.headers.get('Authorization') token = aut...
2d41e2cd41621a0ce6015182badd7a4117c1daf6
21,496
def calc_manual_numbers(n): """ >>> calc_manual_numbers(1) 20151125 >>> calc_manual_numbers(2) 31916031 >>> calc_manual_numbers(3) 18749137 >>> calc_manual_numbers(21) 33511524 """ return (BASE * pow(FACTOR, n - 1, MOD)) % MOD
d0a276da3eb931afcf6b60b1b6172b468e59b95c
21,497
def accuracy(y0, y1): """ compute accuracy for y1 and y2 does not meter if either of them is in vector or integer form :param y0: list of - labels or vector of probabilities :param y1: list of - labels or vector of probabilities :return: accuracy """ if not isinstance(y0[0], (int, float, np....
b0e1077a8443e3d325b3238355c1a578af8823e3
21,498
import random def random_function(*args): """Picks one of its arguments uniformly at random, calls it, and returns the result. Example usage: >>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2)) """ choice = random.randint(0, len(args) - 1) return args[choi...
3f8d11becc52fde5752671e3045a9c64ddfeec97
21,499
def get_transceiver_sensor_sub_id(ifindex, sensor): """ Returns sub OID for transceiver sensor. Sub OID is calculated as folows: sub OID = transceiver_oid + XCVR_SENSOR_PART_ID_MAP[sensor] :param ifindex: interface index :param sensor: sensor key :return: sub OID = {{index}} * 1000 + {{lane}} * ...
4c718feb45384ab6bef11e1f3c42ab4cd8d0ae2c
21,500
def patch_twitter_get_following_users(value): """Return a function decorator which patches the TwitterClient.get_following_user_ids method.""" return patch_twitter_client_method("get_following_user_ids", value)
296d20a3dbce3684cb2af2568c64fac25ab345c9
21,501
def conv1x1_1d(inplanes: int, outplanes: int, stride: int = 1) -> nn.Conv1d: """1x1一维卷积,用于短接时降采样""" return nn.Conv1d( inplanes, outplanes, kernel_size=(1,), stride=(stride,), padding=0, bias=False )
481dc7b71b31ae6199bcafd1112bf1541d7a5d25
21,502
import struct def unpack_mmap_block(mm, n): """Decode the nth 4-byte long byte string from mapped memory.""" return struct.unpack("<L", mm[n*DATA_BLOCK_SIZE:(n+1)*DATA_BLOCK_SIZE])[0]
a75ac48e188e03e1ec7d3c289ffdd8e12173bc6f
21,504
def tobs(): """Return a list of temperatures for prior year""" # * Query for the dates and temperature observations from the last year. # * Convert the query results to a Dictionary using `date` as the key and `tobs` as the value. # * Return the json representation of your dictionary. las...
c7411130bb5c8d956d10a2ba3ce535f41ca04474
21,505
def reactToAMQPMessage(message, send_back): """ React to given (AMQP) message. `message` is expected to be :py:func:`collections.namedtuple` structure from :mod:`.structures` filled with all necessary data. Args: message (object): One of the request objects defined in ...
fd34510d58e6b164f37f93c0b17f2b2a1c8d32d2
21,506
def recE(siEnergy, layer): """ Reconstructed energy from sim energy """ return ( (siEnergy/mipSiEnergy) * layerWeights[layer-1] + siEnergy)*\ secondOrderEnergyCorrection
9efde4432f3a81ff06505c6fbb529be7404027d4
21,507
def get_account_id(): """ Retrieve the AWS account ID """ client = boto3.client("sts") account_id = client.get_caller_identity()["Account"] return account_id
579bdc686a0ceb5d71e180bf8ce7a17243cff849
21,508
def process_tag(item, profile, level=0): """ Processes element with <code>tag</code> type @type item: ZenNode @type profile: dict @type level: int """ if not item.name: # looks like it's root element return item attrs = make_attributes_string(item, profile) cursor = profile['place_cursor'] and zen_codin...
7d06160cadb0d828799713d888327a41e7ab0b80
21,509
from typing import Optional import google def read_secret(project_id: str, secret_name: str) -> Optional[str]: """Reads the latest version of a GCP Secret Manager secret. Returns None if the secret doesn't exist.""" secret_manager = secretmanager.SecretManagerServiceClient() secret_path = secret_man...
388fa51983452f0852646d1ed1ab183da706c0ab
21,510
import xml def find_in_xml(data, search_params): """Try to find an element in an xml Take an xml from string or as xml.etree.ElementTree and an iterable of strings (and/or tuples in case of findall) to search. The tuple should contain the string to search for and a true value. """ if isinstan...
1cb4685a042349231cd946116a4894ca5b9d68d5
21,511
def conditional_expect( X, func, reg, method=None, quantile_method=None, n_integration_samples=10, quad_dict=None, random_state=None, include_x=False, include_idx=False, vector_func=False, ): """Calculates the conditional expectation, i.e. E[func(Y)|X=x_eval], where Y...
fb89adedeada5e100f2483d927d945ffe2d99034
21,512
def getSumOfSquaresPixel16_Image16(Image): """getSumOfSquaresPixel16_Image16(Image) -> unsigned __int16""" return _ImageFunctions.getSumOfSquaresPixel16_Image16(Image)
9ba21171e26fc32d938a3f377684830df5f03b8f
21,513
def parse_statement(parsed, output): """Parses a tokenized sql_parse token and returns an encoded table.""" # Get the name of the table being created table_name = next(token.value for token in parsed.tokens if isinstance(token, Identifier)) # Add the table metadata to the cached tables to access later. ...
a81791deac59e496145993bba0547294d5d5a7fa
21,514
def create_hue_success_response(entity_number, attr, value): """Create a success response for an attribute set on a light.""" success_key = f"/lights/{entity_number}/state/{attr}" return {"success": {success_key: value}}
c8570ca95ada89bd26d93f659261c91032c915c7
21,515
import warnings def get_deaths(): """***DEPRECATED - Use get_data_jhu instead.*** Get most recent fatality counts from JHU.""" # Deprecated warning url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/" warnings.warn("This function is...
c747d27b10d0845520f4dbbfbb5efcf23c655b7e
21,516
def transform_sentence(text, model): """ Mean embedding vector """ def preprocess_text(raw_text, model=model): """ Excluding unknown words and get corresponding token """ raw_text = raw_text.split() return list(filter(lambda x: x in model.vocab, raw_text)) ...
57f9002e4f7fccefa824f1691324b4593b11fbe0
21,517
from typing import Sequence from typing import List import inspect def model_primary_key_columns_and_names(Model: DeclarativeMeta) -> (Sequence[Column], List[str]): """ Get the list of primary columns and their names as two separate tuples Example: pk_columns, pk_names = model_primary_key_columns_an...
9466524452a77459042081e7becf968302b3dd3b
21,518
def biweekly_test_data(): """ Provides test data for the full system test when using "biweekly" time_scale.""" time_scale = "biweekly" time_per_task = { "Free" : 480 * 9 * 2, "Work" : 480 * 5 * 2, "Sleep" : 480 * 7 * 2 } min_task_time = 60 preferences = { "Free" :...
b5f354a17819133c3c29e7652f6b1132599e89b6
21,519
def plot_bar_whiskers_jitter_significance(data, comparison_columns, significant_comparison_columns, heights, ylabel, xlabels=None, ax_handle=None, ...
dfdaf95034d3d53fac7c79eb4c7b387f9ac18f5b
21,520
def _is_trans_valid(seed, mutate_sample): """ Check a mutated sample is valid. If the number of changed pixels in a seed is less than pixels_change_rate*size(seed), this mutate is valid. Else check the infinite norm of seed changes, if the value of the infinite norm less than pixel_value_change_rate...
118dc0e566fc4f5c481d21f8c8aec7fe4f1ece29
21,521
def split_axis(x, indices_or_sections, axis): """Splits given variables along an axis. Args: x (tuple of Variables): Variables to be split. indices_or_sections (int or 1-D array): If this argument is an integer, N, the array will be divided into N equal arrays along axis. ...
245841aaef14ea130b20254775152a9199d63c41
21,522
def status(**kwargs): """Execute \"git status\" on the repository.""" status = check_output(["git", "status"]).decode("utf-8") repo_clean = True for keyword in ["ahead", "modified", "untracked"]: if keyword in status: repo_clean = False return {"clean": repo_clean, "status": st...
8e81264579628407e8560a6d89be884179636ea9
21,523
from typing import Counter def find_listener_frequent_words(df, num): """ Given a conversation dataframe from a certain subreddit, find the top frequent words spoken by listeners. Args: df: A specified dataframe from a subreddit. num: A ranking number used for finding the top frequent wor...
80bc4b95e5713429751ff1725afce4ac02f0bddd
21,525
def is_rescue_entry(boot_entry): """ Determines whether the given boot entry is rescue. :param BootEntry boot_entry: Boot entry to assess :return: True is the entry is rescue :rtype: bool """ return 'rescue' in boot_entry.kernel_image.lower()
ba456c2724c3ad4e35bef110ed8c4cc08147b42c
21,526
import base64 def estimate_cost(features, ssd): """Generate a TensorFlow subgraph to estimate the cost of an architecture. Args: features: A 1D float tensor containing features for a single network architecture. ssd: The name of the search space definition to use for the cost model. Returns: ...
2c85cc5d320cd214dae260793a1c779d8019177c
21,527
import yaml def IsResourceLike(item): """Return True if item is a dict like object or list of dict like objects.""" return yaml.dict_like(item) or (yaml.list_like(item) and all(yaml.dict_like(x) for x in item))
bc6ae6c4d84949511c679116454343731e8d8bd2
21,529
import math def rad_to_gon(angle: float) -> float: """Converts from radiant to gon (grad). Args: angle: Angle in rad. Returns: Converted angle in gon. """ return angle * 200 / math.pi
cbf7070a9c3a9796dfe4bffe39fdf2421f7279ed
21,530
def check_interface_status(conn_obj, interface, state, device="dut"): """ API to check the interface state Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param conn_obj: :param interface: :param state: :param device: :return: """ interface_state = get_interface_sta...
484c1a8dcf96a3160791a63979d47096e5e51fbc
21,531
def hungarian_match(self, y_true, y_pred): """Matches predicted labels to original using hungarian algorithm.""" y_true = self.adjust_range(y_true) y_pred = self.adjust_range(y_pred) D = max(y_pred.max(), y_true.max()) + 1 w = np.zeros((D, D), dtype=np.int64) # Confusion matrix. fo...
29a9976edcfa4a935d451f6471641b3836343d83
21,532
import torch def orthantree(scaled, capacity=8): """Constructs a :ref:`tree <presolve>` for the given :func:`~pybbfmm.scale`'d problem. This is a bit of a mess of a function, but long story short it starts with all the sources allocated to the root and repeatedly subdivides overfull boxes, constructing t...
9813697be3b19a2d7e3b71f28b1212c91a590fd3
21,533
def make_sparse( docs_to_fit, min_df=50, stop_words=None, docs_to_transform=None, ngram_range=None, ): """ Take a pre-tokenized document and turn into a sparse matrix. :param docs_to_fit: A list of lists of tokenized words to build the vocabulary from. :param min_df: Number of records th...
467d04f465ed4c19b4e20aa69c05508f6faafdc6
21,534
import random def weightedPriorityReliabilityScore(service_instances, last_records): """ Algorithm to find highest priority of the service based on reliability score achieved in past discovery results """ priority_list = [] for i in range(0, len(service_instances)): sin...
e215ae3e4009de7e8e6e8a8a0b66a66238e30f16
21,535
def calculate_output(param_dict, select_device, input_example): """Calculate the output of the imported graph given the input. Load the graph def from graph file on selected device, then get the tensors based on the input and output name from the graph, then feed the input_example to the graph and retrieve...
e98bf63743d7f940170ca7ab4dcd97b751be178f
21,536
def is_instance_failed_alarm(alarms, instance, guest_hb=False): """ Check if an instance failed alarm has been raised """ expected_alarm = {'alarm_id': fm_constants.FM_ALARM_ID_VM_FAILED, 'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL} return _instance_alarm_raised(alarms...
5c886bea0b72d52392ed38217af20b7ebc87bd91
21,537
def detected(numbers, mode): """ Returns a Boolean result indicating whether the last member in a numeric array is the max or min, depending on the setting. Arguments - numbers: an array of numbers - mode: 'max' or 'min' """ call_dict = {'min': min, 'max': max} if mode not in ca...
b0a5b19e7d97db99769f28c4b8ce998dbe318c5b
21,539
import math def calculate_compass_bearing(point_a, point_b): """ Calculates the bearing between two points. The formulae used is the following: θ = atan2(sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) :Parameters: - `pointA: The tuple repres...
535fc0cfc086974b1e329df297bdbea4aab1f127
21,540
import re def parse_instructions(instruction_list): """ Parses the instruction strings into a dictionary """ instruction_dict = [] for instruction in instruction_list: regex_match = re.match(r"(?P<direction>\w)(?P<value>\d*)",instruction) if regex_match: instruction_dic...
67b773bae0cb2cc0509503f2ea27f3312ce9d41c
21,541
def calc_elapsed_sleep(in_num, hyp_file, fpath, savedir, export=True): """ Calculate minutes of elapsed sleep from a hypnogram file & concatenate stage 2 sleep files Parameters ---------- in_num: str patient identifier hyp_file: str (format: *.txt) file with hypnogram at 30-sec...
61390b205c7dcbd65884e8f073f1b1395f1d1ca2
21,542
def valid_pairs(pairs, chain): """ Determine if the chain contains any invalid pairs (e.g. ETH_XMR) """ for primary, secondary in zip(chain[:-1], chain[1:]): if not (primary, secondary) in pairs and \ not (secondary, primary) in pairs: return False return True
c9e36d0490893e1b1a6cd8c3fb0b14b382d69515
21,543
from typing import Any def fqname_for(obj: Any) -> str: """ Returns the fully qualified name of ``obj``. Parameters ---------- obj The class we are interested in. Returns ------- str The fully qualified name of ``obj``. """ if "<locals>" in obj.__qualname__: ...
6d4e5db255715c999d1bb40533f3dbe03b948b07
21,545
def symbol_size(values): """ Rescale given values to reasonable symbol sizes in the plot. """ max_size = 50.0 min_size = 5.0 # Rescale max. slope = (max_size - min_size)/(values.max() - values.min()) return slope*(values - values.max()) + max_size
a33f77ee8eeff8d0e63035c5c408a0788b661886
21,547
from datetime import datetime def delete(id): """Soft delete a patient.""" check_patient_permission(id) patient = Patient.query.get(id) patient.deleted = datetime.datetime.now() patient.deleted_by = current_user db.session.commit() return redirect(url_for('screener.index'))
0e9c984bb8bf8429c662f1af14945089789b8bc8
21,548
import torch import tensorflow as tf def _to_tensor(args, data): """Change data to tensor.""" if vega.is_torch_backend(): data = torch.tensor(data) if args.device == "GPU": return data.cuda() else: return data elif vega.is_tf_backend(): data = tf.con...
77d87982c81232bac4581eb5269629c268a7fe16
21,551
def materialize_jupyter_deployment( config: ClusterConfig, uuid: str, definition: DeploymentDefinition) -> JupyterDeploymentImpl: # noqa """Materializes the Jupyter deployment definition. :param config: Cluster to materialize the Jupyter deployment with. :param uuid: Unique...
d4a12efd7d4f55d5261734cf3eb0dd3b230c363d
21,552
def _CreateLSTMPruneVariables(lstm_obj, input_depth, h_depth): """Function to create additional variables for pruning.""" mask = lstm_obj.add_variable( name="mask", shape=[input_depth + h_depth, 4 * h_depth], initializer=tf.ones_initializer(), trainable=False, dtype=lstm_obj.dtype) ...
398dd89a9b8251f11aef3ba19523e26861ff5874
21,553
def get_index_fredkin_gate(N, padding = 0): """Get paramaters for log2(N) Fredkin gates Args: - N (int): dimensional of states - padding (int, optional): Defaults to 0. Returns: - list of int: params for the second and third Frekin gates """ indices = [] for i in range(...
d7ab1f4bc414ad741533d5fabfb0f7c8b4fe0959
21,554
def import_by_name(name): """ 动态导入 """ tmp = name.split(".") module_name = ".".join(tmp[0:-1]) obj_name = tmp[-1] module = __import__(module_name, globals(), locals(), [obj_name]) return getattr(module, obj_name)
714ca90704d99a8eafc8db08a5f3df8e17bc6da4
21,555
def f1_score(y_true, y_pred): """F-measure.""" p = precision(y_true, y_pred) r = true_positive_rate(y_true, y_pred) return 2 * (p * r) / (p + r)
e5f79def2db902bb0aa1efd9ea1ccef52b62072a
21,556
def hexColorToInt(rgb): """Convert rgb color string to STK integer color code.""" r = int(rgb[0:2],16) g = int(rgb[2:4],16) b = int(rgb[4:6],16) color = format(b, '02X') + format(g, '02X') + format(r, '02X') return int(color,16)
59b8815d647b9ca3e90092bb6ee7a0ca19dd46c2
21,557
import torch def test(model, X, model_type, test_type, counter=False): """Test functions.""" if model_type == 'notear-mlp': X = np.vstack(X) y = model(torch.from_numpy(X)) y = y.cpu().detach().numpy() mse = mean_squared_loss(y.shape[0], y[:, 0], X[:, 0]) elif model_type == 'notear-castle': ...
cb98e2096052270e786bbb81fafc328076b1aa40
21,558
def scale(): """ Returns class instance of `Scale`. For more details, please have a look at the implementations inside `Scale`. Returns ------- Scale : Class instance implementing all 'scale' processes. """ return Scale()
f5fb9daf9baaf86674be110aae78b1bf91f09371
21,559
def imread_rgb(filename): """Read image file from filename and return rgb numpy array""" bgr = cv2.imread(filename) rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) return rgb
6fcef3f9f5d8b02c28c596f706f3e1fcf685dd24
21,560
def insert_at_index(rootllist, newllist, index): """ Insert newllist in the llist following rootllist such that newllist is at the provided index in the resulting llist""" # At start if index == 0: newllist.child = rootllist return newllist # Walk through the list curllist = rootllist for i in ran...
767cde29fbc711373c37dd3674655fb1bdf3fedf
21,561
def kpi_value(request, body): """kpi值接口 根据 indicator 传入参数不同请求不同的 handler""" params = { "indicator": body.indicator } handler = KpiFactory().create_handler(params["indicator"]) result = handler(params=params) return DashboardResult(content=result)
5f242028d7f95b1ffa81690c3ed1b1d7006cf97c
21,562
def safeReplaceOrder( references ): """ When inlining a variable, if multiple instances occur on the line, then the last reference must be replaced first. Otherwise the remaining intra-line references will be incorrect. """ def safeReplaceOrderCmp(self, other): return -cmp(self.colno, o...
dae29bf1c8da84c77c64210c4d897ac4a9d0c098
21,563
def clean_value(value: str) -> t.Union[int, float, str]: """Return the given value as an int or float if possible, otherwise as the original string.""" try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass return value
52c09e2aaf77cb22e62f47e11226350112390eb2
21,565
import types def sumstat(*L): """ Sums a list or a tuple L Modified from pg 80 of Web Programming in Python """ if len(L) == 1 and \ ( isinstance(L[0],types.ListType) or \ isinstance (L[0], types.TupleType) ) : L = L[0] s = 0.0 for k in L: s = s + k ...
c37aa0aa0b7dbf6adbe77d82b27b25e469891795
21,566
def halref_to_data_url(halref: str) -> str: """ Given a HAL or HAL-data document URIRef, returns the corresponding HAL-data URL halref: str HAL document URL (Most important!) https://hal.archives-ouvertes.fr/hal-02371715v2 -> https://data.archives-ouvertes.fr/document/hal-02371715v...
48ef6629fc3198af2c8004a3dbcbbde6e700cb12
21,567
def find_best_rate(): """ Input: Annual salary, semi-annual raise, cost of home Assumes: a time frame of three years (36 months), a down payment of 25% of the total cost, current savings starting from 0 and annual return of 4% Returns the best savings rate within (plus/minus) $100 of the downpayme...
451fc72c006182b63233376a701b4cbb855ad39a
21,568
def q_inv(a): """Return the inverse of a quaternion.""" return [a[0], -a[1], -a[2], -a[3]]
e8d06e7db6d5b23efab10c07f4b9c6088190fa07
21,569
def divide_hex_grid_flower(points, hex_radius=None): """Partitions a hexagonal grid into a flower pattern (this is what I used for the final product. Returns a list of partition indices for each point.""" if hex_radius is None: # copied from build_mirror_array() mini_hex_radius = (10 * 2.5 / 2) + 1 ...
9f77e85d4bbfd00ea5eff6905209aad84e3a9191
21,570
def fis_gauss2mf(x:float, s1:float, c1:float, s2:float, c2:float): """Split Gaussian Member Function""" t1 = 1.0 t2 = 1.0 if x < c1: t1 = fis_gaussmf(x, s1, c1) if x > c2: t2 = fis_gaussmf(x, s2, c2) return (t1 * t2)
443e02dff7ab3827ac0006443964f45a6f9f4ce2
21,571
def _is_trigonal_prism(vectors, dev_cutoff=15): """ Triangular prisms are defined by 3 vertices in a triangular pattern on two aligned planes. Unfortunately, the angles are dependent on the length and width of the prism. Need more examples to come up with a better way of detecting this shape. For now, this...
2b3ffb318b3201923828eea8f4769a6ce854dd58
21,572
def priority(n=0): """ Sets the priority of the plugin. Higher values indicate a higher priority. This should be used as a decorator. Returns a decorator function. :param n: priority (higher values = higher priority) :type n: int :rtype: function """ def wrapper(cls): cls...
58ab19fd88e9e293676943857a0fa04bf16f0e93
21,575
import math def vecangle(u,v): """ Calculate as accurately as possible the angle between two 3-component vectors u and v. This formula comes from W. Kahan's advice in his paper "How Futile are Mindless Assessments of Roundoff in Floating-Point Computation?" (https://www.cs.berkeley.edu/~wkahan/Mindles...
dde6ebed830130f122b0582d4c19963a061a3d31
21,576