content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime import os def extract_file_name(path, keyword): """ :param path: 备份表所在路径, 例如:root_path + "备份表\\" :param keyword: 关键词,即需要处理汇总的工作表中的关键词, 例如:test :return: 工作表的路径 """ # 初始化一个日期 -- 昨天 up_day = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y%m%d...
68fd8be3ece615ef9acdf46cfeec183e223ceb73
3,602,700
def plot_fl_bars(sta, pval=None, ax=None, imshow_params={"cmap":'gray',"vmin":-1, "vmax":1, "aspect":"auto", "interpolation":"nearest"}): """ Plot the response to a 1D spatial stimulus like Flickering_bars. params: - sta: The STA to the 1D st...
e46647686d5f718f40e5a9060e3df3bfddfe2986
3,602,701
from datetime import datetime def sendpredictivemodel_timeline(year, month, day): """ Predictive model from https://pechlilab.shinyapps.io/output/ by day --- tags: - Data responses: 200: description: '.csv' content: text/plain: ...
a756c21ce61bfd584df5e7db4dcf1ddc0fa1bf00
3,602,702
def release_lock(conn, lockname, identifier): """ Signal/release a lock. Args: conn: redi connection lockname: name of the lock to be released identifier: lock will only be released if identifier matches the identifier that was provided when the lock was acquired. R...
f7ea73c3806621ff3ca7f82f2cf899a28c700ebf
3,602,703
def find_adv_chunk(doc): """ Returns a dictionary representing a adverb chunk with a subject, a verb and an adverb """ for noun_chunk in doc.noun_chunks: # print("noun_chunk is {}".format(noun_chunk)) if noun_chunk.root.dep_ != 'nsubj': continue subj = noun_chunk.root if subj.head.dep_ == 'ROOT': ver...
64775754733a6b5a3ce342b1f0475b188cb00319
3,602,704
import textwrap def get_comment_from_location(location): """Return comment text from location. Args: location: descriptor_pb2.SourceCodeInfo.Location instance to get comment from. Returns: Comment as string. """ return textwrap.dedent(location.leading_comments or ...
d86213ddee50128c8363d2a31a740c5677244612
3,602,705
def make_env(env_id, rank, seed=0): """ Utility function for multiprocessed env. :param env_id: (str) the environment ID :param num_env: (int) the number of environments you wish to have in subprocesses :param seed: (int) the inital seed for RNG :param rank: (int) index of the subprocess ""...
c1a2c89ea4880e9b02f78df97358881628c57913
3,602,706
def yugioh_card_name_regex(cards_json): """Compile a regex matching a yugioh card id.""" return regex_or([card["name"] for card in cards_json])
219efa77e6fce78e5456534c84214ea4488ada12
3,602,707
def get_good_tags(soup): """ Good Tags are the Tags with a positive rating (Benis > 0) :param soup: :return: A List of all positiv tags """ soup = Bs(soup, "html.parser") # Need an explizit cast due to ducktyping problems with the find() in Python and BS # Alle Guten Tags filtern good_...
2973ef2f2537bd5271c673d91f07d12ad4173084
3,602,708
def edges2graph(edges, N=10000): """Creates MultiGraph from list of edges.""" H = nx.MultiGraph() H.add_nodes_from(np.arange(N)) H.add_edges_from(edges) return H
a934b43bf988927edfb44ae629724b2a08e6ca1d
3,602,709
import argparse def init_parser(): """Defines command-line interface""" parser = argparse.ArgumentParser( prog=__file__, description=desc, formatter_class=RawTextHelpFormatter) parser.add_argument('config', type=str, help='Backend configuration file with dat...
5ee3ef409764840fc3ad09da168ca69db921c602
3,602,710
import ctypes def pckopn(name: str, ifname: str, ncomch: int) -> int: """ Create a new PCK file, returning the handle of the opened file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckopn_c.html :param name: The name of the PCK file to be opened. :param ifname: The internal filenam...
392fbf87ee0b53cd190fa6d136fa28e20b6eb09c
3,602,711
from typing import Callable from typing import Optional def build_model_delta_optimizer_process( model_fn: _ModelConstructor, model_to_client_delta_fn: Callable[[Callable[[], model_lib.Model]], ClientDeltaFn], server_optimizer_fn: _OptimizerConstructor, *, we...
a2d6e95618ef5d9a6971a435a0905c2a133aad29
3,602,712
import platform def is_linux(): """Determines if the system is Linux.""" return platform.uname()[0] == 'Linux'
6c50b3ba3495b9f850e69b0ebf98834375a5cb85
3,602,713
def check_scale_xsmode(xsmode): """checking if the scale of xsmode assumes ESLOG(log) or ESLIN(linear) Args: xsmode: xsmode Return: ESLOG/ESLIN/UNKNOWN """ if xsmode=="lpf" or xsmode=="LPF" or xsmode=="modit" or xsmode=="MODIT" or xsmode=="redit" or xsmode=="REDIT": pri...
db6097abc196677063cb6851ce6036fb6e9b61f9
3,602,714
def distort_elastic_cv2(image, alpha=80, sigma=20, random_state=None): """Elastic deformation of images as per [Simard2003]. """ if random_state is None: random_state = np.random.RandomState(None) shape_size = image.shape[:2] # Downscaling the random grid and then upsizing post filter ...
bc1e8276480c023d6afc1a5b8e49706c408c0df6
3,602,715
def square_list(original_list): """ It returns the a list which each element squared Args: original_list: the list which needs to be added Returns: a list with the value: [elem1*elem1,elem2*elem2] """ return [multiplication(x, x) for x in original_list]
986c0c41cf0f49fd108812e2badf175c6ab30d3a
3,602,716
import math import os def predict_k_g_list_of_entries(entries): """ Predict bulk (K) and shear (G) moduli from a list of entries in the same format as retrieved from the Materials Project API. """ lvpa_list = [] cepa_list = [] rowH1A_list = [] rowHn3A_list = [] xH4A_list = [] ...
1febf6c9f96432ad4fb9025ecd97a9eecb390385
3,602,717
import warnings def round(a, mode=None): """round_mode(a) with mode in [half_away_from_zero, half_to_even]. Default to half_to_even.""" if mode is None: mode = "half_to_even" if config.warn__round: warnings.warn( "aesara.tensor.round() changed its default from" ...
89a036036f53b84be05d0aa8808492ed69b1d0ba
3,602,718
import logging def send_request(guid, args): """Send a request to the PrimeNet server.""" try: if idx: args["ss"] = 19191919 args["sh"] = "ABCDABCDABCDABCDABCDABCDABCDABCD" else: secure_v5_url(guid, args) r = s.get(primenet_v5_burl, params=args, time...
594914117df83895b020a40cd9f03b0c6e76579d
3,602,719
def modify_metrics(modify_product, service): """ Modify/add/remove metrics/limits""" # pylint: disable=unused-argument new_metric = service.metrics.create(rawobj.Metric('custom')) service.app_plans.list()[0].limits(new_metric).create({ 'metric_id': new_metric['id'], 'period': 'minute', 'value': ...
65025958fa54e85035cc751ac08dd4b6bead4195
3,602,720
def get_terrapos_residual(): """Get Terrapos residual Dataset by reading Terrapos residual output file Returns: dset (Dataset): Dataset with following fields: ==================== ================== ================================================================= Field ...
2ef745f39dc2457bd872486e22ad062c53ebe5be
3,602,721
def get_name(test): """Gets the name of a test. PARAMETERS: test -- dict; test cases for a question. Expected to contain a key 'name', which either maps to a string or a iterable of strings (in which case the first string will be used) RETURNS: str; the name of the test ...
e9d5a5013b062077c499e0351786819c9bd6bd90
3,602,722
def remove_file(path: str) -> bool: """ Removes a file Parameters ---------- path : str Path to remove Returns ------- bool True if removed, false if failed or doesn't exist """ with SQLiteCursor() as cursor: cursor.execute("DELETE FROM tblFile WHERE Fil...
ff7d8e37a1c93f42bebadc9d33b929c6e160c57a
3,602,723
from io import StringIO import struct def make_wave_header(frame_rate): """ Generate WAV header that precedes actual audio data sent to the speech translation service. :param frame_rate: Sampling frequency (8000 for 8kHz or 16000 for 16kHz). :return: binary string """ if frame_rate not in [80...
8597981ab85cddd4f5edbd3613a620fb694e50e6
3,602,724
def login_process(request): """ Processor-based login continuation. Presents a SAML 2.0 Assertion for POSTing back to the Service Provider. """ logger.debug("Request: %s" % request) proc = registry.find_processor(request) return _generate_response(request, proc)
2fa4df764087a316952ce0804237ec11ec6b2e58
3,602,725
def blur_detect(im, threshold=7): """ Negative log-likelihood on the inverse gradient norm, normalized by image size """ nll = -np.log(blur_measure(im)) return nll > threshold, nll
b8ff41d85101340cae7ad14423f216e4c6e6f677
3,602,726
import random def generar_contrasena(): """generar_contraseña es una funcion que contiene listas Las cuales se unifican en otra lista llamada caracteres en la cual en el ciclo for se genera una contraseña aleatoria de 10 caracteres donde el modulo random elije los caracteres y los inserta en una nuev...
2e3cf3057e9db3a4a761217693c0f557afddcbe0
3,602,727
def check_if_points_escape_box(u, box_boundaries): """ Determine if points u in 2D plane have escaped from box_boundaries limits. Parameters ---------- u : ndarray, shape(n, 2), Points in plane. box_boundaries : list of 2 tuples of floats, Values are interpreted as [[x_...
41b04b72821bc39f387c7557be1b11f14e65c71d
3,602,728
def assign_parents(filtered_tm_gp, unfiltered_tm_gp, chrom_sizes, denovo_gp, min_distance=0.9, stranded=True): """ Main function for assigning parental genes. Parental gene assignment methodology: A) Each denovo transcript is evaluated for overlapping any transMap transcripts. Overlap is defined as havi...
a1c27fc59e880d73cf180457d3e2b2a2fa9466b4
3,602,729
from typing import Any import random def assign_new_ids(items: dict[str, Any]) -> list[str]: """ Assigns new IDs to any item ID that starts with "NEW:" or is an empty string. Will modify the dict in place. Will return a list of new item IDs assigned. """ new_items = [] for item_id in items...
4fb3466566f0fd9981e1c99cb429da629c843dab
3,602,730
def deserialize_model(data, klass): """ Deserializes list or dict to model. :param data: dict, list. :type data: dict | list :param klass: class literal. :return: model object. """ instance = klass() if not instance.swagger_types: return data for attr, attr_type in ite...
42d27abb2a4adbb3eea48a2831f893ccf0d1051d
3,602,731
def isatty(stream): """Check if a stream is attached to a console. Args: stream (:obj:`io.IOBase`): Stream to check. Returns: :obj:`bool` """ return stream.isatty() if hasattr(stream, "isatty") else False
4ec38e35413f0f8af76da5e2681f5502acf3d61e
3,602,732
def preprocess_bert(sents, max_seq_len, tokenizer): """Loads a data file into a list of `InputBatch`s.""" features = [] for sent in sents: # Remove double whitespaces sent = " ".join(str(sent).split()) tokens = tokenizer.tokenize(sent) if len(tokens) > max_seq_len - 2: ...
992f02f2ae60a13b5f6bdc1e4082972f9c392334
3,602,733
def BestPairForLocalCorr(sample, percentile=0.05): """Find the pair of attributes with low correlation in the first percentiles and high correlation in the last percentiles or vice-versa. Returns the pair with the highest difference. Args: sample (DataFrame): A DataFrame. percentile (fl...
32e36fd6637a6fa50f0311933e0e02e2ebb7d2c8
3,602,734
from datetime import datetime async def register_ticket(ticket: Ticket, member: User) -> bool: """Registers the user to the ticket by appending a row with the relevant information to the work sheet """ work_sheet = await get_worksheet(SHEET_ID, WORKSHEET) row = ["", "", "", "", ""] row[REG_BAR...
96814f3e1f7b04e221c52d538f8852095f80249a
3,602,735
def plain_decoder_factory(): """Fixture returning PlainDecoder instance for the purpose of testing.""" return decoders.PlainDecoder()
eea660853d4b13f142e3eb7e3c5e6cc7c35a1338
3,602,736
def load_config(prefix="PF_"): """Load configuration from environmental file and environmental variables.""" envvar_settings = get_envvar(prefix=prefix) verbose = envvar_settings.get("verbose", False) dotenv_path = envvar_settings.get("config_dotenv_path", None) settings = load_dotenv_config(doten...
674b0004c2094cf99b16d0f955d135c3bbf45ef1
3,602,737
import pathlib def load_catalog(catalog_path=None, catalog_file='catalog.json', include_filename=False, keys_only=False): """Get the set of available datasets from the catalog (nodes in the transformer graph). Parameters ---------- include_filename: boolean if True, returns a tuple: (list, fi...
ef2dd6f4c523b75d9d38f502cd10c70a5a34e8dd
3,602,738
def orient_2D(p1, p2, p3): """ Determine the orientation 2D points p1, p2, p3 Args: p1,p2,p3: 2D points. Returns: positive if (p1, p2, p3) is in counterclockwise order. negative if (p1, p2, p3) is in clockwise order. 0.0 if they are collinear. """ return PyMesh.orie...
201b0f9db493148b5390b75aa2e5a68464c655da
3,602,739
def _fileserver_mesh_import(url, filename): """Internal function that adds primitive support for DAE files to the _mesh_import function of compas.robots.""" file_extension = _get_file_format(url) if file_extension == 'dae': # Magic! return _dae_mesh_importer(filename) else: ...
568629088716ce0611645f985ea983e77cec0c43
3,602,740
def remove_whitespace(string: str) -> str: """ This function replace whitespaces for void string -> '' Input: string with (or without) whitespace Output: string without whitespace """ try: if len(string) == 0 or (len(string) == 1 and string != ' '): return string...
6c5db5739913a9c31d70797a220e65ba511e7567
3,602,741
def get_consecutive_path_counts_visits(path_counts: pd.DataFrame, j1: object, j2: object) -> pd.DataFrame: """ Obtains path counts between two given consecutive columns from the given table of path counts. Args: path_...
d90a209c8c09fa360dee89d7a401d4ba4baa7313
3,602,742
def getOption(conf, section, name, option): """Convenience function to retrieve a parsed and converted value from a :class:`ConfigParser`. :param conf: ConfigParser instance or similar :param section: Section name :param name: :class:`Option` name :param option: :class:`Option` instance to use ...
fd67d331c22dda27e6ff0bcd16b0c08979aeb4be
3,602,743
def _weibull_dist(dims, r=5.7, k=0.34): """Generate burst times following a Weibull distribution. Args: r (float): Rate parameter k (float): Shape parameter """ lam = 1/(r*gamma(1 + 1/k)) if not any([isinstance(p, np.ndarray) for p in (r, k)]): return lam*np.random.weibull(k...
c56677d323e47c7b938d1420a57bddd0487095bd
3,602,744
def parameter_indices(*params): """ Parameter indices """ param_inds = dict([("P_kna", 0), ("g_K1", 1), ("g_Kr", 2), ("g_Ks", 3),\ ("g_Na", 4), ("g_bna", 5), ("g_CaL", 6), ("g_bca", 7), ("g_to", 8),\ ("K_mNa", 9), ("K_mk", 10), ("P_NaK", 11), ("K_NaCa", 12), ("K_sat",\ 13), ("Km_...
6012452a48fc770b6da28a6ac09817a3c299282b
3,602,745
def remove_plane(xarr, x_range=None, y_range=None): """ Remove plane background from 2D data. xarr is a multidimensional array of ndim >= 2. x_range and y_range are slices for x-axis and y-axis where the slope of the plane is calculated. Example: flattened = remove_plane(xarr, (xarr.P3 < -0...
99ad68c7166874451f9e6b021a66502ca8aab826
3,602,746
import os import itertools import logging def expand_build_plan(package: str) -> sbol3.Document: """Expand the build plans (libraries & composites sheet) in a package's collated SBOL3 Document Also attempt to compute all missing sequences (including those of the build plans) :param package: path of packa...
afc94e263bf07ff00d8653d30b4c45f2148297f5
3,602,747
def egcd(a, b): """ Calculate the extended Euclidean algorithm. ax + by = gcd(a,b) Args: a (int): An integer. b (int): Another integer. Returns: int: Greatest common denominator. int: x coefficient of Bezout's identity. int: y coefficient of Bezout's identity. ...
87b35ff4e28529d1de2a6fb0063b69cee5dfec74
3,602,748
def gtag_script_tag(): """ Render Google "Global Site Tag" HTML for, e.g., Google Analytics if the GTAG_ID setting is present, non-None and non-empty. If the GTAG_ID setting is not present, None or empty, renders the empty string. """ if not hasattr(settings, 'GTAG_ID'): return '' ...
63a34db421f3c7fde8e8f9043a858fc9ad19095a
3,602,749
import os import requests import json def get_endpoint_groups_id(token, region): """ Get the corresponding id of the region to check. :param token: The admin token. :param region: The region to get the id. :return: the id of the region. """ print('Getting id of the requested region...') ...
6fa10f92567e80a2ef023a78c265def7e2473d04
3,602,750
import uuid from pathlib import Path from typing import Optional async def delete_user_from_group_handler( token_restricted: bool = Depends(is_token_restricted), group_id: uuid.UUID = Path(...), username: Optional[str] = Form(None), email: Optional[str] = Form(None), current_user: models.User = De...
6103a3198806668f111c5ee00ee30614d25801c1
3,602,751
import os def maybe_add_extension(filename): """add .tex extension if needed""" if os.path.exists(filename): return filename elif os.path.exists(filename + '.tex'): return filename + '.tex'
e72a0a2905b2be5a09c9c3e1c7d8fd17b9fb05d9
3,602,752
def debug_storage(n): """ Prints keys and values stored in node n :param n: :return: """ print("--------------------------------") print(f"My node ID is: {n.node_id}") print("Storage content is:") print(n.storage) print("--------------------------------") resp_header = {"sta...
0a48024f12829401d1657f9db693fc08cfeb3ba4
3,602,753
def get_node_name(material, node_id): """ Get the name of a node based on its id Args: material (unicode): Material to get node name from node_id (int): Node id to get name of """ return cmds.shaderfx(sfxnode=material, getPropertyValue=(node_id, "name"))
5f44b1e8c6679a2e0e26c5378d6ef3e3ccb4d662
3,602,754
def get_recent_games(home_team_id, away_team_id): """ Get a list game ids for the 20 most recent games played for each team specified. ---Params--- home_team_id: int away_team_id: int ---Returns--- a tuple of 2 lists. ---> ([home team game ids], [away team game ids]) """ # Ensure...
d19aae83547ae55dab176f3bf90b8f31bd9cf43e
3,602,755
def merc_lon(x): """Convert x in meter to longitude """ return (x / 6378137.000) / np.pi * 180
e82acc50e33829fb371c44d1892d882f1c1b8e2d
3,602,756
from unittest.mock import patch async def test_flux_after_sunrise_before_sunset(hass, legacy_patchable_time): """Test the flux switch after sunrise and before sunset.""" platform = getattr(hass.components, "test.light") platform.init() assert await async_setup_component( hass, light.DOMAIN, {l...
a8f2b5bcb3fb4f74677fd32c940705044955bf82
3,602,757
def Mirror2D(src, dst): """\ Flip an image horizontally. :param src: source image :param dst: destination image :return: None """ return _ecvl.Mirror2D(src, dst)
6c40d26f85ac011b8133333b1f125b1ee9d8c9c5
3,602,758
def rand_median(cube, ncomb, subset, nchoose=None): """ median combine `ncomb`` frames randomly from amongst `nchoose` in the interval `subset` Parameters ---------- cube ncomb subset nchoose Returns ------- """ if isinstance(subset, int): subset = (0, subs...
580dbe6b710d7e1ba25becbc919a2c9f195f488c
3,602,759
def get_temp_filename(filename): """Returns the name of a valid temporary file.""" global config_dict tmpdir=config_dict['tmpdir'][0] return tmpdir+"/"+filename
4e39163ad11a5702bb506cbc5b1213a8f90d595c
3,602,760
def old(sym): """ Return the "old" version of symbol "sym", that is, the one representing "sym" in the pre_state. """ return sym.prefix('old_')
4cc24bd0448195ee1c373106679177ce428e5937
3,602,761
def sample_faces(vertices, faces, n_samples=10**4): """ Samples point cloud on the surface of the model defined as vectices and faces. This function uses vectorized operations so fast at the cost of some memory. Parameters: vertices - n x 3 matrix faces - n x 3 matrix n_sampl...
4bb6ce61c26bc54338e7c9c986a8d2335226f699
3,602,762
from typing import List import logging def uppercase_columns(df: DataFrame, col_list: List) -> DataFrame: """ Rewrite the selected columns with upper cases :param df: dataframe :param col_list: string array of columns to be upper-cased :return: dataframe """ for col in col_list: df...
0d93c2b709e78d96c21866d39c3d960456a70f88
3,602,763
def policy_v2_1(probability=0.7, magnitude=5): """Randomly select one transformation from {color} transformations, and then randomly select two transformations from {shape} transformations.""" policy = { # color augment 0: [[('Mixup', probability, magnitude)], [('Gaussian_noise', probabi...
8938e3a020663fe4cd72cd0a01f87fd60ad4ae91
3,602,764
def possible_edges(g, color_labels=[1, 2, 3, 4]): """ """ g_adj, g_color = util.nx_to_adj(g) out = [] for i in range(g_adj.shape[0]): for j in range(i+1, g_adj.shape[1]): if g_adj[i, j] == 0: for c in color_labels: out.append((i, j, c)) ...
5330818144a563dfb9dd05e2460602f36627d735
3,602,765
import os def validate_file(parser, arg): """Check that the files provided exist.""" if not os.path.exists(arg): parser.error("The file %s doesn't exist" % arg) else: return arg
9bc53d22d0a4a2447be31bee5a9f7ab60f8bc7a7
3,602,766
async def database_morelikethis(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), morelikethis: str=Query(None, title=opasConfig.TITLE_MORELIKETHIS, description=opasConfig.DESCR...
e1f78665e54e1fb17f21f71a99768ede29cb0ba8
3,602,767
import click import os from typing import Optional def create_nrcanlandcover_command(cli: click.Group) -> click.Command: """Creates the nrcanlandcover command line utility.""" @cli.group( "nrcanlandcover", short_help=( "Commands for working with Natural Resources Canada Land Cover ...
96d7389e2e85a55865d49cf7b5c6eff25d739178
3,602,768
def owned(exp, object_class, target_class, query): """Get objects for which the user is owner. Note: only the first id from the list of ids is used. Args: ids: the ids of owners. Returns: sqlalchemy.sql.elements.BinaryExpression if an object of `object_class` is owned by one of the given users. ...
dea080461e64c57fd21a0f684b8f3ab5ad62873b
3,602,769
from typing import Union from typing import Tuple def max(x: Union[ivy.Array, ivy.NativeArray], axis: Union[int, Tuple[int]] = None, keepdims: bool = False) \ -> ivy.Array: """ Calculates the maximum value of the input array ``x``. .. note:: When the number of elements over ...
22010b8bdd016b7aee7bcc6a7743af59bbad5671
3,602,770
def generate_AIF(scan_time_seconds, injection_start_time_seconds, time_interval_seconds, image_numpy=[], AIF_label_numpy=[], AIF_value_data=[], AIF_mode='label_average', dimension=4, AIF_label_value=1): """ This function attempts to create AIFs both from 2D and 3D ROIs, or reroutes to population AIFs. """ ...
aee3e491b3e8916112fa6583fc9f0b6446a47608
3,602,771
def get_files(paths, recursive=True, recurion_limit=None): """Given a list of paths, return a list of paths """ # For now we support only individual files dirs = list(filter(op.isdir, paths)) if dirs: raise NotImplementedError( "ATM supporting only listing of individual files, no...
5a969b332768f8e42640a3a5e4a5d8bb9b7cbbf3
3,602,772
import os def validate_config_http(file, check): """Determines if integration with http wrapper class uses the http template in its spec.yaml file. file -- filepath of file to validate check -- name of the check that file belongs to """ if not os.path.exists(file): return has_in...
a12888b1dfa4aa42c8468c18fd5148a5c25c8d2b
3,602,773
from typing import Optional def current_user() -> Optional[User]: """ Information about the currently logged in user, if any. Returns a :class:`User` object after validating saved credentials, renewing and updating them if necessary. Returns ``None`` if there are no saved credentials or if they'...
a9c11d03ac78078de98fe16719c8d7e89e3178f3
3,602,774
from typing import Counter def return_anagrams(letters: str) -> list: """ This returns all length anagrams from the input string. :param: a string of alphabets :return: a list of anagrams :example: $ python3 anagram_solver.py dive >> ['de', 'ed', 'id', 'di', 'ie', 'vei', 'div', 'vie', 'd...
7b63c00233d3708f4264d5bee35d317700705288
3,602,775
def canada(container, images): """ Creates the Canada tab container within a parent container""" multipane = ttk.Notebook(container) f2 = ttk.Frame(multipane) f5 = ttk.Frame(multipane) multipane.add(f2, text='Southeast Canada') multipane.add(f5, text='Canadian Prairie') multipane.grid(row...
b62f7533b941def30f795949aab6b62be6990456
3,602,776
import sparknlp import sparknlp_jsl def get_authenticated_spark(SPARK_NLP_LICENSE, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, JSL_SECRET, gpu=False, ): """ Authenticates enviroment if not already done so and returns Spark Context with Healthcare Jar loaded 0. If no Spark-NLP-Healthcare, install it via PyPi...
4cae6d4144975739910c7b175d778c5129d23540
3,602,777
def get_memory_version(bv, insn): """ Get the version of the ssa memory for the `MediumLevelILInstruction`. For the `LowLevelILInstruction` it finds out if the insn is memory operation """ if is_mlil(bv, insn): if insn.ssa_memory_version > 0: return insn.ssa_memory_version elif "mem#0" in str...
01ab0994fa3ff300f31f12867595671ca68b62cb
3,602,778
def make_image_set_from_image_entries(modeladmin, request, queryset): """Make an `ImageSet` of the selected `ImageEntry`s. This is an action on `ImageEntry`. """ return _make_image_set_from_images(queryset.all())
1af2fb2a3b7c75ac7eb57241e7f7a9ddcd1de9c6
3,602,779
def chi2(data, data_r, model, dof=1): """ Finds the chi squared (or reduced chi squared) Notes ----- The data, data_r and model arrays must have the same size. Parameters ---------- data : array Array containing the data data_r : array Array containing the errors (o...
fd47e12d0d32332ec810f00f12df9b94b53735db
3,602,780
import os def reported_news(file_paths): """Check if Misc/NEWS has been changed.""" return os.path.join('Misc', 'NEWS') in file_paths
95416284bbb0913d8edf4075f4577b56b9dee5ea
3,602,781
def _make_row(*column_messages, **kwargs): """Makes a formatted string. Args: *column_messages (str): Messages. **kwargs: Returns: """ color = kwargs.get("color", None) col_size = kwargs.get("column_size", 40) message = "" for m in column_messages: if m is not ...
47e7a369974ad3ed9ecf93047ad9100aa101ab25
3,602,782
def join(bot, input): """Joins a channel, admins only""" if not input.admin: return False bot.write_packet(ID.HON_CS_JOIN_CHANNEL,input.group(2)) bot.config.set_add('channels',input.group(2).lower()) bot.reply("Joined channel: {0}".format(input.group(2)))
63433ac90e9d6c35f6bfee097321921d1dfc30a7
3,602,783
def linear_gd(df_train, df_test, Y): """ linear gradient descent """ binary = utils.check_binary(df_train[Y]) model = gd.gradient(df_train, df_train[Y], .00001, max_iterations=50) print model predict = gd.predict(df_train, model, binary) print predict error_train = mystats.get_error(predict,...
5b9cd3d9194606b92eec41db3ea4227fee2b3f7d
3,602,784
import sys def cont_from_future(future): """Create continuation from `Future` object """ def cont_from_future(out_done, out_error): def done_callback(future): try: out_done(future.result()) except Exception: out_error(sys.exc_info()) ...
9b12c4c20a6ce4f9027ca49f8d9369fd374fe32b
3,602,785
def get_extended_due_date(node): """ Gets the actual due date for the logged in student for this node, returning the extendeded due date if one has been granted and it is later than the global due date, otherwise returning the global due date for the unit. """ if isinstance(node, dict): ...
2a90373e10bdb301bc13368d3d1464f2f2aeafa0
3,602,786
def is_void_trader_item_notified(item_id, user_id): """ # & (Voidtrader.inventory.any(Inventory.num == item)) """ Voidtrader = Query() void_trader_items = db.table('void_trader') void_trader_items_list = void_trader_items.search((Voidtrader.id == item_id) & (Voidtrader.users.any([user_id]))) ...
a0eb7fbdcaab32e6b32d96e67f7c2a6eb7cf84eb
3,602,787
from typing import Optional def get_default_url(prefix: str, identifier: str) -> Optional[str]: """Get the default URL for the given CURIE.""" entry = get_resource(prefix) if entry is None: return None return entry.get_default_url(identifier)
aaca83779fc21d26a426ceebce9cbcfb0c8c7f9d
3,602,788
from typing import Sequence def create_home_pos_task(env_spec: EnvSpec, obs_labels: Sequence[str], state_des: np.ndarray) -> MaskedTask: """ Create a task for moving the robot to safe position. .. note:: This task was designed with an RcsPySim environment in mind, but is not restricted to these e...
93c3af36f5469d491fd88a1551bb660480595c6f
3,602,789
from typing import OrderedDict def scalable(): """Scalable network. No parameters are tied to network size.""" fullconfig = configs.get_config('emergeplasticity') fullconfig['train_steps'] = 4001 config = fullconfig['plasticnet'] config['hebb']['weight'] = False config['hebb']['hebb_strength...
1d5cfad09f6c4f32152e38496f4fad5726d881b0
3,602,790
def get_type_for_example(items): """ If all else fails, just use strings for examples. """ if not items: type4example = DEFAULT_EXAMPLE_TYPE else: usable_items = [item for item in items if item != conf.UNKNOWN_ITEM] item_type_names, _item_type_nice_names = get_item_type_names...
05e058754cdbdad53cbe5cc80d8983c65ef3bae7
3,602,791
def milliseconds_to_time_clock_exp(milliseconds): """ Converts time components to a string suitable to be used on time expression fot ttml """ if milliseconds is None: return None expression = '%(hours)02d:%(minutes)02d:%(seconds)02d.%(milliseconds)03d' return expression % utils.mill...
0cb623aab9074b9650b9736422770b2c46a90b0e
3,602,792
from typing import Type from typing import List from typing import Union def _create_gpflow_combination_kernel( c: Type, children_types: List[Type] ) -> Union[gpflow.kernels.Sum, gpflow.kernels.Product]: """ Create GPflow combination kernel, either gpflow.kernels.Sum or gpflow.kernels.Product. :param ...
302db58e8de2b3131473552a7b7a0f71619c8847
3,602,793
def clean_delete_data(data): """ Clean up the data so it's easier to process """ # Shouldn't be any extra rows, but just in case, drop all with no contents data.dropna(inplace=True, how='all') # replace NaN data = data.replace(np.nan, '', regex=True) # trim all columns data = data.applymap...
fb6ea71ba2d9e936e103aeab08683674c4246518
3,602,794
def _remove_stopwords(line, nlp): """ Helper function for removing stopwords from the given text line. """ line_nlp = nlp(line) line_tokens = [tok.text for tok in line_nlp] filtered_line = list() # Filter for tok in line_tokens: lexeme = nlp.vocab[tok] if not lexeme.is_stop: ...
58932dc254874ea7a9e93e7e8d7fbf9f306f740b
3,602,795
def get_concatenated_data(data_set_fnames, shuffle=True, seed=None): """Helper to take a set of data.npz filenames (from label-maker) and concatenate them""" x_trains, x_tests = [], [] y_trains, y_tests = [], [] # Load each dataset and append for data_set_fname in data_set_fnames: pilot_se...
5bacaf5ed8c3cdf70da099a2c53f6da780da255f
3,602,796
def dict_fetch_all_by_month(cursor): """ We need the data in this format data = [ Month: "jan", "type1": value , "type2": value, Month: "feb", "type1": value , "type2": value, ...... ] do the below code helps to build the dictionary on that method """ collectors = [] ...
e1056dd16310915d6acb3ae5570df85920681da3
3,602,797
import re def pypi_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): """Role for linking to PyPI packages.""" env = inliner.document.settings.env text = utils.unescape(text) has_explicit, title, target = split_explicit_title(text) m = re.match(r'(.*)\s+\((.*?)\)', target) if m...
fa75191fcd4e661c08e3269aeabbb091ec991e33
3,602,798
import sami.db.export as export import os def queryMaster(h5file, queryIn, version='', idfile='sami_query.lis', verbose=False, returnID=False, tabulate=True, overwrite=True): # ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ """ Read a SAMI master table and perform a...
7370065a1eade35a25d35ae833ed3bae22d5a548
3,602,799