content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def lidar_to_camera(points, r_rect, velo2cam): """ transformation from lidar coordinate to camera coordinate :param points: non-homo coodinates [..., 3] or homogeneous coordinates [..., 4] :param r_rect: [4, 4] camera rectification matrix :param velo2cam: [4, 4] transformation from velo to camera :...
6f259ba6c81b7e2956937e62bbc99e07cdc071bf
3,613,100
import jinja2 def _render(value, params): """Renders text, interpolating params.""" return str(jinja2.Template(value).render(params))
b8d9698dfaf1c2500abfa272c8da98a0cf3dd482
3,613,101
def expand (properties): """ Given a property set which may consist of composite and implicit properties and combined subfeature values, returns an expanded, normalized property set with all implicit features expressed explicitly, all subfeature values individually expressed, and all ...
2ea6eb3159414f04bdd8571ba3bdc63ea15400aa
3,613,102
def login_required(f): """Redirects requests to /login if the user isn't authenticated""" @wraps(f) def decorated_function(*args, **kwargs): user_id = session.get('user_id', None) if user_id: user = User.query.filter_by(id=user_id).one_or_none() if user is not None: ...
0e61a1e6e0da98a502e9ccc204d26da903003a64
3,613,103
def ClusterSetSslCert(mvip, username, password, cert, key): """ Set the SSL certificate used by the cluster Args: mvip: the management IP of the cluster username: the admin user of the cluste...
b4f4794cec600ee887551a9cb489e2944d44110e
3,613,104
def organization_daily_metrics_view(request): """ :param request: :return: """ # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'verified_volunteer'} if not voter_has_authority(request, authority_required)...
512383e4987efd9c7e357c7363fd6f15b36d0794
3,613,105
def from_gen( generator, n_iter, width, height, range, make_xy_proportional=False, log=False ): """Create a 2D histogram with `width * height` bins from `generator`. The generator should be compiled using Numba's `njit` or `jit`. Parameters ---------- generator : generator() -> x, y A ...
66018fcc0beb268ff2644ba5da01f104006b274f
3,613,106
import math def inWhichGrid(coord, grid_info): """ Specify which grid it is in for a given coordinate :param coord: (latitude, longitude) :param grid_info: grid_info dictionary :return: row, column, grid ID """ lat, lng = coord row = math.floor((grid_info['maxLat'] - lat) / grid_info['...
260d31b57413902febf503ac3f7a11232940d245
3,613,107
import os import sys def find_executable(executable, path=None): """Find if 'executable' can be run. Looks for it in 'path' (string that lists directories separated by 'os.pathsep'; defaults to os.environ['PATH']). Checks for all executable extensions. Returns full path or None if no command is found....
265b5f088147628bae25902677011a71c7628de2
3,613,108
def aup(): """Send the user to Acceptable Use Policy page""" # Read AUP from markdown dir domain_name = domain_name_edgecase() with open( brand_dir + "/" + domain_name + "/signup_content/signup_modal.md", "r" ) as file: aup_md = file.read() return render_template("AUP.html", aup...
96059408cf368fe00210b684f02a00a2b4a03d39
3,613,109
def transpose(matrix): """Matrix transpose Args: matrix: list of list Returns: list: list of list """ return list(map(list, zip(*matrix)))
22c45de26bc19ca69ac0d04af8e2e02697290035
3,613,110
from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StringType, IntegerType, DoubleType, DateType, BooleanType, TimestampType import os from pathlib import Path import gzip import shutil def download_metadata_file(url, outputdir, program, max_age=None): """ :param url: :param o...
f5e623f2a0e26c91638dbc9a3426109b42dccee1
3,613,111
from datetime import datetime def timestamp(s, tz=None): """Parse a HOBO timestamp value to Python DateTime""" for fmt in TIME_FMTS: try: dt = datetime.strptime(s, fmt) return dt.replace(tzinfo=tz) if tz else dt except ValueError as e: pass raise ValueEr...
79647ce17ef38f803c9073d2ba4075f3b93a3ec6
3,613,112
def decodeVarint32FromHttp(response): """Decode an 32 bit integer from a varint byte representation. Expects an HTTP Response to read from. """ return _HttpDecodeVarint32(response)
b35886873bd15d608a8408907f80225c321ad869
3,613,113
def get_schema_names(): """Return a dict of vertex and edge base names.""" names = [] # type: list for path in _find_paths(_CONF['spec_paths']['schemas'], '*.yaml'): names.append(_get_file_name(path)) return names
9b746b756f7f8cd27e8a26dfcc9184d00cf58bd3
3,613,114
import os def enumerate_any_files(source_directory, variant_directory = ""): """Forms a list of all files in a project directory @param source_directory Directory containing all of the source files @param variant_directory Variant directory to which source paths will be rewritten""" files =...
f7d6fd89492c8a9f7687cf29da2386a997357a71
3,613,115
def gen_fix_fixups(*args): """ gen_fix_fixups(_from, to, size) Relocate the bytes with fixup information once more (generic function). This function may be called from 'loader_t::move_segm()' if it suits the goal. If 'loader_t::move_segm' is not defined then this function will be called automatically when...
b5e7e1b82c5f1a38fd5c48762cf873f5c4e117c6
3,613,116
import math def line_fit(x,y): """Least-squares fit intercept and slope .. versionadded:: 1.2 :arg x: sequence of independent variable data :arg y: sequence of dependent variable data :rtype: a :class:`~type_b.LineFitOLS` ``y`` must be a sequence of uncertain real...
941e039b1b3d56f4f45e814227b89f88d9c9fc06
3,613,117
import pytz def parse_resolution(json): """ Parse a JSON response from the server into a Resolution object. """ frequency = Frequency.by_tag(json.get("frequency")) timezone = pytz.timezone(json.get("timezone")) return Resolution(frequency, timezone)
e5e64c98aad5f3ef357fda95b3d71068a22e5731
3,613,118
def unbiased_ccd_image_dict(ccd, **kwargs): """Get the images keys by amp for a ccd Parameters ---------- ccd : `MaskedCCD` or `ImageF` CCD data object Keywords -------- bias : `str` or `None` Method for bias subtraction superbias_frame : `MaskedCCD` or `None` B...
bf5637a6f6e6538e615102e43cd45a0a1ffb1ea8
3,613,119
def get_learning_rate_scheduler(optimizer, args): """Build the learning rate scheduler.""" # Add linear learning rate scheduler. if args.lr_decay_iters is not None: num_iters = args.lr_decay_iters else: num_iters = args.train_iters num_iters = max(1, num_iters) init_step = -1 ...
9dcc1350f63aa719a5fffbf7ec0c756186dbfe6d
3,613,120
import tempfile import pkg_resources def plot_raster(demeter_gdf, landclass_list, target_year, font_scale=1.5, scope='conus', resolution='0.083333', value_to_nan=True, nan_less_than=0.01, na...
f333b99df7b420ae208e6e7a48a2dbffb944ec8f
3,613,121
import argparse def parseargs() -> argparse.ArgumentParser: """ Parse arguments """ parser = worker.parseargs('Shadowserver ASN enrichment') parser.add_argument( '--country-codes', help="Should point to file downloaded from {}".format(ISO_3166_FILE)) group = parser.add_mutually_exclus...
8cbfd852b19a847f331d5b4e89cf346be1fbb2ed
3,613,122
def meshgrid(*xi, **kwargs): """Return coordinate matrices from coordinate vectors. Given one-dimensional coordinate arrays x1, x2, ..., xn, this function makes N-D grids. For one-dimensional arrays x1, x2, ..., xn with lengths ``Ni = len(xi)``, this function returns ``(N1, N2, N3, ..., Nn)`` shap...
72af359258994b69a80ef11a3005a03f624bc853
3,613,123
def y_dot(t,y,x,nu,F): """y_dot(t,y,x,nu,F) Describes the differential equation for velocity as given in CW 12. """ return -(nu*y)+x-(x**3)+(F*np.cos(t))
c9494fe04ba01785872ba238387f938f9f53e72e
3,613,124
from re import DEBUG def write_or_cache(outvolume, vol_to_write, buffer, cache, data): """ Arguments: ---------- outvolume: Volume object representing the output block vol_to_write: Volume object representing a write buffer which will write into the output block represented by outvolume...
8c148d7e3c79bffd2f3100d77703fd9ed3f3a4f5
3,613,125
def split_code_into_blocks(code): """Split code into blocks of code, comments, and string literals.""" def is_noncode_start(code, idx=0): """String starts something other than source code (eg, a comment).""" return (is_quote(code, idx) or is_multiline_comment_start(code, idx) o...
47d4faf1f8dc9be7ace265926598496b96ba1150
3,613,126
def lstExcel(filepath, colname): """ lstExcel function analyses the excel file and creates a list of the elements, that should be translated. Parameter: filepath:str: Path of the excel file. colname:str: Name of the column to be translated. Returns list. """ df = pd.read_excel(fi...
d49e75e4e7974cad9fb925de083db099705050d6
3,613,127
def get_model_json_string(model_bigg_id): """Get the model JSON for download.""" path = join(settings.model_dump_directory, model_bigg_id + '.json') try: with open(path, 'r') as f: data = f.read() except IOError as e: raise NotFoundError(e.message) return ...
bb635c4c52d8a584a50efe9f55a5590fdb73fa8a
3,613,128
def compute_shot(way, labels): """Computes the `shot` of the episode containing labels. Args: way: An int constant tensor. The number of classes in the episode. labels: A Tensor of labels of shape [batch_size]. Returns: shots: An int 1D tensor: The number of support examples per class. """ class...
324919b0a73e7c0add83d392e14aab13cb269477
3,613,129
def new_line(string: str): """ Append a new line at the end of the string Args: string: String to make a new line on Returns: Same string with a new line character """ return string + "\n"
f4deeaa94a6980f95a3020fa54570fbe1f0a6e9e
3,613,130
import subprocess def git_commit_and_push(branch: str): """Command to git checkout, commit, and push branch""" subprocess.run( ["git", "add", "build/"], cwd=settings.TRANSLATION_REPOSITORY_DIRECTORY ) subprocess.run( ["git", "commit", "-m", f"{branch}"], cwd=settings.TRANSLATIO...
eec97ba26054fe680908671f59b1cbe3cb5a370b
3,613,131
def convert_to_unicode(text, encoding='utf-8', errors='ignore'): """字符串转换为unicode格式(假设输入为utf-8格式) """ if isinstance(text, bytes): text = text.decode(encoding, errors=errors) return text
6c7d9a7788cd596a9a31a2b8f2aacd25e99c1813
3,613,132
import itertools def decaying(start, decay): """Return an iterator of exponentially decaying values. The first value is ``start``. Every further value is obtained by multiplying the last one by a factor of ``decay``. Examples -------- >>> from climin.schedule import decaying >>> s = dec...
ee88365b3a8e768952fc66d02047b60e3e1a34c1
3,613,133
from pytz import timezone from datetime import datetime def chime_local_datetime(*args): """Create a :class:`datetime.datetime` object in Canada/Pacific timezone. Parameters ---------- *args Any valid arguments to the constructor of :class:`datetime.datetime` except *tzinfo*. Local da...
70c0f8bbe53051514ae48e554924e73c5d2f6327
3,613,134
def build_calling_regions(contigs, regions_to_include, regions_to_exclude): """Builds a RangeSet containing the regions we should call variants in. This function intersects the Ranges spanning all of the contigs with those from regions_to_include, if not empty, and removes all of the regions in regions_to_excl...
13d59aedb55c3728559d5434f366448f9df642f7
3,613,135
import inspect def _is_bound_method(the_function: object) -> bool: """ Returns True if fn is a bound method, regardless of whether fn was implemented in Python or in C. """ if inspect.ismethod(the_function): return True if inspect.isbuiltin(the_function): self = getattr(the_fun...
a0d3121c6c4e1c26b2000af73e25a3d772ef2ad3
3,613,136
import urllib import hmac def _is_valid_output_hash(outputs): """Test if a set of outputs have valid hashes on the staging channel. Parameters ---------- outputs : dict A dictionary mapping each output to its md5 hash. The keys should be the full names with the platform directory, ver...
5c750cc9344e12d44c324a0e057d945fe0adcf97
3,613,137
from sys import flags def _CreateSubnetwork(messages, subnet_ref, network_ref, args, include_alpha_logging, include_beta_logging, include_l7_internal_load_balancing, include_private_ipv6_access): """Create the subnet resource.""" subnetwork = messa...
c8cb23bf1a0e8a90909bc744342b759e3ac6c3de
3,613,138
import os import math import time def convert_video_to_numpy(filenames, width, height, n_frames_per_video, n_channels, dense_optical_flow=False): """Generates an ndarray from multiple video files given by filenames. Implementation chooses frame step size automatically for a equal separation distribution of the vi...
4faedf202bb582a20a39f65c2f9009b1d554de2b
3,613,139
def rm_clusters(name): """ Requires the following pillar to be set: - ceph-salt:execution:fsid """ ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} fsid = __salt__['pillar.get']('ceph-salt:execution:fsid') __salt__['ceph_salt.begin_stage']("Remove cluster {}".format(fsid...
08d4cb05ef1d681891b525196a1fe98e05a5a5ac
3,613,140
def micro_averaged_auprc(df_dict, return_df=False): """ Compute micro-averaged area under the precision-recall curve (AUPRC) from a dictionary of class-wise DataFrames obtained via `evaluate`. """ # List all unique values of thresholds across coarse categories. thresholds = np.unique( np...
b6d53dc94c25d8bf1c66cfa550cacfd90ccca357
3,613,141
def d2vardx2(var, lon, lat, xdim, ydim, cyclic=True, sphere=True): """ calculate second center finite difference along x or longitude. https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py :param var: ndarray, grid values. :param lon: array_like, longitude ...
d7ea5abbfca0ff702b42601724d57f414ec52df7
3,613,142
import json def get_chain() -> str: """ Endpoint to query all of the data to display """ chain_data = [] for block in blockchain.chain: chain_data.append(block.__dict__) return json.dumps({"length": len(chain_data), "chain": chain_data})
6a3e0cde6a737e8d706f632556efaafed847de5b
3,613,143
def read_terrace_csv(DataDirectory,fname_prefix): """ This function reads in the csv file with the extension "_terrace_info.csv" and returns it as a pandas dataframe Args: DataDirectory (str): the data directory fname_prefix (str): the name of the DEM Returns: pandas datafr...
7005b47553f8b9d2b6852a58efa751b65d737ba9
3,613,144
import tqdm import torch def eval_net(net, loader, device, n_val): """Evaluation without the densecrf with the dice coefficient""" net.eval() tot = 0 with tqdm(total=n_val, desc='Validation round', unit='img', leave=False) as pbar: for batch in loader: imgs = batch['image'] ...
d3c9d9ce57e51d39c83c894d36817362c8980560
3,613,145
def load_image(file_path, average=True): """ Load data from an image. Parameters ---------- file_path : str Path to a file. average : bool, optional Average a multi-channel image if True. Returns ------- array_like """ if "\\" in file_path: raise Val...
a879f89c9d015181ce43f627f94992796fa0a284
3,613,146
def interp(frame, idx, **args): """ Get interpolated values at indices """ unique_idx = [i for i in idx if i not in frame.index] aug_frame = frame.append(pd.DataFrame(index=unique_idx), sort=True) in_frame = aug_frame.sort_index().interpolate('index', **args) return in_frame.loc[idx, frame.columns]
9a10c48e2998dca2128d46d9fac9f7f70f2d2874
3,613,147
def calcStateTransitionMatrix(orbit, dt, mu=0.0002959122082855911, max_iter=100, tol=1e-15): """ Calculate the state transition matrix for a given change in epoch. The state transition matrix maps deviations from a state at an epoch t0 to a different epoch t1 (dt = t1 - t0). Parameters ---------- ...
3f107a34c0ef11d755065e11766c25e22656322f
3,613,148
def macro_calc(item): """ Calculate PPV_Macro and TPR_Macro. :param item: PPV or TPR :type item:dict :return: PPV_Macro or TPR_Macro as float """ try: item_sum = sum(item.values()) item_len = len(item.values()) return item_sum / item_len except Exception: ...
ec74fe80a4f52d7676beeca1f9abd701043c77af
3,613,149
def convert_from_pj_fat_food(pj_fat_food): """ Convert the given PyJSON Fat-Food to a Natural :param pj_fat_food: The PyJSON Fat-Food being converted :type pj_fat_food: PJ_FatFood :return: The resulting Natural :rtype: Natural """ if not is_pj_fat_food(pj_fat_food): raise ValueError(...
a4e6b635e9406f0bada11f131e09e12e047f299b
3,613,150
def raw_to_multiindex(raw_df, name): """ Takes a raw dataframe (vertically oriented) and transforms it in a multiindexed one. The indices are (date, feature). """ iterables = [raw_df.index, raw_df.columns] index = pd.MultiIndex.from_product(iterables, names=[DATE_COL, FEATURE_COL]) data_df =...
5a02c1a7faf12293a92d4f239cab69351784bf42
3,613,151
def sizeof_fmt(num, suffix='B'): """Size to human readable format. From stack overflow. """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
f4b568f35e152519a12d7a154e93fa71828d5976
3,613,152
from typing import Optional def op_register(tag: str, selector: str, info: str, min_version: Optional[str] = None): """ Decorator used for registering operational-data items with the op catalog. The class being decorated needs to be a subclass of OperationalItem. @param tag: Tag string associated with...
d1271251789a6dfbf3fc29a9dcdeae506f6c02bc
3,613,153
def macdext(candles: np.ndarray, fast_period: int = 12, fast_matype: int = 0, slow_period: int = 26, slow_matype: int = 0, signal_period: int = 9, signal_matype: int = 0, source_type: str = "close", sequential: bool = False) -> MACDEXT: """ MACDEXT - MACD with controllable MA type :...
9cf3db38be7f705a7a3b2c6bf48b4ac601109735
3,613,154
def user_info(): """ 个人中心 :return: """ user = g.user if not user: return credits("/") data = { "user_info":user.to_dict() } return render_template("/news/user.html", data=data)
12b527595323d043ae2a6aef13401ca4c1dd6a20
3,613,155
def height_implied_by_aspect_ratio(W, X, Y): """ Utility function for calculating height (in pixels) which is implied by a width, x-range, and y-range. Simple ratios are used to maintain aspect ratio. Parameters ---------- W: int width in pixel X: tuple(xmin, xmax) x-range i...
8c3225a27f0284acb708434238d4861bb49b0899
3,613,156
def convert_to_valid(seq, correction_dictionary=None, alignment=False): """ Function that converts non-standard amino acid residues to standard ones. Specifically: B -> N U -> C X -> G Z -> Q ' ' -> <empty string> (i.e. an empty space) * -> <empty string> - -> <empty string> (ON...
1fe1f934a6c4ba92be988bb310600aee3356b95c
3,613,157
def CTPixel8_getPixelName(): """CTPixel8_getPixelName() -> char const *""" return _VPLPython.CTPixel8_getPixelName()
01cb3ae9fe00370806f42c15373dca5f856219c1
3,613,158
import os def get_output_folder_path(provided_folder_path, first_font_path): """ If the path to the output folder was NOT provided, create a folder in the same directory where the first font is. If the path was provided, validate it. Returns a valid output folder. """ if provided_folder_pa...
52b326f6cae70b520197417cf167baec78a22388
3,613,159
from datetime import datetime def create_access_token(identity: str) -> bytes: """Create a jwt based on identity.""" payload = { "identity": identity, "exp": datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS), } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) # ty...
bb257506df76d004466be210bd374a9363b54909
3,613,160
import site def apply_vs30_mod_non_parametric( im_values: pd.DataFrame, site_info: site.SiteInfo, im: IM ) -> pd.Series: """Applies the user vs30 modification for non-parametric data""" assert "PGA" in im_values.columns pga = im_values["PGA"].copy() return im_values[str(im)] * __get_site_amp_rati...
c8006ce81dff810f2505af7f30225b4ad713d175
3,613,161
def calc_earfcn(low_freq_hz: int, high_freq_hz: int) -> int: """ Calculate EARFCN in mhz for CBRS Args: low_freq_hz: int, Low frequency limit taken from available channel high_freq_hz: int, High frequency limit taken from available channel Returns: EARFCN in mhz """ mid...
f757f94d65af96289fd5fe360fceb7a055788c44
3,613,162
def sortino_ratio(returns, required_return=0, period=DAILY): """ Determines the Sortino ratio of a strategy. Parameters ---------- returns : pd.Series or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. returns_s...
fffc6552f23f676d9a460e23383300dbc897218a
3,613,163
def confusion_matrix( prediction_detections: ndarray, truth_detections: ndarray, threshold: float = DEFAULT_NEG_THRESHOLD, num_foreground_classes: int = 3, ) -> np.ndarray: """ Compute confusion matrix to evaluate the accuracy of a classification. By definition a confusion matrix :math:`C` is s...
2c12478668e5ea421e98b9dfaaf75638d8c35bb7
3,613,164
def subsol_vector(str1, str2, in11, str3, str4): """subsol_vector(ConstSpiceChar * str1, ConstSpiceChar * str2, ConstSpiceDouble * in11, ConstSpiceChar * str3, ConstSpiceChar * str4)""" return _cspyce0.subsol_vector(str1, str2, in11, str3, str4)
30b59f04243c9b299848408a66eb05eb2f45305f
3,613,165
def compute_per_char(ground_truth, predictions): """ compute per char accuracy :param ground_truth: :param predictions: :return: """ accuracy = [] for index, label in enumerate(ground_truth): prediction = predictions[index] total_count = len(label) correct_count =...
dc33b3cf7890755d9c9ef5901b4201e572323a4a
3,613,166
def getBinaryFormat(name: str) -> type[BinaryFormat]: """ Looks up a binary format by its name attribute. Returns the binary format with the given value for its name attribute. Raises KeyError if there is no match. """ return _formatsByName[name]
41461d9426bac31b934490aacf7b9c1b2d0ba2c4
3,613,167
import scipy import time import numpy import multiprocessing def cholesky_method( A, B=None, gram=False, exponent=1, invert_cholesky=True, cholmod=None): """ Computes trace of inverse of matrix using Cholesky factorization by .. math:: \\mathrm{tra...
a502e29684e0f348b44e6a4897a0904aea503224
3,613,168
def extractNextlevelforthePLOT(item): """ 'Next level for the PLOT' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp is not None or vol is not None or frag is not None) or 'preview' in item['title'].lower(): return None if 'scan-trad' in item['tags']: return None ...
983a0c1a9605922d15ee47be934cdd82bce58517
3,613,169
def kitti_squeezeSeg16_config(): """Specify the parameters to tune below.""" mc = base_model_config('KITTI') mc.CLASSES = ['unknown', 'car', 'pedestrian', 'cyclist'] mc.NUM_CLASS = len(mc.CLASSES) mc.CLS_2_ID = dict(zip(mc.CLASSES, range(len(mc.CLASSES)))) mc...
7ed52b9b20f5f1cc04220df137470fd0050fe2a0
3,613,170
def filter_modules(command_loader, help_file_entries, modules=None, include_whl_extensions=False): """ Modify the command table and help entries to only include certain modules/extensions. : param command_loader: The CLICommandsLoader containing the command table to filter. : help_file_entries: The dict of...
2f0ec2164a67abc9c691e66a0470977a06d51b97
3,613,171
import os async def async_setup(hass, config): # pylint: disable=unused-argument """Set up this component.""" _LOGGER.info(STARTUP) config_dir = hass.config.path() github_token = config[DOMAIN]["token"] if config[DOMAIN]["appdaemon"]: ELEMENT_TYPES.append("appdaemon") if config[DOMAI...
d4465e9c8c77d1d09859946f18ab64f673d86575
3,613,172
from texar.agents.agent_utils import Space def convert_gym_space(spc): """Converts a :gym:`gym.Space <#spaces>` instance to a :class:`~texar.agents.Space` instance. Args: spc: An instance of `gym.Space` or :class:`~texar.agents.Space`. """ if isinstance(spc, Space): re...
d9362e00a95a76a60d9aaf6b6935dc9ec5bb92d6
3,613,173
from typing import List def save_inventory( session: SessionABC, inventory: List[InventoryType], merge_samples: bool = False ) -> List[InventoryType]: """Saves a list of inventory items to the server. :param session: the AqSession instance :param inventory: list of inventory items :param merge_sa...
d01956ba2334a3ab824845a4db3261fbdec25a94
3,613,174
def positional_encoding(max_position, d_model): """Return the tensor encoding the position of elements in a sequence Compute the positional encoding with a combination of sinusoidal functions as suggested in (Vaswani at al., "Attention is all you need", 2017) Note: When we add the positional e...
7ecc8ba093ab9be744ba945975fdb57570fc09be
3,613,175
import re def get_namespace(element): """Extract the namespace using a regular expression.""" match = re.match(r"\{.*\}", element.tag) return match.group(0) if match else ""
9380e104d05ae6b56463b96bf87d9c0fcd8202cf
3,613,176
import os def get_model_name(filename): """ >>> get_model_name("logs/0613/0613-q1-0000.train") '0613-q1-0000' """ return os.path.splitext(os.path.basename(filename))[0]
a050918e827b6cbce0ecb19d002cc30619f34c6e
3,613,177
import numpy def create_LOFAR_configuration(antfile: str, meta: dict = None, params={}): """ Define from the LOFAR configuration file :param antfile: :type str: :param name: :type str: :param meta: :type dict: :param params: Dictionary containing paramet...
affed3d6e7c7fa24d434fb51af5f15648a7e202e
3,613,178
import random def get_fittest_solution(solutions): """Return the fittest of the passed solutions, using tie-breaking criteria if there are ties and only using random tie-breaking as a last resort""" # ensure that there are solutions if not solutions: return None # a single solution is the ...
9bdf8274e9f8be491da2de14b76114e95c4f0584
3,613,179
import json def get_subs_v2(request: Request) -> HTTPResponse: """根据域名模糊匹配手动指定并获取订阅,在 Debug 部署模式下请求的订阅不会被删除。 如:要获取订阅 https://www.modu.me/link?token=123, 传入 modu 或 mod 或订阅实例所对应的 action-alias 既可匹配 alive action-alias 通过 pool_status() 获知, alias 格式为 Action[Something]Cloud,如 ActionModuCloud :para...
70799992f78fa1827e8c79737bef977b49f7fefc
3,613,180
import itertools def sphere_plane(map, mapi) -> plt.Figure: """ Plots map from (3d) sphere to (2d) plane and its inverse. :param map: Map from sphere to plane. :param mapi: Map from plane to sphere. :return: Figure. """ # Init plot object: fig = plt.figure() ax = np.array([[fig.ad...
a07d747fd0e1a12629591a3fdd8db2a71b6ba8e2
3,613,181
import json import hashlib def hash_config(configuration: dict) -> str: """Computes a SHA256 hash from a dictionnary. Args: configuration (dict): The configuration to hash Returns: str: _description_ """ stringified = json.dumps(configuration, sort_keys=True) return hashlib.s...
ccf30915fc736ce4724eb0ceceab59220e94efd0
3,613,182
def get_bag_of_communities(network, partition): """ :param network: dictionary containing for each key (each node/page) a dictionary containing the page categories. :param partition: list of the community assignment :return: list of dictionaries, one dictionary per community. Each dictionary contains th...
615e88393b30b1989d98eeea1ac7123588a51ea9
3,613,183
import asyncio def connect( stream_generator, user=None, database=None, password=None, loop=None, **kwargs): """Creates a connection to a PostgreSQL database. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_; however, the arguments of the function are...
954e5a0b3bdb2718910f6f50df7064966fdc806f
3,613,184
def add_neighbor_count_features(edge_df, X_df, structures_df): """ edge_df must be symmetric. """ cnt_df = edge_df.groupby( ['molecule_name', 'atom_index_0']).size().to_frame('EF_neighbor_count') cnt_df.reset_index(inplace=True) cnt_df.rename({'atom_index_0': 'atom_index_zero'}, inplace=...
688e04893035f1340c7a14a0173f7059604665cb
3,613,185
def _to_pascal_case(value: str) -> str: """Converts a snake_case string into a PascalCase one.""" value = value.replace("-", "_") if value.find("_") == -1: return value[0].upper() + value[1:] return "".join([v.capitalize() for v in value.split("_")])
d41985f1d182b723c9861473e4f9eca8c7a7977e
3,613,186
import yaml def load(modelSpecFilename): """ Need the following items in the model spec file: costFn decisionFn stages specs :param modelSpecFilename: :return: """ with open(modelSpecFilename) as f: modelDict = yaml.load(f) for stageDict in modelDict['specs']: ...
5033aec67b5f0a19651cdffe96b5ce5e704aa816
3,613,187
from typing import Any from typing import Union from typing import Set import re def _replace_prefixed(text: Any, prefix: Union[str, Set[str]], value: str) -> Any: """ Replace all substrings starting with the prefix(es) with the value. """ if pd.isna(text): return text text = str(text) ...
cc034958d2e175e93ef9fdb252e7e0e66e2442f2
3,613,188
def perma(mat,m): """ Permanent of the matrix """ if not mat.isSquare: return None if mat.isIdentity: return 1 if mat.dim[0]==2: return m[0][0]*m[1][1] + m[1][0]*m[0][1] if mat.dim[0]==3: return (m[0][0]*m[1][1]*m[2][2] + m[0][1...
71e2408c79e09b4fa5eb328130d2b5b7e7efdf41
3,613,189
def realtime_to_gametime(secs=0, mins=0, hrs=0, days=1, weeks=1, months=1, yrs=0, format=False): """ This method calculates how much in-game time a real-world time interval would correspond to. This is usually a lot less interesting than the other way around. Keyword Args: times (int): The ...
3fa4c85f4f5a71357c64d4aab53248b348736a10
3,613,190
def char_class_abbrev(cc_abbrev: str, **config): """ Constructs a char_class spec :param cc_abbrev: alternative type abbreviation i.e. ascii, cc-ascii, visible, cc-visible :param config: in **kwargs format :return: the char_class spec """ spec = { "type": 'char_class_abbrev' } ...
da14e16657cf5666bde881c0a27d995327878ecb
3,613,191
import sys import os import types import importlib def load_command_extension(command, path): """Loads a command extension from the path passed as argument. Args: command (str): name of the command (contains ``-``, not ``_``). path (str): base path of the command extension Returns: ...
df36869374da6f032e3b11ec9a609583176c1892
3,613,192
def trial_division(n): """Return a list of the prime factors for a natural number.""" if n < 2: return [] prime_factors_list = [] temp = primeGenerate(int(n**0.5) + 1) for p in temp: if p*p > n: break while n % p == 0: prime_factors_list.append(p) ...
1c5dc9beb3ca237e2a7f663cb7e864bfb42c3141
3,613,193
def occlusion(net: Module, input_image: Tensor, n_top_classes: int = 3) -> Tensor: """Creates a attribution heatmap by occluding parts of the input image. Args: net: the network to visualize attribution for input_image: image tensor of dimensions (c, h, w) or (1, c, h, w) n_top_classes:...
e40c1ecf7293fe5b0d51de999b5f4cad3d3d2dd1
3,613,194
def log_pos(x): """Computes log with the assumption that x values are positive. """ return jnp.log(jnp.maximum(x, jnp.finfo(float).eps))
f963ed2a38b9d81ed05e698da66a0c4e3c96a47e
3,613,195
import os import grp def install_script(conf_dir: str, group: str): """ Function copies script and config files to needed directories :param conf_dir: Path to config directory to create :type: str :param group: Group name to set chown root:group to config directory :type: str :return: Tru...
0292ba68579d5a2b9c56fa97fb0da277d653f55b
3,613,196
from typing import List import json def import_tree_to_json_str(imports=List[Import]) -> str: """ Print the imported modules tree in json format. """ exclude_root = imports[0]["nested_imports"] return json.dumps(exclude_root, indent=2)
8796c1099fb39d8cac72a50e83da23ca25e1f821
3,613,197
from typing import Tuple def place_targets_with_goal_distance_ratio( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, object_placements: np.ndarray, goal_distance_ratio: float, goal_distance_min: float, max_placement_...
26962960db0d6a4c4681890d553cafe0d78150f7
3,613,198
import torch import tqdm def predict(model, test_batch_generator, num_batches, device, label_map, class_weight): """ Main evaluation routine """ epoch_loss = 0 epoch_acc = 0 epoch_results = {} epoch_results_by_tag = {} epoch_CR = "" output_t_pred = None model.eval() with ...
0ec7d472a4cc2b17ecd5e6a033243300e1184f60
3,613,199