content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def convert_coevalcube_to_sphere_surface_inpdict(inpdict): """ ----------------------------------------------------------------------------- Covert a cosmological coeval cube at a given resolution (in physical comoving distance) to HEALPIX coordinates of a specified nside covering the whole sky or...
e99f4ca3d6ff1a76ce95c4e929521ccf857148df
3,637,734
def postmsg(message): """!Sends the message to the jlogfile logging stream at level INFO. This is identical to: @code jlogger.info(message). @endcode @param message the message to log.""" return jlogger.info(message)
b7cad54650fd769ef9c56f8a03e68d0ef9fa485d
3,637,735
def dec_lap_pyr(x, levs): """ constructs batch of 'levs' level laplacian pyramids from x Inputs: x -- BxCxHxW pytorch tensor levs -- integer number of pyramid levels to construct Outputs: pyr -- a list of pytorch tensors, each representing a pyramid level, ...
d0b48660b194c71e34e7f838525d0814081939fb
3,637,736
def mif2amps(sh_mif_file, working_dir, dsi_studio_odf="odf8"): """Convert a MRTrix SH mif file to a NiBabel amplitudes image. Parameters: =========== sh_mif_file : str path to the mif file with SH coefficients """ verts, _ = get_dsi_studio_ODF_geometry(dsi_studio_odf) num_dirs, _...
2defa9d0656bc6c884e6f0591041efdea743db95
3,637,738
import struct import array def write_nifti_header(hdrname, hdr, newfile=True): #************************************************* """ filename is the name of the nifti header file. hdr is a header dictionary. Contents of the native header will be used if it is a nifti header. Returns: 0 if no er...
8b9239ff96d453f8bcb7a667e62434fa9f1bfbc6
3,637,739
import struct def get_array_of_float(num, data): """Read array of floats Parameters ---------- num : int Number of values to be read (length of array) data : str 4C binary data file Returns ------- str Truncated 4C binary data file list List of flo...
92a0a4cc653046826b14c2cd376a42045c4fa641
3,637,740
def AUcat(disk=None, first=1, last=1000, Aname=None, Aclass=None, Aseq=0, giveList=False): """ Catalog listing of AIPS UV data files on disk disk Strings use AIPS wild cards: * blank => any '?' => one of any character "*" => arbitrary string If giveList then r...
501bb5a1eaa82fd162d17478f5bd9b14d8b76124
3,637,741
def process_threat_results(matching_threats, context): """ prepare response from threat results """ threats = [ThreatSerializer(threat).data for threat in matching_threats] response_data = { "id": context.id, "hits": threats, } status_code = status.HTTP_200_OK if context.pending...
b6f763f1a2983967dd0ccc68237408bf3871f9ac
3,637,742
def entropy_logits(logits): """ Computes the entropy of an unnormalized probability distribution. """ probs = F.softmax(logits, dim=-1) return entropy(probs)
a9806dfbafbe77f74df55b81cc19603826e2d994
3,637,743
def convert_int_to_str(number: int, char: str = "'"): """Converts an ugly int into a beautiful and sweet str Parameters: nb: The number which is gonna be converted. char: The characters which are gonna be inserted between every 3 digits. Example: 2364735247 --> 2'364'735'247""" number ...
ae8e2b0e4cc9a332e559e3128c440fff59cf6c78
3,637,744
def exists(index, doc_type, id, **kwargs): """ Returns a boolean indicating whether or not given document exists in Elasticsearch. http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html """ res = request("exists", None, index, doc_type, id, **kwargs) jsonprint(res) retu...
fd5488acef16b22b0da7302345eab2de6073523c
3,637,745
def deserialize_cookie(string): """Deserialize cookie""" parts = string.split("#") length = len(parts) if length == 0 or length < 3: return None if not is_int(parts[2]): return None return create_internal_cookie( unquote(parts[0]), unquote(parts[1]), pa...
9887eb18c4cc91a13048b987ec962deb83a4da2b
3,637,746
def choose(n, k): """This is a binomial coeficient nCk used in binomial probablilty this funtion uses factorial() Usage: choose(n, k) args: n = total number k = total number of sub-groups """ try: return factorial(n)/(factorial(k) * factorial(n - k)) except(ValueError, ZeroD...
3e9fe5212a2ddf680fc6681c0a7d7bd1ec9a4de2
3,637,747
import grp from typing import cast def get_os_group(name: _STR_OR_INT_OR_NONE = None) -> grp.struct_group: """Get an operating system group object. Args: name (:obj:`str` or :obj:`int`, optional): The "group name" or ``gid``. Defaults to the current users's group. Raises: OSE...
6c359b46cdd2766cbdea7fb5412b1e03a3fbecac
3,637,749
def _process_output(response, context): """Post-process TensorFlow Serving output before it is returned to the client. Args: response (obj): the TensorFlow serving response context (Context): an object containing request and configuration details Returns: (bytes, string): data to r...
19805fc9ce122b4c02a596167edbc01398dfa2ab
3,637,750
from bs4 import BeautifulSoup import requests def make_soup(text: str, mode: str="url", parser: str=PARSER) -> BeautifulSoup: """ Returns a soup. """ if mode == "url" or isinstance(mode, dict): params = mode if isinstance(mode, dict) else {} text = requests.get(text, params=params).text el...
9641a7a0807194c911614e2ac41551b04bdbe22d
3,637,752
import ast def _merge_inner_function( class_def, infer_type, intermediate_repr, merge_inner_function ): """ Merge the inner function if found within the class, with the class IR :param class_def: Class AST :type class_def: ```ClassDef``` :param infer_type: Whether to try inferring the typ (f...
5c891ba82cb5b41a5b5d311611f5d318d249a31e
3,637,753
def pb_set_defaults(): """Set board defaults. Must be called before using any other board functions.""" return spinapi.pb_set_defaults()
30d360a15e4602c64a81900a581a2f4429f7d71e
3,637,754
def count_routes_graph(graph, source_node, dest_node): """ classic tree-like graph traversal """ if dest_node == source_node or dest_node - source_node == 1: return 1 else: routes = 0 for child in graph[source_node]: routes += count_routes_graph(graph, child, dest...
f952b35f101d9f1c42eb1d7444859493701c6838
3,637,755
from typing import Dict def pluck_state(obj: Dict) -> str: """A wrapper to illustrate composing the above two functions. Args: obj: The dictionary created from the json string. """ plucker = pipe(get_metadata, get_state_from_meta) return plucker(obj)
d9517346b701f9ff434452992a4f3e8ca3dccf08
3,637,756
from typing import Callable from typing import Mapping from typing import Any from typing import Optional def value( parser: Callable[[str, Mapping[str, str]], Any] = nop, tag_: Optional[str] = None, var: Optional[str] = None, ) -> Parser: """Return a parser to parse a simple value assignment XML tag....
dcb2ad9b9e83015f1fd86323a156bbe92d505211
3,637,757
def compute_Rnorm(image, mask_field, cen, R=12, wid=1, mask_cross=True, display=False): """ Compute (3 sigma-clipped) normalization using an annulus. Note the output values of normalization contain background. Paramters ---------- image : input image for measurement mask_field : mask map wi...
7c0b2aebf009b81c19de30e3a0d9f91fcfcebd52
3,637,758
import six def inject_timeout(func): """Decorator which injects ``timeout`` parameter into request. On client initiation, default timeout is set. This timeout will be injected into any request if no explicit parameter is set. :return: Value of decorated function. """ @six.wraps(func) de...
479ed7b6aa7005d528ace0ff662840d14c23035c
3,637,759
def test_match_partial(values): """@match_partial allows not covering all the cases.""" v, v2 = values @match_partial(MyType) class get_partial_value(object): def MyConstructor(x): return x assert get_partial_value(v) == 3
826a08066822e701c2077c2b71be48152c401b3f
3,637,760
def assert_sim_of_model_with_itself_is_approx_one(mdl: nn.Module, X: Tensor, layer_name: str, metric_comparison_type: str = 'pwcca', metric_as_sim_or_dist: str = 'dist') ...
76d9b88063b69b69217f28cb98c985ff92f9b6e0
3,637,761
def cver(verstr): """Converts a version string into a number""" if verstr.startswith("b"): return float(verstr[1:])-100000 return float(verstr)
1ad119049b9149efe7df74f5ac269d3dfafad4e2
3,637,762
import urllib def _GetGaeCookie(host, service, auth_token, secure): """This function creates a login cookie using the authentication token obtained after logging in successfully in the Google account. Args: host: Host where the user wants to login. service: Service code where the user wants to login. ...
9bef7516f6b43c2b744e6bb0a75a488e8aee3934
3,637,763
async def ping_handler() -> data.PingResponse: """ Check server status. """ return data.PingResponse(status="ok")
77d1130aa31f54fbcac351d58b8ae4e4b893c5e9
3,637,764
def create_session_cookie(): """ Creates a cookie containing a session for a user Stolen from https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django :param username: :param password: :return: """ # First, create a new test user user =...
d4d7eef96e7b0136aa888d362b3278eb24ae91b8
3,637,767
def _replace_oov(original_vocab, line): """Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode ...
2e2cb1464484806b79263a14fd32ed4d40d0c9ba
3,637,770
def linear_CMD_fit(x,y,xerr,yerr): """ Does a linear fit to CMD data where x is color and y is amplitude, returning some fit statistics Parameters ---------- x : array-like color y : array-like magnitude xerr : array-like color errors yerr : array-like ...
fb145d5caf48d2ab1b49a17b1e05ddd32e97c3f1
3,637,771
def _verify_path_value(value, is_str, is_kind=False): """Verify a key path value: one of a kind, string ID or integer ID. Args: value (Union[str, int]): The value to verify is_str (bool): Flag indicating if the ``value`` is a string. If :data:`False`, then the ``value`` is assumed t...
3d8db518f244e6d09826d29dfcc42769a0015c33
3,637,772
def _is_tipologia_header(row): """Controlla se la riga corrente e' una voce o l'header di una nuova tipologia di voci ("Personale", "Noli", etc). """ if type(row.iloc[1]) is not str: return False if type(row.iloc[2]) is str: if row.iloc[2] != HEADERS["units"]: return Fal...
0fdbc6bea8d961fbe990d607a175815ccc475f88
3,637,773
def validateFloat( value, blank=False, strip=None, allowRegexes=None, blockRegexes=None, min=None, max=None, lessThan=None, greaterThan=None, excMsg=None, ): # type: (str, bool, Union[None, str, bool], Union[None, Sequence[Union[Pattern, str]]], Union[None, Sequence[Union[Pat...
e11bbef1b0f53fa803918f9871e9779549e3cdb8
3,637,774
from typing import Dict from typing import Any def send_sms(mobile: str, sms_code: str) -> Dict[str, Any]: """发送短信""" sdk: SmsSDK = SmsSDK( celery.app.config.get("SMS_ACCOUNT_ID"), celery.app.config.get("SMS_ACCOUNT_TOKEN"), celery.app.config.get("SMS_APP_ID") ) try: re...
f1117d0543cc84d0429ce67f1415e6ab371ef2a6
3,637,775
def from_dataframe(df, name='df', client=None): """ convenience function to construct an ibis table from a DataFrame EXPERIMENTAL API Parameters ---------- df : DataFrame name : str, default 'df' client : Client, default new PandasClient client dictionary will be mutated wi...
23d64170f078652e60d65be5346293ea3c4aedb5
3,637,776
def filter_list(prev_list, current_list, zeta): """ apply filter to the all elements of the list one by one """ filtered_list = [] for i, current_val in enumerate(current_list): prev_val = prev_list[i] filtered_list.append( moving_average_filter(current_val, prev_val...
842d71f58b07dbe771c7fdd43797f26e75565ef5
3,637,781
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for word in dict_list: if word.startswith(sub_s): return True return False
78900ed757d4a1a94832f5a2f6d19da784935966
3,637,782
import yaml def main(): """ """ try: # read parameters configuration file yaml with open(setupcfg.extraParam, "r") as stream: try: param = yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) # check parameters file ...
67da82991e8ae5b36dae81c6ac107099a54ab7e4
3,637,784
def primary_key(field_type): """ * Returns the field to be treated as the "primary key" for this type * Primary key is determined as the first of: * - non-null ID field * - ID field * - first String field * - first field * * @param {object_type_definition} type *...
5beef62f9311b013b6c6cbe3c36260783bc61506
3,637,785
def get_discussion_data_list_with_percentage(session: Session, doi, limit: int = 20, min_percentage: float = 1, dd_type="lang"): """ get discussion types with count an percentage from postgresql """ query = """ WITH result AS ( ...
4842566f7a891ce53cfc8170cc0fb5db2a6b298b
3,637,786
import collections import torch import time def validate(config, model, val_iterator, criterion, scheduler=None): """Runs one standard validation pass over the val_iterator. This function automatically measures timing for various operations such as host to device transfer and processing time for the batc...
4f10e68c2e863e11e33f4f49b8378de51ff2b8fe
3,637,787
def geq_indicate(var, indicator, var_max, thr): """Generates constraints that make indicator 1 iff var >= thr, else 0. Parameters ---------- var : str Variable on which thresholding is performed. indicator : str Identifier of the indicator variable. var_max : int An uppe...
319f18f5343b806b7108dd9c02ca5d647e132dab
3,637,790
import re def parse_manpage_number(path): """ Parse number of man page group. """ # Create regular expression number_regex = re.compile(r".*/man(\d).*") # Get number of manpage group number = number_regex.search(path) only_number = "" if number is not None: number = nu...
b45edb65705592cd18fd1fd8ee30bb389dbd8dff
3,637,791
def sample_coordinates_from_coupling(c, row_points, column_points, num_samples=None, return_all = False, thr = 10**(-6)): """ Generates [x, y] samples from the coupling c. If return_all is True, returns [x,y] coordinates of every pair with coupling value >thr """ index_samples = sample_indices_fro...
a8343291a34ff31a2fc7b86c9b83872e7c787b76
3,637,792
import ast def is_suppress_importerror(node: ast.With): """ Returns whether the given ``with`` block contains a :func:`contextlib.suppress(ImportError) <contextlib.suppress>` contextmanager. .. versionadded:: 0.5.0 (private) :param node: """ # noqa: D400 item: ast.withitem for item in node.items: if not...
341d106b62d7940e4d84a359cd2f2ca254d3434e
3,637,793
def random_flip_left_right(data): """ Randomly flip an image or batch of image left/right uniformly Args: data: tensor of shape (H, W, C) or (N, H, W, C) Returns: Randomly flipped data """ data_con, C, N = _concat_batch(data) data_con = tf.image.random_flip_left_right(data_con)...
bcdd0dfd35ff7ee0237d585d5a6cd70f92d7df2b
3,637,794
def get_all_lobbyists(official_id, cycle=None, api_key=None): """ https://www.opensecrets.org/api/?method=candContrib&cid=N00007360&cycle=2020&apikey=__apikey__ """ if cycle is None: cycle = 2020 # I don't actually know how the cycles work; I assume you can't just take the current year? #...
a2d8267881e871cb54201d243357739e689f187e
3,637,798
def get_sale(this_line): """Convert the input into a dictionary, with keys matching the CSV column headers in the scrape_util module. """ sale = {} sale['consignor_name'] = this_line.pop(0) sale['consignor_city'] = this_line.pop(0).title() try: maybe_head = this_line[0].split() ...
39fee66b4c92a2cb459722f238e4a3b6e5848f4d
3,637,799
def validate_besseli(nu, z, n): """ Compares the results of besseli function with scipy.special. If the return is zero, the result matches with scipy.special. .. note:: Scipy cannot compute this special case: ``scipy.special.iv(nu, 0)``, where nu is negative and non-integer. The correc...
a8102c014fdcb2d256adf94aea842d1e5733ba72
3,637,800
from typing import Any from typing import List def delete_by_ip(*ip_address: Any) -> List: """ Remove the rules connected to specific ip_address. """ removed_rules = [] counter = 1 for rule in rules(): if rule.src in ip_address: removed_rules.append(rule) execut...
88b430b83a5c3c82491f210e218a10719b5b75df
3,637,801
def findMaxWindow(a, w): """ :param a: input array of integers :param w: window size :return: array of max val in every window """ max = [0] * (len(a)-w+1) maxPointer = 0 maxCount = 0 q = Queue() for i in range(0, w): if a[i] > max[maxPointer]: max[maxPointer...
af3e7f010b162e8f378e541be32a2d295e31e51c
3,637,802
import logging def filtering_news(news: list, filtered_news: list): """ Filters news to remove unwanted removed articles Args: news (list): List of articles to remove from filtered_news (list): List of titles to filter the unwanted news with Returns: news (list): List of arti...
98049b6bd826109fe7bc8e2e42de4c50970988a9
3,637,803
def extract_subsequence(sequence, start_time, end_time): """Extracts a subsequence from a NoteSequence. Notes starting before `start_time` are not included. Notes ending after `end_time` are truncated. Args: sequence: The NoteSequence to extract a subsequence from. start_time: The float time in second...
cf8e1be638163a6cb7c6fd6e69121ccc7100afd6
3,637,804
import re def read_data(filename): """Read the raw tweet data from a file. Replace Emails etc with special tokens """ with open(filename, 'r') as f: all_lines=f.readlines() padded_lines=[] for line in all_lines: line = emoticonsPattern.sub(lambda m: rep[re.escape(m.group(0)...
8e15d6e4bd9e4a6b3b01ea5baffad8e6bc390034
3,637,805
def client(): """AlgodClient for testing""" client = _algod_client() client.flat_fee = True client.fee = 1000 print("fee ", client.fee) return client
ad51102a58d9ffad4a9dd43c3e2b4bd5adc0f467
3,637,806
def GRU_sent_encoder(batch_size, max_len, vocab_size, hidden_dim, wordembed_dim, dropout=0.0, is_train=True, n_gpus=1): """ Implementing the GRU of skip-thought vectors. Use masks so that sentences at different lengths can be put into the same batch. sent_seq: sequence of tokens c...
fe7090efe78ec97ba88651ecf8f7918bb5277eec
3,637,807
def process_contours(frame_resized): """Get contours of the object detected""" blurred = cv2.GaussianBlur(frame_resized, (11, 9), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, constants.blueLower, constants.blueUpper) mask = cv2.erode(mask, None, iterations=2) mask = ...
5725b12a3e5e0447a3b587d091f4fdeae1f5bac9
3,637,808
from typing import Optional from typing import List import itertools def add_ignore_file_arguments(files: Optional[List[str]] = None) -> List[str]: """Adds ignore file variables to the scope of the deployment""" default_ignores = ["config.json", "Dockerfile", ".dockerignore"] # Combine default files and ...
f7e7487c4a17a761f23628cbb79cbade64237ce6
3,637,809
import torch def compute_accuracy(logits, targets): """Compute the accuracy""" with torch.no_grad(): _, predictions = torch.max(logits, dim=1) accuracy = torch.mean(predictions.eq(targets).float()) return accuracy.item()
af15e4d077209ff6e790d6fdaa7642bb65ff8dbf
3,637,810
def division_by_zero(number: int): """Divide by zero. Should raise exception. Try requesting http://your-app/_divide_by_zero/7 """ result = -1 try: result = number / 0 except ZeroDivisionError: logger.exception("Failed to divide by zero", exc_info=True) return f"{number} divi...
b97d7f38aea43bfb6ee4db23549e89799bd299b7
3,637,811
def is_ELF_got_pointer_to_external(ea): """Similar to `is_ELF_got_pointer`, but requires that the eventual target of the pointer is an external.""" if not is_ELF_got_pointer(ea): return False target_ea = get_reference_target(ea) return is_external_segment(target_ea)
cd62d43bb266d229ae31e477dc60d21f73b8850a
3,637,812
from pathlib import Path def _normalise_dataset_path(input_path: Path) -> Path: """ Dataset path should be either the direct imagery folder (mtl+bands) or a tar path. Translate other inputs (example: the MTL path) to one of the two. >>> tmppath = Path(tempfile.mkdtemp()) >>> ds_path = tmppath.jo...
cf61da9a043db9c67714d7437c7ef18ee6235acb
3,637,813
def get_customers(): """returns an array of dicts with the customers Returns: Array[Dict]: returns an array of dicts of the customers """ try: openConnection with conn.cursor() as cur: result = cur.run_query('SELECT * FROM customer') cur.close() ...
4440fb5d226070facb4e5c1b854535e40f42d607
3,637,814
def fixtureid_es_server(fixture_value): """ Return a fixture ID to be used by pytest for fixture `es_server()`. Parameters: fixture_value (:class:`~easy_server.Server`): The server the test runs against. """ es_obj = fixture_value assert isinstance(es_obj, easy_server.Server) ...
f795a8e909354e0004ea81ebdf71f7da81153a64
3,637,815
def topn_vocabulary(document, TFIDF_model, topn=100): """ Find the top n most important words in a document. Parameters ---------- `document` : The document to find important words in. `TFIDF_model` : The TF-IDF model that will be used. `topn`: Default = 100. Amount of top words. ...
4c58e2f041c76407bb2e7c686713b12e2c1e8256
3,637,816
def embedding_table(inputs, vocab_size, embed_size, zero_pad=False, trainable=True, scope="embedding", reuse=None): """ Generating Embedding Table with given parameters :param inputs: A 'Tensor' with type 'int8' or 'int16' or 'int32' or 'int64' containing the ids to be looked up in '...
bc509e18048230372b8f52dc5bbb77295014aec8
3,637,817
def get_trading_dates(start_date, end_date): """ 获取某个国家市场的交易日列表(起止日期加入判断)。目前仅支持中国市场。 :param start_date: 开始日期 :type start_date: `str` | `date` | `datetime` | `pandas.Timestamp` :param end_date: 结束如期 :type end_date: `str` | `date` | `datetime` | `pandas.Timestamp` :return: list[`datetime.date`...
5b0bf331376c5b2f9d1c8308be285b54fa053e5f
3,637,818
def gm_put(state, b1, b2): """ If goal is ('pos',b1,b2) and we're holding b1, Generate either a putdown or a stack subtask for b1. b2 is b1's destination: either the table or another block. """ if b2 != 'hand' and state.pos[b1] == 'hand': if b2 == 'table': return [('a_putdown...
c9076ac552529c60b5460740c74b1602c42414f2
3,637,819
def pad_to_shape_label(label, shape): """ Pad the label array to the given shape by 0 and 1. :param label: The label for padding, of shape [n_batch, *vol_shape, n_class]. :param shape: The shape of the padded array, of value [n_batch, *vol_shape, n_class]. :return: The padded label array. """ ...
e40d7c1949cc891353c9899767c92419202c325d
3,637,821
def download_report( bucket_name: str, client: BaseClient, report: str, location: str ) -> bool: """ Downloads the original report to the temporary work area """ response = client.download_file( Bucket=bucket_name, FileName=report, Location=location ) return response
d46fb279d5a315c60f1908664951436edc997ab8
3,637,822
def get_service(hass, config): """Get the Google Voice SMS notification service.""" if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD]}, _LOGGER): return None return GoogleVoiceS...
c7fda936ca9448587e2c4167d9c765186344fb43
3,637,825
import random import time def hammer_op(context, chase_duration): """what better way to do a lot of gnarly work than to pointer chase?""" ptr_length = context.op_config["chase_size"] data = list(range(0, ptr_length)) random.shuffle(data) curr = random.randint(0, ptr_length - 1) # and away we...
f4a51fe1e2f89443b79fd4c9a5b3f5ee459e79ca
3,637,826
from typing import Callable from typing import Mapping import copy import torch def generate_optimization_fns( loss_fn: Callable, opt_fn: Callable, k_fn: Callable, normalize_grad: bool = False, optimizations: Mapping = None, ): """Directly generates upper/outer bilevel program derivative funct...
5e70f05c5aa0e754e5c1fbe585e4a0856a732006
3,637,828
def get_weighted_spans(doc, vec, feature_weights): # type: (Any, Any, FeatureWeights) -> Optional[WeightedSpans] """ If possible, return a dict with preprocessed document and a list of spans with weights, corresponding to features in the document. """ if isinstance(vec, FeatureUnion): return...
0896a8449690895d922ae409c7e278f38002f111
3,637,829
def get_child(parent, child_index): """ Get the child at the given index, or return None if it doesn't exist. """ if child_index < 0 or child_index >= len(parent.childNodes): return None return parent.childNodes[child_index]
37f7752a4a77f3d750413e54659f907b5531848c
3,637,830
def extinction(species, adj, z, independent): """ Returns the presence/absence of each species after taking into account the secondary extinctions. Parameters ---------- species : numpy array of shape (nbsimu, S) with nbsimu being the number of simulations (decompositions). This ar...
2a9cb1884cfceb3a7c06aede60191d8a86f4741b
3,637,832
def fix_variable_mana(card): """ This function was created to fix a problem in the dataset. We're currently pretty up against the wall and I realized that 'Variable' mana texts were not correctly converted to {X} so this function is fed cards and corrects their mana values if it detects this pro...
de0a0fe10d7ebbe02cd36088765be373c7dd9789
3,637,833
def cli_arg( runner: CliRunner, notebook_path: Path, mock_terminal: Mock, remove_link_ids: Callable[[str], str], mock_tempfile_file: Mock, mock_stdin_tty: Mock, mock_stdout_tty: Mock, ) -> Callable[..., str]: """Return function that applies arguments to cli.""" def _cli_arg( ...
5d7e02b11ace8ee44fa85ce7d2dc4c5a24fb72cf
3,637,834
def distinguish_system_application(vulner_info): """ Test whether CVE has system CIA loss or application CIA loss. :param vulner_info: object of class Vulnerability from cve_parser.py :return: result impact or impacts """ result_impacts = [] if system_confidentiality_changed( vu...
c10ec04a761b038fe3c0d6408a31660ccf23a205
3,637,836
from typing import Tuple def nearest_with_mask_regrid( distances: ndarray, indexes: ndarray, surface_type_mask: ndarray, in_latlons: ndarray, out_latlons: ndarray, in_classified: ndarray, out_classified: ndarray, vicinity: float, ) -> Tuple[ndarray, ndarray]: """ Main regriddin...
75b69ddbbdca4c316ecf2d4e3933f6e3a55ff0e1
3,637,840
def get_renaming(mappers, year): """Get original to final column namings.""" renamers = {} for code, attr in mappers.items(): renamers[code] = attr['df_name'] return renamers
33197b5c748b3ecc43783d5f1f3a3b5a071d3a4e
3,637,842
async def clap(text, args): """ Puts clap emojis between words. """ if args != []: clap_str = args[0] else: clap_str = "👏" words = text.split(" ") clappy_text = f" {clap_str} ".join(words) return clappy_text
09865461e658213a2f048b89757b75b2a37c0602
3,637,843
from typing import Union from typing import Callable from typing import List def apply_binary_str( a: Union[pa.Array, pa.ChunkedArray], b: Union[pa.Array, pa.ChunkedArray], *, func: Callable, output_dtype, parallel: bool = False, ): """ Apply an element-wise numba-jitted function on tw...
853cd326b5812314bb6595fee191ca1c6e1f89f6
3,637,844
def product_review(product_id: str): """ Shows review statistics for a product. Returns a python dictionary with content-type: application/json """ session = Session() date = request.args.get('date') # parse a query string formatted as BIGINT unixReviewTime # SELECT AVG(overall)...
945f29a536a5645b602633c4558ac3d68affe85a
3,637,845
def remove_extra_two_spaces(text: str) -> str: """Replaces two consecutive spaces with one wherever they occur in a text""" return text.replace(" ", " ")
d8b9600d3b442216b1fbe85918f313fec8a5c9cb
3,637,846
def reflect_table(table_name, engine): """ Gets the table with the given name from the sqlalchemy engine. Args: table_name (str): Name of the table to extract. engine (sqlalchemy.engine.base.Engine): Engine to extract from. Returns: table (sqlalchemy.ext.declarative.api.Declara...
414a04172cec7e840bf257eaf5b15b1fc3fa9d59
3,637,847
def load_utt_list(utt_list): """Load a list of utterances. Args: utt_list (str): path to a file containing a list of utterances Returns: List[str]: list of utterances """ with open(utt_list) as f: utt_ids = f.readlines() utt_ids = map(lambda utt_id: utt_id.strip(), utt_...
6a77e876b0cc959ac4151b328b718ae45522448b
3,637,848
def kfunc_vals(points, area): """ Input points: a list of Point objects area: an Extent object Return ds: list of radii lds: L(d) values for each radius in ds """ # This function is taken from kfunction file in spatialanalysis library n = len(points) density = n/area...
2fd56da45f8fb4ede38a219b158dce802d68ae44
3,637,849
from datetime import datetime async def get_locations(): """ Retrieves the locations from the categories. The locations are cached for 1 hour. :returns: The locations. :rtype: List[Location] """ # Get all of the data categories locations. confirmed = await get_category("confirmed") de...
24272f06ca3732f053d6efcc41a31ec205603a27
3,637,850
def MDAPE(y_true, y_pred, multioutput='raw_values'): """ calculate Median Absolute Percentage Error (MDAPE). :param y_true: array-like of shape = (n_samples, *) Ground truth (correct) target values. :param y_pred: array-like of shape = (n_samples, *) Estimated target values. :param m...
05cfbef6bd3e63ca151a584dc25b9b6574d2aa37
3,637,851
def read_line1(line): """! Function read_line1 Reads as argument a string formatted as a Line 1 in SEISAN's Nordic format Returns a Hypocenter dataclass with all the fields in a SEISAN's Line 1 @param[in] line string with SEISAN's Nordic hypocenter format (Line 1) @return Hypocenter...
871f468c2ec4dd9e0a5e8784d2beb7dd958d068d
3,637,854
def getInfo_insert(sql : str, tableInfo : table_info_module.TableInfo) -> tuple: """테이블 이름과 컬럼을 반환합니다.""" sql = string_module.removeNoise(sql) tableName = string_module.getParenthesesContext2(sql, "INSERT INTO ", " ") columns = tableInfo[tableName] return (tableName, columns)
25f2087b5fbb15ab1012d3f37749430a74e6faaa
3,637,858
def compute_flow_for_supervised_loss( feature_model, flow_model, batch, training ): """Compute flow for an image batch. Args: feature_model: A model to compute features for flow. flow_model: A model to compute flow. batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triple...
a74f392c1d4e234fdb66d18e63d7c733ec6669a7
3,637,859
def farey_sequence(n): """Return the nth Farey sequence as order pairs of the form (N,D) where `N' is the numerator and `D' is the denominator.""" a, b, c, d = 0, 1, 1, n sequence=[(a,b)] while (c <= n): k = int((n + b) / d) a, b, c, d = c, d, (k*c-a), (k*d-b) sequence.append( (a...
d55bb90d05b4930d05a83dac9feb58e747288754
3,637,861
def make_vgg19_block(block): """Builds a vgg19 block from a dictionary Args: block: a dictionary """ layers = [] for i in range(len(block)): one_ = block[i] for k, v in one_.items(): if 'pool' in k: layers += [nn.MaxPool2d(kernel_size=v[0], stride=...
512543dfb32f9ed97b6ce99dd6ffc692d0ffa3b8
3,637,862
def tld(): """ Return a random tld (Top Level Domain) from the tlds list below :return: str """ tlds = ('com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ru', 'eu',) return pickone(tlds)
8e9341058ccf79d991aab6317ab3c29858f00fdf
3,637,864
def validate_boolean(option, value): """Validates that 'value' is 'true' or 'false'. """ if isinstance(value, bool): return value elif isinstance(value, basestring): if value not in ('true', 'false'): raise ConfigurationError("The value of '%s' must be " ...
85b9a256e57ce7715fceea556ff7ad48b05bd996
3,637,865
def A2RT(room_size, A_wall_all, F_abs, c=343, A_air=None, estimator='Norris_Eyring'): """ Estimate reverberation time based on room acoustic parameters, translated from matlab code developed by Douglas R Campbell Args: room_size: three-dimension measurement of shoebox room A_wall_all: sound ...
8a8df0bf8f91c93dfb7480775ea9eadc552edcfe
3,637,866
def GetVideoFromRate(content): """ 从视频搜索源码页面提取视频信息 """ #av号和标题 regular1 = r'<a href="/video/av(\d+)/" target="_blank" class="title" [^>]*>(.*)</a>' info1 = GetRE(content, regular1) #观看数 regular2 = r'<i class="b-icon b-icon-v-play" title=".+"></i><span number="([^"]+)">\1</span>' info2 = ...
446343bc3f2597310b7e4b22dd784bb0bc9b06ea
3,637,867