id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
165,612
from enum import Enum import random import sys import json import progressbar import model.torch_utils import data_util.sql_util import torch def write_prediction(fileptr, identifier, input_seq, probability, prediction, ...
Evaluates a sample of interactions.
165,613
from enum import Enum import random import sys import json import progressbar import model.torch_utils import data_util.sql_util import torch def write_prediction(fileptr, identifier, input_seq, probability, prediction, ...
null
165,618
import torch.nn as nn import torch import math import torch.nn.functional as F import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from .layer_norm import LayerNorm from .position_ffn import PositionwiseFeedForward from .multi_headed_attn import MultiHeadedAttention from .rat_transformer_layer i...
matrix: n x n label: len(str) == n
165,619
import torch.nn as nn import torch import math import torch.nn.functional as F from .layer_norm import LayerNorm from .position_ffn import PositionwiseFeedForward from .multi_headed_attn import MultiHeadedAttention from ..encoder import Encoder as Encoder2 def gelu(x): return x * 0.5 * (1.0 + torch.erf(x / math.sq...
null
165,623
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np The provided code snippet includes necessary dependencies for implementing the `compute_loss` function. Write a Python function `def compute_loss(gold_seq, scores, index_to_token_maps, ...
Computes the loss of a gold sequence given scores. Inputs: gold_seq (list of str): A sequence of gold tokens. scores (list of dy.Expression): Expressions representing the scores of potential output tokens for each token in gold_seq. index_to_token_maps (list of dict str->list of int): Maps from index in the sequence to...
165,625
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np The provided code snippet includes necessary dependencies for implementing the `per_token_accuracy` function. Write a Python function `def per_token_accuracy(gold_seq, pred_seq)` to solve the following problem: Returns the per-token ...
Returns the per-token accuracy comparing two strings (recall). Inputs: gold_seq (list of str): A list of gold tokens. pred_seq (list of str): A list of predicted tokens. Returns: float, representing the accuracy.
165,627
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np The provided code snippet includes necessary dependencies for implementing the `create_multilayer_lstm_params` function. Write a Python function `def create_multilayer_lstm_params(num_layers, in_size, state_size, name="")` to solve t...
Adds a multilayer LSTM to the model parameters. Inputs: num_layers (int): Number of layers to create. in_size (int): The input size to the first layer. state_size (int): The size of the states. model (dy.ParameterCollection): The parameter collection for the model. name (str, optional): The name of the multilayer LSTM.
165,628
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np The provided code snippet includes necessary dependencies for implementing the `add_params` function. Write a Python function `def add_params(size, name="")` to solve the following problem: Adds parameters to the model. Inputs: model...
Adds parameters to the model. Inputs: model (dy.ParameterCollection): The parameter collection for the model. size (tuple of int): The size to create. name (str, optional): The name of the parameters.
165,629
import os import torch import torch.nn.functional as F from . import torch_utils from . import utils_bert from data_util.vocabulary import DEL_TOK, UNK_TOK from .encoder import Encoder from .embedder import Embedder from .token_predictor import construct_token_predictor import numpy as np from data_util.atis_vocab impo...
Maps from a gold token (string) to a list of indices. Inputs: token (string): String to look up. index_to_token (list of tokens): Ordered list of tokens. Returns: list of int, representing the indices of the token in the probability distribution.
165,630
import os import torch import torch.nn.functional as F from . import torch_utils from . import utils_bert from data_util.vocabulary import DEL_TOK, UNK_TOK from .encoder import Encoder from .embedder import Embedder from .token_predictor import construct_token_predictor import numpy as np from data_util.atis_vocab impo...
Gets a flat sequence from a sequence of utterances. Inputs: utterances (list of list of str): Utterances to concatenate. Returns: list of str, representing the flattened sequence with separating delimiter tokens.
165,631
import os import torch import torch.nn.functional as F from . import torch_utils from . import utils_bert from data_util.vocabulary import DEL_TOK, UNK_TOK from .encoder import Encoder from .embedder import Embedder from .token_predictor import construct_token_predictor import numpy as np from data_util.atis_vocab impo...
Encodes snippets by using previous query states instead. Inputs: snippets (list of Snippet): Input snippets. states (list of dy.Expression): Previous hidden states to use. TODO: should this by dy.Expression or vector values?
165,632
import os import torch import torch.nn.functional as F from . import torch_utils from . import utils_bert from data_util.vocabulary import DEL_TOK, UNK_TOK from .encoder import Encoder from .embedder import Embedder from .token_predictor import construct_token_predictor import numpy as np from data_util.atis_vocab impo...
null
165,633
import os, json import random as rd from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from .bert import tokenization as tokenization from .bert.modeling import BertConfig, BertModel device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def get_bert(params): ...
null
165,636
import re import os import json import torch import random import pickle import argparse import torch.nn as nn from tqdm import tqdm from model import SegModel from torch.cuda import amp import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from torch.utils.data.distributed import DistributedSampl...
null
165,637
import os import re import json import torch import random import pickle import IPython import argparse import subprocess import numpy as np from tqdm import tqdm from torch.nn import CrossEntropyLoss from collections import defaultdict, Counter from transformers import BertTokenizer from torch.nn.utils.rnn import pad_...
null
165,638
import torch import bisect import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from transformers import BertForNextSentencePrediction, AutoModel from transformers.models.bert.modeling_bert import * def tet(scores): output_scores = [] for i in range(len...
null
165,639
import torch from torch import Tensor from typing import List import numpy as np The provided code snippet includes necessary dependencies for implementing the `split_matrix` function. Write a Python function `def split_matrix(matrix: Tensor, lengths: List, reduction='mean') -> Tensor` to solve the following problem: ...
:param matrix: torch.tensor :param lengths: list :return:
165,642
import math import torch from torch.optim import Optimizer from torch.nn.utils import clip_grad_norm_ def warmup_linear(x, warmup=0.002): if x < warmup: return x/warmup return 1.0 - x
null
165,643
import os import codecs import argparse import logging from typing import List import pickle from tqdm import tqdm from optimization import BERTAdam from data import data_provider from network import Dial2vec from metrics import * from utils import split_matrix def str2bool(v): if v.lower() in ('yes', 'true', 't',...
null
165,644
import os import codecs import math from multiprocessing import Pool import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler, DistributedSampler from transformers import AutoTokenizer, AutoConfig import config from model.plato.configuration_plato import PlatoConfig The pro...
统计文件行数
165,645
import codecs import os import argparse import config The provided code snippet includes necessary dependencies for implementing the `get_session_content` function. Write a Python function `def get_session_content(file_path)` to solve the following problem: 读取数据 Here is the function: def get_session_content(file_pat...
读取数据
165,646
import codecs from tqdm import tqdm import random import os import config sample_role = "0" data_dict, flatten_neg_samples = get_data_dict("./rawdata/preprocess_session_%s.txt" % config.data_prefix) The provided code snippet includes necessary dependencies for implementing the `get_data_dict` function. Write a Python ...
读取数据
165,647
import codecs from tqdm import tqdm import random import os import config def get_single_sample(data_dict, key, select_key, flatten_neg_samples, use_ins=False): """ 构建一条样本 """ text_str = "" ins_samples = [data_dict[select_key]["text"][i] for i in range(len(data_dict[select_key]["text"])) if ...
构建数据集
165,648
import codecs from tqdm import tqdm import random import os import config anchor_role = "1" if os.path.exists(train_file_path) is False: os.makedirs(train_file_path) The provided code snippet includes necessary dependencies for implementing the `write_tsv` function. Write a Python function `def write_tsv(train_fil...
输出至训练文件
165,649
import copy import json import math import six import torch import torch.nn as nn from torch.nn import CrossEntropyLoss import numpy as np from sklearn.metrics import f1_score import config as user_config The provided code snippet includes necessary dependencies for implementing the `gelu` function. Write a Python fun...
Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
165,650
The provided code snippet includes necessary dependencies for implementing the `semantic_relatedness` function. Write a Python function `def semantic_relatedness(y_true=None, features=None, scores_from_subject=None, scores_from_model=None)` to solve the following problem: :param y_true: ground_truth labels about doma...
:param y_true: ground_truth labels about domains :param features: produced features :return:
165,651
def clustering_evaluation(y_true, y_pred, logger=None): y_true = np.array(y_true) y_pred = np.array(y_pred) y_true = np.array(y_true).astype(int) y_pred = np.array(y_pred).astype(int) ## RI pre = time() RI = adjusted_rand_score(y_true, y_pred) RI_time = time() - pre ## NMI p...
null
165,652
The provided code snippet includes necessary dependencies for implementing the `evaluate_all_metrics_at_once` function. Write a Python function `def evaluate_all_metrics_at_once(features, y_true, y_pred, tsne_visualization_output=None, logger=None, note='')` to solve the following problem: :param features: :param y_t...
:param features: :param y_true: :param y_pred: :param strategy: :param tsne_visualization_output: :return:
165,653
The provided code snippet includes necessary dependencies for implementing the `feature_based_evaluation_at_once` function. Write a Python function `def feature_based_evaluation_at_once(features, labels, gpu_features=None, n_average=1, tsne_visualization_output=None, tasks=None, dtype='float64', logger=None, note='')...
Evaluate all metrics with features :param features: numpy.array :param labels: list :param n_average: :param tsne_visualization_output: :param tasks: :param dtype: :param logger: :param note: :return:
165,656
import torch import mmcv from mmdet.core.bbox.match_costs.builder import MATCH_COST The provided code snippet includes necessary dependencies for implementing the `smooth_l1_loss` function. Write a Python function `def smooth_l1_loss(pred, target, beta=1.0)` to solve the following problem: Smooth L1 loss. Args: pred (...
Smooth L1 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning target of the prediction. beta (float, optional): The threshold in the piecewise function. Defaults to 1.0. Returns: torch.Tensor: Calculated loss
165,668
import copy import mmcv import numpy as np import pyquaternion import tempfile import torch import warnings from nuscenes.utils.data_classes import Box as NuScenesBox from os import path as osp from mmdet3d.core import bbox3d2result, box3d_multiclass_nms, xywhr2xyxyr from mmdet.datasets import DATASETS, CocoDataset fro...
Convert the output to the box class in the nuScenes. Args: detection (dict): Detection results. - boxes_3d (:obj:`BaseInstance3DBoxes`): Detection bbox. - scores_3d (torch.Tensor): Detection scores. - labels_3d (torch.Tensor): Predicted box labels. - attrs_3d (torch.Tensor, optional): Predicted attributes. Returns: lis...
165,669
import copy import mmcv import numpy as np import pyquaternion import tempfile import torch import warnings from nuscenes.utils.data_classes import Box as NuScenesBox from os import path as osp from mmdet3d.core import bbox3d2result, box3d_multiclass_nms, xywhr2xyxyr from mmdet.datasets import DATASETS, CocoDataset fro...
Convert the box from camera to global coordinate. Args: info (dict): Info for a specific sample data, including the calibration information. boxes (list[:obj:`NuScenesBox`]): List of predicted NuScenesBoxes. classes (list[str]): Mapped classes in the evaluation. eval_configs (object): Evaluation configuration object. e...
165,670
import copy import mmcv import numpy as np import pyquaternion import tempfile import torch import warnings from nuscenes.utils.data_classes import Box as NuScenesBox from os import path as osp from mmdet3d.core import bbox3d2result, box3d_multiclass_nms, xywhr2xyxyr from mmdet.datasets import DATASETS, CocoDataset fro...
Convert the box from global to camera coordinate. Args: info (dict): Info for a specific sample data, including the calibration information. boxes (list[:obj:`NuScenesBox`]): List of predicted NuScenesBoxes. classes (list[str]): Mapped classes in the evaluation. eval_configs (object): Evaluation configuration object. e...
165,671
import copy import mmcv import numpy as np import pyquaternion import tempfile import torch import warnings from nuscenes.utils.data_classes import Box as NuScenesBox from os import path as osp from mmdet3d.core import bbox3d2result, box3d_multiclass_nms, xywhr2xyxyr from mmdet.datasets import DATASETS, CocoDataset fro...
Convert boxes from :obj:`NuScenesBox` to :obj:`CameraInstance3DBoxes`. Args: boxes (list[:obj:`NuScenesBox`]): List of predicted NuScenesBoxes. Returns: tuple (:obj:`CameraInstance3DBoxes` | torch.Tensor | torch.Tensor): \ Converted 3D bounding boxes, scores and labels.
165,672
from __future__ import division from typing import Any, List, Sequence, Tuple import torch from torch import device from torch.nn import functional as F from detectron2.utils.env import TORCH_VERSION The provided code snippet includes necessary dependencies for implementing the `_as_tensor` function. Write a Python fu...
An equivalent of `torch.as_tensor`, but works under tracing if input is a list of tensor. `torch.as_tensor` will record a constant in tracing, but this function will use `torch.stack` instead.
165,673
import numpy as np import torch from pyquaternion import Quaternion from torch.cuda import amp from projects.mmdet3d_plugin.dd3d.utils.geometry import unproject_points2d import projects.mmdet3d_plugin.dd3d.structures.transform3d as t3d The provided code snippet includes necessary dependencies for implementing the `qua...
Convert rotations given as quaternions to rotation matrices. Args: quaternions: quaternions with real part first, as tensor of shape (..., 4). Returns: Rotation matrices as tensor of shape (..., 3, 3).
165,674
import numpy as np import torch from pyquaternion import Quaternion from torch.cuda import amp from projects.mmdet3d_plugin.dd3d.utils.geometry import unproject_points2d import projects.mmdet3d_plugin.dd3d.structures.transform3d as t3d def _to_tensor(x, dim): if isinstance(x, torch.Tensor): x = x.to(torch....
null
165,675
import math import warnings from typing import List, Optional, Union import torch The provided code snippet includes necessary dependencies for implementing the `_axis_angle_rotation` function. Write a Python function `def _axis_angle_rotation(axis: str, angle: torch.Tensor) -> torch.Tensor` to solve the following pro...
Return the rotation matrices for one of the rotations about an axis of which Euler angles describe, for each value of the angle given. Args: axis: Axis label "X" or "Y or "Z". angle: any shape tensor of Euler angles in radians Returns: Rotation matrices as tensor of shape (..., 3, 3).
165,676
import math import warnings from typing import List, Optional, Union import torch Device = Union[str, torch.device] def get_device(x, device: Optional[Device] = None) -> torch.device: """ Gets the device of the specified variable x if it is a tensor, or falls back to a default CPU device otherwise. Allows o...
Helper function to handle parsing logic for building transforms. The output is always a tensor of shape (N, 3), but there are several types of allowed input. Case I: Single Matrix In this case x is a tensor of shape (N, 3), and y and z are None. Here just return x. Case II: Vectors and Scalars In this case each of x, y...
165,677
import math import warnings from typing import List, Optional, Union import torch Device = Union[str, torch.device] def get_device(x, device: Optional[Device] = None) -> torch.device: """ Gets the device of the specified variable x if it is a tensor, or falls back to a default CPU device otherwise. Allows o...
Helper function for building a rotation function using angles. The output is always of shape (N,). The input can be one of: - Torch tensor of shape (N,) - Python scalar - Torch scalar
165,678
import math import warnings from typing import List, Optional, Union import torch The provided code snippet includes necessary dependencies for implementing the `_broadcast_bmm` function. Write a Python function `def _broadcast_bmm(a, b) -> torch.Tensor` to solve the following problem: Batch multiply two matrices and ...
Batch multiply two matrices and broadcast if necessary. Args: a: torch tensor of shape (P, K) or (M, P, K) b: torch tensor of shape (N, K, K) Returns: a and b broadcast multiplied. The output batch dimension is max(N, M). To broadcast transforms across a batch dimension if M != N then expect that either M = 1 or N = 1....
165,679
import math import warnings from typing import List, Optional, Union import torch def _safe_det_3x3(t: torch.Tensor): """ Fast determinant calculation for a batch of 3x3 matrices. Note, result of this function might not be the same as `torch.det()`. The differences might be in the last significant digit...
Determine if R is a valid rotation matrix by checking it satisfies the following conditions: ``RR^T = I and det(R) = 1`` Args: R: an (N, 3, 3) matrix Returns: None Emits a warning if R is an invalid rotation matrix.
165,680
import torch The provided code snippet includes necessary dependencies for implementing the `smooth_l1_loss` function. Write a Python function `def smooth_l1_loss(input: torch.Tensor, target: torch.Tensor, beta: float, reduction: str = "none") -> torch.Tensor` to solve the following problem: Smooth L1 loss defined in ...
Smooth L1 loss defined in the Fast R-CNN paper as: | 0.5 * x ** 2 / beta if abs(x) < beta smoothl1(x) = | | abs(x) - 0.5 * beta otherwise, where x = input - target. Smooth L1 loss is related to Huber loss, which is defined as: | 0.5 * x ** 2 if abs(x) < beta huber(x) = | | beta * (abs(x) - 0.5 * beta) otherwise Smooth ...
165,681
import torch from fvcore.nn import sigmoid_focal_loss from torch import nn from torch.nn import functional as F from detectron2.layers import Conv2d, batched_nms, cat, get_norm from detectron2.structures import Boxes, Instances from detectron2.utils.comm import get_world_size from mmcv.runner import force_fp32 from pro...
null
165,682
import torch import torch.nn.functional as F from torch import nn from detectron2.layers import Conv2d, cat, get_norm from mmcv.runner import force_fp32 from projects.mmdet3d_plugin.dd3d.layers.normalization import ModuleListDial, Offset, Scale from .disentangled_box3d_loss import DisentangledBox3DLoss from projects.mm...
null
165,683
from collections import OrderedDict import numpy as np import seaborn as sns from torch.utils.data import Dataset from tqdm import tqdm from detectron2.structures.boxes import BoxMode from nuscenes.eval.detection.utils import category_to_detection_name from nuscenes.nuscenes import NuScenes from nuscenes.utils.splits i...
Parameters ---------- box1, box2: (x1, y1, x2, y2)
165,684
import numpy as np import torch from detectron2.data import transforms as T from detectron2.structures import Boxes, BoxMode, Instances from projects.mmdet3d_plugin.dd3d.structures.boxes3d import Boxes3D The provided code snippet includes necessary dependencies for implementing the `transform_instance_annotations` fun...
Adapted from: https://github.com/facebookresearch/detectron2/blob/master/detectron2/data/detection_utils.py#L254 The changes from original: - The presence of 2D bounding box (i.e. "bbox" field) is assumed by default in d2; here it's optional. - Add optional 3D bounding box support. - If the instance mask annotation is ...
165,685
import numpy as np import torch from detectron2.data import transforms as T from detectron2.structures import Boxes, BoxMode, Instances from projects.mmdet3d_plugin.dd3d.structures.boxes3d import Boxes3D def _create_empty_instances(image_size): target = Instances(image_size) target.gt_boxes = Boxes([]) targ...
Create an :class:`Instances` object used by the models, from instance annotations in the dataset dict. Args: annos (list[dict]): a list of instance annotations in one image, each element for one instance. image_size (tuple): height, width Returns: Instances: It will contain fields "gt_boxes", "gt_classes", "gt_masks", ...
165,686
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `compute_features_locations` function. Write a Python function `def compute_features_locations(h, w, stride, dtype=torch.float32, device='cpu', offset="none")` to solve the following problem: Ada...
Adapted from AdelaiDet: https://github.com/aim-uofa/AdelaiDet/blob/master/adet/utils/comm.py Key differnece: offset is configurable.
165,687
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `aligned_bilinear` function. Write a Python function `def aligned_bilinear(tensor, factor, offset="none")` to solve the following problem: Adapted from AdelaiDet: https://github.com/aim-uofa/Adel...
Adapted from AdelaiDet: https://github.com/aim-uofa/AdelaiDet/blob/master/adet/utils/comm.py
165,688
import logging from functools import wraps import torch.distributed as dist from detectron2.utils import comm as d2_comm LOG = logging.getLogger(__name__) _NESTED_BROADCAST_FROM_MASTER = False def is_distributed(): return d2_comm.get_world_size() > 1 The provided code snippet includes necessary dependencies for im...
If distributed, only the master executes the function and broadcast the results to other workers. Usage: @broadcast_from_master def foo(a, b): ...
165,689
import logging from functools import wraps import torch.distributed as dist from detectron2.utils import comm as d2_comm The provided code snippet includes necessary dependencies for implementing the `master_only` function. Write a Python function `def master_only(fn)` to solve the following problem: If distributed, o...
If distributed, only the master executes the function. Usage: @master_only def foo(a, b): ...
165,690
import logging from functools import wraps import torch.distributed as dist from detectron2.utils import comm as d2_comm The provided code snippet includes necessary dependencies for implementing the `gather_dict` function. Write a Python function `def gather_dict(dikt)` to solve the following problem: Gather python d...
Gather python dictionaries from all workers to the rank=0 worker. Assumption: the keys of `dikt` are disjoint across all workers. If rank = 0, then returned aggregated dict. If rank > 0, then return `None`.
165,691
import logging from functools import wraps import torch.distributed as dist from detectron2.utils import comm as d2_comm def is_distributed(): return d2_comm.get_world_size() > 1 The provided code snippet includes necessary dependencies for implementing the `reduce_sum` function. Write a Python function `def reduc...
Adapted from AdelaiDet: https://github.com/aim-uofa/AdelaiDet/blob/master/adet/utils/comm.py
165,692
import colorsys import os import cv2 import matplotlib.colors as mplc import numpy as np from PIL import Image, ImageDraw The provided code snippet includes necessary dependencies for implementing the `fill_color_polygon` function. Write a Python function `def fill_color_polygon(image, polygon, color, alpha=0.5)` to s...
Color interior of polygon with alpha-blending. This function modified input in place.
165,693
import colorsys import os import cv2 import matplotlib.colors as mplc import numpy as np from PIL import Image, ImageDraw The provided code snippet includes necessary dependencies for implementing the `change_color_brightness` function. Write a Python function `def change_color_brightness(color, brightness_factor)` to...
Copied from detectron2.utils.visualizer.py ------------------------------------------- Depending on the brightness_factor, gives a lighter or darker color i.e. a color with less or more saturation than the original color. Args: color: color of the polygon. Refer to `matplotlib.colors` for a full list of formats that ar...
165,694
import colorsys import os import cv2 import matplotlib.colors as mplc import numpy as np from PIL import Image, ImageDraw The provided code snippet includes necessary dependencies for implementing the `draw_text` function. Write a Python function `def draw_text(ax, text, position, *, font_size, color="g", horizontal_a...
Copied from Visualizer.draw_text() ----------------------------------- Args: text (str): class label position (tuple): a tuple of the x and y coordinates to place text on image. font_size (int, optional): font of the text. If not provided, a font size proportional to the image width is calculated and used. color: color...
165,695
import colorsys import os import cv2 import matplotlib.colors as mplc import numpy as np from PIL import Image, ImageDraw def float_to_uint8_color(float_clr): assert all([c >= 0. for c in float_clr]) assert all([c <= 1. for c in float_clr]) return [int(c * 255.) for c in float_clr]
null
165,696
import colorsys import os import cv2 import matplotlib.colors as mplc import numpy as np from PIL import Image, ImageDraw The provided code snippet includes necessary dependencies for implementing the `mosaic` function. Write a Python function `def mosaic(items, scale=1.0, pad=3, grid_width=None)` to solve the followi...
Creates a mosaic from list of images. Parameters ---------- items: list of np.ndarray List of images to mosaic. scale: float, default=1.0 Scale factor applied to images. scale > 1.0 enlarges images. pad: int, default=3 Padding size of the images before mosaic grid_width: int, default=None Mosaic width or grid width of ...
165,697
import logging import cv2 import numpy as np import torch import torch.nn.functional as F def project_points3d(Xw, K): _, C = Xw.shape assert C == 3 uv, _ = cv2.projectPoints( Xw, np.zeros((3, 1), dtype=np.float32), np.zeros(3, dtype=np.float32), K, np.zeros(5, dtype=np.float32) ) return uv...
null
165,704
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare data related to Kitti dataset. Related data consists of '.pkl' files recording basic infos, 2D annotations and groundtruth database. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. version (str): Dataset version. out_dir (str): Output directory of the groundtruth da...
165,705
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare data related to nuScenes dataset. Related data consists of '.pkl' files recording basic infos, 2D annotations and groundtruth database. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. version (str): Dataset version. dataset_name (str): The dataset class name. out_di...
165,706
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare data related to Lyft dataset. Related data consists of '.pkl' files recording basic infos. Although the ground truth database and 2D annotations are not used in Lyft, it can also be generated like nuScenes. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. version (st...
165,707
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare the info file for scannet dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): Number of threads to be used.
165,708
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare the info file for s3dis dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): Number of threads to be used.
165,709
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare the info file for sunrgbd dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): Number of threads to be used.
165,710
from data_converter.create_gt_database import create_groundtruth_database from data_converter import nuscenes_converter as nuscenes_converter from data_converter import lyft_converter as lyft_converter from data_converter import kitti_converter as kitti from data_converter import indoor_converter as indoor import argpa...
Prepare the info file for waymo dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): Number of threads to be used. max_sweeps (int): Number of input consecutive frames. Default: 5 \ Here we store...
165,723
import argparse import base64 import mmcv import numpy as np from nuimages import NuImages from nuimages.utils.utils import mask_decode, name_to_index_mapping from os import path as osp def parse_args(): parser = argparse.ArgumentParser(description='Data converter arg parser') parser.add_argument( '--d...
null
165,724
import argparse import base64 import mmcv import numpy as np from nuimages import NuImages from nuimages.utils.utils import mask_decode, name_to_index_mapping from os import path as osp nus_categories = ('car', 'truck', 'trailer', 'bus', 'construction_vehicle', 'bicycle', 'motorcycle', 'pedestrian', '...
null
165,726
import numpy as np from collections import OrderedDict from concurrent import futures as futures from os import path as osp from pathlib import Path from skimage import io def get_image_index_str(img_idx, use_prefix_id=False): if use_prefix_id: return '{:07d}'.format(img_idx) else: return '{:06d...
null
165,727
import mmcv import numpy as np from collections import OrderedDict from nuscenes.utils.geometry_utils import view_points from pathlib import Path from mmdet3d.core.bbox import box_np_ops from .kitti_data_utils import get_kitti_image_info, get_waymo_image_info from .nuscenes_converter import post_process_coords The pro...
convert kitti info v1 to v2 if possible. Args: info (dict): Info of the input kitti data. - image (dict): image info - calib (dict): calibration info - point_cloud (dict): point cloud info
165,728
import mmcv import numpy as np from concurrent import futures as futures from os import path as osp from scipy import io as sio The provided code snippet includes necessary dependencies for implementing the `random_sampling` function. Write a Python function `def random_sampling(points, num_points, replace=None, retur...
Random sampling. Sampling point cloud to a certain number of points. Args: points (ndarray): Point cloud. num_points (int): The number of samples. replace (bool): Whether the sample is with or without replacement. return_choices (bool): Whether to return choices. Returns: points (ndarray): Point cloud after sampling.
165,729
import argparse import numpy as np import os def fix_lyft(root_folder='./data/lyft', version='v1.01'): # refer to https://www.kaggle.com/c/3d-object-detection-for-autonomous-vehicles/discussion/110000 # noqa lidar_path = 'lidar/host-a011_lidar1_1233090652702363606.bin' root_folder = os.path.join(root_fold...
null
165,737
import argparse import torch from mmcv.runner import save_checkpoint from torch import nn as nn from mmdet.apis import init_model def fuse_conv_bn(conv, bn): """During inference, the functionary of batch norm layers is turned off but only the mean and var alone channels are used, which exposes the chance to ...
null
165,740
from typing import Union, Dict, Optional, Any import logging import traceback from typing_extensions import Literal from .pygwalker import PygWalker from pygwalker.services.data_parsers import get_parser from pygwalker.services.preview_image import render_gw_chart_preview_html from pygwalker.data_parsers.base import Fi...
Generate embeddable HTML code of Graphic Walker with data of `df`. Args: - df (pl.DataFrame | pd.DataFrame, optional): dataframe. - gid (Union[int, str], optional): GraphicWalker container div's id ('gwalker-{gid}') Kargs: - field_specs (Dict[str, FieldSpec], optional): Specifications of some fields. They'll been autom...
165,741
from typing import Union, Dict, Optional, Any import logging import traceback from typing_extensions import Literal from .pygwalker import PygWalker from pygwalker.services.data_parsers import get_parser from pygwalker.services.preview_image import render_gw_chart_preview_html from pygwalker.data_parsers.base import Fi...
Generate HTML code of a chart by graphic-walker or vega spec. Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataset. - spec (Dict[str, Any]): chart config data. Kargs: - spec_type (Literal["graphic-walker", "vega"]): type of spec. - theme_key ('vega' | 'g2'): theme type. - dark ('media' | 'light'...
165,742
from typing import Union, Dict, Optional from typing_extensions import Literal from .pygwalker import PygWalker from pygwalker.communications.gradio_comm import ( BASE_URL_PATH, GradioCommunication, PYGWALKER_ROUTE ) from pygwalker.data_parsers.base import FieldSpec from pygwalker.data_parsers.database_pars...
Get pygwalker html render to gradio Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataframe. - gid (Union[int, str], optional): GraphicWalker container div's id ('gwalker-{gid}') Kargs: - env: (Literal['Jupyter' | 'Streamlit'], optional): The enviroment using pygwalker. Default as 'Jupyter' - fie...
165,743
from typing import Union, Dict, Optional, TYPE_CHECKING, List, Any from distutils.version import StrictVersion import json from typing_extensions import Literal from pydantic import BaseModel from cachetools import cached, TTLCache import arrow import streamlit.components.v1 as components from .pygwalker import PygWalk...
Initialize pygwalker communication in streamlit
165,744
from typing import Union, Dict, Optional, TYPE_CHECKING, List, Any from distutils.version import StrictVersion import json from typing_extensions import Literal from pydantic import BaseModel from cachetools import cached, TTLCache import arrow import streamlit.components.v1 as components from .pygwalker import PygWalk...
Get pygwalker html render to streamlit Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataframe. - gid (Union[int, str], optional): GraphicWalker container div's id ('gwalker-{gid}') Kargs: - field_specs (Dict[str, FieldSpec], optional): Specifications of some fields. They'll been automatically in...
165,745
from typing import Dict, Optional, Union from datetime import datetime from pygwalker.data_parsers.base import FieldSpec from pygwalker._typing import DataFrame from pygwalker.utils.display import display_html from pygwalker.data_parsers.database_parser import Connector from pygwalker.services.cloud_service import Clou...
Create a dataset in kanaries cloud Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataset. Kargs: - name (str): dataset name in kanaries cloud. - is_public (bool): whether to make this dataset public. Returns: str: dataset id in kanaries cloud
165,746
from typing import Dict, Optional, Union from datetime import datetime from pygwalker.data_parsers.base import FieldSpec from pygwalker._typing import DataFrame from pygwalker.utils.display import display_html from pygwalker.data_parsers.database_parser import Connector from pygwalker.services.cloud_service import Clou...
(deprecated) Create a pygwalker in kanaries cloud Args: - dataset (pl.DataFrame | pd.DataFrame, optional): dataframe. Kargs: - chart_name (str): pygwalker chart name in kanaries cloud. - workspace_name (str): kanaries workspace name. - field_specs (Dict[str, FieldSpec]): Specifications of some fields. They'll been auto...
165,747
from typing import Dict, Optional, Union from datetime import datetime from pygwalker.data_parsers.base import FieldSpec from pygwalker._typing import DataFrame from pygwalker.utils.display import display_html from pygwalker.data_parsers.database_parser import Connector from pygwalker.services.cloud_service import Clou...
(deprecated) render a pygwalker in kanaries cloud Args: - chart_name (str): pygwalker chart name in kanaries cloud. - workspace_name (str): kanaries workspace name.
165,748
from typing import Union, Dict, Optional import inspect from typing_extensions import Literal from .pygwalker import PygWalker from pygwalker.data_parsers.base import FieldSpec from pygwalker.data_parsers.database_parser import Connector from pygwalker._typing import DataFrame from pygwalker.services.format_invoke_walk...
Walk through pandas.DataFrame df with Graphic Walker Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataframe. - gid (Union[int, str], optional): GraphicWalker container div's id ('gwalker-{gid}') Kargs: - env: (Literal['Jupyter' | 'JupyterWidget'], optional): The enviroment using pygwalker. Defau...
165,749
from typing import Union, Dict, Optional import inspect from typing_extensions import Literal from .pygwalker import PygWalker from pygwalker.data_parsers.base import FieldSpec from pygwalker.data_parsers.database_parser import Connector from pygwalker._typing import DataFrame from pygwalker.services.format_invoke_walk...
Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataframe. - spec (str): chart config data. config id, json, remote file url Kargs: - theme_key ('vega' | 'g2'): theme type. - dark (Literal['media' | 'light' | 'dark']): 'media': auto detect OS theme. - use_kernel_calc(bool): Whether to use kernel co...
165,750
from typing import Union, Dict, Optional import inspect from typing_extensions import Literal from .pygwalker import PygWalker from pygwalker.data_parsers.base import FieldSpec from pygwalker.data_parsers.database_parser import Connector from pygwalker._typing import DataFrame from pygwalker.services.format_invoke_walk...
Args: - dataset (pl.DataFrame | pd.DataFrame | Connector, optional): dataframe. Kargs: - theme_key ('vega' | 'g2'): theme type. - dark (Literal['media' | 'light' | 'dark']): 'media': auto detect OS theme. - use_kernel_calc(bool): Whether to use kernel compute for datas, Default to None. - kanaries_api_key (str): kanari...
165,751
from typing import Any, Dict, List, Optional from functools import lru_cache from decimal import Decimal import logging import json import io from sqlalchemy import create_engine, text from sqlalchemy.engine import Engine import pandas as pd import sqlglot.expressions as exp import sqlglot from .base import BaseDataPar...
check view sql, it will raise ViewSqlSameColumnError if view sql contain same column
165,752
from typing import Generic, Dict, List, Any, Optional, NamedTuple from typing_extensions import Literal from functools import lru_cache from datetime import datetime, date from datetime import timedelta import abc import io import duckdb import arrow import pytz from pygwalker._typing import DataFrame from pygwalker.ut...
check if field is temporal
165,753
from typing import Generic, Dict, List, Any, Optional, NamedTuple from typing_extensions import Literal from functools import lru_cache from datetime import datetime, date from datetime import timedelta import abc import io import duckdb import arrow import pytz from pygwalker._typing import DataFrame from pygwalker.ut...
check if filed is
165,754
from typing import Generic, Dict, List, Any, Optional, NamedTuple from typing_extensions import Literal from functools import lru_cache from datetime import datetime, date from datetime import timedelta import abc import io import duckdb import arrow import pytz from pygwalker._typing import DataFrame from pygwalker.ut...
Convert temporal fields to a fixed format
165,755
from typing import Generic, Dict, List, Any, Optional, NamedTuple from typing_extensions import Literal from functools import lru_cache from datetime import datetime, date from datetime import timedelta import abc import io import duckdb import arrow import pytz from pygwalker._typing import DataFrame from pygwalker.ut...
null
165,756
from typing import Generic, Dict, List, Any, Optional, NamedTuple from typing_extensions import Literal from functools import lru_cache from datetime import datetime, date from datetime import timedelta import abc import io import duckdb import arrow import pytz from pygwalker._typing import DataFrame from pygwalker.ut...
null
165,757
from typing import Dict, Any, Optional import segment.analytics as analytics import kanaries_track from pygwalker.services.global_var import GlobalVarManager from pygwalker.services.config import get_local_user_id analytics.write_key = 'z58N15R8LShkpUbBSt1ZjdDSdSEF5VpR' kanaries_track.config.auth_token = kanaries_publi...
Track an event in Segment and Kanaries. When privacy config of user is 'events', PyGWalker will collect certain events data share which events about which feature is used in pygwalker, it only contains events tag about which feature you arrive for product optimization. No DATA YOU ANALYZE IS SENT. We only use these dat...
165,758
from urllib import request from typing import Tuple, Dict, Any, List from distutils.version import StrictVersion from copy import deepcopy import json import os from pygwalker.services.global_var import GlobalVarManager from pygwalker.utils.randoms import rand_str from pygwalker.services.fname_encodings import rename_c...
when df schema changed, fill new fields to every chart config
165,759
from urllib import request from typing import Tuple, Dict, Any, List from distutils.version import StrictVersion from copy import deepcopy import json import os from pygwalker.services.global_var import GlobalVarManager from pygwalker.utils.randoms import rand_str from pygwalker.services.fname_encodings import rename_c...
null
165,760
from typing import Dict, Any, List import time import json import html as m_html from pygwalker.utils.randoms import rand_str from pygwalker.utils.display import display_html from pygwalker.utils.encode import DataFrameEncoder from pygwalker.communications.base import BaseCommunication from pygwalker import __hash__ de...
null
165,761
from typing import Dict, Any, List import time import json import html as m_html from pygwalker.utils.randoms import rand_str from pygwalker.utils.display import display_html from pygwalker.utils.encode import DataFrameEncoder from pygwalker.communications.base import BaseCommunication from pygwalker import __hash__ d...
null
165,762
from http.server import BaseHTTPRequestHandler, HTTPServer from typing import Any from urllib.parse import urlparse, parse_qs, quote from threading import Thread, Lock import socket import webbrowser from pygwalker.services.config import set_config AUTH_HOST = "https://kanaries.net" auth_info = {} wait_lock = Lock() cl...
null
165,763
from typing import List from math import ceil from collections import defaultdict def base36encode(s: str) -> str: """Converts an string to a base36 string.""" alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' number = int.from_bytes(s.encode(), "big") if not isinstance(number, int): raise TypeE...
Encode fname in base32 Args: - fname (str): Suppose to be str Returns: str
165,764
from typing import List from math import ceil from collections import defaultdict def base36decode(s: str) -> str: """Converts a base36 string to an string.""" number = int(s, 36) return number.to_bytes(ceil(number.bit_length() / 8), "big").decode() The provided code snippet includes necessary dependencies...
Decode fname in base32
165,765
from typing import Optional, List, Dict, Any import base64 import zlib import json from pydantic import BaseModel, Field from pygwalker.utils.encode import DataFrameEncoder from pygwalker.utils.display import display_html from pygwalker.utils.randoms import generate_hash_code from pygwalker.services.render import jinja...
null