content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def check_peak(data: List[DataPoint]) -> bool: """ This is a function to check the condition of a simple peak of signal y in index i :param data: :return: """ if len(data) < 3: return False midpoint = int(len(data) / 2) test_value = data[0] for i ...
59811943a68136978a4018f50895431ccb028834
36,651
def load_subtensor(g, labels, seeds, input_nodes, device): """ Copys features and labels of a set of nodes onto GPU. """ batch_inputs = g.ndata['feat'][input_nodes].to(device) batch_labels = labels[seeds].to(device) return batch_inputs, batch_labels
34da3bb7f0d17b4a37f4f0abc990ff24116a0e58
36,652
def node_index_at_link_ends(shape): """Array of nodes at each end of links.""" node_ids = np.arange(np.prod(shape)) node_ids.shape = shape return (node_at_link_tail(node_ids), node_at_link_head(node_ids))
62f5f6d6cecd2de6b45a2cce39a34239c9a35e9f
36,653
import sympy def get_symbol_list(number_of_symbols): """ Returns a list of sympy expression, each being an identity of a variable. To be used for input layer.""" return sympy.symbols(['x_{}'.format(i + 1) for i in range(number_of_symbols)], real=True)
2d81bfc1a162e52b42bf69d4cf68786717ba6f3c
36,654
def get_viewer_frame(frame, viewer_size): """Get viewer frame. Parameters ---------- frame : numpy.ndarray viewer_size : tuple Returns ------- viewer_frame : numpy.ndarray """ return cv2.resize(frame, (viewer_size[1], viewer_size[0]), interpolation=cv2.IN...
2883fb1130b66bbbff2b35c3831bb91e7308a6ad
36,655
def preprocess_waveform(y, sample_rate, target_sample_rate, preemphasis_coeff=0.95, stft_args={}): """Resample, preemphasize, and compute the magnitude spectrogram. Inputs: y: 1D numpy array containing signal to featurize (np.ndarra...
a3f731e163fec00865391e811d5ec696d7920b07
36,656
from typing import List def patients_from_tissue(df: pd.DataFrame, tissue: str) -> List[str]: """Given a tissue, return all patients within that tissue""" return df[df.tissue == tissue].id.tolist()
61d33879f2ddeb1f84d76ce168df723ed8237e88
36,657
def asst70_gene_descriptors(moa_abl1): """Create assertion70 gene_descriptors test fixture.""" return [moa_abl1]
a68a349aaebf107cdd645e213fb56f268046a619
36,658
def medoid(collection, bands=None, discard_zeros=False): """ Medoid Composite :param collection: the collection to composite :type collection: ee.ImageCollection :param bands: the bands to use for computation. The composite will include all bands :type bands: list :param discard_zeros: ...
c0876ddb3cf9940f665eee7e833082d80e304ae6
36,661
def match_bool(value: bool) -> models.Match: """_summary_ Args: value (bool): _description_ Returns: models.Match: _description_ """ # Check if value: # Return return models.Match( accuracy=models.Accuracy.RIGHT, direction=models.Directio...
3631b03ad5b3f1f17ca0de9661bf711b2ed464ca
36,663
def p_ibd_1(f): """Compute Joint-PMF for sibling pair genotypes given IBD1. Args: f : :class:`float` allele frequency Returns: P : :class:`~numpy:numpy.array` matrix of probabilities """ fmatrix = np.array([[0.0,1.0,0.0],[1.0,1.0,2.0],[0.0,2.0,3.0]]) mi...
870a307b287556d5d5db032bf47213a5aa2e818a
36,664
from typing import Any from typing import Callable import click def argument(*args: Any, **kwargs: Any) -> Callable[[Any], Any]: """Create command-line argument. SeeAlso: :func:`click.argument` """ return click.argument(*args, **kwargs)
cebe48c946f48ab90368779052302e650a29679a
36,665
def nvctl(*args, **kwargs): """ Run the nvctl command with the specified args returning the output as a parsed json object by default. The kwargs support 'json=false' and 'no_login=true'. Exception is raised for errors. """ cmd_list = list(args) json_out = True if 'json' in kwargs an...
b2b904d40477ff78c882b572afddfd7899e0435b
36,666
import ctypes def load_libgmt(env=None): """ Find and load ``libgmt`` as a :py:class:`ctypes.CDLL`. By default, will look for the shared library in the directory specified by the environment variable ``GMT_LIBRARY_PATH``. If it's not set, will let ctypes try to find the library. Parameters ...
656c8d9297a26ff27ab7b45af6531b80e1d68e9a
36,667
def validate(board: list) -> bool: """ Main functrion of the module. Recieves board and checks if it is a valid one or not with the help of other functions. >>> board = board = [\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ "...
499128dbd1817be880b7a17e0fcb7fdefa7002e0
36,668
def build_table_separator(outer_left='╠', inner='╬', outer_right='╣'): """ Builds formatted unicode header for the stopwatch table. :return: formatted unicode header """ return f"{outer_left}{'═' * 14}{inner}{'═' * 18}{inner}{'═' * 20}{outer_right}"
22d9aef799e2245a072e9032b9d8dcc2f138386e
36,669
import hashlib def _hash_feature(feature): """Calculate SHA256 hash of feature geometry as WKT""" geom = shape(feature["geometry"]) return hashlib.sha256(geom.wkt.encode("utf-8")).hexdigest()
59013e7fb643b5261e1ca9557e4c875a1fda72f3
36,670
def review_pull_request_event(event): """Determine whether this is a valid pull request review event.""" try: source = event["source"] detail_type = event["detail-type"] event_type = event["detail"]["event"] return ( source == "aws.codecommit" and detail_...
2182ec385f2521e016ebee8995611df73944d569
36,671
import ast from typing import Optional from typing import Any def safe_eval(expr: ast.expr, culprit: ast.AST) -> Optional[Any]: """Return the given expression as evaluated at compile-time. NOTE Use this instead of Python's `eval` to avoid potential arbitrary code execution. """ _erro...
cd93df7a1c4c59806327165a2bf10307a6720e45
36,673
import tqdm import torch def bert_cos_score_idf(model, refs, hyps, tokenizer, idf_dict, verbose=False, batch_size=64, device='cuda:0'): """ Compute BERTScore. Args: - :param: `model` : a BERT model in `pytorch_pretrained_bert` - :param: `refs` (list of str): referenc...
bf5be0252066caf2ab143d06fe9f1b8d03fc26f9
36,674
from datetime import datetime def search_tickets(request, **kwargs): """Return the tickets search page.""" template = 'tickets/search_tickets.html' check_groups(request.user, [GROUP_SUPERVISOR, GROUP_SUPPORT]) # If the REFERER is a page other than the tickets # search page, don't do any extra wo...
6aa91d6b69c7ce51185ba87606070fc4473d1de5
36,675
def lidar_classify_phase(instrument, model, beta_p_phase_thresh=None, convert_zeros_to_nan=False, remove_sub_detect=True): """ Phase classification based on fixed thresholds of a lidar's LDR and tot beta_p variables. Parameters ---------- instrument: Instrument ...
34f37919d10102eb41ed485b905bc83e0f304c4d
36,677
def compute_cog(d): """ Args: d: dict Returns: percentage """ accuracy=(d['22']+d['25']+d['23']+d['24'])/27 return round(accuracy*100, 3)
a83cb11f4d5fdec3bb63533352eb4fd0b62782ea
36,678
from pathlib import Path def get_builddir() -> PathLike: """Obtain Sphinx base build directory for a given docset. Returns: Base build path. """ parser = get_parser() args = parser.parse_args() return (Path(args.outputdir) / ".." / "..").resolve()
7bd5d5e498a679c64fbf10b7461a19c6f5b4c0b2
36,679
from typing import Union from typing import List from typing import TextIO from pathlib import Path from typing import BinaryIO from typing import Any from typing import ContextManager from typing import Iterator from io import StringIO import fsspec def _prepare_file_arg( file: Union[str, List[str], TextIO, Path...
d266a50d2832018031b2d1dd7660bde35cd11345
36,680
import json def read_file(file): """Reads in a data file and generates insert statements for the sql dump.""" rs = "\n" with open(file, "r", encoding='utf-8') as f: data = json.load(f) # Insert conf rs += '''INSERT INTO Conference (conf_name, time, location) VALUES ("{}", "{}", "{}...
bf5db1e737278182bbddae836bbfc2f3fe8dc013
36,681
from typing import Optional def retrieve_price(user: Optional[UserProtocol], price_id: str) -> PriceSubscription: """ Retrieve a single price with subscription info """ price_future = executor.submit(stripe.Price.retrieve, price_id) subscription_info = is_subscribed_and_cancelled_time(user, price_...
e149c02d2bc6e55ae673970a8b4a02eef02120c5
36,682
def transform(claims): """label encode value of claims Parameters ---------- claims: panda.DataFrame a data frame [source_id, object_id, value] where source_id, and object_id is already label encoded. Returns ------- claims_value_enc: pandas.DataFrame a data frame [...
9e24656726834df10de6e8136558abb6bb01da9a
36,683
def set_callback(ar, cb): """ Runs when confimation is requred, checks if answer is present in request data, if so, runs corisponding function Otherwise returns with data that will pop up a dialog. """ cb_id = cb.uid answer = ar.xcallback_answers.get("xcallback__" + cb_id, None) if answer is...
90acf651ad324b6e4958ed90f4bf8d76f37a6073
36,684
import re def parse_args(): """ Parses the command line arguments. """ # Override epilog formatting OptionParser.format_epilog = lambda self, formatter: self.epilog parser = OptionParser(usage="usage: %prog -i INPUT_STRING | --input INPUT_STRING " "| --load FILE", epilog=EXAMPLES) parser.add_...
14f67abde64178cf6dae8ae5548ceac56db7aab9
36,686
def clicked_watchtime_reward(responses): """Calculates the total clicked watchtime from a list of responses. Args: responses: A list of IEvResponse objects Returns: reward: A float representing the total watch time from the responses """ reward = 0.0 for response in responses: if response.clicke...
a931fd235a0e70add98c3b8cb70adbfbf74b4fb9
36,687
def watersheds_gdb_reader(): """reader watersheds gdb into geopandas""" #watersheds_gdb = 'WRIWatersheds.gdb' # watersheds_gdb = 'AQID_Watwershed_Jan2020/AQID_Watwershed_Jan2020.shp' # watersheds = geopandas.read_file(watersheds_gdb) # watersheds.set_index("aqid",inplace=True) #pfaf_id, ar...
13b64789e1f7e246d520cf757948d089c3948ef2
36,689
def cast_to_list(emoticons_list): """ Fix list of emoticons with a single name to a list for easier future iterations, and cast iterables to list. """ emoticons_tuple = [] for emoticons, image in emoticons_list: if isinstance(emoticons, basestring): emoticons = [emoticons...
5d955e493924a7ce1b206a30e4e8b9ea25068ba0
36,690
def merge_sorted(arr1: t.List[float], arr2: t.List[float]) -> t.List[float]: """ Merge two sorted arrays into a third sorted array. Using two pointers, this algorithm is in O(n1 + n2), where n1 and n2 are respectively the lengths of ``arr1`` and ``arr2``. Args: arr1: The first array to mer...
4bb2a42d378ffc17f7b2d0231dab5a8e22545a6d
36,691
def history(locs: ArrayLike, name: int) -> np.void: """Creates a named and sorted location history. Args: locs: An iterable of location numpy structured arrays. name: A 64-bit int that labels the history. Returns: A structured array with attributes "name" and "locs". """ lo...
e2903ab4d29ddb233af541e6625dd7267ba415ed
36,692
def conv1x1(in_planes, out_planes, stride=1, bias=False): """1x1 convolution""" return nn.Conv2d( in_planes, out_planes, kernel_size=1, stride=stride, bias=bias )
c491d90c74e798fa798a946e38fb0a04563bfb4b
36,693
def argv_obj(input): """argv_obj(PyObject * input) -> char **""" return _strumpack.argv_obj(input)
ba0d3cd61f93d2414d598e7a6cff95eeef9cbcd9
36,694
import types def atom(token: str) -> types.Atom: """Convert token to proper types When parsing, we get all tokens represented as strings. Here we convert all integers and floats to their proper types, and keep all other types as `types.Symbol` objects. """ try: return int(token) e...
5122747a0d3b25c10a47d405949184aa987ae754
36,696
def _descend_namespace(caller_globals, name): """ Given a globals dictionary, and a name of the form "a.b.c.d", recursively walk the globals expanding caller_globals['a']['b']['c']['d'] returning the result. Raises an exception (IndexError) on failure. """ names = name.split('.') cur = call...
111a5277907b60d3f27f037868ac8c84e390e159
36,697
def str_to_int(string): """Converts a DNA sequence to a list of integers. Parameters ---------- string : str The string of nucleobases. Returns ------- list of int A list with the integer value for each nucleobase in the string. """ return [ut.nucleotide[nb] for nb...
c8f4431a79d77f5e92b592a44a824ff3c060bda4
36,698
def _get_extension_point_url_from_name(domain, category, pluggable_name): """Get the extension point URL based on a pluggable method name""" return '{}/{}/{}'.format(domain, category, pluggable_name).replace('//', '/')
a4a34409dac26e42d123c4fda66ddc0947134e00
36,699
def get_feature(feature_name, example): """Gets Tensorflow feature by name. Args: feature_name: The name of the feature. example: A Tensorflow example. Returns: The Tensorflow feature with the given feature name in the example. Raises: ValueError: If the given feature name is ...
80e35d7e1fe15e7a455123cbd139139dd977f216
36,700
def fcn_VR_FMS(r_div_R): """ Transversal velocity factor of FMS in Eq. (31) in [2] """ return (1/4.)*(3.*r_div_R - r_div_R**3.0 + 2.0)
9a1a4dd8acfe0af910677c30e1a98b5e8f765e20
36,701
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" # C.f. http://wiki.python.org/moin/PythonDecoratorLibrary def newFunc(*args, **kwargs): warnings.warn("Cal...
44641d06b0e68652723c4de4ad8dfb7cc6f8f5ee
36,702
def temperature(wair,pres,entr=None,temp=None,airf=None,dhum=None, chkvals=False,chktol=_CHKTOL,airf0=None,temp0=None,dhum0=None, chkbnd=False,mathargs=None): """Calculate icy air temperature. Calculate the temperature of icy air. :arg float wair: Total dry fraction in kg/kg. :arg floa...
9d90016c71c888fc824485bc00ffbca82e35ac45
36,704
def check_gnn_get_sampled_neighbors(method): """A wrapper that wraps a parameter checker around the GNN `get_sampled_neighbors` function.""" @wraps(method) def new_method(self, *args, **kwargs): [node_list, neighbor_nums, neighbor_types, _], _ = parse_user_args(method, *args, **kwargs) che...
1af65d6db1c79516617179b7e1ccc935c0a29e8c
36,705
def bound(x, lower, upper): """ Bound x between lower and upper, where x is a numpy array. """ # Lower bound. y = np.where(x < lower, lower, x) # Upper bound. z = np.where(y > upper, upper, y) return z
1ec35b81cb5571544278a1f2f07681b1b0bad2a3
36,706
def esc(code: int) -> str: """ Converts the integer code to an ANSI escape sequence :param code: code :return: escape sequence """ return f"\033[{code}m"
6bdc0679ba9b480220bc088bd09d6356dd539f1f
36,707
import math def compare( line1, line2, method='frechet_dist', precision=6, clip=True, clip_max=0.5 ): """ Compute similarity between two (Multi)LineStrings. Returns value 0.0 (completely dissimilar) to 1.0 (completely similar) Based on Frechet dista...
e45eef23eb844bfdec11b720a84a82ebdab53b47
36,708
def Phi_gradient(x: np.ndarray, mu: np.ndarray, Sigma: np.ndarray) -> np.ndarray: """ Compute gradient of CDF of multivariate Gaussian distribution. :param x: Location where the gradient is evaluated. :param mu: Mean of the multivariate Gaussian. :param Sigma: Covariance of the multivariate Gaussia...
b7b96efcef75a137cf2fd439d0971a1aeca6cadc
36,709
def list_files(directory, extension): """ List files with specified suffixes in the directory (exclude subdirectories) """ file_list = listdir(directory) included_list = [] for f in file_list: for ext in extension: if f.endswith('.' + ext): included_list.append(f)...
967e0a9472d26470af6f326f8ac3f598ed17953f
36,710
from typing import Literal def _estimate_df_regression( y: Float64Array, trend: Literal["n", "c", "ct", "ctt"], lags: int ) -> RegressionResults: """Helper function that estimates the core (A)DF regression Parameters ---------- y : ndarray The data for the lag selection trend : {"n","...
c4b9589bf9dc597756b96828aaf35d0d65407558
36,712
def list_streams(region_name='us-west-2', Limit=10): """ Executes Kinesis.Client.describe_stream_summary function """ client = boto3.client('kinesis', region_name=region_name) result = client.list_streams(Limit=Limit) streams = [] if 'StreamNames' in result: for st in result['Stream...
85bfa452fea0d5350d79b3dd7a9b39fe1cec13e0
36,713
import copy def as_json_object(element: YAMLRoot, contexts: CONTEXTS_PARAM_TYPE = None, inject_type = True) -> JsonObj: """ Return the representation of element as a JsonObj object :param element: element to return :param contexts: context(s) to include in the output :param inject_type: if True (d...
d60af09b906274128a22577a25da64e146d0068a
36,714
import torch def floor_divide(input_, other): """Wrapper of `torch.floor_divide`. Parameters ---------- input_ : DTensor The first operand. other : DTensor The second operand. """ return torch.floor_divide(input_._data, other._data)
eaf842f24e6a3b07e65cb69bde3a50ed7ef9a26d
36,715
def firstTokenPredicate(field): """Finds first word/token in the field. Examples: .. code:: python > print(firstTokenPredicate('John Woodward')) > ('John',) """ first_token = start_word(field) if first_token: return first_token.groups() else: return ()
362f831d6dc0c8510eca21e0032533cc259867cd
36,716
def penalty_of_soft_constraint_1(schedule: Schedule, schedule_param: ScheduleParam, unit_penalty, _inspect=False): """ 1. Instructors should only take certain courses they are are assigned to. """ violation_count = 0 for c in schedule.classes: if c.section.course.idx not in c.instructor.assi...
21102097d14690b95124b5b17224fced2f53a46a
36,717
from statsmodels.tsa.arima_model import ARIMA def run_arima_model(df, ts, p, d, q): """ Run ARIMA model """ # fit ARIMA model on time series model = ARIMA(df[ts], order=(p, d, q)) results_ = model.fit(disp=-1) # get lengths correct to calculate RSS len_results = len(results_.fittedvalues) ts...
f26698de1630774ac29ba5eafb5f66a76fb5db37
36,718
def is_type_bitfld(*args): """is_type_bitfld(type_t t) -> bool""" return _idaapi.is_type_bitfld(*args)
a34fa715f619da8d65a389064461e5aaff6c243f
36,719
def get_arxiv_categories(arxiv_id=None, title=None, doi=None): """ Return a list of arxiv categories based on the specified arXiv identifier and/or title and/or doi. The identifier and title (if given) are both forwarded to the arXiv api. First element of the returned list is the primary category. ...
a4b5aeccb9a082cbde7d2e55bf6bd8c1c8d4e7af
36,721
def set_token(key, token_name, token_value=None): """ Set a token. Overwrites the existing token for a given key, if one exists. If a token value is not specified, a random value is generated. Args: key: the unique identifier object token_name: the name of the token to set ...
db71bb4bece60853d98c09b2fe9009798ab6990b
36,722
def get_custom_annotations_for_alias(data_type): """ Given a Stone data type, returns all custom annotations applied to it. """ # annotations can only be applied to Aliases, but they can be wrapped in # Nullable. also, Aliases pointing to other Aliases don't automatically # inherit their custom ...
17cd8e2b81b376c587f492d27e88c47f31d5d12b
36,723
import base64 import requests def getToken(): """ Method that generates and retrieves a temporary API access token for Reveal(x) 360 authentication. Returns: str: A temporary API access token """ auth = base64.b64encode( bytes(TARGET_ID + ":" + TARGET_SECRET, "utf-8") )...
a58c03e08caba2ed18264c54bd821a23bcc9206d
36,724
def valid_units(span, data): """Validate and update data units.""" units = [t.lower_ for t in span if t.ent_type_ in UNIT_ENTS] if units: units = REPLACE.get(units[0], units[0]) # Remove bad units if units not in ('m', 'ft'): return False data['elev_units'] = u...
5957412769c7941da600a6e09ed153bfe593791d
36,725
def win_active_by_handle(handle): """ :param handle: :return: """ ret = AUTO_IT.AU3_WinActiveByHandle(HWND(handle)) return ret
bb6d89dab59954ef0b59b941127ced1f6d908c49
36,726
from typing import cast def set_title_str(title: str) -> str: """Get the required string, including ANSI escape codes, for setting window title for the terminal. :param title: new title for the window :return: string to write to sys.stderr in order to set the window title to the desired test """ ...
0b9825198570bf50716b457142f6cad27278e3f7
36,727
def two_sum_ver2(nums: list, target: int) -> list: """Use dictionay""" # Save numbers and indexes num_idx = {} for i, num in enumerate(nums): num_idx[num] = i # Search an index using a key target - num for i, num in enumerate(nums): if target - num in num_idx and i != num_idx[ta...
9b15fb92fa42adc3802db40526af408899edf835
36,728
def _GetAndValidateCmekKeyName(args): """Parses the CMEK resource arg, makes sure the key format was correct.""" kms_ref = args.CONCEPTS.kms_key.Parse() if kms_ref: _ShowCmekPrompt() return kms_ref.RelativeName() else: # Check for partially specified disk-encryption-key. for keyword in [ ...
8238d1e0e802170d96ec3e96af7e11f14a1e2314
36,729
import torch def test_get_and_verify_covars_input_with_dependencies_fails(tmp_observe_class, covariates, kwarg_covariates, monkeypatch): """ test _get_and_verify_covars_input which depends on _read_covars_manual_input and _validators.Validators.__validate_num_covars. monkeypatch the user input (when neede...
ec8200de7a14beb662e3eaa3e95b9af4285b5771
36,730
async def clone_projectversion(request): """ Clone a project version. --- description: Clone a project version. tags: - ProjectVersions parameters: - name: project_id in: path required: true type: string - name: projectversion_id i...
38f4ede88f661a4ab829929ba5bdb4e5a8bbcede
36,731
def callback_tag(dataset, data_element, pattern): """ Called from the dataset 'walk' recursive function, will anonymize all the tag 'tag'.""" tag, action = pattern if tag in dataset: tag_repr = repr(data_element.tag)[1:-1].replace(" ", "") value = data_element.value anon_value = ...
25fe638cfd13a3515b0d11ab086e5b03feb8747a
36,732
import json async def bookshelf_read(request): """ Book has now been read. """ payload = await request.content.read() # create an event from this request payload = json.loads(payload.decode('utf-8')) event = make_event(name="book-read", payload=payload) await send_event(b"bookshelf",...
0f8c51be3531931241fc0ed797c978e32e234a3b
36,733
def _repr_unicode(dumper, data): """Fix yaml str representation.""" data = data.encode('ascii', 'ignore').decode() # XXX:Is this the best way? if '\n' in data: return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return du...
4baf9aa67941179909719844c78651b62dce0abe
36,734
def get_paper_data(paper_name): """Gets paper code and paper type based on paper name""" split = paper_name.split("_") code = split[-1] paper_type = split[-2] if len(split) == 5: code = split[-2] + split[-3] paper_type = split[-1] elif len(split) == 3: code = "00" ...
7f5804241a3f97b2c0ea534a4f030841e7c86e3b
36,735
def create_macrobe(): """Create VFDBlToolResult with randomized field data.""" packed_data = create_values() return MacrobeToolResult(macrobes=packed_data).save()
b5ce9689ab2cffa0a0397dd5d9d1612bc0e871ec
36,736
def handler_add_channel(): """Add a channel. .. :quickref: Media; Add a channel. :json string name: The name of the new channel :json string link: The link to fetch the channel from :status 200: The channel was correctly inserted :status 400: The provided JSON is invalid or there is a data...
f6a675a07ed0d0ddc332d11b634f1d4f533c1d5f
36,739
from re import X def is_struct_field_address(xpr: X.XXpr, astree: AbstractSyntaxTree) -> bool: """Return true if the expression is the address of a known struct.""" if xpr.is_int_constant: return astree.is_struct_field_address(xpr.intvalue) return False
95536d96f56ab04ff012f2576d89fb4b4db5e2f6
36,742
def get_scanner(hass, config): """Validate the configuration and return an ASUS-WRT scanner.""" scanner = AsusWrtDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
9748db0ba1f6555b478f000634661e07777de0c1
36,743
def remove_vulgarity_id(sentence): """remove_vulgarity_id Removes uncivilised words in Bahasa Indonesia Prevent words such as "anjir", "babi" etc to be included in natual language generation tasks :param sentence: An input string :type sentence: str :return: A string where common swear words i...
edeb76e102ab4b19d0b27e7b6352b2be40afe1d7
36,744
from typing import List def str_class(s: str) -> str: """Expand a string of character ranges. Example: str_class("a-cx0-9") = "abcx0123456789" """ i = 0 n = len(s) ret: List[str] = [] while i < n: if i + 2 < n and s[i+1] == '-': start = ord(s[i]) end = ord(...
21bbd7b46a964f20377b4f98b203b6bf0ad210c2
36,745
def activate_boolean_map(bool_map): """ Performs activation on a single boolean map. """ # use the boolean map as a mask for flood filling activation = np.array(bool_map, dtype=np.uint8) mask_shape = (bool_map.shape[0] + 2, bool_map.shape[1] + 2) ffill_mask = np.zeros(mask_shape, dtype=...
3fb11188386ae79bb501aeee5c3da8e1c5142c69
36,746
def migrate(migrator, database, fake=False, **kwargs): """Write your migrations here.""" @migrator.create_model class CommentReportLog(pw.Model): rid = pw.ForeignKeyField( db_column="id", model=migrator.orm["sub_post_comment_report"], field="id" ) action = pw.IntegerFiel...
58f7938b17fc2eb797d685d335c991213e91faea
36,747
def adjust_verbs(sentence, conjugator, lemmatizer): """adjusts verbs in sentences to their respective plural form""" tagged = pos_tag(word_tokenize(sentence)) adjusted = [] for t in tagged: if t[1] == 'VBZ': lem = lemmatizer.lemmatize(t[0], pos="v") if lem == 'go': ...
472543ec45d3501ec232b21c47ce6285800f26e4
36,748
def hexstr2int(hexstr): """ Convert string of hex values to list of integers. example: "1a 1b 1c 1d" => [26, 27, 28, 29] """ return [int(x, 16) for x in pairwise(hexstr.replace(" ", ""))]
4833ec873e4969314a4ebb8029f1e95f1e3619d2
36,749
def getlength(): """retrieves the length of every document and stores in a dictionary""" le={} o = open("lengths.txt", 'r') for line in o: li=line.strip().split(' ') le[li[0]]=li[1] o.close() return le
07495647e9614c35af830bcba520cc2f66488824
36,750
def vib_energy_diagram( quant_nums, vibrations, maxV=2, maxE=3000.0, useFull=True, image=None, imagesize=0.1 ): """ Function that will generate a vibrational energy diagram. This function wraps the make_elevel_plot function! Input arguments are quant_nums: A 2D numpy array of ...
4a6d9f7516388245975b183d803cb8a54866251a
36,751
import math import itertools def generate_guide_stars(catalog): """Generate a catalog with the angular distance of all stars combinations""" guide_stars = {} FOV_h = 14.455 * math.pi/180 FOV_v = 10.94 * math.pi/180 FOV_diag = math.sqrt(FOV_h**2 + FOV_v**2)/2 for a, b in itertools.combinat...
92484ed03e5ba7ae59d20dbf9680700bc894f3da
36,752
def create_loaders(full, batch_size, val_split, shuffle=True, min_val=1): """Split full dataset into training and validation :param torch.utils.data.Dataset full: Entire dataset :param int batch_size: Number of samples per batch :param float val_split: Percent of full dataset to use for validation ...
023f324d334052e41e9467b020a0a605b3bb77d3
36,753
def sd_features_length(self): """features_length for SubDataset Args: self (SubDataset): """ return self._dataset.features.features_length()
da46ce72e10f392e3207cbfa997c111f045da65b
36,754
from typing import List from typing import Tuple def filter_edges(nodes:List[int], edges: List[Tuple[int,int,int]]) -> List[Tuple[int,int,int]]: """Filter the edges of a subgraph. Parameters ---------- nodes: list containing the nodes edges: list containing the edges of the original graph Re...
50cf2986a5afa4748cf9b8505fc992f7b7f97db1
36,755
def get_shared_symmetry_operations(struc, pointops, tol=0.1): """ Get all the point group operations shared by a pair of atomic sites in the form [[point operations of site index 1],[],...,[]] Args: struc: Pymatgen structure pointops: list of point group operations from get_site_symmetr...
577e5d5a74d0b83202cf22e8524429c0a1ac4635
36,756
def flatten(node: ir.Node) -> ir.Node: """Flattens an node if possible. Flattens an node if it is: + a singleton BinaryOp; or + a compound BinaryOp with reduction operators; or + a compound Operand; or + a Unary with an identity operator. An Operand is a compound Operand if and only if its attr ...
022b8f97a43e7bd8190445fed71cf2e5114b5450
36,757
import math def is_primes(n) : """return 'True' if 'n' is a prime number. False otherwise""" b =[] if n==1: return False # 1 is not a prime if n==2: return True if n > 2 and n % 2 ==0: return False max_divisor = math.floor(math.sqrt(n)) for i in rang...
8054efd19b2e6a3b0e1de896865ae7e36e1d9125
36,758
import six def _generate_waveform_name_dict(): """Maps _WAVEFORM_DEFS -> _WAVEFORM_NAMES. _WAVEFORM_NAMES is a sparse map of the following keys: "id:device:channel" -> name "id:device:" -> name "id::channel" -> name "id:" -> name """ data = {} for waveform in _WAVEFORM_DEFS: for key, ...
1c9618dd7e49fc94f3ebdc84b954f946d23833d3
36,759
import json def generate_gcode(*args): """ generate gcode for heightmap in a given orientation note: [toBeImproved]heightmap passed as formatted string isnt a good way to structure the code """ arg = args[0][0] orientation = args[0][1] global diameter, step, feed comman...
91308d0b0230b2e314b63e93c7a1cf60485de60b
36,760
def dense_rank_based_voting(score_df, level, column='score'): """ The amount of vote each program component (corresponding to a row in `score_df`) cast is defined by the inverse of the dense rank of its suspiciousness score, which is stored in the column `column` of `score_df`. Then, the total v...
3fdbcbe8fb92e0668f9ea5f5548cebbf32a676bb
36,761
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradien...
c85b0e6a5d94df6a116c7fb389f3633d3c1a2b64
36,762
def power_spectral_density(signal, window, overlap, fmin, fmax, fs, average=True): """Compute PSD using welch method Parameters ---------- signal : array of shape (n_samples,) The signal to compute the PSD on. window : int Length of the segments. overlap : float proporti...
f8051bcb34dfc9fc4535471394357b39896dc304
36,763
def GetStatus(issue): """Get the status of an issue, whether it is explicit or derived.""" return issue.status or issue.derived_status or ''
4f51142dc4e55adaa27eaf3f3e7e748a49d45df2
36,764
def set_safe_attr(instance, attr, val): """Sets the attribute in a thread safe manner. Returns if new val was set on attribute. If attr already had the value then False. """ if not instance or not attr: return False old_val = getattr(instance, attr, None) if val is None and old_val...
92f657a8e8919b47db6f38a31d4c1cad5bea4c93
36,765