content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def SourceRef(filename: str) -> FileSourceRef: """ Deprecated callable that provides a compatible stand-in for the old-style SourceRef class constructor """ return FileSourceRef(filename)
af6edbf6dde68bb64f5519d57113df49d3904eae
56,900
def service_interface_point (sip_uuid): """Retrieve ServiceInterfacePoint by ID :param sip_uuid: ID of ServiceInterfacePoint :type sip_uuid: str :rtype: ServiceInterfacePoint """ for sip in context.service_interface_point: if sip.uuid == sip_uuid: return sip
44ddc6b799b4a619c73d23f90f6c63075cf90b23
56,901
def addError(e, parser): """ assumes errors are lists, and that the state is a position """ return bind(getState, lambda pos: mapError(lambda es: [(e, pos)] + es, parser))
eeabe120be337e1b05584348cf62933856d908f6
56,902
from typing import Optional def get_group(api_management_name: Optional[str] = None, name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGroupResult: """ Use this data source to access info...
b57060641ffa913c117187f6dbeae21140e0b8c2
56,903
async def delete_topic( topic_id: str, usecase: TopicUsecase = Depends(deps.get_topic_usecase) ) -> JSONResponse: """Delete a topic.""" try: deleted: bool = await usecase.delete(topic_id) except TopicCanNotBeChanged as err: return JSONResponse( status_code=status.HTTP_422_UNP...
d1ec1d32ac9f54d09f60702f70ed0a176980ea72
56,904
def _disc_disc(dynamod, measmod): """Check whether the state space model is discrete-discrete.""" dyna_is_disc = issubclass(type(dynamod), DiscreteModel) meas_is_disc = issubclass(type(measmod), DiscreteModel) return dyna_is_disc and meas_is_disc
8fa546a78abe278d3c435686c8f5e09b5c3c65a0
56,905
def reduceby(key, binop, seq, init=no_default): """ Perform a simultaneous groupby and reduction The computation: >>> result = reduceby(key, binop, seq, init) # doctest: +SKIP is equivalent to the following: >>> def reduction(group): # doctest: +SKIP ... re...
698abf3587e1d54313bb40193534d0af82010fa6
56,906
def padaxis(array, new_size, axis, pad_value=0, pad_right=True): """ Padds one axis of an array to a new size This is just a wrapper for np.pad, more usefull when only padding a single axis Parameters ---------- array: ndarray the array to pad new_size: int the new size of ...
3f3f09de43e5c810797973cc2a57974ec65294bd
56,907
def chomp_empty(seq): """Return slice of sequence seq without trailing empty tuples.""" n = len(seq) while (n > 0) and seq[n - 1] == (): n -= 1 return seq[:n]
1c6f5f58bb2e73d44b2638d796b1b0a38bba414c
56,908
def _logit(x): """ Logit function in Theano. Useful for parameterizing alpha. """ return np.log(x/(1. - x))
1dce705a78d7e4084cbb6f1a417517c5d0a17f74
56,909
def nvidia_model(input_shape=(160, 320, 3), drop_out = 0.5, drop_out_sp = 0.2): """ NVIDIA Architecture src:[http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf] """ print('\n\n ') print('>> Building the model (NVIDIA Architecture)...') ...
a7365f69a09143f1c17b382f3ee3495e20ff30df
56,910
def rmv_extra_channels(img): """ If a greyscale image is stored as some color image, it will have 3 (RGB) color channels. Since we assume it is really greyscale, all the channels will have equal value so we create a new image of same width and height, but with just 1 color channel. Parameters ---------...
d4e4d5ca985294219be08dda882d4bed2fcbd0a9
56,911
from typing import Dict import logging from typing import List def get_recommended_channels(**kwargs): """Show some of our Community's favorite channels you can join see https://api.slack.com/methods/channels.list as well as https://api.slack.com/methods/channels.info for API info """ _, text = kwargs...
c61fb77a68d22afe03633f97b02a415d5795b227
56,912
import os def builtin_name(path): """Return the builtin function named in the path.""" name = os.path.basename(path).strip() if name.startswith('<') and name.endswith('>'): return name return None
6dc701e193eb721957b538dc5bfae311ab46d4d8
56,913
def main(args=None): """ Actually runs Pedal from the command line. Args: args (argparse.Namespace): The arguments parsed from the command line. """ # Get command line arguments, unless we were explicitly given them. if args is None: args = parse_args() pipeline = MODES.PIPE...
b1082e49e0c6e5aa33ac6cf709ae0717eb29918f
56,914
def tessdata_to_df(tessdata, keep_garbage=False): """Ingests a string repr of tesseract output and spits out a dataframe""" rows = [r.split("\t") for r in tessdata.split("\n")[:-1]] h = rows[0] rows = rows[1:] df = pd.DataFrame(rows) df.columns = h # set types dtypes = [int] * 10 + [fl...
a55320c90fe848b555e44c447fe95d762756b707
56,915
def find_best_match(gts, pred, pred_idx, threshold=0.5, form='pascal_voc', ious=None) -> int: """Returns the index of the 'best match' between the ground-truth boxes and the prediction. The 'best match' is the highest IoU. (0.0 IoUs are ignored). Args: gts: (List[List[Union[int, float]]]) Coord...
83ccbb67565e92d6b2420d38ac8e90fb6456cc5c
56,916
def rotation(v1, v2 = None, dim = 3): """ Rotation Matrix rotates one matrix onto another """ if not isinstance(v1, Point): if (isinstance(v1, np.ndarray) or isinstance(v1, list)): v1 = Point(*v1) else: raise ValueError("Point must be Point Ojbect or list") else: v1 = Point(*v1.euclidean) if not ...
371979d44a916c0d6d5e9d6ac6fa3423bcd3fdcd
56,917
import secrets async def redirect(request: Request) -> Response: """Return plain password if user follows redirect chain.""" url = request.url_for("level:redirect") secret = request.query_params.get("secret", "") # If secret is not given, use first secret in redirect chain if not secret: ...
a46829391aa543669238835aa0f149d8c41348c2
56,918
def get_time_signature_confidence(h5,songidx=0): """ Get signature confidence from a HDF5 song file, by default the first song in it """ return h5.root.analysis.songs.cols.time_signature_confidence[songidx]
578992f3a3261555fc9003166c725bc82eb00d5c
56,919
def remove_duplicates(probs, curr_teams, classes): """ Iterates through algorithm predictions and if any prediction is the same as a player's current team, replaces it with the next highest scoring team. Parameters: probs (np array): array of probabi...
f72932fa00c4ad291a4195d99b1334ffea9cc080
56,920
from typing import Optional from typing import Sequence def _render( self, frames: Optional[Sequence[int]] = None, *, num_frames: int, ) -> dict[str, np.ndarray]: """Mocked render.""" del frames batch_shape = (num_frames, *self.scene.resolution) return { k: make_array_fn(batch_shape=batc...
6b5a088235fcbb86614998e688c59d3c867e832c
56,921
import os def get_map(lon_min, lon_max, lat_min, lat_max, zoom=19): """ Get an ESRI World Imagery map of the selected region Args: lon_min: Minimum longitude (degrees) lon_max: Maximum longitude (degrees) lat_min: Minimum latitude (degrees) lat_max: Maximum latitude (degre...
93f85ddaa8074ac30d10c5dcb658cff4f6dcfe72
56,922
def tag_id(user_id, tag, escape=False): """tag to feedly ``:tag_id`` format :param user_id: ``:user_id`` format data :type user_id: :class:`basestring` :param tag: :type tag: :class:`basestring` :param escape: :type escape: :class:`bool` :returns: :rtype: :class:`basestring` ...
379320f577e14cfdee892931049481cd6af11514
56,923
import os def get_iam_policies(handler): """ Instantiate the IAM client and request a full list of Policies. We then write this list to the filesystem so that the corresponding XUI for this feature can read previously discovered objects without having to call this API each time the AWS RH detail ...
25b60b151735a9687671ab9e03018c8c3cb8be55
56,924
def read_replica_or_default(): """ If there is a database called "read_replica", return "read_replica", otherwise return "default". This function is similiar to `use_read_replica_if_available`, but is be more syntactically convenient for method call chaining. Also, it always falls back to "defa...
d0b2391e0fbbe0c32e682b2e43d892a6737c8055
56,925
def _delta(x, y): """Computes |y|/|x|.""" return max(float(len(y))/float(len(x)), 1.0)
22a55950406daeb3e7653d9a0a232d52a7bd76e4
56,926
import re def compile(text, **variables): """Compile a table text to a ``Table`` object. :param text: a table text :param variables: values passed to the table :type text: string :type variables: dict :return: a table object :rtype: Table :raise TableMarkupError: the text format is in...
7014d8a07051123cb2df7abffced241fc5dcd2c6
56,927
def emphasized_url( name: str, rawtext: str, text: str, lineno: int, inliner: docutils.parsers.rst.states.Inliner, *__ ) -> tuple[list, list]: """ Sphinx role to add hyperlinked literals. ReST: :literal-url:`Google <https://google.com>` Markdown equivalent: [`Google`](https://google.com) Refer...
50c744063c6b65e02044d0711236e3058cec4ebb
56,928
def choose_named_type(*args): """ choose_named_type(out_sym, root_til, title, ntf_flags, predicate=None) -> bool Choose a type from a type library. @param out_sym: pointer to be filled with the chosen type (C++: til_symbol_t *) @param root_til: pointer to starting til (the function wil...
75d5bbc1179149d12e03992f4d91e551d9dd8a65
56,929
from datetime import date def voto(ano): """ -> Função recebe o ano de nascimento do usuário . :return: A idade e a verificação se o usuário está em idade eleitoral. """ atual = date.today().year idade = atual - anonasc if idade < 16: return f'Você tem {idade} e não voto' elif ...
b392efba24d943f591ca0ba3060bfc06313006e5
56,930
def quiet_call(cmd, devnull): """Calls an external command while suppressing stdout. Args: cmd (str): The command to run devnull (object): File-like object Returns: bool: True if the commabd return code was zero, else otherwise Examples: >>> with open(os.devnull, 'wb')...
b24a68f7abe7b51feb44290aa15805a93d31e502
56,931
def _l2_clogistic_gradient_intercept(IL, Y, alpha): """ Gradient of penalized loglikelihood with respect to the intercept parameters Args: IL : array_like. See _l2_clogistic_gradient_IL Y : array_like. response matrix alpha : array_like. intercepts. must have shape == one less than the ...
3e818e7d010a6261a14df2c2b666d55ab86c5257
56,932
def dict_to_margins(margin_dict): """Convert a dictionary with margins informations into a list of distributions. Parameters ---------- margin_dict : dict A dictionary of information on the margins Returns ------- margins """ margins = [] for i in sorted(margin_dict.key...
ad82c5f4748d1e3b9b9128c33632aecca85e338d
56,933
def omp_in_parallel(): """Return 1 if the active-levels-var ICV is greater than zero; \ otherwise, return 0. The effect of the omp_in_parallel routine is to return 1 if the current task is enclosed by an active parallel region, and the parallel region is enclosed by the outermost initial task...
ab2203bfe4f22b2ece40b469267fd94953ab7637
56,934
def get_token_time(token_index, sentence, duration): """ Linearly interpolate to guess the time a token was utterred """ return (token_index + 1) / max(1, len(sentence)) * duration
d227e782083ae6265e1bc4e286269c421e809985
56,935
def is_ip_addr(candidate): """Check a string to see if it is a valid v4 or v6 IP address :param candidate: string to check :return boolean """ return is_ipv4_addr(candidate) or is_ipv6_addr(candidate)
31f531fc2279713376c327c360fcdbf61086701a
56,936
import os import shutil import atexit import tempfile import io def make(destDir, verbose = 0): """ Make an executable zip file of project """ zipAppFileName = os.path.join(destDir, ZIPAPP_NAME) zipPkg = ZipPkg(__name__) if zipPkg.zipexists: src, dst = zipPkg.zippath, zipAppFileName ...
a276151d68718be1fee86546f5c7eb71767c72fb
56,937
def get_voxel_file(category, model_id): """Get the voxel absolute filepath for the model specified by category and model_id. Args: category: Category of the model as a string (eg. '03001627') model_id: Model ID of the model as a string (eg. '587ee5822bb56bd07b11ae648ea92233') ...
7a2934267ff43df56e553b92b94e2b4658ff4d2d
56,938
def ccn(curr_div, curr_mod, curr_list, prev_level): """ Caclulate current neighbours """ value = 0 largest_mod = max(2 * prev_level - 1, 0) #TODO error: larges mod gets calculated wrong if (curr_div == 3) and curr_mod > largest_mod-2: value += curr_list[0] if curr_mod > 0: # Defa...
6761bc2748ab09bf3d1214555e82c7d894f97691
56,939
from ..scene import SceneCanvas from vispy.app import use_app def TestingCanvas(bgcolor='black', size=(100, 100), dpi=None, decorate=None, **kwargs): """Avoid importing scene until necessary.""" # On Windows decorations can force windows to be an incorrect size # (e.g., instead of 100x10...
a41e399adcdff4bb68385ccb824a966b0ff65855
56,940
def bold(string, *funcs, **additional): """Text effect - bold. (see sgr_combiner()).""" return sgr_combiner(string, ansi.BOLD, *funcs, **additional)
45804a5ea85b0bc0cc213054f37403a0429122b9
56,941
def forward_method_kwargs(**kwargs) -> dict: """Return all the keyword-arguments of a method, excluding the 'self' argument""" retval = {} for key, value in kwargs.items(): if key == 'self' or key.startswith('_'): continue elif key == 'kwargs': retval.update(value) ...
571ad0c61f33e608ce253c16f452e488257cbf31
56,942
def esc_ansicolor (color): """convert a named color definition to an escaped ANSI color""" control = '' if ";" in color: control, color = color.split(";", 1) control = AnsiControl.get(control, '')+";" cnum = AnsiColor.get(color, '0') return AnsiEsc % (control+cnum)
71737fbd83a39b220e7e283da2978a1f12c6cd65
56,943
def load_inputs_twitter_(input_file, word_id_file, sentence_len, type_='', is_r=True, target_len=10, encoding='utf8'): """ Method obtained from Trusca et al. (2020). NOTE: not used in this project :param input_file: :param word_id_file: :param sentence_len: :param type_: :param is_r: :p...
386b769b5fb3467ecb1164d309fe9b479e23445d
56,944
def log_softmax(x): """ Compute log-domain softmax of logits Args: x: tensor, here logits Returns: tensor, log-domain softmax of input """ x_dev = x - tf.reduce_max(x, 1, keepdims=True) logsoftmax = x_dev - tf.math.log(tf.reduce_sum(tf.exp(x_dev), 1, keepdims=True)) r...
469c2fb6999c370e6926531480ddad8c106f70f9
56,945
import numpy def standardize_and_check_cloud_variable( var ): """Checks whether var is a legitimate cloud variable for histogram plotting. Presently only the axes are checked. They need to be prs and tau axes where each value falls within the standard bounds defined above.""" var = cloud_regrid_to_st...
5d39626739edccf6218f1249ceefa350522ab278
56,946
def percent_identity(perc_indentities): """Plots read percent identity as a distribution/histogram plot. Args: perc_indentities: A list of the percentage identity figures. Returns: A matplotlib figure object containing the plot. """ bins = 100 xlabel = 'Read percent identity' ...
43f8c0f49ce1ad8e5f3bdf8eebbf4d47a9412fdd
56,947
def vel_disp_function_CPV2007(vel_disp_grid): """Evaluate the velocity dispersion function from the fit on SDSS DR6 by [1]_ on a provided grid and normalizes the result to unity, so it can be used as a PMF from which to draw the velocity dispersion. Parameters ---------- vel_disp_grid : array-...
c5e82a485a169ccb9c47ece39e4d1ab07e5f3b6a
56,948
def match_json(json, mongo_filter): """ Returns the json that matches the given filter :param json: json dict or list of json dicts :param mongo_filter: json dict in mongo query syntax :return: list of json dicts that match """ if type(json) is list: fset = make_filter_chain(json, mo...
5115d88c3b68e00a40599d3c6ab7a708a8bc13ce
56,949
def mask_to_3ch(mask, r=True, g=True, b=True): """ Convert binary mask to 3 channel image. (for visualization purposes) :param mask: binary 1-channel mask :param r: fill red channel with 255 where mask==1 :param g: fill green channel with 255 where mask==1 :param b: fill blue channel with 255 w...
e0a3bd992fc2be291b8e372597113e8021cb6dd5
56,950
def load_cs( src_file: str, dhis2_instance: str, dhis2_username: str, dhis2_password: str, dhis2_groups: str, ) -> gpd.GeoDataFrame: """Load cases de santé geometries from source file or DHIS2.""" # from source file if src_file: cs = gpd.read_file(src_file) n_geoms = sum(...
e3cfa9795543fbeac9f4a54e048c208cd3d15577
56,951
def get_fs_info(): """return a list containing the info returned by 'df -k', i.e, file systems size and occupation, in Mb. And the filesystem type: [dev, size, used, available, use%, mount point, fs type]""" try: buf = os.popen('df -k').readlines() except (IOError, os.error), (errno, strerr...
16952d7bf76639fb92c6b01b5a714dbea6cbc3ec
56,952
import json def get_details(details_string): """Return details content. * If JSON as a formatted string * Otherwise as a string as-is. """ content = details_string rv = '' try: details = json.loads(content) rv = ''.join(['<li>{k}: {v}</li>'.format(k=k, v=get_str_value(v))...
6b2737b2f5c90b564842760ec55ecade5f49576f
56,953
import os def load_letter(folder, min_num_images): """Load the data for a single letter label.""" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for image in image_files: im...
3704657bc6a7f2660755b5881bf6120f70bb7bc2
56,954
from re import DEBUG def train_with_ludwig(model_definition, train_file_csv, target_model_path): """ Wrap around Ludwig training routine. :param model_definition: dictionary defining deep learning architecture with Ludwig conventions :param train_file_csv: path to csv file for training :param tar...
53537cedbf3aa52352b095118cfcf488de3e7d31
56,955
def calc_load_matrix(M,Minv=None,isSparse=False): """ Assembles _load matrix_ as used in state-space representation of equation of motion $$ B = [[0],[M^{-1}]] $$ where **M** is the system mass matrix. *** Required: * `M`, mass matrix, shape [n x n]. Unused i...
2f2274691c44edb993c810fecc0cc51e4a6402ce
56,956
def _get_keywords_with_score(extracted_lemmas, lemma_to_word): """Get words of `extracted_lemmas` and its scores, words contains in `lemma_to_word`. Parameters ---------- extracted_lemmas : list of (float, str) Given lemmas with scores lemma_to_word : dict Lemmas and corresponding w...
385a54878e508a56ab772fec31f4ff9838048492
56,957
def url_scan_sync(url, timeout): """ Execute SlashNext's url/scansync API against the requested URL scan sync with the given parameters :param url: URL to be scanned :param timeout: Timeout value in seconds :return: Response of the SlashNext url/scansync API """ # Create the required data di...
feb60c21124ca61cd4776f0fc2c067310b37cafe
56,958
def create_app(config_object='webfront_service.settings.__init__'): """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split('.')[0]) app.config.from_object(config_object) ...
ce01d13da269063d3886f4614426ec69d14802c8
56,959
def get_user_friend_profiles(proxies, auth, limit=None, user_id='', screen_name='', skip_status='', include_user_entities=''): """ Returns a list of user dictionaries for every user the specified user is following (otherwise known as their 'friends'). Either either user ID or screen name, if both are specif...
0dd00c095b366088c4c17d9b7cab44266bfb09d6
56,960
def deci_class_logger(): """ This decorator wraps every class method with deci_func_logger decorator. It works by checking if class method is callable and if so it will set a new decorated method as the same method name. """ def wrapper(cls): # TODO: Not Working - Breaks the code, tests doe...
69a4fa9c70ee37ec20d0cfd0aba2ad2f1bbd7dac
56,961
from typing import List from typing import Dict from typing import Tuple from typing import Optional async def apply_actions( conns: Connections, conv_id: int, actions: List[Action], *, spam: bool = False, warnings: Dict[str, str] = None, allow_multiple_actors: bool = False, ) -> List[int]...
172650023ebc39045f85b7cbe2c837bc8bd9bc3c
56,962
def _file_metadata_by_replacing_path(f, new_path, new_is_dir=None): """Returns a copy of the f _file_metadata struct with the given path.""" root_path = _get_opt_attr(f, 'rootPath') if new_is_dir == None: new_is_dir = f.is_dir return _struct_omitting_none( path=new_path, src=f.src, root=r...
c38930f17664843525cad6afe0eb580282abac49
56,963
import re def tokenize(text): """" Tokenization function for use in TfidfVectorizer in build_model() 1. Normalizes text (converts to lowercase) 2. Removes punctuation 3. Removes stop_words 4. Splits sentence into words (tokens) 5. Performs POS tagging Parameters: text: string to b...
f1903b3151a3a42622ec8ee3f9cf31ff51d64b63
56,964
def transform_gcp_firewall(fw_response): """ Adjust the firewall response objects into a format that is easy to write to Neo4j. Also see _transform_fw_entry and _parse_port_string_to_rule(). :param fw_response: Firewall response object from the GCP API :return: List of transformed firewall rule obje...
d9d6d1a9dfcbd0e7eb2b51a67c0d35ab55768384
56,965
import requests def export_highlights_to_readwise(readwise_token, highlight_objects): """ Submits highlights to Readwise via their API and return the API response. The function takes 2 parameters: - readwise_token: the token used for accessing the user's Readwise highlights through the Readwise API. ...
c6b2928aa488fb62d40470e441232ed67d61a020
56,966
def test_reddit(): """The ShareOnReddit link enables sharing a link to an url on Reddit. Here we test that - The link can be instantiated with a link to https://awesome-panel.org - It works when clicked """ return TestApp( test_reddit, ShareOnReddit(url="https://awesome-panel.org")....
5035521ae933ad1b433fc91348f587e730dd1ed7
56,967
from typing import List def filter_relative_import_names(import_names: List[str]) -> List[str]: """Given a list of import names, filters out the relative import names.""" return list(name for name in import_names if is_relative_import_name(name))
d4d4c43584f496d9d3392861dbb5cbf559a97f1e
56,968
import pickle def make_pred_dataframe(key, mask, image): """Takes an image id and a mask and returns a dataframe with all cells""" classes = ["tumor", "immune cells"] with open(c.MODEL_DIR / "cell_classifier.pickle", "rb") as f: features, model = pickle.load(f) df_pred = pd.DataFrame( ...
9148ecd9f7428aebe77e29b309d3398b92cc3e4a
56,969
def initialize_omlet_config(cfg: DictConfig): """ See _omlet_config_schema() """ assert isinstance(cfg, DictConfig) OmegaConf.set_struct(cfg, False) om = _omlet_config_schema() om.update(cfg.get('omlet', {})) cfg.omlet = om # this is a copy operation om = cfg.omlet om._internal...
d041d844aca394bf43825cd1ab37820f1d868c8e
56,970
import os def path(name=""): """ Retrieve the relative filepath to a supplied name from the BrightEdge root directory. If the name begins with a "/", then consider the supplied name to be an absolute path. Example: If BrightEdge Root is: /home/vagrant/modbus_simu_cli path() will return "/...
d4ccd6edd34c4d0576e0b1e9d6322d9ca708a4cb
56,971
def h(p1, p2): """Heuristic function""" x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2)
0d7522a3f92ae851bfa9b1a316a1fa97baccf98f
56,972
import torch def pdist(X, Y): """ Computes all the pairwise distances Parameters ---------- X : torch.tensor shape [n, d] Y : torch.tensor shape [m, d] Returns ------- torch.tensor shape [n, m] of all pairwise distances """ n, m = X.shape[0], Y.shape[0...
10fce38b390211999344bd1b0daf0a4484aee2a8
56,973
def detab(self, elem="", lab="", v1="", v2="", v3="", v4="", v5="", v6="", **kwargs): """Modifies element table results in the database. APDL Command: DETAB Parameters ---------- elem Element for which results are to be modified. If ALL, modify all selected elements [ESE...
01f13f7e971c2c24e291712a7e634838e2e2ac5a
56,974
from typing import Optional def retriever_factory( opt: Opt, dictionary: DictionaryAgent, shared=None ) -> Optional[RagRetriever]: """ Build retriever. Override to build special BB2 Search Retrievers, if necessary :param opt: ParlAI Opt :param dictionary: dictionary agent ...
aa37babfffabf5491c542fa173352080b702f180
56,975
import argparse from typing import Dict from typing import Tuple from typing import List def add_target_parser( target: Target, subparsers, common: argparse.ArgumentParser, existing: Dict[str, Tuple[argparse.ArgumentParser, List[str]]], ) -> str: """Add a subparser for a given build target Fo...
941c7e9e1e7fefed148ad93cff5e28e36bf2a816
56,976
import pathlib import json def import_skin_data(mesh_name: str, path: pathlib.Path, import_type: ImportType = ImportType.order): """ Load skin data from disk and apply it to the given mesh. """ with open(path, "wb") as path_data: skin_data = json.load(path_data) return set_skin_weights(mesh_name, skin_data) ...
ef34bbe580000ead33a427c1f45c22243cad4398
56,977
from typing import List from typing import Dict def combine_fields( fields: List[xr.DataArray], field_record: Dict, dim: str="valid_time", ) -> xr.DataArray: """ 按维度 step 合并 """ field = xr.concat(fields, dim=dim) return field
df1973443eadd18730b0cb195bc41539ba53da72
56,978
import warnings def derivest(fun, x, par = None, **kwargs): """ Estimate the derivative of a function of one variable. Arguments: fun : Callable object with signature fun(x, *args) -> float, with x the (scalar) argument, and args an optional list of parameters. ...
7a66b5499ccb5e72125a2b323929c2196d747c48
56,979
def norm(vec): """ Calculate norm of a vector or list thereof Args: vec (Vector or List[Vector]): vector(s) to compute norm of Returns: Scalar or List[Scalar]: norms """ if len(vec.shape) == 1: # it's just a single column vector return np.sqrt(vec.dot(vec)) else: # tr...
c225467905ccd30b826d8ef5e0112bb23f106ec9
56,980
import PIL def get_image_size(img_filename,img_directory_path): """ Return the size of the specified image img_filename : the name of the image file img_directory_path : the path to the directory where the image is Return : (width, height) width : the width in pixel of the image height : t...
b46934940f1c62f9110efa219e042a39026db76c
56,981
import torch def train_deep_encoder(torch_dataset, model, optimizer, criterion, lr, n_epochs, batchsize, verbose=False): """Train label encoder for categorical features Parameters ---------- torch_dataset : Torch_Dataset Dataset to feed the NN containing categorical fea...
c89aa6be474233d7521361190f7fdfc0b1cc29a3
56,982
def convert(s): """ Convert a probability string to a float number. :param s: probability string. :return: a float probability. """ try: return float(s) except ValueError: num, denom = s.split('/') return float(num) / float(denom)
84333f21edfdcb2f3c917f23c23b9d399c5f6e56
56,983
def tree_ones_like(tree: Pytree) -> Pytree: """ Return a new tree with the same structure as t, but with all values set to 1. """ return jax.tree_util.tree_map(lambda x: jnp.ones_like(x), tree)
3fa06e05111741eda6a5af8f558e2e6dce29755e
56,984
def writeOctetStream(oStr, minValue = 0): """ @summary: write string as octet stream with per header @param oStr: octet stream to convert @param minValue: min length value @return: per header follow by tuple of UInt8 """ length = len(oStr) mlength = minValue if length - minValue...
0eeb4578f51b4488e762d3f49b1d5c5accdd5b4d
56,985
from typing import Sequence def _find_fuzzy_line( py_line_no: int, py_by_line_no: Sequence[str], cheetah_by_line_no: Sequence[str], prefer_first: bool, ) -> int: """Attempt to fuzzily find matching lines.""" stripped_line = _fuzz_py_line(py_by_line_no[py_line_no]) cheetah_l...
07e088df7ca73d52d47d37ff0971c43c496bc68a
56,986
def ensemble_adjustment_kalman_filter_update( state, observation, observation_fn, minimum_observation_prior_variance=None, name=None): """Ensemble Adjustment Kalman Filter Update. The Ensemble Adjustment Kalman Filter (EAKF) [1], is a deterministic variant of the [Ensemble Kalman Filter]( h...
19738e67bfafa3866ea7dfbca6adbf7181636384
56,987
def S_vib(r,r0,B0,M,grun,T): """Vibrational entropy.""" x = debye_temp(r,r0,B0,M,grun) / T return 3*kb*(4.0/3*debye_func(x) - np.log(1-np.exp(-x)))
4fbbde4a33219947d523e2ab3d190a441a77333d
56,988
def countExtn(fimg, extname='SCI'): """ Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions. """ closefits = False if isinstance(fimg, string_types): fimg = fits.open(fimg) closefits = True n = 0 for e in fimg: if 'extn...
44051dcef1bef901d4905d7b4b805dc9140a32c0
56,989
def tensor(dimensions): """ Create a tensor :param dimensions: The list of dimensions :return: A tensor """ global csp check_engine() csp.variables.append(csp.int(size=None, deep=dimensions)) return csp.variables[-1]
e96338ed9df016bb425642f4fd05de4775aa2d92
56,990
import random def makeData(test=False): """ Make the data and return a dict that contains the data and goal.""" # open the files, I already made them smaller; they contain 3000 pics each Ball = np.load("../data/sBasketball.npy") LightBulb = np.load("../data/sLight_bulb.npy") Sun = np.load("../dat...
427fca4cb41b776f4281dadda2971930214a2864
56,991
from typing import Union from pathlib import Path import re def model_from_checkpoint( filename: Union[Path, str], model_name=None, backbone_name=None, classes=None, is_coco=False, img_size=None, map_location=None, strict=False, revise_keys=[ (r"^module\.", ""), ], ...
4296da4efc9499a8d10d09a5c0a2329bbc8cb54d
56,992
def get_problem(pid=None, name=None, tid=None, show_disabled=True): """ Gets a single problem. Args: pid: The problem id name: The name of the problem show_disabled: Boolean indicating whether or not to show disabled problems. Defaults to True Returns: The problem dictio...
5e781b867bd4ebc26d451e522262a954dd2ea27c
56,993
def mock_boto_client_upload_success(*args, **kwargs): """ Mock boto client, so uploading always returns success """ return MagicMock()
3fec23fa670a9066ae9fc881d0cf1d874f9cf480
56,994
def git_log_file(file_name): """要求文件路径是相对于git仓库更目录到文件完整路径""" cmd = "git log -1 %s |grep Date" % file_name return cmd
e7d0481d4ee7e1a68492df07ed9c35e95a87ab5c
56,995
import json def sfjson_loads(s): """Exception safe json.loads()""" try: return rlk_jsonloads(s) except json.decoder.JSONDecodeError: return {}
cbc7bc01d895cc0cce46b9c8d865eeee31442e3d
56,996
import math def calc_tols(polys_truth, tick_dist=5, max_d=250, rel_tol=0.25): """ Calculate tolerance values for every GT baseline according to https://arxiv.org/pdf/1705.03311.pdf. :param polys_truth: groundtruth baseline polygons (normalized) :param tick_dist: desired distance of points of the baseline...
c26cecf5a8bdd2fbca85aa1d3bc6fce4593869e2
56,997
def to_terminal(group: list, outcomes: list) -> float: """ Create a terminal node value :param group: group of samples with target as last element :return: most representative class value for group """ outcomes = [row[-1] for row in group] return [max(set(outcomes), key=outcomes.count), outc...
886c397aaef82d1e38c371436c69b4152f6ce760
56,998
def _log_multivariate_normal_density_spherical(X, means, covars): """Compute Gaussian log-density at X for a spherical model.""" cv = covars.copy() if covars.ndim == 1: cv = cv[:, np.newaxis] if cv.shape[1] == 1: cv = np.tile(cv, (1, X.shape[-1])) return _log_multivariate_normal_dens...
f74f18c76103bed534c1d98c4931dab9a2f12a72
56,999