content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def enwik8_local_cluster8k(): """Routing attention on sequence length 8k.""" hparams = enwik8_local8k() hparams.sparsity_cluster_size = 16 hparams.local_num_heads = 4 hparams.sparsity_cluster_num_heads = 4 hparams.sparsity_cluster_attention_window = 512 hparams.num_decoder_layers = 12 hparams.attention...
98e038124ce598cead8ea5dd37a2da0f3dd16c4b
56,500
def selfeval_docs(docdata_list, classifier_path=None, **kwargs): """ Given a list of documents, run classification on each, and evaluate according to the original labels/spans given in the document itself. """ cw = ClassifierWrapper.load(classifier_path) results = get_classifications(docdata_li...
c3d3762249e94d2852928c9fc663567627a40e18
56,501
def load_user(fn): """Loads the user""" @wraps(fn) def _wrapper(*args, **kwargs): user_code = kwargs.get('user_code', None) user = None if user_code is not None: user = User.get(user_code) return fn(user=user, *args, **kwargs) return _wrapper
731cbaf63b660c9a06a1f5854d62d48bc820d4eb
56,502
def load_sdf_files(input_files, clean_mols): """Load SDF file into dataframe.""" dataframes = [] for input_file in input_files: # Tasks are stored in .sdf.csv file raw_df = next(load_csv_files([input_file + ".csv"], shard_size=None)) # Structures are stored in .sdf file print...
8c2a38a6f8f52247b93b8273ce30987b66599928
56,503
def get_complex_portal_species_ids(): """Gets a dictionary of Complex portal datasets Returns a dictionary of species as keys and dataset url as values. """ domain = "ftp.ebi.ac.uk" complex_data = "pub/databases/intact/complex/current/complextab/" print("====== Getting Complex Portal Species ID...
a624d5c386ca6ebcb61f80d68bfed2c64903e9eb
56,504
def domain_lookup(domain): """ Execute SlashNext's host/reputation API against the requested domain with the given parameters :param domain: Domain whose reputation needs to be fetched :return: Response of the SlashNext host/reputation API """ # Create the required data dictionary for Host/Reput...
35bc2fa5fd20182202e113c6a24376fe671c4eed
56,505
def getter_wrapper(row_orders, *args): """ Wrapper running I/O operations within the table_proxy's associated executor """ # Infer number of shape arguments nextent_args = len(args) - 4 # Extract other arguments table_proxy, column, col_shape, dtype = args[nextent_args:] # Handle da...
8238097e21d9f4597e16d12e0521062f6cc847a1
56,506
def new_ffs(): """ Create a new Filecoin Filesystem (FFS), including a default wallet and config """ form = NewFfsForm() new_ffs = create_ffs(default=form.default.data) return redirect(url_for("config", ffs_id=new_ffs.ffs_id))
4dfd0519ef15ca4e6e2b5145561a55d08ffff2c7
56,507
def redM(m1, m2): """The reduced mass shows up in Kepler formulae, m1*m2/(m1+m2) """ return( m1*m2/(m1+m2) )
84e14ff9d0f22e31641dfb186e0dc298af036a0f
56,508
import re def _parse_mqtt_message(topic, payload): """ Parsitaan viestistä virheilmoitus """ match = re.match(MQTT_REGEX, topic) if match: sijainti = match.group(1) laite = match.group(2) return SensorData(sijainti, laite, payload) else: return None
7d382c1b53dbb9483db129eebbe38dc68198bdcd
56,509
import codecs import re def get_bookmarks_tree(bookmarks_filename): """Get bookmarks tree from TEXT-format file Bookmarks tree structure: >>> get_bookmarks_tree('sample_bookmarks.txt') [(u'Foreword', 0, []), (u'Chapter 1: Introduction', 1, [(u'1.1 Python', 1, [(u'1.1.1 Basic syntax', 1, []),...
a1cd349be3570900ae48ffc5e6ae217c8655cc42
56,510
def single_npjpe_not_mean(gt_cam0_pose, pred_cam0_pose, allow_mirror = True): """Normalized PJPE optionally resolving "mirrored" solutions. Arguments: gt_cam0_pose: GT 3D pose in the zero's camera frame pred_cam0_pose: predicted 3D pose in the zero's came...
e14e174c5c246d20c9455ef24b252ddfa9656412
56,511
def head(repo, subset, x): """Changeset is a named branch head. """ # i18n: "head" is a keyword getargs(x, 0, 0, _("head takes no arguments")) hs = set() cl = repo.changelog for ls in repo.branchmap().itervalues(): hs.update(cl.rev(h) for h in ls) return subset & baseset(hs)
047b1e9601751f5cfca215c095c53fb453880533
56,512
import jinja2 def render_template(authors, configuration): """ Renders a template in `adoc`, `html`, `md`, `rst`, or `txt` format. Parameters ---------- authors : list The authors to include in the rendered template. configuration : dict Configuration settings rel...
879693831529fb1786a04df3df1173601adebd63
56,513
def is_running(): """Make sure the controller is running Returns: object: will only reply if the controller is alive """ # This endpoint needed without authentication return HTTPResponse( j.data.serializers.json.dumps({"running": True}), status=200, headers={"Content-Type": "applica...
7f15538f37c05ae8ef9d0fe1ad02e8f1142b0afd
56,514
from datetime import datetime import asyncio async def set_system_time(new_time_dt: datetime, loop: asyncio.AbstractEventLoop = None ) -> datetime: """ Set the system time unless system time is already being synchronized using an RTC or NTPsync. Rais...
400158090b76839dcf709585cab4959250008cdc
56,515
import os def demo_model(preset, **kwargs): """ Utility function to create preset :class:`Model` objects for demonstration and testing purposes. The particular presets are :: * `constant-isotropic` : Constant velocity (1.5km/sec) isotropic model * `constant-tti` : Constant anisotropic model. Velo...
fd7e4345a4210e86736c1077f4da49d893632fe1
56,516
import re def ranks_unclassified(desc): """ Returns number of unclassified ranks in description :param desc: :return: """ regex = re.compile(".+(_[X]+)$") return sum( [1 if x else 0 for x in [regex.match(s) for s in desc.split(";")]])
3a016315019b03e0456e7315afd5b3fa303e265a
56,517
def expand_output(out): """Plotly callback outputs for `update_simulator` function""" return [ *out["alert"], *out["mrsim"], *out["children"], *out["mrsim_config"], *out["processor"], ]
b1d1135c8fb16d2245f882a29c622e1da42f501a
56,518
def _load_strategies(): """Load all strategy modules.""" modules = {} namespace = "glance.common.image_location_strategy.modules" ex = stevedore.extension.ExtensionManager(namespace) for module_name in ex.names(): try: mgr = stevedore.driver.DriverManager( namespa...
cf705509f3535c824c3c4a84f9d950a7532cd670
56,519
def drop_table_if_exists(): """ Removes all tables on app start so as to start working with no data """ drop_users = """ DROP TABLE IF EXISTS users """ drop_meetups = """ DROP TABLE IF EXISTS meetups """ drop_questions = """ DROP TABLE IF EXISTS questions """ drop_comments = """ DROP TABLE IF EXISTS...
d3e79992c88becd5f398162938bd22990e238803
56,520
def autocorr_periodic_arrivals(t, gamma, A_mean, A_rms, norm=True): """Calculates the closed expression of the autocorrelation function of a process of periodic Lorentzian pulses with duration time td = 1 Args: time: array[floats], time array gamma: float, intermittency parameters A...
dfcacba81c1e15abdadf66a29f01b97b11be53c1
56,521
def get_the_data(): """ Function to hold data getting stuff. """ dic_dates = {'2014-03-29': ('2014-03-29 00:00:00', '2014-03-30 00:00:00'), '2012-07-06': ('2012-07-06 00:00:00', '2012-07-07 00:00:00'), '2017-09-06': ('2017-09-06 00:00:00', '2017-09-07 00:00:00'), '...
4b0edf1df22538e31b55ac233dfdab1fce2c9615
56,522
from typing import Optional def get_available_regions(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAvailableRegionsResult: """ Retrieve a list of available cloud regions in Astra ## Example Usage ```python import pulumi import pulumi_astra as astra regions = astra.get_ava...
962d20c86dc62f36b676c7e359b7403c4514db88
56,523
def pause(name): """ Pauses a container name Container name or ID **RETURN DATA** A dictionary will be returned, containing the following keys: - ``status`` - A dictionary showing the prior state of the container as well as the new state - ``result`` - A boolean noting whe...
825073c51afc48e488faa884f0cf696d83fcecec
56,524
import json def fablabNowFlask(): """! @brief URL pro získání aktuálního stavu strojů ve Fsblabu. @return JSON s aktuálním stavem strojů ve Fsblabu """ # return request_error("Neni implementovano :-(") try: fablab = Fablab() machinesStat = fablab.getMachinesStatus() json...
abd33f697fd3615ac64d4f1dd0a1343f7d7e8526
56,525
def find_by_email(email, session): """ Fetches a single user by email :param session: :param email: :return: a single user if found else None """ users = session.query(User).filter(User.email == email).all() return users[0] if len(users) > 0 else None
88c24fb15ee394b7a353aa54eb1a6f9c274749f9
56,526
def admin_author(): """Updates author info""" obj = models.getAuthor(int(current_user.rowid)) # Hold on to this until we validate the fields from the form password = models.getAuthor(int(current_user.rowid)).password form = AuthorForm(obj=obj) # populate the form with our blog data if requ...
18115aa97809f7b1f1e55923f45bf1d8092ce35e
56,527
import os def create_tempdir(path): """Create temp folder""" temp_path = str(path + "/temp") if not os.path.exists(temp_path): os.makedirs(temp_path) return temp_path
ad3e8d483d841f73d02885eaea826ea71cf15b8d
56,528
def _diff(rankx, ranky): """ Return the valuation difference from int64 rankx to int64 ranky """ shift = int64(32) mask = int64((1 << 32) - 1) scale = float64(mask + 1) hi = ranky >> shift hi -= rankx >> shift lo = ranky & mask lo -= rankx & mask out = scale * hi out += lo re...
964f49ac3a89759ede85f109e81b9ab114c5db58
56,529
def get_body_part_colour(shot): """ Decide the colour of a plot element based on the shooter's body part. """ body_part = shot['shot']['body_part']['name'] if body_part == 'Right Foot': return 'orange' if body_part == 'Left Foot': return 'red' if body_part == 'Head': ...
89a6187840ee2f830f2c07579a555fc1944ea086
56,530
from datetime import datetime def login_resolver(obj, info, username, password): """ Login user :param obj: :param info: :param username: email user :param password: password user :return: token """ try: if username is not None and password is not None: reposit...
1f328942741ad9f91204598828ab6d401fc8796c
56,531
def plot_f1_per_phylum(test_phyla, figsize): """ Create barplot showing median F1 score per phylum in the test set Arguments: test_phyla (dict of lists) -- for each phylum in the test set (keys), list of F1 scores (float) for all genome vectors in that phylum figsize (tuple) -- figure size in (inches, inches) ...
5b0bcae91bd9421c111c9312cc30194d40f713bf
56,532
def _list2str(x): """! # List To Str TODO_DOC @param x: TODO_DOC @return TODO_DOC ## Profile * line count: 9 * characters: 79 * returns: out[:-2] * calls: _list2str, .format """ out = "" for y in x: out += '{}, '.format(y) return out[:-2]
bb9fc3086ef17047589f67f44401e26f9adac9a7
56,533
import scipy def load_npz(file): """Load a sparse matrix from a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be loaded. Returns ------- result : csc_matr...
8508a01c3c1fe7c7666b2857b19a06600415e967
56,534
def clear_submissions(uid=None, tid=None, pid=None): """ Clear submissions for a given team, user, or problems. Args: uid: the user's uid to clear from. tid: the team's tid to clear from. pid: the pid to clear from. """ db = api.common.get_conn() match = {} if pi...
92255c6b83e6bc5a0b7df2569f504b5f705e5c0f
56,535
import crypt def login(request, access_token): """ Validate a google access token and retrieve user's email. Returns ------- user : str User email. permissions : list List of permissions that the user has. """ try: idinfo = client.verify_id_token(access_token,...
bc9f8c6c18c96669e92bc3fca64b3a8e6a079af7
56,536
import os import base64 def transfer_file_to_str(file_path): """Transfer image to a string :param file_path: file path :return: msg_dict including file name and file str encoded by base64 package """ file_name = os.path.basename(file_path) with open(file_path, 'rb') as f: img_byte = b...
c68021e13b9be162f36a621e92bc6078d2f10de2
56,537
import random def generate_key(num_digit): """Generate key using user email and random str""" min_val = 10 ** (num_digit - 1) max_val = (10 ** num_digit) - 1 otp = random.randint(min_val, max_val) return otp
132716dd643af309a8e7e90a72fbed60e47bd255
56,538
import inspect import sys def get_all(): """ Returns a dictionary of all output classes where the key is the class name (string) and the value is the class object """ temp = inspect.getmembers(sys.modules[__name__], inspect.isclass) return temp
014b43a97cf14d46525c05b512de1707a93acdbe
56,539
import os def import_table(scenario_settings, con, engine, role, input_name, csv_import_function=None): """ Imports table from csv given the name of the csv Parameters ---------- **scenario_settings** : 'SQL schema' Schema in which to look for the scenario settings **con** : 'SQL ...
48230166ac3e4ae4332c6a40ed783dce6ce4894a
56,540
from datetime import datetime def to_date(value: str, format="%Y-%m-%d") -> date: """Convert value to a date""" return datetime.strptime(str(value), format=format).date()
68febd40f5a3d4d49a47d64755addd8956a0a690
56,541
def visualize_featuregroup_clusters(featuregroup_name, featurestore=None, featuregroup_version=1, figsize=(16,12), plot=True): """ Visualizes the feature clusters (if they have been computed) for a featuregroup in the featurestore Example usage: >>> featurestore.vis...
516b0e6c207996b97e360a3efdbfc45e47c61fb7
56,542
def memoized(old_f): """Decorator that memoizes calls to old_f into a single instance-specific _memoized_data hash""" def new_f(self, *args, **kw): """Function to wrap the decorated method""" if not self._memoized_data: self._memoized_data = {} #generate a hash using the prov...
2e7133e88d1dd684d3a7338debb06036cedd09e1
56,543
def intensityPSF_Blues(N=1000): """Return ColorBrewer 2.0 9-class Blues based matplotlib colormap optimized for showing intensity PSF This colormap is a sequential colormap, however it has more color distribution near zero. Parameters ---------- N : integer Length of the colormap ...
a56fac9dceba1a70c8ab420e9b46da5dc422c580
56,544
def split(allFpdsDict): """ Splits an allFpdsDict (eg for bestOutOfSampleCorrs with returnErrors=True) """ N = scipy.shape(allFpdsDict.values()[0][0])[-1] allFpdsDictList = [] for i in range(N): d = {} for key in allFpdsDict.keys(): itemList = [] for item ...
54543352ea4fd2383220979e1d00dd0725eb8a1a
56,545
import re def parse_rst_index(rstpth): """ Parse the top-level RST index file, at `rstpth`, for the example python scripts. Returns a list of subdirectories in order of appearance in the index file, and a dict mapping subdirectory name to a description. """ pthidx = {} pthlst = [] wit...
0e57abb09c85b0023926eed29c1eedc11ea6d018
56,546
def get_stats(summoner_id, season=None): """ https://developer.riotgames.com/api/methods#!/1018/3453 Args: summoner_id (int): the summoner to get ranked stats for season (str): the season to get ranked stats for ("SEASON2015", "SEASON2014", "SEASON3") (default None) Returns: Pl...
61abc3cb3ad9234bd7cbae4418b6efa7a867b707
56,547
from datetime import datetime import pathlib import copy def start_transfer_from_file_list(src_endpoint, dst_endpoint, dst_base_path, file_list, src_base_path=None): """ Start a new transfer task for a list of files. Parameters ---------- src_endpoint : `str` ...
8c5c92b066a6089d81fa7131f052e25e10081e00
56,548
def harmonic_bond(conf, params, box, lamb, bond_idxs): """ Compute the harmonic bond energy given a collection of molecules. This implements a harmonic bond potential: V(conf) = \sum_bond kbs[bond] * (distance[bond] - r0s[bond])^2 Parameters: ----------- conf: shape [num_atoms, 3] np.a...
c6450ba9af0ba66bb29e8ac3fdb99089940ebb64
56,549
from typing import Optional from typing import Dict from typing import Any from typing import List import requests def metadata(api_url : str, network_id : NetworkIdentifier, options : Optional[Dict[str, Any]] = None, public_keys : Optional[List[PublicKey]] = None, session : Optional[requests.Session] =...
6be91260e2752e77363b1306cbd302e301248b86
56,550
from pathlib import Path def initialize(protoPath: Path) -> Prototypes: """Load item, fluid, group, and recipe prototypes. Returns a Prototypes object with all relevant prototypes loaded from the definition files located at protoPath. Parameters ---------- protoPath: Path The path to Factorio's 'pro...
ad1b4bf4cc083801e42dd79381806f276dd14a36
56,551
import json def extract_json(fname: str) -> Export: """Extract JSON from supplied Day One journal export. Parameters ---------- fname: `str` path to file Returns ------- `Export` Nested dictionary object with Day One JSON properties """ with open(fname, "r") as f...
1aff9227237f1bea77d35d1c76e772b3d4d53323
56,552
def serialize_mc(analysis, type): """serialised function for the Monte Carlo Analysis""" return { 'id': None, 'type': type, 'attributes': { 'window': analysis.get('window', None), 'mc_number': analysis.get('mc_number', None), 'bin_number': analysis.get...
f5c7b890312997bd7c5f712e52d63ff066c358c7
56,553
def check_3(sigs): """ Repository managed by both SIG and Private. """ print("Repository managed by both SIG and Private.") supervisors = {} for sig in sigs: for repo in sig["repositories"]: # Gitee requries strict case senstive naming for direct access # repo =...
908737c960ce54bb8c724a792977e23b36775174
56,554
import http def server_handshake_headers(client_key, protocol=None, extensions=None): """ The server response is a valid HTTP 101 response. Returns an instance of http.Headers """ h = http.Headers( connection="upgrade", upgrade="websocket", sec_websocket_accept=create_serv...
878c880556c91424ce544a8632ed775077cbb5e2
56,555
def removeLines(s): """ Replace \\r and \\n with a space. """ return removeR(removeN(s))
3cc6e6886db11e8cbb36fc8d581eef6a9e1c68a0
56,556
def init_dashboard(server): """ Initialize the dashboard. --- Args: server: the main Flask app Returns: a hug ༼ つ ◕_◕ ༽つ """ # Initialize the Dash app dash_app = Dash( __name__, title="Dashmap", server=server, url_base_pathname='/helsinki/' )...
86191c9205ac8d58f81c19b3e69d195ce70aebb0
56,557
def _HasOption(_, option): """Validate the option exists in the config file. Args: option: string, the config option to check. Returns: bool, True if test is not in the option name. """ return 'test' not in option
5c8304b8e4abe91ec8e3e55f14201a1a3d7f5c57
56,558
def final_time(): """ Real Name: FINAL TIME Original Eqn: 1 Units: Month Limits: (None, None) Type: constant Subs: None The final time for the simulation. """ return 1
48e128bab98fb7d8f11bc8607e65cf4759e68481
56,559
def bronchus_data(): """Gets the data needed for the bronchus tests Returns: dict -- Data for broncus test """ return fetch_data("LCTSC", patient_ids=["LCTSC-Train-S1-001"])
d47bd84b33bd160e441c095fa8b5475e09a7b4e0
56,560
def hashtag_counts_in(collection, geometry, skip_users=None): """ Returns hashtag counts for all tweets in a geometry. Parameters ---------- collection : MongoDB collection The collection of tweets. geometry : GeoJSON-like geometry or list The GeoJSON-like object representing th...
d97239c1a323603a96a690594b41aa2f60a284ad
56,561
def hist_last_time(check_type, check_action): """ Get the last time the type + action occurred Primarily used to get the last time a song was added / updated in history. If this time is greater than time top directory was last changed then refresh not required. """ global HISTORY_ID...
b72c927de8310b15130052e8196d8454c4abfae8
56,562
from ipywidgets import HTML def fingerprint_table(fingerprint_df, as_widget=True, structure=None): """ Create HTML and CSS table layout for the calculated fingerprint. Parameters ---------- fingerprint_df : pd.DataFrame Fingerpint in dataframe form as_widget: bool Whether to b...
cb7788152cd4d0f62ae51535d43bdea472036cba
56,563
def change_partition_by_name(in_partition, in_partition_type: str, out_partition_type: str): """Switch between partition types. Only for 1-D partition tensors. Uses RaggedTensor partition scheme naming. Not all partition schemes are fully complete or can be converted into each other. Args: in_parti...
5b055a6a8cde3a096837fcf8934338fd458b4566
56,564
def donation_payment(request, account, project=None, campaign=None): """Collect donor contact information. Expects a GET param, payment_amount, in dollars.""" form = DonationAmountForm(data=request.GET, account=account) if not form.is_valid(): if project: url = reverse('donate projec...
f05991043c39daf675daa6956e448cd9c1c028b8
56,565
import pdb def putInBed(conscensus, value, window=10, mergetype='mean', columns=['foldchange']): """ given a conscensus bed-like dataframe and another one, will merge the second one into the first Args: ----- conscensus df[start,end,chrom] the conscensus (first one) value df[start, end, chrom]+columns the v...
a2816aa037f5ce86563c6d4240064c221e0e7040
56,566
def _segment(binary): """ Parses a chunk of text provided in a boolean numpy array. Returns: a tuple with a list of unique tags for each each individual 'letter' a numpy array with these tags inserted where the 'letters' are. The skimage.measure.label() function segments an arra...
214dbc094755c6b2d00040559570278329413db0
56,567
def get_parameters_nodes(input_nodes): """Find operations containing the parameters of the model. Args: input_nodes (:obj:`list` of :obj:`Node`): the input operations of the model. Returns: parameters (:obj:`list` of :obj:`Node`): the operations containing the par...
a4185512a577521f0ed3d7cc9b098800fda58974
56,568
import logging def cycles_engine(**kwargs): """engine to extract cycles""" logging.debug("cycles_engine::Not finished yet (sorry).") # raise NotImplementedError experiments = kwargs["experiments"] farms = [] barn = "raw_dir" # Its a murder in the red barn - murder in the red barn for e...
a1f0b0c1554bdcc8b06e7113d924f198e1c56fd3
56,569
def get_method(interface, method): """ Get a specific method Parameters: ---------- interface : interface of CST Studio method : string Specific method that you want Returns: ---------- instance : function Instance of the method """ return getattr(interface,...
bd0a8322e2a47f8c0b760894617c9ed2429fcb02
56,570
def read_file_header( filename ): """ A header is: 1. Any number of blank lines before the header 2. Any number of KEY=value pairs (anything else is ignored) 3. One or more blank lines stops the header Returns a tuple (format type, version integer, header dict, hdr lines), where the ...
54bec5d22db1d04ba081786b287abe678c71e487
56,571
def create_norm_pipelines(features): """ create_norm_pipelines() returns a dict of normalization pipeline instances of four subsets of the dataset taking as parameter features (pandas.DataFrame). """ # break into subset (timbral_rhythmic_predictors, predictors_with_pos_corr, wavel...
e219356deb351de453cfd3c46d6a9352205ad7d8
56,572
def tutorial(): """Render the tutorial page""" return render_template('meta/help.html')
5c89bf30e03ff520c4b2aa5f4e72722260929059
56,573
from datetime import datetime import os def calculate_tif_data_basin_mean( eta_tif_files: list, camels_shp_file: str ) -> np.ndarray: """ Calculate basin mean values for tif data Parameters ---------- eta_tif_files a list with tif files path camels_shp_file shapefile of al...
95e385311af5cae86cf714fb092bee7c4c13aff0
56,574
def is_valid(token_line, token_type=cluster_tokens_file): """ Check whether a token is valid :param token: token to be checked :param token_type: the type of token (bootstrap or signature) :returns: True for a valid token, False otherwise """ token = token_line.strip() # Ensure token is...
f22f8e92860648d2844c213129783eace4ba8e77
56,575
import os def feature_metadata_path(export_path: Text) -> Text: """Returns the path to the feature metadata for the given export dir.""" return os.path.join(export_path, 'assets.extra', 'feature_metadata')
2e33bbb00e80d18881a2150275e65665f314a08c
56,576
def create_24_hour_means(raw_data, value_column, date_column): """Takes raw sensor data and produces 24 hour mean for each data point. :param raw_data: The raw sensor data to aggregate :type raw_data: DataFrame :param value_column: Name of the column with values to aggregate :type value_column: str...
2247279a878d2973e8ef7c6bb0c5412fc49d494f
56,577
def decode_values(mfg_data: bytes, device_type_id: int) -> dict: """Decode values""" pack_params = SENSORPUSH_PACK_PARAMS.get(device_type_id, None) if pack_params is None: _LOGGER.error("SensorPush device type id %s unknown", device_type_id) return {} values = {} packed_values = 0 ...
0351e9db8468238b799f3d04e2dcbe2915f87877
56,578
import re def short_page_img_url(book_page): """Return a short url for the book page image. Args: book_page: BookPage instance Returns: string, url, eg http://101.zco.mx/My_Book/001.jpg """ book_page_url = short_page_url(book_page) if not book_page_url: return m ...
81b244bc881778c20db419125549a4cd93d1e878
56,579
def dot2svg(dot): """ Render Graphviz data to SVG """ svg = graphviz.Source(dot).pipe(format='svg').decode('utf8') # strip doctype and xml declaration svg = svg[svg.index('<svg'):] return svg
1ff440d8e55fa9d68208d9cc914465c0c8595c29
56,580
def load_mash(dist_file, simplify_names=True): """Loads fastANI output calculates overlap. Outputs a table with ['Genome1','Genome2','Distance','Pvalue','Fraction','Identity'] in header""" F = load_ani_table_( dist_file, ["Distance", "Pvalue", "Fraction"], simplify_names=simplify_names ) F[...
b17a3839c163a840cfbae3f196adc433b64d6732
56,581
def get_pip_command_packages(command): """Return packages included in a pip command.""" return command.split()[2:]
63757643862b590f27eed927b2037ad45eaf4792
56,582
def t_rel_len2048_h384_att512_fs1024_n8_dropout10(): """Hparams for LM with relative attention.""" hparams = transformer.transformer_base() update_transformer_hparams_for_music(hparams) update_truncate_length(hparams, 2048) update_small(hparams) hparams.self_attention_type = "dot_product_relativ...
490371f12e2b668f1252b1e644feb4c086dd2289
56,583
def get_file(request, file_hash) -> JsonResponse: """ Получает информацию о файле вместе с прямыми ссылками на эскиз и контент. :param request: Запрос. :param file_hash: SHA512 хэш файла. :raise Http404: Если файл не найден. """ file = get_object_or_404(File, hash=file_hash) serializer ...
bb3b35e3ef3ca0a56546365658c7fdd8d8a534df
56,584
import re def get_all_versions_from_tags(tags): """this is like a reverse match from a template""" # build a regex from our version template re_safe_placeholder = r"A_PLACEHOLDER_FOR_THE_VERSION_DETECTOR" re_version_detector = r"(\d+\.\d+\.\d+(-\w+.\d+)?(\+\w+.\d+)?)" tag_re = ( "^" ...
d365bfe7f01971bdc49c0cfad9cf386bd534506a
56,585
def median(x): """ Get column median Parameters ---------- x : Expr, Series Column to operate on Examples -------- >>> df.summarize(median_x = tp.median('x')) >>> df.summarize(median_x = tp.median(col('x'))) """ x = _col_expr(x) return x.median()
cbaf11f14e3069a259876171d8a312b4297b6bb2
56,586
def decode(expr, *argv): """ --------------------------------------------------------------------------- Compares expression to each search value one by one. Parameters ---------- expr: object Expression. argv: object Infinite Number of Expressions. The expression generated will look like: even: CA...
4bdd6f02dd94622ad6fc3e62258ee9d69dd3b374
56,587
import json def elvanto(end_point, **kwargs): """Shortcut to create Elvanto API instance.""" base_url = "https://api.elvanto.com/v1/" e_url = "{0}{1}.json".format(base_url, end_point) resp = retry_request(e_url, "post", json=kwargs, auth=(settings.ELVANTO_KEY, "_")) data = json.loads(resp.text) ...
27a0327457447dc8eb9682da842ec1d3bd7a3000
56,588
def fuzzy_match(keys, fuzzy_key): """Match a fuzzy key against sequence of canonical key names. :param keys: Sequence of canonical key names. :param str fuzzy_key: Fuzzy key to match against canonical keys. :returns: Canonical matching key name. :raises KeyError: If fuzzy key does not match. "...
0739a57a82979d6e184f1a5021173c2433f6bd08
56,589
def random_walker(data, labels, beta=130, mode='cg_mg', tol=1.e-3, copy=True): """ Segmentation with random walker algorithm by Leo Grady, given some data and an array of labels (the more labeled pixels, the less unknowns and the faster the resolution) Parameters ---------...
62aa341bfd7379bc28c1feeec623d7a5c240441a
56,590
def utctime(nist_lookup=0, time=time.time, DateTimeDeltaFromSeconds=DateTime.DateTimeDeltaFromSeconds, utctime=DateTime.utctime,_diffs=_diffs): """ Returns the current UTC time as DateTime instance. Works must like the standard DateTime.now(), but tries to use ...
bea96ff02db1d20ea3827ee02c1a2acdc7d4127a
56,591
def gini(k_proportions): """ Gini impurity function. This is used to determine the impurity of a given set of data, given the proportions of the classes in the dataset. This is equivalent to: H = ∑ pk(1-pk) for all k classes. k_proportions, in this case, is an array of pk's :param k_propo...
db0e74b29166603ed2bda3aa5fa9614ba9206b67
56,592
from pathlib import Path def fixture_project_dir() -> Path: """Return path to the Python project directory. :return: a path """ return Path(__file__).parent.parent
08ef4059aa5fa4b125928e9843b83f2befff8576
56,593
def return_element_from_list(i, l): """ Returns an element from the list @param: i is an integer corresponding to the index of the element in the list @param: l is a list of elements return: element of the list if 0 <= i <= len(l) - 1 None otherwise """ if(i < 0 or i >= ...
7d57263d67fe85c13f34428c23cdaf9ae7671855
56,594
def integer_identical_to_index(nums): """ :param nums: array :return: the number equals its index """ left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) >> 1 if nums[mid] < mid: left = mid + 1 elif nums[mid] > mid: right = mid...
8f289bdf268839659d68565a69e61eb36a717b40
56,595
def sprint_prefixes_db_full(prefix_db, loopback_only=False): """given serialized prefixes output an array of lines representing those prefixes. IPV6 prefixes come before IPV4 prefixes. :prefix_db openr_types.PrefixDatabase: prefix database :loopback_only : is only loopback address expected :re...
5a9b10647a30ea32a9e1664b57194cf802c4098f
56,596
def pidlist2indexlist(painting_df, painting_list): """From a list of painting ID, returns the indexes of the paintings Input: painting_df: dataframe of paintings painting_list: list of paintings ID (e.g ['000-02T4-0000', '000-03WC-0000...']) Output: index_list: list of th...
17435b9871878f5f7f0fd5a8b34bbaccc93d43f7
56,597
from typing import List def countOccupiedSeats(seats: List[str], rowBound, colBound) -> int: """ Counts number of occupied seats """ numSeats: int = 0 for i in range(0, rowBound): for j in range(0, colBound): if seats[i][j] == OCCUPIED: numSeats += 1 return numSeats
db990f1a5dda0e141c8282026e0e735823aa2abe
56,598
def maxcut_obj(x,w): """Compute -1 times the value of a cut. Args: x (numpy.ndarray): binary string as numpy array. w (numpy.ndarray): adjacency matrix. Returns: float: value of the cut. """ X = np.outer(x, (1 - x)) return -np.sum(w * X)
422a982252c4b6d718ff1a6f7421bdfce4a16277
56,599