content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_package_attribute(name): """Retrieve package attributes from the package itself.""" with open("darwin/__init__.py") as init_file: for line in init_file: if line.startswith(name): return eval(line.split("=")[-1])
33e7cdb53fffa844576e4e9387218b3ccbe6926d
3,609,752
def legacy_redirect(id): """Redirect to the documents.""" error = { "code": PIDDoesNotExistRESTError.code, "description": PIDDoesNotExistRESTError.description, } try: record = get_record_by_legacy_recid(Record, id) except PIDDoesNotExistError: return error schema ...
9e1716a3b978922954360334271c285a14d80708
3,609,753
def get_service(hass, config, discovery_info=None): """Get the Pushetta notification service.""" api_key = config[CONF_API_KEY] channel_name = config[CONF_CHANNEL_NAME] send_test_msg = config[CONF_SEND_TEST_MSG] pushetta_service = PushettaNotificationService( api_key, channel_name, send_tes...
5ae13b5dc464d597b144632770067ca97dd173ae
3,609,754
from typing import Optional from typing import Dict from typing import Any import copy def filter_end_events_per_object_type(ocel: OCEL, object_type: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL: """ Filters the events in which an object for the given object type terminates its lifecycle. (E....
1cc42b4c362802516ea410b6856868c0cebf08ed
3,609,755
import logging def scrape_inverter(): """ Connect to the inverter and scrape the metrics """ client.connect() if "sungrow-" in options['model']: for i in bus["read"]: if not load_registers("read", i["start"], int(i["range"])): return False for i in bus["holdin...
9426618499ef6663ef62bfc5bd071fe21f6abc26
3,609,756
def call(cfg, clargs, cmds, **kwargs): """ IMPURE Delegates work to appropriate `call_*` functions. Parameters ---------- cfg: dict Configuration dictionary. clargs: Namespace Command line arguments (normalized). cmds: iter(tuple) Iterator of commands to be passed to `subpro...
098269efe7a3f20a15fd55b3d9aaa69cc288e772
3,609,757
import scipy def plotPeaks(x, y, peaks, showPeaks=True, plotLabels=False, fig=10, plotScore=False, plotsmooth=True, plothalf=False, plotbottom=False, plotmarker='.-b'): """ Plot detected peaks Arguments --------- x,y : numpy arrays scandata peaks : list list of pe...
db8475879ec60cd0de7750927ec2710196ce3ed5
3,609,758
def connect(creds): """ Connect to cloudformation, with user-provided options. :param region_creds: The region name and AWS credentials. :type region_creds: kaws.config.AwsCreds or kaws.config.RegionAwsCreds :rtype: boto.cloudformation.connection.CloudFormationConnection Note: IAM cannot authenticate a user us...
b45794b343115f87daae68d38805ae602678ad30
3,609,759
import re def isBaidu(url): """Return True if this url matches the pattern for Baidu searches""" #Example: http://www.baidu.com/s?wd=mao+is+cool&rsv_bp=0&ch=&tn=baidu&bar=&rsv_spt=3&ie=utf-8 pattern = 'http://www.baidu.com/s\?wd=[\S+]+' matches = re.match(pattern, url) if matches != None: return True...
b4c06154f1f4f2bd6a18bbcb08c2ce0b4d2cbbc9
3,609,760
def table_to_json(table): """ returns a table as JSON """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") return arcpy.RecordSet(table).JSON
40eb4469853779144cb1a60df706bfeb21030a94
3,609,761
def epost_history_with_retries(qids, dbname, maxretries): """Entrez EPost for a batch of queryids. qids - Collection of query IDs dbname - target NCBI database maxretries - maximum download attempts Returns the generated history, as parsed by Entrez.read() """ trie...
232bd19d3366e3a1c67a786c948d2deb67dc59a2
3,609,762
def cross_join(df1, df2): """ Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401 """ if len(df1) == 0: return df2 if len(df2) == 0: return df1 # Add as lists so that the new index keeps the items in #...
5db6b7184e133f1bb2c7c63aff791292a4ad3dbf
3,609,763
import FWCore.ParameterSet.Modules def getModulesOfSequence(sequence): """ returns the modules found in a sequence. Note that a module can appear more than once. """ class Visitor: #---------------------------------------- def __init__(self): self.modules_found = [] ...
79fc93d5a5ea798db419b1156a596993d32b0f40
3,609,764
def client(clusterrole, namespace, kubeconfig, port, admin_client): """I have <clusterrole> permissions in <namespace>.""" needs_admin = namespace == 'all namespaces' if needs_admin: return admin_client ensure_namespace(admin_client, namespace) k8s_client = kubernetes.config.new_client_fro...
aed5faafc2cc194ed4a69a2d6815b5e4f5fa4b3b
3,609,765
import numpy as np def read_cnf_mols ( filename, with_v=False, quaternions=False ): """Read in molecular configuration.""" with open(filename,"r") as f: n=int(f.readline()) # Number of atoms box=float(f.readline()) # Simulation box length (assumed cubic) revw=np.loadtxt(filename,...
f9ff9578d66d4f57740a10fae727202796b58cc6
3,609,766
from re import T def multiply_series(*series) -> Series[T]: """ multiple addition """ if len(series) < 2: return series[0] return multiply_2series(series[0], multiply_series(*series[1:]))
025adb3b0ce42170438a28d88010942d87935a27
3,609,767
def get_app_id(c, app_name): """ Retrieve app-id for a given app name (in full). Called from get_id, not for use as sub-task. :return: False on error, True on not found (continue), or string with app uuid """ print(f'{CYAN}Retrieving app-id for {app_name}...{COL_END}') response = c.config.contro...
5be7a04a770fc927909ebc9d9eba6fff0524080f
3,609,768
def lnL_EB(time: np.ndarray, flux: np.ndarray, sigma: float, R_EB: float, EB_fluxratio: float, P_orb: float, inc: float, a: float, R_s: float, u1: float, u2: float, companion_fluxratio: float = 0.0, companion_is_host: bool = False): """ Calculates the log likelihood o...
9d17cbff17eefe29d271778b6c819f514026e374
3,609,769
def detect_burst(relevant_list, total_list): """ Assume (num. of relevant docs, total num. docs) as the two input lists returns state costs """ state_costs = [(0.0, 0.0)] # for the initial step s = 2 R = sum(relevant_list) D = sum(total_list) p_0 = (1.0 * R) / D p_1 = p_...
bf4d505d47eb0db2e2f32e254877391359ed408a
3,609,770
def generate_inside_field(center, segment, n, max_features, min_features, feature_variance): """ Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Ar...
2355631e9dc43b766c0420478f49629da0b29c9c
3,609,771
import torch def diversity_score(xyz, distance_type:str, **kwargs) -> torch.tensor.shape == [1]: """ :param xyz: [B, P, N, 3] tensor :param distance_type: shape/part :param kwargs: {downsample_type:None, npoint_per_part:10} :return: [1] tensor of divs_score """ if distance_type == "shape":...
c04112b7dc8e0049ee318a118720bf7345ee7526
3,609,773
def find_left_element(sorted_data, right, comparator): """! @brief Returns the element's index at the left side from the right border with the same value as the last element in the range `sorted_data`. @details The element at the right is considered as target to search. `sorted_data` must ...
7edc5ba49da8dbcbdc45310331b68c8ebe0c4ee1
3,609,774
def CreateTestBudget(client): """Creates a budget to run tests with. Args: client: AdWordsClient client to obtain services from. Returns: int Budget ID """ budget_service = client.GetBudgetService(SERVER, VERSION, HTTP_PROXY) budget = { 'name': 'Budget #%s' % Utils.GetUniqueName(), 'am...
881095c68260a96195b3c97f4cf83f6a7d30e8f7
3,609,777
def logout(): """Used to logout users""" logout_user() return redirect(url_for('home'))
6e59dbb50b6813c67b0804e226dc1ce951d39daa
3,609,778
def gaussian_kernel(x1: np.ndarray, x2: np.ndarray, sigma: int) -> np.ndarray: """ Compute the Gaussian kernel between x1 and x2. Args: x1: The first vector. x2: The second vector. sigma: The sigma of the Gaussian function. Returns: The Gaussian kernel between x1 an...
912f71fe3063b44b39f24886637d3e71cf1f0178
3,609,779
from datetime import datetime def make_windows_timestamp_value_getter(value_name): """ return a function that fetches the value from the registry key as a Windows timestamp. """ f = make_value_getter(value_name) def _value_getter(key): try: return parse_windows_timestamp(...
3ad16c5a76cc50a1b1e8632da95807ceb62dc179
3,609,780
def compute_area(c, target_layer): """ Compute area of the component on a given layer """ _print("Computing area ", c.name) c.flatten() # return c.area(by_spec=True)[layer] polys_by_spec = c.get_polygons(by_spec=True) _area = 0 for (layer, polys) in polys_by_spec.items(): _pr...
89039cd084a51353c2b8b539c9580c38f416b24a
3,609,781
import json def admin_add_user(request): """ :param request: :return: """ # Make sure user has permissions # Get data group_results = group.objects.filter( is_deleted=False, ).values() permission_set_results = permission_set.objects.filter( is_deleted=False, ...
8903f410b05c27a3d26a32f1943958dd7180cc88
3,609,783
def generate_flac_dirname(library_root, metadata): """Build the directory for a track's FLAC file. :arg str library_root: the FLAC library directory :arg dict metadata: the finalized metadata for a single track :return: an absolute directory path :rtype: :obj:`str` """ _log.call(library_ro...
7e58d138ef98df8e08ca002f8920b5bc0a9a032c
3,609,784
def NamedParameterNames(fn): """! @brief Get names available to use as named parameters. """ try: co = fn.__code__ except AttributeError: return () return co.co_varnames[co.co_posonlyargcount:co.co_argcount+co.co_kwonlyargcount]
6d62a5d10d02483ee288b765c7e63a060871d839
3,609,785
def create_and_validate_config(parsed_config: YAML = None) -> Config: """Run validation on config values.""" if parsed_config is None: parsed_config = fetch_config_from_yaml() # specify the data attribute from the strictyaml YAML type. _config = Config( app_config=AppConfig(**parsed_con...
ddb4eeb5a0b73d82cee49ca7fe652ba96d31b47e
3,609,787
def optimizer(): """ Get the optimizer to use for training :return: optimizer object """ opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) return opt
ba1fbe6e59287f31423be28dfc33efd70a29e3d1
3,609,788
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload Trafikverket Weatherstation config entry.""" return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
160038c53297a915087c591ed64e00f5d049a2cb
3,609,789
from typing import List from typing import Tuple from typing import Any def min_w_ind(lst: List) -> Tuple[int, Any]: """ Returns the min value and its index :param lst: The list to get the max value in :return: Min value and its index """ val = min(lst) ind = lst.index(val) return ind,...
d0da7d1ab1c762f1af2333de6e8b829f8218fd25
3,609,792
def run_transition(): """ Transition execution/"stepping" - run color change for long dimming periods - runs the generated color dimming generators :return: Execution verdict """ if None not in Data.FADE_OBJ: try: r = Data.FADE_OBJ[0].__next__() g = Data.F...
ec9df50fa790384d570fbe8c2e4a30515defbecb
3,609,793
def DatetimesRangeFieldWidget(field, request): # pylint: disable=invalid-name """Datetimes range widget factory""" return FieldWidget(field, DatetimesRangeWidget(request))
d389b5a8388813add654afe5084b24c8c75a2edd
3,609,794
from typing import List from typing import Dict def get_company_news( ticker: str, s_start: str, s_end: str, ) -> List[Dict]: """Get news from a company. [Source: Finnhub] Parameters ---------- ticker : str company ticker to look for news articles s_start: str date to ...
8bbcadb8a1278203bb5c7e76a7a06f1bee4ce718
3,609,795
def count(iterable): """ Returns the number of items in `iterable`. """ return sum(1 for whatever in iterable)
a9bb4ac70cef36613372c1225202f97f70a642cf
3,609,796
def scipy_rankdata(a): """ Ranks the data, dealing with ties appropriately. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. Parameters ---------- a : array_like ...
a3b3cd0e87550238ecc3d0be3b444091b5b864dd
3,609,797
def _return_4roles(Z_com_deg, parti_coef): """private function for computing 4 roles""" assert Z_com_deg.shape[0] == parti_coef.shape[0], ("Error, Z_com_deg {} \ should have same length as parti_coef {} ".format(Z_com_deg.shape[0], parti_coef.sha...
7e680891f07eabe5ee226227962acb50b2f1461a
3,609,798
import torch def xy_to_cxcy(xy): """ Convert bounding boxes from boundary coordinates (x_min, y_min, x_max, y_max) to center-size coordinates (c_x, c_y, w, h). :param xy: bounding boxes in boundary coordinates, a tensor of size (n_boxes, 4) :return: bounding boxes in center-size coordinates, a tensor...
46eef5bb63c85a84050a57a2fb27618721b31eaa
3,609,799
def delete_app_env(appname, envname): """Delete the specified environmental variable set""" app = _get_app(appname) deleted = app.remove_env_set(envname) if not deleted: abort(404, 'App `%s` has no env `%s`' % (app.name, envname)) return DEFAULT_RETURN_VALUE
c967ee5b8ffa3a66c97179c9386e27cd8f6bc7f7
3,609,800
def _angle(p,q,r): """ compute the positive angle formed by PQR """ return np.abs(get_angle_between(Ray(q,p),Ray(q,r)))
1c0933c1cd8f7385be6942d57bca71b50ff9c3ce
3,609,801
from typing import Sequence def plotMatrix(matrix, title, xticklabels: Sequence[str], yticklabels: Sequence[str], xlabel: str, ylabel: str, normalize=True, figsize=(9,9), titleAdd: str = None) -> matplotlib.figure.Figure: """ :param matrix: matrix whose data to plot, where matrix[i, j] will be rendere...
868b884b27054129716e397b3a308cd870b5cd7f
3,609,802
def _sample_flux_snr(distances, fwhm, plsc, n_injections, flux_min, flux_max, nproc=10, random_seed=42, wavelengths=None, spectrum=None, mode='median', scaling='temp-standard', svd_mode='randsvd'): """ Sensible flux intervals depend on a combination...
cfd94d10870d599fd4c786aff87f600397debf44
3,609,803
def addBrightness(image, scale): """Adds Brightness to an image. Parameters: image (PIL.Image.Image) = The image to be modified. Returns: bright.enhance(1.1) = The modified image. """ #Use the pillow brightness method to add brightness bright = ImageEnhan...
de91ca415f03a82c431b67e1fe059ea307362f21
3,609,804
import requests import shutil def download_log_simple(): """ Download the log of job types that have a single console log :return: 0 in case of success, -1 in case of an error """ response = requests.get("{}/job/{}/{}/consoleText".format(jenkins_url, job_name, build_id), stream=True, ...
0630bec178113ef11c120ccef9142ab13d6e25d3
3,609,805
async def _compose(choice): """Figure out exactly what resource we're requesting and return the correct class.""" nchoice = list(choice.keys())[0] id = list(choice.values())[0] if '_id' in nchoice: nchoice = nchoice[:-3] return ('/'.join([base_uri, nchoice, str(id), '']), nchoice)
c82afd7129068c6f80acb3d61e30031078c59c38
3,609,806
def validate(guess: str, solution: str) -> str: """Validates the user guess against the solution, coloring correct characters""" return "".join([validate_char(i, guess, solution) for i in range(WORD_LENGTH)])
58af7fd7ba42bf591b9689f74e9f5007b5e70d0d
3,609,807
def infection_rate_symptomatic_80x40(): """ Real Name: b'infection rate symptomatic 80x40' Original Eqn: b'Susceptible 40*Infected symptomatic 40x80*contact infectivity symptomatic 40x80*(self quarantine policy SWITCH self 40\\\\ * self quarantine policy 40+(1-self quarantine policy SWITCH self 40))/non con...
aca50b41f7241c1c357feee21048e0942e980545
3,609,808
import re def input_text(frame_r: tk.Frame, label_text: str, text_width: int, initial: str = None, side_: constants = TOP, side_label: constants = LEFT, fmt: str = None): """テキストの入力ボックスを作成 Args: frame_r (tkinter...
57d4fb91627b24172991d28eac5e8182a100009e
3,609,809
def plot_pca_variance(data): """Runs PCA on passed data and creates the plot figure to visualize the variance corresponding to each component and returns finally the figure object. Consider that the method matplotlib.pyplot.show is called inside this function and the plot is showed if the regarding exec...
22e03892aa47ef3bbb87c76c6cf5a2874f6fb7ee
3,609,810
def on_volume_balance_vec(data_df, window=14): """ On Volume Balance (OBV). :param data_df: Unstacked for one symbol only. :param window: An integer number of days to look back. :return: A pandas Series with the values of OBV for all the valid dates. """ obv_delta = data_df['Volume'] * np.si...
fba02e8c0416e2b0e5871a207fb20cc9b94f7852
3,609,813
def centroidCalculator(cell): """ Centroid is assumed to be roundish so the euclidean distance will always be larger at that region than along protrusions. """ edt = distance_transform_edt(cell) centroid = np.where(edt == np.max(edt)) centroid = [centroid[0][0], centroid[1][0]] return ...
0cdca26bed775e792bd761cb5aa484c633041d1f
3,609,814
def is_ethernet_port(interface): """Judge whether it is ethernet port""" ethernet_port = ['ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'meth'] if_type = get_interface_type(interface) if if_type in ethernet_port: return True return False
668826ae07161ecd64714c065bd67adf9e9dd6e2
3,609,815
def parse_distribution(s): """ Parses the distribution from the given string """ segments = s.split(' ') dist = segments[0] args = segments[1:] # Check to see if the given distribution is supported if dist not in distributions.keys(): raise ValueError('Unsupported distribution %...
0a7bcfaa6f7385e09bfc5e4de4474a2b02eb6048
3,609,817
def calculate_p_b(*args): """ Determines how difficult a text is according to the number of words that are, most likely, unknown to readers. The other formulas we referred to based the score on the number of words and sentences only """ words_count, sentences_count, diff_words_count = args[0...
420b8269390f50b163c89e97f95b27a282f6f829
3,609,819
def part1(entries: tuple) -> int: """part1 solver""" card_key, door_key = entries loop_size = 0 key = 1 while key not in (card_key, door_key): loop_size += 1 key = (key * 7) % 20201227 if key == card_key: return pow(door_key, loop_size, 20201227) return pow(card_key,...
cb4e38704229c3a67a67d7ffd7d8a7e0d2d72628
3,609,820
def id_function(fixture_value): """Convert a param from the use_case fixture to a nicer name. By default, the name (used in the test generated from the parameterized fixture) will use the fixture name and a number. Eg: test_foo[use_case0] Providing explicit 'ids' (either as strings, or as a functi...
3db81ccf652a82249f2455d695b563c12017b654
3,609,821
def application_create(request, name, redirect_uris, scopes=['all_info'], client_type='confidential', description=None, grant_type='authorization_code', **kwargs): """ Registers a new consumer in the Keystone OAuth2 extension. In FIWARE applications is the name OAu...
a36fec62ac062abd6a3fdf9d4fc109241646359b
3,609,822
def create_spreadsheets_json(worksheet_title=None): """ create base parameters json for spreadsheets api call """ if worksheet_title is None: raise ValueError('Missing worksheet_title parameter') return { "spreadsheet_key": SPREADSHEET_KEY, "worksheet_title": worksheet_t...
8177cb3749399b1ff367cc198d27aaed54e2d06e
3,609,823
def constraint_configure_mentoring(model, tracks, v_tdh): """Configure the mentoring of onboarders appropriately.""" # If agent is on, he/she to be paired with exactly 1 mentor: for d in range(num_days): for h in agents_onb: model.Add( sum(v_mentors.loc[(d, h)].values.tol...
69c97ee94bf040ce853d25e5c5cf6184e33e0418
3,609,825
def _parts_span_selector(pspec): """ Selector for `System`Span` part specification """ if len(pspec.leaves) > 3: raise MessageException("Part", "span", pspec) start = 1 stop = None step = 1 if len(pspec.leaves) > 0: start = pspec.leaves[0].get_int_value() if len(pspec...
0144c5aeb31225a5ed46a5e95a3c4d2c0c7f970f
3,609,826
def selection(triple, variables): """Apply selection on a RDF triple""" bindings = set() if variables[0] is not None: bindings.add((variables[0], triple[0])) if variables[1] is not None: bindings.add((variables[1], triple[1])) if variables[2] is not None: bindings.add((variab...
7f237f271d7c980e5ece21eacde671ee0f8a1d05
3,609,827
from typing import Type from pydantic import BaseModel # noqa: E0611 from typing import List def schema_factory( schema_cls: Type[BaseModel], name: str = "", excludes: List[str] = ["id", "created_at", "updated_at"], ) -> Type[BaseModel]: """ Is used to create a CreateSchema which does not contain...
729971dc3c2bbab4926da8acd5690678152d666d
3,609,828
def daily_std_error(merged_data): """Calculates daily seasonal standard error of the timeseries data in a DataFrame Parameters ---------- merged_data: DataFrame A pandas DataFrame with a datetime index and columns containing float type values. Returns ------- DataFrame A p...
11b5f72ff1a68425cd17d7638590290f5ac883d8
3,609,829
def bruteforce(model, c, max_iter=1000): """ Generiere Zufallsdaten, bis diese eine Klasse maximieren oder die maximale Anzahl an Iterationen verbraucht ist. """ shape = (1,) + model.input_shape[1:] for i in range(max_iter): image = np.random.random(shape) prediction = model.predict(...
ccf6d4b899237511b5799c5682de5387108122ab
3,609,830
def process_logic(op): """ Parse the binary operation binary expression. Convert operator to fabric of AST-classes 'AndBexp' / 'OrBexp'. """ if op == '&&': return lambda l, r: AndBexp(l, r) elif op == '||' or op == '!!': return lambda l, r: OrBexp(l, r) else: raise Ru...
4f1b5af939b3909ea25bdb95cdffa1da44fd1fc5
3,609,831
def _build_chef_properties(env, config_file): """ Build python object representation of the Chef-solo node.json file from node_extra.json in config dir and the fabric environment. """ json_properties = _parse_json(config_file) return build_properties(env, "chef", json_properties)
0c012c55895597abcd4c82cadd43113dacdb5e68
3,609,832
def bond_vector(xi, xi_neig, box_length): """ Determine the normalized bond vector between atoms i and j. """ bond = xi - nearest_atom_image(xi_neig, xi, box_length) bond /= np.linalg.norm(bond) return bond
13211c0bfd63971edad8f5839cdbe320d901b572
3,609,833
def get_activation_fn(name, framework="tf"): """Returns a framework specific activation function, given a name string. Args: name (str): One of "relu" (default), "tanh", or "linear". framework (str): One of "tf" or "torch". Returns: A framework-specific activtion function. e.g. tf....
51306d72aa3f1d05111929c841befdd8807318a7
3,609,834
def rolling_weighted_triangle_conv(values, weights, window_size): """Smoothes the data with a window and given the weights Original algorithm: stackoverflow.com/a/46232913/1257075 Returns: Smoothed values Args: values: data to smoothen weights: weights for each data point window_s...
fec4c0bd655d774a5ff138a801edd2a465a2c319
3,609,835
def par(q): """Parameterize using t^3 + t, where t is the polar angle.""" t = np.arctan2(q[1], q[0]) # A simple diffeomorphism from R^1 -> R^1. return t**3 + t
9d37a105a66cc9908284a1501fa89fc5c75f3541
3,609,836
def tanimoto_sparse(str1, str2): """! Calculate the tanimoto coefficient for a pair of sparse vectors @param str1 str: String of 1s and 0s representing the first compound fingerprint @param str2 str: String of 1s and 0s representing the second compound fingerprint @return Returns float """ n...
2a7a6e7c585ceb3aaaa4dfed7e98b01f151e7c06
3,609,837
import itertools import time def perform_experiment(relax: bool, spring_constant: Vector, random_strength: Vector, seed: Vector): """ A function that takes potential values of parameters and returns a dataframe with experiment results for all possible combinations of these parameters. Parameters ...
7d6b89993f8df97a0424077569d443598d31bd89
3,609,838
from bs4 import BeautifulSoup import codecs def get_saml_response(html): """ Parse SAMLResponse from Shibboleth page >>> get_saml_response('<input name="a"/>') >>> get_saml_response('<body xmlns="bla"><form><input name="SAMLResponse" value="eG1s"/></form></body>') 'xml' """ soup = Beauti...
24800c318f7f5f6000c6652d15421c68a97a04a6
3,609,839
def _is_namespace_visible(context, namespace): """Return true if namespace is visible in this context""" if context.is_admin: return True if namespace.get('visibility', '') == 'public': return True if namespace['owner'] is None: return True if context.owner is not None: ...
4f3119684681aa2f3c34a62e1674aaa58d26105e
3,609,840
def create_quantum_model(): """Create a QNN model circuit and readout operation to go along with it.""" data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid. readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1] circuit = cirq.Circuit() # Prepare the readout qubit. circuit.a...
3574dec302b4a3c0b5bf3767ff66936af2eaaf70
3,609,841
def get_aa_subseq_df(sg_designs, aa_seq_df, width, id_cols, transcript_base_col='Transcript Base', target_transcript_col='Target Transcript', aa_index_col='AA Index'): """Get the amino acid subsequences for a design dataframe :param sg_designs: Dat...
181b16fd9887ffe41fea9bbefafa02e0a3e6e557
3,609,842
def _exception_to_dict(exception): """Convert exception to an error object to be sent as response to APIs.""" return {"error": {"type": type(exception).__name__, "message": exception}}
4abb81516b604bdfd2f6360a1272556b0b6f6932
3,609,843
import torch from typing import List def get_depth_prediction( depth_logits: torch.Tensor, use_dgc_scaling: bool, camera_matrix: torch.Tensor = None, real_camera_height: torch.Tensor = None, panoptic_seg: torch.Tensor = None, road_class_id: int = -1, depth_filter_class_ids: List[int] = Non...
8839c1873c0fd6cd04bc9add7e9cb16b1bfb87af
3,609,844
from typing import Optional def sync_wait_and_get_s3_object( uri: Optional[str]=None, bucket: Optional[str]=None, key: Optional[str]=None, sess: Optional[boto3.session.Session]=None, region_name: Optional[str]=None, max_wait_seconds: float=DEFAULT_S3_OBJECT_WAIT_TIMEOUT_SECONDS, # ...
57379f99ce4add147a1570d6e419f1dab47a330b
3,609,845
def read_ceps_test(test_file): """ Reads the MFCC features from disk and returns them in a numpy array. """ X = [] y = [] ceps = np.load(test_file) num_ceps = len(ceps) X.append(np.mean(ceps[int(num_ceps / 10):int(num_ceps * 9 / 10)], axis=0)) return np.array(X), np.array...
c235d222e610d17f5302cc467867f6989891da3b
3,609,847
def dict_to_object(dictionary): """ parse a dictionary and return a dynamic object :param dictionary: dict :return: dynamic_object """ obj = DynamicClass() for key in dictionary: setattr(obj, key, dictionary[key]) return obj
31135f58545c000a7ee64d71a7938222028d63e6
3,609,848
import torch def batchify(fn, chunk): """ Constructs a version of 'fn' that applies to smaller batches. """ if chunk is None: return fn def ret(inputs): return torch.cat([fn(inputs[i:i + chunk]) for i in range(0, inputs.shape[0], chunk)], 0) return ret
4629520fb5aef3a6e280e2eaee30e39baad51f98
3,609,849
def log_loss(y, p): """ Compute the log loss by tensorflow from binary truth and predicted score Parameters ---------- y: The binary truth: 0 or 1 p: The predicted score in [0, 1] Returns ------- the value of the log loss """ return -( y*log(p) + (1-y)*log(1-p) ...
2e8d02b3a1a1542f5be24df0c0e3ffdbc860e206
3,609,850
def cleanstrings(df, columns, stringmaps, unmapped=None, simplify=True): """Consolidate freeform strings in several dataframe columns. This function will consolidate freeform strings found in `columns` into simplified categories, as defined by `stringmaps`. This is useful when a field contains many dif...
f9fd09efd5f27b19ef275dfc4ff62aa18a4bbbf0
3,609,851
import datasets import torch def get_tst_loader( data_dir: str, batch_size: int, shuffle: bool = True, num_workers: int = 4, pin_memory: bool = False, ): """ Utility function for loading and returning a multi-process test iterator over the CIFAR-100 dataset. If using CUDA, num_work...
ed6bf3a4cab0717e6f2de6c2caa4b40e05d9ee9b
3,609,852
def _any_none(*args): """Returns a boolean indicating if any argument is None""" for arg in args: if arg is None: return True return False
fadb9330fc1f4ffca2cf0105d8513d0be0d5fae1
3,609,853
def precision(judged_data): """ Our relevance judgments are on a graded scale of 0-3, where scores of 1-3 are considered relevant, and less than 1 is irrelevant. We compute precision of the result set based on this quanitization. Args: judged_data (pandas.DataFrame): A DataFrame with at a m...
6d4c4ee7793625e4590c01120318afe33cba0b0c
3,609,854
def filter_cycles(cycle_list, **filters): """Puts cycles through filters to meet specific requirements. cycle_list is a list of tuples where the first item is an intake and the second action is a placement or drop. filters are the specifications that certain data points inside the cycles must fit t...
1abdcf76365cbaced4ac1dcfff96a91282c38370
3,609,855
def ansi_escape(text): """ Replace characters with a special meaning. """ return text.replace('\x1b', '?').replace('\b', '?')
86ff3e7cfce8fcc17e826896e32c28e0d30ee83c
3,609,856
def ajax_get_commandes(request): """ This view comes before the feature of sending mass mails to customers. It goes up the number of customers selected by status. """ if request.method == 'POST': try: event = request.POST.get('event').split(',') if request.POST.get('event').split(',...
9953c6bff7dd1b5476ee0a17e57f208d1a234bbd
3,609,857
def global_counter() -> int: """ A really dumb global counter. This is useful for giving output files a unique number, so if we run the same command multiple times we can keep their output separate. """ global _global_counter _global_counter += 1 return _global_counter
8771b81f459ab116998e6927c8e2d0d71676ac0f
3,609,858
def _GetAndroidVersionFromMetadata(metadata): """Return the Android version from metadata; None if is does not exist. In Android PFQ, Android version is set to metadata in master (MasterSlaveLKGMSyncStage). """ version_dict = metadata.GetDict().get('version', {}) return version_dict.get('android')
e1d1ed9d0bbf2f65d646c11007739f6b5a9b78ec
3,609,859
from functools import reduce def get_in(d, t, default=None): """ look up if you can get a tuple of values from a nested dictionary, each item in the tuple a deeper layer example: get_in({1: {2: 3}}, (1, 2)) -> 3 example: get_in({1: {2: 3}}, (2, 3)) -> {} """ result = reduce(lambda d, t: d...
f92e6c94e3485f4b02a8487f832064de7a42eba5
3,609,860
def divisible_by_five(n: int) -> bool: """Return True if an integer is divisible by 5, and false otherwise.""" if n % 5 > 0: return False return True
e4cd2adf7067000f10aa655bb9fd819e525527d2
3,609,861
def get_imaging_root_data_dir() -> str: """ get_imaging_root_data_dir() -> str Retrieve the root data directory - e.g. containing all subject/sessions data :return: a string for full path to the root data directory """ return _linking_module.get_imaging_root_data_dir()
9a697c7665de45ba235d3584898799c77e91591d
3,609,863
from typing import Union from typing import List def _input_is_valid( dataset: np.ndarray, predictive_model: object, as_probabilistic: bool, categorical_indices: Union[None, List[Index]], class_names: Union[None, List[str]], classes_number: Union[None, int], feature_names: Union[None, ...
38f473129ce0ead9831024351f2b084c68f60bd6
3,609,864
def cvPtr1D(*args): """cvPtr1D(CvArr arr, int idx0, int type=None) -> uchar""" return _cv.cvPtr1D(*args)
db40872eed3bda3a859ccc11838a3ea0a65d4a2d
3,609,865