id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
143,237 | from __future__ import annotations
from aiohttp import ClientSession
from hashlib import sha256
from ...typing import AsyncResult, Messages, Dict
from ..base_provider import AsyncGeneratorProvider
from ..helper import format_prompt
def _create_payload(message: str) -> Dict[str, str]:
return {
'message': me... | null |
143,238 | from __future__ import annotations
import hashlib
import time
import uuid
import json
from datetime import datetime
from aiohttp import ClientSession
from ...typing import SHA256, AsyncResult, Messages
from ..base_provider import AsyncGeneratorProvider
SHA256 = NewType('sha_256_hash', str)
def _hash(json_data: dict[s... | null |
143,239 | from __future__ import annotations
import hashlib
import time
import uuid
import json
from datetime import datetime
from aiohttp import ClientSession
from ...typing import SHA256, AsyncResult, Messages
from ..base_provider import AsyncGeneratorProvider
def _format_timestamp(timestamp: int) -> str:
e = timestamp
... | null |
143,240 | from __future__ import annotations
import re
import json
from urllib import parse
from datetime import datetime
from ...typing import AsyncResult, Messages
from ..base_provider import AsyncGeneratorProvider
from ...requests import StreamSession
def prng_general(seed, multiplier, addend, modulus):
a = seed * multipl... | null |
143,241 | from __future__ import annotations
import time
import hashlib
from ...typing import AsyncResult, Messages
from ...requests import StreamSession
from ..base_provider import AsyncGeneratorProvider
def generate_signature(timestamp: int, message: str, secret: str = "undefined"):
data = f"{timestamp}:{message}:{secret}... | null |
143,242 | from __future__ import annotations
import json, uuid, hashlib, time, random
from aiohttp import ClientSession
from aiohttp.http import WSMsgType
import asyncio
from ...typing import AsyncResult, Messages
from ..base_provider import AsyncGeneratorProvider, format_prompt
def generate_timestamp() -> str:
return str(
... | null |
143,243 | from __future__ import annotations
import json, uuid, hashlib, time, random
from aiohttp import ClientSession
from aiohttp.http import WSMsgType
import asyncio
from ...typing import AsyncResult, Messages
from ..base_provider import AsyncGeneratorProvider, format_prompt
def xor_hash(B: str):
r = []
i = 0
def... | null |
143,244 | from __future__ import annotations
import random
import json
import uuid
import time
import asyncio
from urllib import parse
from datetime import datetime
from aiohttp import ClientSession, ClientTimeout, BaseConnector, WSMsgType
from ..typing import AsyncResult, Messages, ImageType, Cookies
from ..image import ImageRe... | Creates a context string from a list of messages. :param messages: A list of message dictionaries. :return: A string representing the context created from the messages. |
143,245 | from __future__ import annotations
import random
import json
import uuid
import time
import asyncio
from urllib import parse
from datetime import datetime
from aiohttp import ClientSession, ClientTimeout, BaseConnector, WSMsgType
from ..typing import AsyncResult, Messages, ImageType, Cookies
from ..image import ImageRe... | Asynchronously streams generated responses from the Bing API. :param prompt: The user's input prompt. :param tone: The desired tone for the response. :param image: The image type involved in the response. :param context: Additional context for the prompt. :param cookies: Cookies for the session. :param web_search: Flag... |
143,246 | from __future__ import annotations
import time, hashlib, random
from ..typing import AsyncResult, Messages
from ..requests import StreamSession
from .base_provider import AsyncGeneratorProvider
from ..errors import RateLimitError
def generate_signature(timestamp: int, message: str, secret: str = ""):
data = f"{tim... | null |
143,247 | from __future__ import annotations
from aiohttp import ClientSession
from ...requests import raise_for_status
The provided code snippet includes necessary dependencies for implementing the `list_conversations` function. Write a Python function `async def list_conversations(session: ClientSession) -> list` to solve the... | List all conversations asynchronously. Args: session (ClientSession): An instance of aiohttp's ClientSession. Returns: list: A list of conversations. |
143,248 | from __future__ import annotations
import asyncio
import time
import json
from aiohttp import ClientSession, BaseConnector
from urllib.parse import quote
from typing import List, Dict
from ...providers.create_images import CreateImagesProvider
from ..helper import get_connector
from ...providers.types import ProviderTy... | Retrieves cookies from the browser using webdriver. Args: proxy (str, optional): Proxy configuration. Returns: dict[str, str]: Retrieved cookies. |
143,249 | from __future__ import annotations
import asyncio
import time
import json
from aiohttp import ClientSession, BaseConnector
from urllib.parse import quote
from typing import List, Dict
from ...providers.create_images import CreateImagesProvider
from ..helper import get_connector
from ...providers.types import ProviderTy... | Creates a new client session with specified cookies and headers. Args: cookies (Dict[str, str]): Cookies to be used for the session. Returns: ClientSession: The created client session. |
143,250 | from __future__ import annotations
import asyncio
import time
import json
from aiohttp import ClientSession, BaseConnector
from urllib.parse import quote
from typing import List, Dict
from ...providers.create_images import CreateImagesProvider
from ..helper import get_connector
from ...providers.types import ProviderTy... | Creates images based on a given prompt using Bing's service. Args: session (ClientSession): Active client session. prompt (str): Prompt to generate images. proxy (str, optional): Proxy configuration. timeout (int): Timeout for the request. Returns: List[str]: A list of URLs to the created images. Raises: RuntimeError: ... |
143,251 | from __future__ import annotations
import asyncio
import time
import json
from aiohttp import ClientSession, BaseConnector
from urllib.parse import quote
from typing import List, Dict
from ...providers.create_images import CreateImagesProvider
from ..helper import get_connector
from ...providers.types import ProviderTy... | Patches a provider to include image creation capabilities. Args: provider (ProviderType): The provider to be patched. Returns: CreateImagesProvider: The patched provider with image creation capabilities. |
143,252 | from __future__ import annotations
import re
import os
import time
import random
import string
from .stubs import ChatCompletion, ChatCompletionChunk, Image, ImagesResponse
from .typing import Union, Iterator, Messages, ImageType
from .providers.types import BaseProvider, ProviderType
from .image import ImageResponse a... | null |
143,253 | from __future__ import annotations
import re
import os
import time
import random
import string
from .stubs import ChatCompletion, ChatCompletionChunk, Image, ImagesResponse
from .typing import Union, Iterator, Messages, ImageType
from .providers.types import BaseProvider, ProviderType
from .image import ImageResponse a... | null |
143,254 | from __future__ import annotations
import re
import os
import time
import random
import string
from .stubs import ChatCompletion, ChatCompletionChunk, Image, ImagesResponse
from .typing import Union, Iterator, Messages, ImageType
from .providers.types import BaseProvider, ProviderType
from .image import ImageResponse a... | null |
143,255 | from __future__ import annotations
import re
import os
import time
import random
import string
from .stubs import ChatCompletion, ChatCompletionChunk, Image, ImagesResponse
from .typing import Union, Iterator, Messages, ImageType
from .providers.types import BaseProvider, ProviderType
from .image import ImageResponse a... | null |
143,256 | from __future__ import annotations
import re
import os
import time
import random
import string
from .stubs import ChatCompletion, ChatCompletionChunk, Image, ImagesResponse
from .typing import Union, Iterator, Messages, ImageType
from .providers.types import BaseProvider, ProviderType
from .image import ImageResponse a... | null |
143,257 | from __future__ import annotations
import asyncio
import random
from ..typing import Type, List, CreateResult, Messages, Iterator
from .types import BaseProvider, BaseRetryProvider
from .. import debug
from ..errors import RetryProviderError, RetryNoProviderError
class RetryProviderError(Exception):
...
class Ret... | Raise a combined exception if any occurred during retries. Raises: RetryProviderError: If any provider encountered an exception. RetryNoProviderError: If no provider is found. |
143,258 | from __future__ import annotations
import sys
import asyncio
from asyncio import AbstractEventLoop
from concurrent.futures import ThreadPoolExecutor
from abc import abstractmethod
from inspect import signature, Parameter
from ..typing import CreateResult, AsyncResult, Messages, Union
from .types import BaseProvider
fro... | null |
143,259 | from __future__ import annotations
import random
import string
from ..typing import Messages
Messages = List[Dict[str, str]]
The provided code snippet includes necessary dependencies for implementing the `format_prompt` function. Write a Python function `def format_prompt(messages: Messages, add_special_tokens=False)... | Format a series of messages into a single string, optionally adding special tokens. Args: messages (Messages): A list of message dictionaries, each containing 'role' and 'content'. add_special_tokens (bool): Whether to add special formatting tokens. Returns: str: A formatted string containing all messages. |
143,260 | from __future__ import annotations
import random
import string
from ..typing import Messages
The provided code snippet includes necessary dependencies for implementing the `get_random_string` function. Write a Python function `def get_random_string(length: int = 10) -> str` to solve the following problem:
Generate a r... | Generate a random string of specified length, containing lowercase letters and digits. Args: length (int, optional): Length of the random string to generate. Defaults to 10. Returns: str: A random string of the specified length. |
143,261 | from __future__ import annotations
import random
import string
from ..typing import Messages
The provided code snippet includes necessary dependencies for implementing the `get_random_hex` function. Write a Python function `def get_random_hex(length: int = 32) -> str` to solve the following problem:
Generate a random ... | Generate a random hexadecimal string with n length. Returns: str: A random hexadecimal string of n characters. |
143,262 | import sys
import os.path
import webview
from g4f.gui.run import gui_parser
from g4f.gui.server.api import Api
import g4f.version
import g4f.debug
import webview
class Api():
def get_models(self) -> list[str]:
"""
Return a list of all models.
Fetches and returns a list of all available m... | null |
143,263 | from argparse import ArgumentParser
def gui_parser():
parser = ArgumentParser(description="Run the GUI")
parser.add_argument("-host", type=str, default="0.0.0.0", help="hostname")
parser.add_argument("-port", type=int, default=8080, help="port")
parser.add_argument("-debug", action="store_true", help="... | null |
143,264 | from argparse import ArgumentParser
def run_gui(host: str = '0.0.0.0', port: int = 8080, debug: bool = False) -> None:
try:
from .server.app import app
from .server.website import Website
from .server.backend import Backend_Api
except ImportError:
raise MissingRequirementsEr... | null |
143,265 | import logging
import json
from typing import Iterator
from g4f import version, models
from g4f import get_last_provider, ChatCompletion
from g4f.errors import VersionNotFoundError
from g4f.Provider import ProviderType, __providers__, __map__
from g4f.providers.base_provider import ProviderModelMixin
from g4f.Provider.... | Generates a formatted error message from an exception. Args: exception (Exception): The exception to format. Returns: str: A formatted error message string. |
143,266 | from __future__ import annotations
from aiohttp import ClientSession, ClientTimeout
from ...errors import MissingRequirementsError
import asyncio
async def search(query: str, n_results: int = 5, max_words: int = 2500, add_text: bool = True) -> SearchResults:
if not has_requirements:
raise MissingRequirement... | null |
143,267 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `normalize_data` function. Write a Python function `def normalize_data(batch_data)` to solve the following problem:
Normalize the batch data, use coordinates of the block centered at origin, Input: BxNxC array Output: BxN... | Normalize the batch data, use coordinates of the block centered at origin, Input: BxNxC array Output: BxNxC array |
143,268 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `shuffle_data` function. Write a Python function `def shuffle_data(data, labels)` to solve the following problem:
Shuffle data and labels. Input: data: B,N,... numpy array label: B,... numpy array Return: shuffled data, l... | Shuffle data and labels. Input: data: B,N,... numpy array label: B,... numpy array Return: shuffled data, label and shuffle indices |
143,269 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `shuffle_points` function. Write a Python function `def shuffle_points(batch_data)` to solve the following problem:
Shuffle orders of points in each point cloud -- changes FPS behavior. Use the same shuffling idx for the ... | Shuffle orders of points in each point cloud -- changes FPS behavior. Use the same shuffling idx for the entire batch. Input: BxNxC array Output: BxNxC array |
143,270 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_point_cloud` function. Write a Python function `def rotate_point_cloud(batch_data)` to solve the following problem:
Randomly rotate the point clouds to augument the dataset rotation is per shape based along up dir... | Randomly rotate the point clouds to augument the dataset rotation is per shape based along up direction Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds |
143,271 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_point_cloud_z` function. Write a Python function `def rotate_point_cloud_z(batch_data)` to solve the following problem:
Randomly rotate the point clouds to augument the dataset rotation is per shape based along up... | Randomly rotate the point clouds to augument the dataset rotation is per shape based along up direction Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds |
143,272 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_point_cloud_with_normal` function. Write a Python function `def rotate_point_cloud_with_normal(batch_xyz_normal)` to solve the following problem:
Randomly rotate XYZ, normal point cloud. Input: batch_xyz_normal: B... | Randomly rotate XYZ, normal point cloud. Input: batch_xyz_normal: B,N,6, first three channels are XYZ, last 3 all normal Output: B,N,6, rotated XYZ, normal point cloud |
143,273 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_perturbation_point_cloud_with_normal` function. Write a Python function `def rotate_perturbation_point_cloud_with_normal(batch_data, angle_sigma=0.06, angle_clip=0.18)` to solve the following problem:
Randomly per... | Randomly perturb the point clouds by small rotations Input: BxNx6 array, original batch of point clouds and point normals Return: BxNx3 array, rotated batch of point clouds |
143,274 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_point_cloud_by_angle` function. Write a Python function `def rotate_point_cloud_by_angle(batch_data, rotation_angle)` to solve the following problem:
Rotate the point cloud along up direction with certain angle. I... | Rotate the point cloud along up direction with certain angle. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds |
143,275 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_point_cloud_by_angle_with_normal` function. Write a Python function `def rotate_point_cloud_by_angle_with_normal(batch_data, rotation_angle)` to solve the following problem:
Rotate the point cloud along up directi... | Rotate the point cloud along up direction with certain angle. Input: BxNx6 array, original batch of point clouds with normal scalar, angle of rotation Return: BxNx6 array, rotated batch of point clouds iwth normal |
143,276 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotate_perturbation_point_cloud` function. Write a Python function `def rotate_perturbation_point_cloud(batch_data, angle_sigma=0.06, angle_clip=0.18)` to solve the following problem:
Randomly perturb the point clouds by... | Randomly perturb the point clouds by small rotations Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds |
143,277 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `jitter_point_cloud` function. Write a Python function `def jitter_point_cloud(batch_data, sigma=0.01, clip=0.05)` to solve the following problem:
Randomly jitter points. jittering is per point. Input: BxNx3 array, origin... | Randomly jitter points. jittering is per point. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, jittered batch of point clouds |
143,278 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `shift_point_cloud` function. Write a Python function `def shift_point_cloud(batch_data, shift_range=0.1)` to solve the following problem:
Randomly shift point cloud. Shift is per point cloud. Input: BxNx3 array, original... | Randomly shift point cloud. Shift is per point cloud. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, shifted batch of point clouds |
143,279 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `random_scale_point_cloud` function. Write a Python function `def random_scale_point_cloud(batch_data, scale_low=0.8, scale_high=1.25)` to solve the following problem:
Randomly scale the point cloud. Scale is per point cl... | Randomly scale the point cloud. Scale is per point cloud. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, scaled batch of point clouds |
143,280 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `random_point_dropout` function. Write a Python function `def random_point_dropout(batch_pc, max_dropout_ratio=0.875)` to solve the following problem:
batch_pc: BxNx3
Here is the function:
def random_point_dropout(batch... | batch_pc: BxNx3 |
143,281 | import argparse
import os
from data_utils.S3DISDataLoader import S3DISDataset
import torch
import datetime
import logging
from pathlib import Path
import sys
import importlib
import shutil
from tqdm import tqdm
import provider
import numpy as np
import time
if __name__ == '__main__':
args = parse_args()
main(ar... | null |
143,282 | import argparse
import os
from data_utils.S3DISDataLoader import S3DISDataset
import torch
import datetime
import logging
from pathlib import Path
import sys
import importlib
import shutil
from tqdm import tqdm
import provider
import numpy as np
import time
def parse_args():
parser = argparse.ArgumentParser('Model... | null |
143,283 | import argparse
import os
import torch
import datetime
import logging
import sys
import importlib
import shutil
import provider
import numpy as np
from pathlib import Path
from tqdm import tqdm
from data_utils.ShapeNetDataLoader import PartNormalDataset
if __name__ == '__main__':
args = parse_args()
main(args)
... | null |
143,284 | import argparse
import os
import torch
import datetime
import logging
import sys
import importlib
import shutil
import provider
import numpy as np
from pathlib import Path
from tqdm import tqdm
from data_utils.ShapeNetDataLoader import PartNormalDataset
The provided code snippet includes necessary dependencies for imp... | 1-hot encodes a tensor |
143,285 | import argparse
import os
import torch
import datetime
import logging
import sys
import importlib
import shutil
import provider
import numpy as np
from pathlib import Path
from tqdm import tqdm
from data_utils.ShapeNetDataLoader import PartNormalDataset
def parse_args():
parser = argparse.ArgumentParser('Model')
... | null |
143,286 | import math
import sys
import numpy as np
def mat2euler(M, cy_thresh=None):
''' Discover Euler angle vector from 3x3 matrix
Uses the conventions above.
Parameters
----------
M : array-like, shape (3,3)
cy_thresh : None or scalar, optional
threshold below which to give up on straightforwar... | Return Euler angles corresponding to quaternion `q` Parameters ---------- q : 4 element sequence w, x, y, z of quaternion Returns ------- z : scalar Rotation angle in radians around z-axis (performed first) y : scalar Rotation angle in radians around y-axis x : scalar Rotation angle in radians around x-axis (performed ... |
143,287 | import math
import sys
import numpy as np
def euler2quat(z=0, y=0, x=0):
''' Return quaternion corresponding to these Euler angles
Uses the z, then y, then x convention above
Parameters
----------
z : scalar
Rotation angle in radians around z-axis (performed first)
y : scalar
Rotat... | Return angle, axis corresponding to these Euler angles Uses the z, then y, then x convention above Parameters ---------- z : scalar Rotation angle in radians around z-axis (performed first) y : scalar Rotation angle in radians around y-axis x : scalar Rotation angle in radians around x-axis (performed last) Returns ---... |
143,288 | import math
import sys
import numpy as np
def mat2euler(M, cy_thresh=None):
''' Discover Euler angle vector from 3x3 matrix
Uses the conventions above.
Parameters
----------
M : array-like, shape (3,3)
cy_thresh : None or scalar, optional
threshold below which to give up on straightforwar... | Convert angle, axis pair to Euler angles Parameters ---------- theta : scalar angle of rotation vector : 3 element sequence vector specifying axis for rotation. is_normalized : bool, optional True if vector is already normalized (has norm of 1). Default False Returns ------- z : scalar y : scalar x : scalar Rotations i... |
143,289 | import numpy as np
import ctypes as ct
import cv2
import sys
import os
showsz = 800
mousex, mousey = 0.5, 0.5
changed = True
def onmouse(*args):
global mousex, mousey, changed
y = args[1]
x = args[2]
mousex = x / float(showsz)
mousey = y / float(showsz)
changed = True | null |
143,290 | import numpy as np
import ctypes as ct
import cv2
import sys
import os
showsz = 800
mousex, mousey = 0.5, 0.5
zoom = 1.0
changed = True
cv2.namedWindow('show3d')
cv2.moveWindow('show3d', 0, 0)
cv2.setMouseCallback('show3d', onmouse)
dll = np.ctypeslib.load_library(os.path.join(BASE_DIR, 'render_balls_so'), '.')
def sh... | null |
143,291 | import os
import sys
from visualizer.eulerangles import euler2mat
import numpy as np
from visualizer.plyfile import PlyData, PlyElement
def point_cloud_to_volume(points, vsize, radius=1.0):
""" input is Nx3 points.
output is vsize*vsize*vsize
assumes points are in range [-radius, radius]
"""
... | Input is BxNx3 batch of point cloud Output is Bx(vsize^3) |
143,292 | import os
import sys
from visualizer.eulerangles import euler2mat
import numpy as np
from visualizer.plyfile import PlyData, PlyElement
from PIL import Image
class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to rea... | read XYZ point cloud from filename PLY file |
143,293 | import os
import sys
from visualizer.eulerangles import euler2mat
import numpy as np
from visualizer.plyfile import PlyData, PlyElement
from PIL import Image
class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to rea... | input: Nx3, write points to filename as PLY format. |
143,294 | import os
import sys
from visualizer.eulerangles import euler2mat
import numpy as np
from visualizer.plyfile import PlyData, PlyElement
def point_cloud_three_views(points):
""" input points Nx3 numpy array (+y is up direction).
return an numpy array gray image of size 500x1500. """
# +y is up direction
... | Demo for draw_point_cloud function |
143,295 | import os
import sys
from visualizer.eulerangles import euler2mat
import numpy as np
from visualizer.plyfile import PlyData, PlyElement
def volume_to_point_cloud(vol):
""" vol is occupancy grid (value = 0 or 1) of size vsize*vsize*vsize
return Nx3 numpy array.
"""
vsize = vol.shape[0]
assert (vo... | vol is of size vsize*vsize*vsize output an image to output_filename |
143,296 | from itertools import islice as _islice
import numpy as _np
from sys import byteorder as _byteorder
_data_types = dict(_data_type_relation)
_data_type_reverse = dict((b, a) for (a, b) in _data_type_relation)
_types_list = []
def _lookup_type(type_str):
if type_str not in _data_type_reverse:
try:
... | null |
143,297 | from itertools import islice as _islice
import numpy as _np
from sys import byteorder as _byteorder
def _split_line(line, n):
fields = line.split(None, n)
if len(fields) == n:
fields.append('')
assert len(fields) == n + 1
return fields | null |
143,298 | from itertools import islice as _islice
import numpy as _np
from sys import byteorder as _byteorder
The provided code snippet includes necessary dependencies for implementing the `make2d` function. Write a Python function `def make2d(array, cols=None, dtype=None)` to solve the following problem:
Make a 2D array from a... | Make a 2D array from an array of arrays. The `cols' and `dtype' arguments can be omitted if the array is not empty. |
143,299 | from itertools import islice as _islice
import numpy as _np
from sys import byteorder as _byteorder
def _open_stream(stream, read_or_write):
if hasattr(stream, read_or_write):
return (False, stream)
try:
return (True, open(stream, read_or_write[0] + 'b'))
except TypeError:
raise Run... | null |
143,300 | import os
import numpy as np
import warnings
import pickle
from tqdm import tqdm
from torch.utils.data import Dataset
def pc_normalize(pc):
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
pc = pc / m
return pc | null |
143,301 | import os
import numpy as np
import warnings
import pickle
from tqdm import tqdm
from torch.utils.data import Dataset
The provided code snippet includes necessary dependencies for implementing the `farthest_point_sample` function. Write a Python function `def farthest_point_sample(point, npoint)` to solve the followin... | Input: xyz: pointcloud data, [N, D] npoint: number of samples Return: centroids: sampled pointcloud index, [npoint, D] |
143,302 | import os
import json
import warnings
import numpy as np
from torch.utils.data import Dataset
def pc_normalize(pc):
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))
pc = pc / m
return pc | null |
143,303 | import os
import numpy as np
from tqdm import tqdm
from torch.utils.data import Dataset
def worker_init_fn(worker_id):
random.seed(manual_seed + worker_id) | null |
143,304 | import numpy as np
import glob
import os
import sys
def data_to_obj(data,name='example.obj',no_wall=True):
fout = open(name, 'w')
label = data[:, -1].astype(int)
for i in range(data.shape[0]):
if no_wall and ((label[i] == 2) or (label[i]==0)):
continue
fout.write('v %f %f %f %d ... | null |
143,305 | import numpy as np
import glob
import os
import sys
g_easy_view_labels = [7,8,9,10,11,1]
g_label2color = {g_classes.index(cls): g_class2color[cls] for cls in g_classes}
The provided code snippet includes necessary dependencies for implementing the `point_label_to_obj` function. Write a Python function `def point_label... | For visualization of a room from data_label file, input_filename: each line is X Y Z R G B L out_filename: OBJ filename, visualize input file by coloring point with label color easy_view: only visualize furnitures and floor |
143,306 | import numpy as np
import glob
import os
import sys
def room2blocks_plus(data_label, num_point, block_size, stride,
random_sample, sample_num, sample_aug):
""" room2block with input filename and RGB preprocessing.
"""
data = data_label[:,0:6]
data[:,3:6] /= 255.0
label = data_la... | null |
143,307 | import numpy as np
import glob
import os
import sys
def room2blocks_plus_normalized(data_label, num_point, block_size, stride,
random_sample, sample_num, sample_aug):
""" room2block, with input filename and RGB preprocessing.
for each block centralize XYZ, add normalized XYZ ... | null |
143,308 | import numpy as np
import glob
import os
import sys
def room2samples_plus_normalized(data_label, num_point):
def room2samples_wrapper_normalized(data_label_filename, num_point):
if data_label_filename[-3:] == 'txt':
data_label = np.loadtxt(data_label_filename)
elif data_label_filename[-3:] == 'npy':
... | null |
143,309 | import numpy as np
import glob
import os
import sys
g_classes = [x.rstrip() for x in open(os.path.join(BASE_DIR, 'meta/class_names.txt'))]
g_class2label = {cls: i for i,cls in enumerate(g_classes)}
The provided code snippet includes necessary dependencies for implementing the `collect_bounding_box` function. Write a P... | Compute bounding boxes from each instance in original dataset files on one room. **We assume the bbox is aligned with XYZ coordinate.** Args: anno_path: path to annotations. e.g. Area_1/office_2/Annotations/ out_filename: path to save instance bounding boxes for that room. each line is x1 y1 z1 x2 y2 z2 label, where (x... |
143,310 | import numpy as np
import glob
import os
import sys
g_classes = [x.rstrip() for x in open(os.path.join(BASE_DIR, 'meta/class_names.txt'))]
g_easy_view_labels = [7,8,9,10,11,1]
g_label2color = {g_classes.index(cls): g_class2color[cls] for cls in g_classes}
The provided code snippet includes necessary dependencies for ... | Visualization of bounding boxes. Args: input_filename: each line is x1 y1 z1 x2 y2 z2 label out_filename_prefix: OBJ filename prefix, visualize object by g_label2color easy_view: if True, only visualize furniture and floor Returns: output a list of OBJ file and MTL files with the same prefix |
143,311 | import numpy as np
import glob
import os
import sys
g_classes = [x.rstrip() for x in open(os.path.join(BASE_DIR, 'meta/class_names.txt'))]
g_easy_view_labels = [7,8,9,10,11,1]
g_label2color = {g_classes.index(cls): g_class2color[cls] for cls in g_classes}
The provided code snippet includes necessary dependencies for ... | Visualization of bounding boxes. Args: input_filename: each line is x1 y1 z1 x2 y2 z2 label out_filename_prefix: OBJ filename prefix, visualize object by g_label2color easy_view: if True, only visualize furniture and floor permute: if not None, permute XYZ for rendering, e.g. [0 2 1] center: if True, move obj to have z... |
143,312 | import numpy as np
import glob
import os
import sys
g_classes = [x.rstrip() for x in open(os.path.join(BASE_DIR, 'meta/class_names.txt'))]
g_class2label = {cls: i for i,cls in enumerate(g_classes)}
The provided code snippet includes necessary dependencies for implementing the `collect_point_bounding_box` function. Wri... | Compute bounding boxes from each instance in original dataset files on one room. **We assume the bbox is aligned with XYZ coordinate.** Save both the point XYZRGB and the bounding box for the point's parent element. Args: anno_path: path to annotations. e.g. Area_1/office_2/Annotations/ out_filename: path to save insta... |
143,313 | import os
import sys
import torch
import numpy as np
import datetime
import logging
import provider
import importlib
import shutil
import argparse
from pathlib import Path
from tqdm import tqdm
from data_utils.ModelNetDataLoader import ModelNetDataLoader
The provided code snippet includes necessary dependencies for im... | PARAMETERS |
143,314 | import os
import sys
import torch
import numpy as np
import datetime
import logging
import provider
import importlib
import shutil
import argparse
from pathlib import Path
from tqdm import tqdm
from data_utils.ModelNetDataLoader import ModelNetDataLoader
if __name__ == '__main__':
args = parse_args()
main(args)... | null |
143,315 | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
def timeit(tag, t):
print("{}: {}s".format(tag, time() - t))
return time() | null |
143,316 | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
def pc_normalize(pc):
l = pc.shape[0]
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
pc = pc / m
return pc | null |
143,317 | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
def index_points(points, idx):
"""
Input:
points: input points data, [B, N, C]
idx: sample index data, [B, S]
Return:
new_points:, indexed points data, [B, S, C]
"""
de... | Input: npoint: radius: nsample: xyz: input points position data, [B, N, 3] points: input points data, [B, N, D] Return: new_xyz: sampled points position data, [B, npoint, nsample, 3] new_points: sampled points data, [B, npoint, nsample, 3+D] |
143,318 | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `sample_and_group_all` function. Write a Python function `def sample_and_group_all(xyz, points)` to solve the following problem:
Inp... | Input: xyz: input points position data, [B, N, 3] points: input points data, [B, N, D] Return: new_xyz: sampled points position data, [B, 1, 3] new_points: sampled points data, [B, 1, N, 3+D] |
143,335 | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
def feature_transform_reguliarzer(trans):
d = trans.size()[1]
I = torch.eye(d)[None, :, :]
if trans.is_cuda:
I = I.cuda()
lo... | null |
143,340 | import json
from typing import List, Optional
from langchain.base_language import BaseLanguageModel
from langchain.chat_models.anthropic import ChatAnthropic
from codeinterpreterapi.prompts import determine_modifications_prompt
def get_file_modifications(
code: str,
llm: BaseLanguageModel,
retry: int = 2,
... | null |
143,341 | import json
from typing import List, Optional
from langchain.base_language import BaseLanguageModel
from langchain.chat_models.anthropic import ChatAnthropic
from codeinterpreterapi.prompts import determine_modifications_prompt
async def aget_file_modifications(
code: str,
llm: BaseLanguageModel,
retry: in... | null |
143,342 | from langchain.base_language import BaseLanguageModel
from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import AIMessage, OutputParserException
from codeinterpreterapi.prompts import remove_dl_link_prompt
def remove_download_link(
input_response: str,
llm: BaseLanguageModel,
) -> str:
... | null |
143,343 | from langchain.base_language import BaseLanguageModel
from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import AIMessage, OutputParserException
from codeinterpreterapi.prompts import remove_dl_link_prompt
async def aremove_download_link(
input_response: str,
llm: BaseLanguageModel,
) ->... | null |
143,344 | from langchain.base_language import BaseLanguageModel
from langchain.chat_models.anthropic import ChatAnthropic
def extract_python_code(
text: str,
llm: BaseLanguageModel,
retry: int = 2,
) -> str:
return "TODO" | null |
143,345 | from langchain.base_language import BaseLanguageModel
from langchain.chat_models.anthropic import ChatAnthropic
async def aextract_python_code(
text: str,
llm: BaseLanguageModel,
retry: int = 2,
) -> str:
return "TODO" | null |
143,346 | import base64
import re
import traceback
from io import BytesIO
from types import TracebackType
from typing import Any, Optional, Type
from uuid import UUID, uuid4
from codeboxapi import CodeBox
from codeboxapi.schema import CodeBoxOutput
from langchain.agents import (
AgentExecutor,
BaseSingleActionAgent,
... | null |
143,347 | import asyncio
import json
from json import JSONDecodeError
from typing import List, Union
from langchain_core.agents import AgentAction, AgentActionMessageLog, AgentFinish
from langchain_core.exceptions import OutputParserException
from langchain_core.messages import (
AIMessage,
BaseMessage,
)
from langchain_... | Patch the parser. |
143,348 | import chainlit as cl
from codeinterpreterapi import CodeInterpreterSession
from codeinterpreterapi import File as CIFile
UPLOADED_FILES: list[CIFile] = []
async def on_action(action: cl.Action) -> None:
files = None
# Wait for the user to upload a file
while files is None:
files = await cl.AskF... | null |
143,349 | import chainlit as cl
from codeinterpreterapi import CodeInterpreterSession
from codeinterpreterapi import File as CIFile
async def start_chat() -> None:
actions = [
cl.Action(name="upload_file", value="example_value", description="Upload file")
]
await cl.Message(
content="Hello, How ca... | null |
143,350 | import chainlit as cl
from codeinterpreterapi import CodeInterpreterSession
from codeinterpreterapi import File as CIFile
UPLOADED_FILES: list[CIFile] = []
async def run_conversation(user_message: str) -> None:
session = CodeInterpreterSession()
await session.astart()
files = [CIFile(name=it.name, conte... | null |
143,351 | import os
import shutil
import tempfile
from typing import Optional
import streamlit as st
from codeinterpreterapi import CodeInterpreterSession
The provided code snippet includes necessary dependencies for implementing the `create_temp_folder` function. Write a Python function `def create_temp_folder() -> str` to sol... | Creates a temp folder |
143,352 | import os
import shutil
import tempfile
from typing import Optional
import streamlit as st
from codeinterpreterapi import CodeInterpreterSession
async def get_images(prompt: str, files: Optional[list] = None) -> list:
if files is None:
files = []
with st.chat_message("user"): # type: ignore
st... | null |
143,353 | import glob
import os
import torch
from setuptools import find_packages
from setuptools import setup
from torch.utils.cpp_extension import CUDA_HOME
from torch.utils.cpp_extension import CppExtension
from torch.utils.cpp_extension import CUDAExtension
def get_extensions():
extensions_dir = os.path.join("fcos_core"... | null |
143,354 | import cv2
import torch
from torchvision import transforms as T
from fcos_core.modeling.detector import build_detection_model
from fcos_core.utils.checkpoint import DetectronCheckpointer
from fcos_core.structures.image_list import to_image_list
from fcos_core.modeling.roi_heads.mask_head.inference import Masker
from fc... | Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob). |
143,355 | import torch
def _create_flip_indices(names, flip_map):
full_flip_map = flip_map.copy()
full_flip_map.update({v: k for k, v in flip_map.items()})
flipped_names = [i if i not in full_flip_map else full_flip_map[i] for i in names]
flip_indices = [names.index(i) for i in flipped_names]
return torch.te... | null |
143,356 | import torch
def kp_connections(keypoints):
kp_lines = [
[keypoints.index('left_eye'), keypoints.index('right_eye')],
[keypoints.index('left_eye'), keypoints.index('nose')],
[keypoints.index('right_eye'), keypoints.index('nose')],
[keypoints.index('right_eye'), keypoints.index('righ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.