repo_name stringlengths 2 55 | dataset stringclasses 1
value | owner stringlengths 3 31 | lang stringclasses 10
values | func_name stringlengths 1 104 | code stringlengths 20 96.7k | docstring stringlengths 1 4.92k | url stringlengths 94 241 | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
sound_dataset_tools2 | github_2023 | kslz | python | del_dataset | def del_dataset(self, dataset_id, dataset_name):
"""
考虑做伪删除,但是感觉没必要
"""
msg_box = QMessageBox() # 后悔药(不
msg_box.setWindowTitle("提示")
msg_box.setText(f"确认删除数据集 {dataset_name} 吗?\n{dataset_name} 将会永久失去!(真的很久!)")
msg_box.setIcon(QMessageBox.Question)
# 添加按... | """
考虑做伪删除,但是感觉没必要
""" | https://github.com/kslz/sound_dataset_tools2/blob/5b4ce54c2c597b16e246f709322156ca69aa1a20/ui/mygui.py#L397-L434 | 5b4ce54c2c597b16e246f709322156ca69aa1a20 |
R2ET | github_2023 | Kebii | python | quat2euler | def quat2euler(q, order='xyz', degrees=True):
"""
Convert (w, x, y, z) quaternions to xyz euler angles. This is used for bvh output.
"""
q0 = q[..., 0]
q1 = q[..., 1]
q2 = q[..., 2]
q3 = q[..., 3]
es = torch.empty(q0.shape + (3,), device=q.device, dtype=q.dtype)
if order == 'xyz':
... | """
Convert (w, x, y, z) quaternions to xyz euler angles. This is used for bvh output.
""" | https://github.com/Kebii/R2ET/blob/41c7e40fcb8a40eb3fb0deccf3d6b88b8230d572/outside-code/transforms.py#L103-L123 | 41c7e40fcb8a40eb3fb0deccf3d6b88b8230d572 |
TerminalGPT | github_2023 | adamyodinsky | python | test_get_printer | def test_get_printer(self):
"""Tests the get_printer method."""
self.assertIsInstance(PrinterFactory.get_printer("plain"), PlainPrinter)
self.assertIsInstance(PrinterFactory.get_printer("markdown"), MarkdownPrinter) | """Tests the get_printer method.""" | https://github.com/adamyodinsky/TerminalGPT/blob/29aab7d9db5287b70c06abe161937bedc86e7933/tests/unit/test_printer.py#L145-L148 | 29aab7d9db5287b70c06abe161937bedc86e7933 |
coding-competitions-archive | github_2023 | google | python | _utils_ToFloat | def _utils_ToFloat(s):
"""Returns float(s) if s is a float. Otherwise None.
Disallows infinities and nans.
Args:
s: A string to convert to a float.
Returns:
An float or None.
"""
try:
x = float(s)
if x not in [float('inf'), float('-inf')] and x == x: # not NaN
return x
else:
... | """Returns float(s) if s is a float. Otherwise None.
Disallows infinities and nans.
Args:
s: A string to convert to a float.
Returns:
An float or None.
""" | https://github.com/google/coding-competitions-archive/blob/87385db7dbd81b281225412b8ad496334536d016/codejam/2019/round_3/napkin_folding/output_validators/validator/napkin_folding.py#L141-L159 | 87385db7dbd81b281225412b8ad496334536d016 |
ChatGPT-for-Translation | github_2023 | Raychanan | python | check_file_path | def check_file_path(file_path: Path):
"""
Ensure file extension is in ALLOWED_FILE_TYPES or is a URL.
If file ends with _translated.txt or _bilingual.txt, skip it.
If there is any txt file ending with _translated.txt or _bilingual.txt, skip it.
"""
if not file_path.suffix.lower() in ALLOWED_FILE... | """
Ensure file extension is in ALLOWED_FILE_TYPES or is a URL.
If file ends with _translated.txt or _bilingual.txt, skip it.
If there is any txt file ending with _translated.txt or _bilingual.txt, skip it.
""" | https://github.com/Raychanan/ChatGPT-for-Translation/blob/0c6fe5d1fe66c1faed967e1b3403de5627bc85cc/ChatGPT-translate.py#L234-L262 | 0c6fe5d1fe66c1faed967e1b3403de5627bc85cc |
CFINet | github_2023 | shaunyuan22 | python | get_proposal_pos_embed | def get_proposal_pos_embed(self,
proposals,
num_pos_feats=128,
temperature=10000):
"""Get the position embedding of proposal."""
scale = 2 * math.pi
dim_t = torch.arange(
num_pos_feats, dtype... | """Get the position embedding of proposal.""" | https://github.com/shaunyuan22/CFINet/blob/45af342276e883aaacd49e280dba641331786603/mmdet/models/utils/transformer.py#L875-L891 | 45af342276e883aaacd49e280dba641331786603 |
OpenOcc | github_2023 | wzzheng | python | get_reference_points | def get_reference_points(H, W, Z=8, num_points_in_pillar=4, dim='3d', bs=1, device='cpu', dtype=torch.float):
"""Get the reference points used in image cross-attention and single plane self-attention.
Args:
H, W: spatial shape of tpv.
Z: hight of pillar.
D: sample D points uniformly from... | """Get the reference points used in image cross-attention and single plane self-attention.
Args:
H, W: spatial shape of tpv.
Z: hight of pillar.
D: sample D points uniformly from each pillar.
device (obj:`device`): The device where
reference_points should be.
Returns:... | https://github.com/wzzheng/OpenOcc/blob/dc80f79276e7048e0a9dc312531ad04c850963fb/model/encoder/tpvformer/utils.py#L76-L114 | dc80f79276e7048e0a9dc312531ad04c850963fb |
vscode-ocp-cad-viewer | github_2023 | bernhard-42 | python | get_default | def get_default(key):
"""Get default value for key"""
return DEFAULTS.get(key) | """Get default value for key""" | https://github.com/bernhard-42/vscode-ocp-cad-viewer/blob/d32b3b482ee90b6762fa2c9819b6c9edbcf2d66b/ocp_vscode/config.py#L240-L242 | d32b3b482ee90b6762fa2c9819b6c9edbcf2d66b |
jaxonnxruntime | github_2023 | google | python | BatchNormalization.version_9 | @classmethod
def version_9(
cls, node: onnx_node.OnnxNode, inputs: Sequence[Any]
) -> Callable[..., Any]:
"""ONNX version_9 BatchNormalization op."""
cls._prepare(node, inputs, onnx_batchnormalization)
return onnx_batchnormalization | """ONNX version_9 BatchNormalization op.""" | https://github.com/google/jaxonnxruntime/blob/e20b8defdfd4263c89a5682e6d993499ad5bcb74/jaxonnxruntime/onnx_ops/batchnormalization.py#L56-L62 | e20b8defdfd4263c89a5682e6d993499ad5bcb74 |
jaxonnxruntime | github_2023 | google | python | Mul.version_13 | @classmethod
def version_13(
cls, node: onnx_node.OnnxNode, inputs: Sequence[Any]
) -> Callable[..., Any]:
"""ONNX version_13 Mul op."""
cls._prepare(node, inputs, onnx_mul)
return onnx_mul | """ONNX version_13 Mul op.""" | https://github.com/google/jaxonnxruntime/blob/e20b8defdfd4263c89a5682e6d993499ad5bcb74/jaxonnxruntime/onnx_ops/mul.py#L53-L59 | e20b8defdfd4263c89a5682e6d993499ad5bcb74 |
llama.cpp | github_2023 | ggerganov | python | generate_markdown_documentation | def generate_markdown_documentation(
pydantic_models: list[type[BaseModel]], model_prefix="Model", fields_prefix="Fields",
documentation_with_field_description=True
) -> str:
"""
Generate markdown documentation for a list of Pydantic models.
Args:
pydantic_models (list[type[BaseModel]]): li... | """
Generate markdown documentation for a list of Pydantic models.
Args:
pydantic_models (list[type[BaseModel]]): list of Pydantic model classes.
model_prefix (str): Prefix for the model section.
fields_prefix (str): Prefix for the fields section.
documentation_with_field_descri... | https://github.com/ggerganov/llama.cpp/blob/4078c77f9891831f29ffc7c315c8ec6695ba5ce7/examples/pydantic_models_to_grammar.py#L676-L738 | 4078c77f9891831f29ffc7c315c8ec6695ba5ce7 |
home-assistant-streamdeck-yaml | github_2023 | basnijholt | python | _ButtonDialBase.templatable | @classmethod
def templatable(cls: type[Button]) -> set[str]:
"""Return if an attribute is templatable, which is if the type-annotation is str."""
schema = cls.schema()
properties = schema["properties"]
return {k for k, v in properties.items() if v["allow_template"]} | """Return if an attribute is templatable, which is if the type-annotation is str.""" | https://github.com/basnijholt/home-assistant-streamdeck-yaml/blob/e04dc7229b8a6148a511ed455e2df5988bbcf6c4/home_assistant_streamdeck_yaml.py#L187-L192 | e04dc7229b8a6148a511ed455e2df5988bbcf6c4 |
camel | github_2023 | camel-ai | python | GroqModel.stream | @property
def stream(self) -> bool:
r"""Returns whether the model supports streaming. But Groq API does
not support streaming.
"""
return False | r"""Returns whether the model supports streaming. But Groq API does
not support streaming.
""" | https://github.com/camel-ai/camel/blob/4536d76610140ac02f92cb38a3dfc56d95f231ac/camel/models/groq_model.py#L134-L139 | 4536d76610140ac02f92cb38a3dfc56d95f231ac |
MaterialSearch | github_2023 | chn-lee-yumi | python | clean_cache | def clean_cache():
"""
清空搜索缓存
"""
search_image_by_text_path_time.cache_clear()
search_image_by_image.cache_clear()
search_video_by_image.cache_clear()
search_video_by_text_path_time.cache_clear()
search_pexels_video_by_text.cache_clear() | """
清空搜索缓存
""" | https://github.com/chn-lee-yumi/MaterialSearch/blob/c7a5e94d67c8dd67fc6c7d3f1eb6cf8c89d5467c/search.py#L21-L29 | c7a5e94d67c8dd67fc6c7d3f1eb6cf8c89d5467c |
entaoai | github_2023 | akshata29 | python | __validate_time_delta | def __validate_time_delta(value: str) -> str:
"""
Check to see if passed string is in the list of possible Time Deltas.
:param value: Time Delta name.
:return: Passed value or No Return
"""
valid_values = TIME_DELTA_VALUES
if value in valid_values:
return value
else:
logg... | """
Check to see if passed string is in the list of possible Time Deltas.
:param value: Time Delta name.
:return: Passed value or No Return
""" | https://github.com/akshata29/entaoai/blob/aa6cfbfbf6f19128bcc9135bc75effe38857bd31/api/Python/Utilities/fmp.py#L456-L468 | aa6cfbfbf6f19128bcc9135bc75effe38857bd31 |
ai.deploy.box | github_2023 | TalkUHulk | python | intree_extensions | def intree_extensions(
paths: Iterable[str], package_dir: Optional[Dict[str, str]] = None
) -> List[Pybind11Extension]:
"""
Generate Pybind11Extensions from source files directly located in a Python
source tree.
``package_dir`` behaves as in ``setuptools.setup``. If unset, the Python
package r... | """
Generate Pybind11Extensions from source files directly located in a Python
source tree.
``package_dir`` behaves as in ``setuptools.setup``. If unset, the Python
package root parent is determined as the first parent directory that does
not contain an ``__init__.py`` file.
""" | https://github.com/TalkUHulk/ai.deploy.box/blob/f937195eab6de38078d1524dae598fd5f142c8c8/python/pybind11/pybind11/setup_helpers.py#L293-L332 | f937195eab6de38078d1524dae598fd5f142c8c8 |
vscode-mypy | github_2023 | microsoft | python | update_sys_path | def update_sys_path(path_to_add: str) -> None:
"""Add given path to `sys.path`."""
if path_to_add not in sys.path and os.path.isdir(path_to_add):
sys.path.append(path_to_add) | """Add given path to `sys.path`.""" | https://github.com/microsoft/vscode-mypy/blob/a5cf3e1e33b09dd401190801b5ad32702344540d/bundled/tool/_debug_server.py#L11-L14 | a5cf3e1e33b09dd401190801b5ad32702344540d |
LocalAI | github_2023 | mudler | python | LoadModel | def LoadModel(self, request, context):
"""
A gRPC method that loads a model into memory.
Args:
request: A LoadModelRequest object that contains the request parameters.
context: A grpc.ServicerContext object that provides information about the RPC.
Returns:
... | """
A gRPC method that loads a model into memory.
Args:
request: A LoadModelRequest object that contains the request parameters.
context: A grpc.ServicerContext object that provides information about the RPC.
Returns:
A Result object that contains the result... | https://github.com/mudler/LocalAI/blob/e01acc88c984c60b5a3e60bb1e12d4e232a20f6c/backend/python/rerankers/backend.py#L45-L70 | e01acc88c984c60b5a3e60bb1e12d4e232a20f6c |
BlenderGPT | github_2023 | gd3kr | python | _frozen_setattrs | def _frozen_setattrs(self, name, value):
"""
Attached to frozen classes as __setattr__.
"""
if isinstance(self, BaseException) and name in (
"__cause__",
"__context__",
):
BaseException.__setattr__(self, name, value)
return
... | """
Attached to frozen classes as __setattr__.
""" | https://github.com/gd3kr/BlenderGPT/blob/3fbc3bd3f169d904f8bf8a067807c4a71d3d3b4b/lib/attr/_make.py#L587-L598 | 3fbc3bd3f169d904f8bf8a067807c4a71d3d3b4b |
BlenderGPT | github_2023 | gd3kr | python | ChatCompletion.create | @classmethod
def create(cls, *args, **kwargs):
"""
Creates a new chat completion for the provided messages and parameters.
See https://platform.openai.com/docs/api-reference/chat-completions/create
for a list of valid parameters.
"""
start = time.time()
timeo... | """
Creates a new chat completion for the provided messages and parameters.
See https://platform.openai.com/docs/api-reference/chat-completions/create
for a list of valid parameters.
""" | https://github.com/gd3kr/BlenderGPT/blob/3fbc3bd3f169d904f8bf8a067807c4a71d3d3b4b/lib/openai/api_resources/chat_completion.py#L12-L30 | 3fbc3bd3f169d904f8bf8a067807c4a71d3d3b4b |
xTuring | github_2023 | stochasticai | python | __getattr__ | def __getattr__(self, name: str):
"""Forward missing attributes to the wrapped module."""
try:
return super().__getattr__(name) # defer to nn.Module's logic
except AttributeError:
return getattr(self.model, name) | """Forward missing attributes to the wrapped module.""" | https://github.com/stochasticai/xTuring/blob/570a0d6f971e47d9dde3d8b183c186e2010ba384/src/xturing/engines/lora_engine/lora.py#L399-L404 | 570a0d6f971e47d9dde3d8b183c186e2010ba384 |
UniDetector | github_2023 | zhenyuw16 | python | __init__ | def __init__(self,
inplanes,
planes,
groups=1,
base_width=4,
base_channels=64,
**kwargs):
"""Bottleneck block for ResNeXt.
If style is "pytorch", the stride-two layer is the 3x3 conv layer, if
... | """Bottleneck block for ResNeXt.
If style is "pytorch", the stride-two layer is the 3x3 conv layer, if
it is "caffe", the stride-two layer is the first 1x1 conv layer.
""" | https://github.com/zhenyuw16/UniDetector/blob/eb182535178ecfad18142bed2e03b458a0a8f451/mmdet/models/backbones/detectors_resnext.py#L14-L95 | eb182535178ecfad18142bed2e03b458a0a8f451 |
UniDetector | github_2023 | zhenyuw16 | python | init_weights | def init_weights(self):
"""Initialize weights of the head."""
bias_init = bias_init_with_prob(0.1)
self.heatmap_head[-1].bias.data.fill_(bias_init)
for head in [self.wh_head, self.offset_head]:
for m in head.modules():
if isinstance(m, nn.Conv2d):
... | """Initialize weights of the head.""" | https://github.com/zhenyuw16/UniDetector/blob/eb182535178ecfad18142bed2e03b458a0a8f451/mmdet/models/dense_heads/centernet_head.py#L72-L79 | eb182535178ecfad18142bed2e03b458a0a8f451 |
robocorp | github_2023 | robocorp | python | insert_missing_modules | def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None:
"""
Used by ``import_path`` to create intermediate modules.
When we want to import a module as "src.tests.test_foo" for example, we need
to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo... | """
Used by ``import_path`` to create intermediate modules.
When we want to import a module as "src.tests.test_foo" for example, we need
to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo",
otherwise "src.tests.test_foo" is not importable by ``__import__``.
Based on: ... | https://github.com/robocorp/robocorp/blob/3df7714109713269f9e6122254bd0d97a55e9f6a/tasks/src/robocorp/tasks/_collect_tasks.py#L37-L66 | 3df7714109713269f9e6122254bd0d97a55e9f6a |
robocorp | github_2023 | robocorp | python | __init__ | def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationinvokepattern"""
self.pattern = pattern | """Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationinvokepattern""" | https://github.com/robocorp/robocorp/blob/3df7714109713269f9e6122254bd0d97a55e9f6a/windows/src/robocorp/windows/_vendored/uiautomation/uiautomation.py#L4192-L4194 | 3df7714109713269f9e6122254bd0d97a55e9f6a |
ViPT | github_2023 | jiawen-zhu | python | forward | def forward(self, x):
'''
x: [batch_size, features, k]
'''
b, c, h, w = x.shape
x = x.contiguous().view(b, c, h*w)
if self.smooth:
mask = self.softmax(x * self.smooth)
else:
mask = self.softmax(x)
output = mask * x
outp... | '''
x: [batch_size, features, k]
''' | https://github.com/jiawen-zhu/ViPT/blob/b316fb0cf29a0552f169360556bdc691e43f8452/lib/models/vipt/vit_ce_prompt.py#L33-L47 | b316fb0cf29a0552f169360556bdc691e43f8452 |
torch-merf | github_2023 | ashawkey | python | _march_rays_train.forward | @staticmethod
@custom_fwd(cast_inputs=torch.float32)
def forward(ctx, rays_o, rays_d, bound, contract, density_bitfield, C, H, nears, fars, perturb=False, dt_gamma=0, max_steps=1024):
''' march rays to generate points (forward only)
Args:
rays_o/d: float, [N, 3]
bound: fl... | ''' march rays to generate points (forward only)
Args:
rays_o/d: float, [N, 3]
bound: float, scalar
density_bitfield: uint8: [CHHH // 8]
C: int
H: int
nears/fars: float, [N]
step_counter: int32, (2), used to count the actual num... | https://github.com/ashawkey/torch-merf/blob/a669be605349c3af5167832f8ead6f69bbf8e697/raymarching/raymarching.py#L195-L251 | a669be605349c3af5167832f8ead6f69bbf8e697 |
hnsqlite | github_2023 | jiggy-ai | python | Collection._save_index_to_disk | @classmethod
def _save_index_to_disk(cls, name: str, hnsw_ix : dbHnswIndexConfig) -> Tuple[str, str, int]:
"""
Save the current index to disk and return the filename, md5sum, and count of items in the index
"""
count = len(hnsw_ix.get_ids_list())
filename = f"index_{name}.hns... | """
Save the current index to disk and return the filename, md5sum, and count of items in the index
""" | https://github.com/jiggy-ai/hnsqlite/blob/9824e6c73508d844ea3424ba9f3033da46b9de9f/hnsqlite/collection.py#L255-L269 | 9824e6c73508d844ea3424ba9f3033da46b9de9f |
3D_Corruptions_AD | github_2023 | thu-ml | python | apply_jigsaw | def apply_jigsaw(arr, destinations):
"""Move cells of an image similar to a jigsaw puzzle.
This function will split the image into ``rows x cols`` cells and
move each cell to the target index given in `destinations`.
Added in 0.4.0.
**Supported dtypes**:
* ``uint8``: yes; fully tested
... | """Move cells of an image similar to a jigsaw puzzle.
This function will split the image into ``rows x cols`` cells and
move each cell to the target index given in `destinations`.
Added in 0.4.0.
**Supported dtypes**:
* ``uint8``: yes; fully tested
* ``uint16``: yes; fully tested
... | https://github.com/thu-ml/3D_Corruptions_AD/blob/48c23f77fe82beab599f8248b7794928334a3fb5/OpenPCDet/OpenPCDet/pcdet/datasets/kitti/utils/imgaug/augmenters/geometric.py#L386-L474 | 48c23f77fe82beab599f8248b7794928334a3fb5 |
3D_Corruptions_AD | github_2023 | thu-ml | python | remove_out_of_image_ | def remove_out_of_image_(self, fully=True, partly=False):
"""
Remove all LS that are fully/partially outside of an image in-place.
Added in 0.4.0.
Parameters
----------
fully : bool, optional
Whether to remove line strings that are fully outside of the image... | """
Remove all LS that are fully/partially outside of an image in-place.
Added in 0.4.0.
Parameters
----------
fully : bool, optional
Whether to remove line strings that are fully outside of the image.
partly : bool, optional
Whether to remove l... | https://github.com/thu-ml/3D_Corruptions_AD/blob/48c23f77fe82beab599f8248b7794928334a3fb5/utils/imgaug/augmentables/lines.py#L1928-L1954 | 48c23f77fe82beab599f8248b7794928334a3fb5 |
CEASC | github_2023 | Cuogeihong | python | show_result | def show_result(self,
img,
result,
score_thr=0.3,
bbox_color=(72, 101, 241),
text_color=(72, 101, 241),
mask_color=None,
thickness=2,
font_size=13,
... | """Draw `result` over `img`.
Args:
img (str or Tensor): The image to be displayed.
result (dict): The results.
score_thr (float, optional): Minimum score of bboxes to be shown.
Default: 0.3.
bbox_color (str or tuple(int) or :obj:`Color`):Color of... | https://github.com/Cuogeihong/CEASC/blob/2abfd1a99f1b0fe1ed3d51588b64549e1584da50/mmdet/models/detectors/panoptic_two_stage_segmentor.py#L208-L279 | 2abfd1a99f1b0fe1ed3d51588b64549e1584da50 |
CEASC | github_2023 | Cuogeihong | python | forward_train | def forward_train(self, gt_masks=None, gt_semantic_seg=None, **kwargs):
"""HeuristicFusionHead has no training loss."""
return dict() | """HeuristicFusionHead has no training loss.""" | https://github.com/Cuogeihong/CEASC/blob/2abfd1a99f1b0fe1ed3d51588b64549e1584da50/mmdet/models/seg_heads/panoptic_fusion_heads/heuristic_fusion_head.py#L23-L25 | 2abfd1a99f1b0fe1ed3d51588b64549e1584da50 |
GPTCache | github_2023 | zilliztech | python | EvictionBase | def EvictionBase(name: str, **kwargs):
"""Generate specific CacheStorage with the configuration.
:param name: the name of the eviction, like: memory
:type name: str
:param policy: eviction strategy
:type policy: str
:param maxsize: the maxsize of cache data
:type maxsize: int
:param cl... | """Generate specific CacheStorage with the configuration.
:param name: the name of the eviction, like: memory
:type name: str
:param policy: eviction strategy
:type policy: str
:param maxsize: the maxsize of cache data
:type maxsize: int
:param clean_size: will clean the size of data when ... | https://github.com/zilliztech/GPTCache/blob/48f8e768d7dcd7f66d948ad07914a630a382b45b/gptcache/manager/eviction/__init__.py#L10-L32 | 48f8e768d7dcd7f66d948ad07914a630a382b45b |
gptme | github_2023 | ErikBjare | python | write | def write(self, branches=True) -> None:
"""
Writes to the conversation log.
"""
# create directory if it doesn't exist
Path(self.logfile).parent.mkdir(parents=True, exist_ok=True)
# write current branch
self.log.write_jsonl(self.logfile)
# write other br... | """
Writes to the conversation log.
""" | https://github.com/ErikBjare/gptme/blob/ebc076bb75a3af2eafbe498634abb032772f11df/gptme/logmanager.py#L167-L186 | ebc076bb75a3af2eafbe498634abb032772f11df |
yolov8-face | github_2023 | derronqi | python | set_api_key | def set_api_key(self, key: str):
"""
Set the API key for authentication.
Args:
key (str): The API key string.
"""
self.api_key = key | """
Set the API key for authentication.
Args:
key (str): The API key string.
""" | https://github.com/derronqi/yolov8-face/blob/18f9fde9862ecee74a28e56a8f09bbfc3bcff6d4/ultralytics/hub/auth.py#L132-L139 | 18f9fde9862ecee74a28e56a8f09bbfc3bcff6d4 |
yolov8-face | github_2023 | derronqi | python | __init__ | def __init__(self, c1, c2, num_heads, num_layers):
"""Initialize a Transformer module with position embedding and specified number of heads and layers."""
super().__init__()
self.conv = None
if c1 != c2:
self.conv = Conv(c1, c2)
self.linear = nn.Linear(c2, c2) # lear... | """Initialize a Transformer module with position embedding and specified number of heads and layers.""" | https://github.com/derronqi/yolov8-face/blob/18f9fde9862ecee74a28e56a8f09bbfc3bcff6d4/ultralytics/nn/modules/transformer.py#L123-L131 | 18f9fde9862ecee74a28e56a8f09bbfc3bcff6d4 |
q-diffusion | github_2023 | Xiuyu-Li | python | makedir_exist_ok | def makedir_exist_ok(dirpath):
"""
Python2 support for os.makedirs(.., exist_ok=True)
"""
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise | """
Python2 support for os.makedirs(.., exist_ok=True)
""" | https://github.com/Xiuyu-Li/q-diffusion/blob/715783da70baa267321d6700ceb8941400c309d1/ddim/datasets/utils.py#L36-L46 | 715783da70baa267321d6700ceb8941400c309d1 |
prompt-pretraining | github_2023 | amazon-science | python | __init__ | def __init__(
self,
dataset_name,
tasks=None,
distributed=True,
output_dir=None,
*,
max_dets_per_image=None,
):
"""
Args:
dataset_name (str): name of the dataset to be evaluated.
It must have the following correspond... | """
Args:
dataset_name (str): name of the dataset to be evaluated.
It must have the following corresponding metadata:
"json_file": the path to the LVIS format annotation
tasks (tuple[str]): tasks that can be evaluated under the given
config... | https://github.com/amazon-science/prompt-pretraining/blob/24bca56b21b4fab1d493c8758c31fd6d1c40bb96/third_party/Detic/cherry_pick.py#L627-L677 | 24bca56b21b4fab1d493c8758c31fd6d1c40bb96 |
AttentionShift | github_2023 | MingXiangL | python | gen_single_level_base_anchors | def gen_single_level_base_anchors(self, base_sizes_per_level, center=None):
"""Generate base anchors of a single level.
Args:
base_sizes_per_level (list[tuple[int, int]]): Basic sizes of
anchors.
center (tuple[float], optional): The center of the base anchor
... | """Generate base anchors of a single level.
Args:
base_sizes_per_level (list[tuple[int, int]]): Basic sizes of
anchors.
center (tuple[float], optional): The center of the base anchor
related to a single feature grid. Defaults to None.
Returns:
... | https://github.com/MingXiangL/AttentionShift/blob/dc3b87d35d2334d8675cb899ead2c02d74c163c1/mmdet/core/anchor/anchor_generator.py#L639-L665 | dc3b87d35d2334d8675cb899ead2c02d74c163c1 |
uuid-utils | github_2023 | aminalaee | python | uuid8 | def uuid8(bytes):
"""Generate a custom UUID comprised almost entirely of user-supplied bytes.."""
return UUID(bytes=uuid_utils.uuid8(bytes).bytes) | """Generate a custom UUID comprised almost entirely of user-supplied bytes..""" | https://github.com/aminalaee/uuid-utils/blob/9ddd132c46278ac8aeb70474e688acec3465ce30/python/uuid_utils/compat/__init__.py#L75-L77 | 9ddd132c46278ac8aeb70474e688acec3465ce30 |
the-algorithm | github_2023 | twitter | python | __init__ | def __init__(self, calibrator_name=None, **kwargs):
'''
Arguments:
calibrator_name.
Default: if set to None it will be the same as the class name.
Please be reminded that if in the model there are many calibrators
of the same type the calibrator_name should be changed to avoid conf... | '''
Arguments:
calibrator_name.
Default: if set to None it will be the same as the class name.
Please be reminded that if in the model there are many calibrators
of the same type the calibrator_name should be changed to avoid confusion.
''' | https://github.com/twitter/the-algorithm/blob/72eda9a24f815f6d566818cbf8518138e29d83e9/twml/twml/contrib/calibrators/calibrator.py#L62-L74 | 72eda9a24f815f6d566818cbf8518138e29d83e9 |
Retrieval-based-Voice-Conversion-WebUI | github_2023 | RVC-Project | python | _absolute_position_to_relative_position | def _absolute_position_to_relative_position(self, x):
"""
x: [b, h, l, l]
ret: [b, h, l, 2*l-1]
"""
batch, heads, length, _ = x.size()
# padd along column
x = F.pad(
x,
[0, length - 1, 0, 0, 0, 0, 0, 0],
)
x_flat = x.view([b... | """
x: [b, h, l, l]
ret: [b, h, l, 2*l-1]
""" | https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/blob/7ef19867780cf703841ebafb565a4e47d1ea86ff/infer/lib/infer_pack/attentions_onnx.py#L356-L374 | 7ef19867780cf703841ebafb565a4e47d1ea86ff |
timefold-solver | github_2023 | TimefoldAI | python | SolutionManager.create | @staticmethod
def create(solver_factory: SolverFactory[Solution_] | SolverManager[Solution_, Any]) -> \
'SolutionManager[Solution_]':
"""
Uses a `SolverFactory` or `SolverManager` to build a SolutionManager.
Parameters
----------
solver_factory : SolverFactory | ... | """
Uses a `SolverFactory` or `SolverManager` to build a SolutionManager.
Parameters
----------
solver_factory : SolverFactory | SolverManager
Returns
-------
SolutionManager
A `SolutionManager` instance.
""" | https://github.com/TimefoldAI/timefold-solver/blob/f67c507a421ee113dd2e76f825480aa058b14767/python/python-core/src/main/python/_solution_manager.py#L29-L45 | f67c507a421ee113dd2e76f825480aa058b14767 |
timefold-solver | github_2023 | TimefoldAI | python | diff | def diff(self, other: 'ScoreAnalysis') -> 'ScoreAnalysis':
"""
Compare this `ScoreAnalysis to another `ScoreAnalysis`
and retrieve the difference between them.
The comparison is in the direction of `this - other`.
Example: if `this` has a score of 100 and `other` has a score of ... | """
Compare this `ScoreAnalysis to another `ScoreAnalysis`
and retrieve the difference between them.
The comparison is in the direction of `this - other`.
Example: if `this` has a score of 100 and `other` has a score of 90,
the returned score will be 10.
If this and othe... | https://github.com/TimefoldAI/timefold-solver/blob/f67c507a421ee113dd2e76f825480aa058b14767/python/python-core/src/main/python/score/_score_analysis.py#L631-L659 | f67c507a421ee113dd2e76f825480aa058b14767 |
JaxMARL | github_2023 | FLAIROx | python | JaxNav.reset | @partial(jax.jit, static_argnums=[0])
def reset(self, key: chex.PRNGKey) -> Tuple[Dict[str, chex.Array], State]:
""" Reset environment. Returns initial agent observations, states and the enviornment state """
state = self.sample_test_case(key)
obs = self._get_obs(state)
re... | """ Reset environment. Returns initial agent observations, states and the enviornment state """ | https://github.com/FLAIROx/JaxMARL/blob/3dc2cf6e002b5f1b97ce3edd45aff7e1c003f8e3/jaxmarl/environments/jaxnav/jaxnav_env.py#L202-L208 | 3dc2cf6e002b5f1b97ce3edd45aff7e1c003f8e3 |
JaxMARL | github_2023 | FLAIROx | python | action_space | def action_space(
self, agent_id: Union[int, None] = None
) -> spaces.Discrete:
"""Action space of the environment."""
return spaces.Discrete(len(Actions)) | """Action space of the environment.""" | https://github.com/FLAIROx/JaxMARL/blob/3dc2cf6e002b5f1b97ce3edd45aff7e1c003f8e3/jaxmarl/environments/storm/storm_2p.py#L921-L925 | 3dc2cf6e002b5f1b97ce3edd45aff7e1c003f8e3 |
unmasked_teacher | github_2023 | OpenGVLab | python | encode_teacher | def encode_teacher(self, image):
"""encode image / videos as features.
Args:
image (torch.Tensor): The input images.
Returns: tuple.
- mask (torch.Tensor): Mask. Shape: [B,N1].
- clip_output (torch.Tensor): The features of clip. Shape: [K,B,N,C].
""... | """encode image / videos as features.
Args:
image (torch.Tensor): The input images.
Returns: tuple.
- mask (torch.Tensor): Mask. Shape: [B,N1].
- clip_output (torch.Tensor): The features of clip. Shape: [K,B,N,C].
""" | https://github.com/OpenGVLab/unmasked_teacher/blob/4fb4049f5a87919882e68ccc427615ae7dab1c33/multi_modality/models/umt.py#L117-L169 | 4fb4049f5a87919882e68ccc427615ae7dab1c33 |
YOSO | github_2023 | hujiecpp | python | load_lvis_json | def load_lvis_json(json_file, image_root, dataset_name=None):
"""
Load a json file in LVIS's annotation format.
Args:
json_file (str): full path to the LVIS json annotation file.
image_root (str): the directory where the images in this json file exists.
dataset_name (str): the name ... | """
Load a json file in LVIS's annotation format.
Args:
json_file (str): full path to the LVIS json annotation file.
image_root (str): the directory where the images in this json file exists.
dataset_name (str): the name of the dataset (e.g., "lvis_v0.5_train").
If provided,... | https://github.com/hujiecpp/YOSO/blob/04b898d395ffd8318aa3761b0b2b6d20b3514f26/detectron2/data/datasets/lvis.py#L40-L147 | 04b898d395ffd8318aa3761b0b2b6d20b3514f26 |
FreeSeg | github_2023 | bytedance | python | __call__ | def __call__(self, dataset_dict):
"""
Args:
dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.
Returns:
dict: a format that builtin models in detectron2 accept
"""
# assert self.is_train, "MaskFormerSemanticDatasetMapper should only... | """
Args:
dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.
Returns:
dict: a format that builtin models in detectron2 accept
""" | https://github.com/bytedance/FreeSeg/blob/7707335cc3f2a1a73d4d2829f3cdbb0e031d3961/mask2former/data/dataset_mappers/mask_former_binary_semantic_dataset_mapper.py#L95-L194 | 7707335cc3f2a1a73d4d2829f3cdbb0e031d3961 |
Blender-GPT | github_2023 | TREE-Ind | python | append_form | def append_form(
self,
obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]],
headers: Optional[MultiMapping[str]] = None,
) -> Payload:
"""Helper to append form urlencoded part."""
assert isinstance(obj, (Sequence, Mapping))
if headers is None:
header... | """Helper to append form urlencoded part.""" | https://github.com/TREE-Ind/Blender-GPT/blob/cf8b62ebd327940ec7d1d47cc7baa7fc595ddd44/lib/aiohttp/multipart.py#L845-L864 | cf8b62ebd327940ec7d1d47cc7baa7fc595ddd44 |
Otter | github_2023 | EvolvingLMMs-Lab | python | generate | def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
"""Wraps original generate to enable PrefixLM attention."""
attn_modules = _get_attn_modules(model)
for attn_module in attn_modules:
attn_module.bias.data[:] = 1
output = self._original_generate(*ar... | """Wraps original generate to enable PrefixLM attention.""" | https://github.com/EvolvingLMMs-Lab/Otter/blob/1e7eb9a6fb12ef410082e796c463b99495637b85/src/otter_ai/models/mpt/hf_prefixlm_converter.py#L161-L169 | 1e7eb9a6fb12ef410082e796c463b99495637b85 |
DB-GPT | github_2023 | TsinghuaDatabaseGroup | python | forward | def forward(self, x: torch.Tensor, x_pos: torch.Tensor):
"""
Args:
x (:obj:`torch.Tensor` of shape ``(..., dim)``): Inputs.
x_pos (:obj:`torch.Tensor` of shape ``(...)``): Positions of inputs.
"""
x_pos = x_pos * self.distance_scale
freqs = x_pos[..., None... | """
Args:
x (:obj:`torch.Tensor` of shape ``(..., dim)``): Inputs.
x_pos (:obj:`torch.Tensor` of shape ``(...)``): Positions of inputs.
""" | https://github.com/TsinghuaDatabaseGroup/DB-GPT/blob/0ced623935ae23b390bf7a4bb4de7fb26bbc777a/multiagents/localized_llms/cpm/layers/position_embedding.py#L218-L234 | 0ced623935ae23b390bf7a4bb4de7fb26bbc777a |
EA-LSS | github_2023 | hht1996ok | python | __repr__ | def __repr__(self):
"""str: a string that describes the module"""
repr_str = self.__class__.__name__
repr_str += f'(in_channels={self.in_channels}, '
repr_str += f'feat_channels={self.feat_channels}, '
repr_str += f'out_channels={self.out_channels_raw}, '
repr_str += f'in... | """str: a string that describes the module""" | https://github.com/hht1996ok/EA-LSS/blob/193c30141da8625f442d10f0fa29c226694bc3c3/mmdetection-2.11.0/mmdet/models/utils/transformer.py#L851-L860 | 193c30141da8625f442d10f0fa29c226694bc3c3 |
RSP | github_2023 | ViTAE-Transformer | python | _bbox_forward | def _bbox_forward(self, x, rois):
"""Box head forward function used in both training and testing time"""
bbox_cls_feats = self.bbox_roi_extractor(
x[:self.bbox_roi_extractor.num_inputs], rois)
bbox_reg_feats = self.bbox_roi_extractor(
x[:self.bbox_roi_extractor.num_inputs... | """Box head forward function used in both training and testing time""" | https://github.com/ViTAE-Transformer/RSP/blob/f29818739165215d341af2ef8c20f9e2daecf128/Object Detection/mmdet/models/roi_heads/double_roi_head.py#L16-L33 | f29818739165215d341af2ef8c20f9e2daecf128 |
Directional-Stimulus-Prompting | github_2023 | Leezekun | python | add | def add(self, *args, action_masks: Optional[np.ndarray] = None, **kwargs) -> None:
"""
:param action_masks: Masks applied to constrain the choice of possible actions.
"""
if action_masks is not None:
self.action_masks[self.pos] = action_masks.reshape(
(self.n_... | """
:param action_masks: Masks applied to constrain the choice of possible actions.
""" | https://github.com/Leezekun/Directional-Stimulus-Prompting/blob/93b44f9e74d608732fd7809e664cdc6c9f1f769b/rl4lms/algorithms/common/maskable/buffers.py#L72-L80 | 93b44f9e74d608732fd7809e664cdc6c9f1f769b |
Directional-Stimulus-Prompting | github_2023 | Leezekun | python | _ngram_counts | def _ngram_counts(sequence, order):
"""Returns count of all ngrams of given order in sequence."""
if len(sequence) < order:
return collections.Counter()
return collections.Counter(_ngrams(sequence, order)) | """Returns count of all ngrams of given order in sequence.""" | https://github.com/Leezekun/Directional-Stimulus-Prompting/blob/93b44f9e74d608732fd7809e664cdc6c9f1f769b/rl4lms/data_pools/task_utils/totto/eval_utils/totto_parent_eval.py#L285-L289 | 93b44f9e74d608732fd7809e664cdc6c9f1f769b |
Grounded-Segment-Anything | github_2023 | IDEA-Research | python | apply_image | def apply_image(self, image: np.ndarray) -> np.ndarray:
"""
Expects a numpy array with shape HxWxC in uint8 format.
"""
target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
return np.array(resize(to_pil_image(image), target_size)) | """
Expects a numpy array with shape HxWxC in uint8 format.
""" | https://github.com/IDEA-Research/Grounded-Segment-Anything/blob/126abe633ffe333e16e4a0a4e946bc1003caf757/segment_anything/segment_anything/utils/transforms.py#L26-L31 | 126abe633ffe333e16e4a0a4e946bc1003caf757 |
efficientvit | github_2023 | mit-han-lab | python | compute_sigma_t | def compute_sigma_t(self, t):
"""Compute coefficient of x0"""
p_sigma_t = 2 * self.log_mean_coeff(t)
sigma_t = th.sqrt(1 - th.exp(p_sigma_t))
d_sigma_t = th.exp(p_sigma_t) * (2 * self.d_log_mean_coeff(t)) / (-2 * sigma_t)
return sigma_t, d_sigma_t | """Compute coefficient of x0""" | https://github.com/mit-han-lab/efficientvit/blob/b94ff779828eea399c78f626b574da2d50ef2e49/efficientvit/diffusioncore/models/sit_sampler/path.py#L162-L167 | b94ff779828eea399c78f626b574da2d50ef2e49 |
xhs | github_2023 | ReaJason | python | create_video_note | def create_video_note(
self,
title,
video_path: str,
desc: str,
cover_path: str = None,
ats: list = None,
post_time: str = None,
topics: list = None,
is_private: bool = False,
wait_time: int = 3,
... | """发布视频笔记
:param title: 笔记标题
:param video_path: 视频文件路径,目前只支持本地路径
:param desc: 笔记详情
:param cover_path: 可选,封面文件路径
:param ats: 可选,@用户信息
:param post_time: 可选,发布时间
:param topics: 可选,话题信息
:param is_private: 可选,是否私密发布
:param wait_time: 可选,默认 3 s,循环等待获取视频... | https://github.com/ReaJason/xhs/blob/613036c431f1f8b68d6d4e8125e20629679bee41/xhs/core.py#L1013-L1080 | 613036c431f1f8b68d6d4e8125e20629679bee41 |
lerf | github_2023 | kerrj | python | BaseImageEncoder.name | @abstractproperty
def name(self) -> str:
"""
returns the name of the encoder
""" | """
returns the name of the encoder
""" | https://github.com/kerrj/lerf/blob/db08d578038d884542688511bd9ad7b489a65673/lerf/encoders/image_encoder.py#L16-L20 | db08d578038d884542688511bd9ad7b489a65673 |
ETPNav | github_2023 | MarSaKi | python | __init__ | def __init__(self, equ_h: int, equ_w: int):
"""Args:
equ_h: (int) the height of the generated equirect
equ_w: (int) the width of the generated equirect
"""
# Cubemap input
input_projections = get_cubemap_projections(equ_h,equ_h)
# Equirectangular output
... | """Args:
equ_h: (int) the height of the generated equirect
equ_w: (int) the width of the generated equirect
""" | https://github.com/MarSaKi/ETPNav/blob/8dec13a4e24f8bc671a3269bbcf3238793607621/habitat_extensions/obs_transformers.py#L197-L210 | 8dec13a4e24f8bc671a3269bbcf3238793607621 |
MS3D | github_2023 | darrenjkt | python | get_coor_colors | def get_coor_colors(obj_labels):
"""
Args:
obj_labels: 1 is ground, labels > 1 indicates different instance cluster
Returns:
rgb: [N, 3]. color for each point.
"""
colors = matplotlib.colors.XKCD_COLORS.values()
max_color_num = obj_labels.max()
color_list = list(colors)[:ma... | """
Args:
obj_labels: 1 is ground, labels > 1 indicates different instance cluster
Returns:
rgb: [N, 3]. color for each point.
""" | https://github.com/darrenjkt/MS3D/blob/ffed761a6846183966cc38d3144c90d91446fa4a/tools/visual_utils/open3d_vis_utils.py#L30-L46 | ffed761a6846183966cc38d3144c90d91446fa4a |
owlvit_segment_anything | github_2023 | ngthanhtin | python | apply_coords | def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
"""
Expects a numpy array of length 2 in the final dimension. Requires the
original image size in (H, W) format.
"""
old_h, old_w = original_size
new_h, new_w = self.get_preprocess_s... | """
Expects a numpy array of length 2 in the final dimension. Requires the
original image size in (H, W) format.
""" | https://github.com/ngthanhtin/owlvit_segment_anything/blob/2deca3a5d9760e6863e088db4d9a46912c6d83b9/segment_anything/segment_anything/utils/transforms.py#L33-L45 | 2deca3a5d9760e6863e088db4d9a46912c6d83b9 |
Synthetic-Voice-Detection-Vocoder-Artifacts | github_2023 | csun22 | python | f_train_wrapper | def f_train_wrapper(args, pt_model, loss_wrapper, device, \
optimizer_wrapper, \
train_dataset_wrapper, \
val_dataset_wrapper = None, \
checkpoint = None):
"""
f_train_wrapper(args, pt_model, loss_wrapper, device,
... | """
f_train_wrapper(args, pt_model, loss_wrapper, device,
optimizer_wrapper
train_dataset_wrapper, val_dataset_wrapper = None,
check_point = None):
A wrapper to run the training process
Args:
args: argument information given by ... | https://github.com/csun22/Synthetic-Voice-Detection-Vocoder-Artifacts/blob/f67a2714489f39eda34f6347e2617ee3a3df2a6b/core_scripts/nn_manager/nn_manager.py#L192-L470 | f67a2714489f39eda34f6347e2617ee3a3df2a6b |
textual-paint | github_2023 | 1j01 | python | AnsiArtDocument.decode_based_on_file_extension | @staticmethod
def decode_based_on_file_extension(content: bytes, file_path: str, default_bg: str = "#ffffff", default_fg: str = "#000000") -> 'AnsiArtDocument':
"""Creates a document from the given bytes, detecting the file format.
Raises FormatReadNotSupported if the file format is not supported f... | """Creates a document from the given bytes, detecting the file format.
Raises FormatReadNotSupported if the file format is not supported for reading. Some are write-only.
Raises UnicodeDecodeError, which can be a very long message, so make sure to handle it!
Raises UnidentifiedImageError if the... | https://github.com/1j01/textual-paint/blob/d61de649a6a3a660d2b024e4259d99acbd45116b/src/textual_paint/ansi_art_document.py#L1033-L1061 | d61de649a6a3a660d2b024e4259d99acbd45116b |
fastapi_best_architecture | github_2023 | fastapi-practices | python | update | async def update(self, db: AsyncSession, dept_id: int, obj_in: UpdateDeptParam) -> int:
"""
更新部门
:param db:
:param dept_id:
:param obj_in:
:return:
"""
return await self.update_model(db, dept_id, obj_in) | """
更新部门
:param db:
:param dept_id:
:param obj_in:
:return:
""" | https://github.com/fastapi-practices/fastapi_best_architecture/blob/1d1a9175801291ae614d983b1e77c3455bb0839c/backend/app/admin/crud/crud_dept.py#L69-L78 | 1d1a9175801291ae614d983b1e77c3455bb0839c |
neuralsim | github_2023 | PJLab-ADG | python | enable | def enable(self, scene: Scene = None):
""" Actually loads the learnable params into the scene nodes attr
Args:
scene (Scene, optional): An optional target scene to load the learnable params.
If not provided, `self.scene` will be used. Defaults to None.
"""
se... | """ Actually loads the learnable params into the scene nodes attr
Args:
scene (Scene, optional): An optional target scene to load the learnable params.
If not provided, `self.scene` will be used. Defaults to None.
""" | https://github.com/PJLab-ADG/neuralsim/blob/faba099e0feb11ea0089490a5e87565e25bc4a2c/app/models/scene/learnable_params.py#L194-L226 | faba099e0feb11ea0089490a5e87565e25bc4a2c |
AgentForge | github_2023 | DataBassGit | python | TripleExtract.find_subject_predicate_object_with_chunk | @staticmethod
def find_subject_predicate_object_with_chunk(sentence, chunk):
"""
Extract subject, predicate, and object from a sentence, using a chunk for context.
Args:
sentence (str): The input sentence.
chunk (str): A chunk of text providing context.
Retu... | """
Extract subject, predicate, and object from a sentence, using a chunk for context.
Args:
sentence (str): The input sentence.
chunk (str): A chunk of text providing context.
Returns:
tuple: A tuple containing (subject, predicate, object), each as a string... | https://github.com/DataBassGit/AgentForge/blob/feabdd0febe7172e1b99b5dcacc1f7138847f7e3/src/agentforge/tools/triple_extract.py#L137-L241 | feabdd0febe7172e1b99b5dcacc1f7138847f7e3 |
phasellm | github_2023 | wgryc | python | test_complete_chat_sse_kwargs | def test_complete_chat_sse_kwargs(self):
"""
Tests that the StreamingClaudeWrapper can be used to perform streaming chat completion with kwargs.
"""
fixture = StreamingClaudeWrapper(anthropic_api_key, model="claude-v1", format_sse=True, append_stop_token=False,
... | """
Tests that the StreamingClaudeWrapper can be used to perform streaming chat completion with kwargs.
""" | https://github.com/wgryc/phasellm/blob/974d026dc649e4a71da4c25bf8c934622e56cf5d/tests/e2e/llms/test_e2e_llms.py#L624-L631 | 974d026dc649e4a71da4c25bf8c934622e56cf5d |
Prompt-Segment-Anything | github_2023 | RockeyCoss | python | get_rel_pos | def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
"""
Get relative positional embeddings according to the relative positions of
query and key sizes.
Args:
q_size (int): size of query q.
k_size (int): size of key k.
rel_pos (Tensor): relative po... | """
Get relative positional embeddings according to the relative positions of
query and key sizes.
Args:
q_size (int): size of query q.
k_size (int): size of key k.
rel_pos (Tensor): relative position embeddings (L, C).
Returns:
Extracted positional embeddings accord... | https://github.com/RockeyCoss/Prompt-Segment-Anything/blob/5d1704db7489e79d4cd2a6eed99b7a39d8d5acf0/projects/instance_segment_anything/models/segment_anything/modeling/image_encoder.py#L292-L322 | 5d1704db7489e79d4cd2a6eed99b7a39d8d5acf0 |
HumanSD | github_2023 | IDEA-Research | python | join_path | def join_path(self, filepath: Union[str, Path],
*filepaths: Union[str, Path]) -> str:
"""Concatenate all file paths.
Join one or more filepath components intelligently. The return value
is the concatenation of filepath and any members of *filepaths.
Args:
... | """Concatenate all file paths.
Join one or more filepath components intelligently. The return value
is the concatenation of filepath and any members of *filepaths.
Args:
filepath (str or Path): Path to be concatenated.
Returns:
str: The result of concatenation.... | https://github.com/IDEA-Research/HumanSD/blob/c5db29dd66a3e40afa8b4bed630f0aa7ea001880/comparison_models/ControlNet/annotator/uniformer/mmcv/fileio/file_client.py#L1079-L1092 | c5db29dd66a3e40afa8b4bed630f0aa7ea001880 |
samm | github_2023 | bingogome | python | normalize | def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
"""Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std."""
return TF.normalize(x, mean, std, inplace=inplace) | """Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std.""" | https://github.com/bingogome/samm/blob/ee627cd5ad43d65d57182a7a1ae0fca3e51a79fd/samm-python-terminal/thirdparty/MedicalSAMAdapter/models/MobileSAMv2/ultralytics/yolo/data/dataloaders/v5augmentations.py#L59-L61 | ee627cd5ad43d65d57182a7a1ae0fca3e51a79fd |
EasyDeL | github_2023 | erfanzar | python | ring_attention_tpu | @partial(
jax.custom_vjp,
nondiff_argnums=[6, 7, 8, 9, 10, 11],
)
def ring_attention_tpu(
query: chex.Array,
key: chex.Array,
value: chex.Array,
bias: tp.Optional[chex.Array] = None,
segment_ids: tp.Optional[SegmentIds] = None,
cache_idx: tp.Optional[int] = None,
axis_name: tp.Optional[str] = None,
float32_lo... | """Computes ring attention using FlashAttention on TPU.
Args:
query: Query array of shape (batch, query_len, num_heads, dim_per_head).
key: Key array of shape (batch, kv_len, num_heads, dim_per_head).
value: Value array of shape (batch, kv_len, num_heads, dim_per_head).
bias: tp.Optional bias arra... | https://github.com/erfanzar/EasyDeL/blob/104bb42a9cf23050382a53392b677dc4d4b8d579/easydel/kernels/tpu_ops/pallas_ring_attention.py#L323-L375 | 104bb42a9cf23050382a53392b677dc4d4b8d579 |
EasyDeL | github_2023 | erfanzar | python | pack_sequences | def pack_sequences(
dataset: Dataset,
max_length: int = 512,
pad_token_id: int = 0,
reset_position_ids: bool = False,
num_proc: tp.Optional[int] = None,
):
"""
Pack sequences together with their attention masks and position IDs
# With continuous position IDs
packed_dataset = pack_sequences(
dataset,
max... | """
Pack sequences together with their attention masks and position IDs
# With continuous position IDs
packed_dataset = pack_sequences(
dataset,
max_length=512,
pad_token_id=0,
reset_position_ids=False
)
# With reset position IDs for each sequence
packed_dataset = pack_sequences(
dataset,
max_... | https://github.com/erfanzar/EasyDeL/blob/104bb42a9cf23050382a53392b677dc4d4b8d579/easydel/trainers/packer.py#L11-L149 | 104bb42a9cf23050382a53392b677dc4d4b8d579 |
vosk-tts | github_2023 | alphacep | python | solve_heun | def solve_heun(self, x, t_span, mu, mask, spks, cond, training=False, guidance_scale=0.0):
"""
Fixed heun solver for ODEs.
Args:
x (torch.Tensor): random noise
t_span (torch.Tensor): n_timesteps interpolated
shape: (n_timesteps + 1,)
mu (torch.... | """
Fixed heun solver for ODEs.
Args:
x (torch.Tensor): random noise
t_span (torch.Tensor): n_timesteps interpolated
shape: (n_timesteps + 1,)
mu (torch.Tensor): output of encoder
shape: (batch_size, n_feats, mel_timesteps)
... | https://github.com/alphacep/vosk-tts/blob/89b23a8b033133e25e3e7f53d07939645b8ea51c/training/stabletts/matcha/models/components/flow_matching.py#L91-L126 | 89b23a8b033133e25e3e7f53d07939645b8ea51c |
discord-ext-voice-recv | github_2023 | imayhaveborkedit | python | reset | def reset(self) -> None:
"""
Clear buffer and reset internal counters.
"""
self._buffer.clear()
self._has_item.clear()
self._prefill = self.prefill
self._last_tx = self._last_rx = self._generation = self._generation_ts = 0 | """
Clear buffer and reset internal counters.
""" | https://github.com/imayhaveborkedit/discord-ext-voice-recv/blob/3398a4d9d2f646cfcd60f68e626cd750b759893f/discord/ext/voice_recv/buffer.py#L202-L210 | 3398a4d9d2f646cfcd60f68e626cd750b759893f |
caikit | github_2023 | caikit | python | has_data_stream | def has_data_stream(arg_type: Type) -> bool:
"""Recursive check for a DataStream container in a type annotation"""
if _is_data_stream(arg_type):
return True
typing_args = get_args(arg_type)
if len(typing_args) > 0:
for typ in typing_args:
if has_data_stream(typ):
... | """Recursive check for a DataStream container in a type annotation""" | https://github.com/caikit/caikit/blob/ce3fa2c129ce15a5e2095d466a8f01ec2e0c577d/caikit/runtime/service_generation/type_helpers.py#L26-L37 | ce3fa2c129ce15a5e2095d466a8f01ec2e0c577d |
DB-GPT | github_2023 | eosphoros-ai | python | AppResource.app_name | @property
def app_name(self):
"""Return the app name."""
return self._app_name | """Return the app name.""" | https://github.com/eosphoros-ai/DB-GPT/blob/0310ce9fa333f14954bed4c4994da5ef419c27c7/dbgpt/agent/resource/app.py#L99-L102 | 0310ce9fa333f14954bed4c4994da5ef419c27c7 |
DB-GPT | github_2023 | eosphoros-ai | python | Document.langchain2doc | @classmethod
def langchain2doc(cls, document):
"""Transform Langchain to Document format."""
metadata = document.metadata or {}
return cls(content=document.page_content, metadata=metadata) | """Transform Langchain to Document format.""" | https://github.com/eosphoros-ai/DB-GPT/blob/0310ce9fa333f14954bed4c4994da5ef419c27c7/dbgpt/core/interface/knowledge.py#L28-L32 | 0310ce9fa333f14954bed4c4994da5ef419c27c7 |
DB-GPT | github_2023 | eosphoros-ai | python | get_table_summary | def get_table_summary(self, table_name):
"""Get table summary for table.
example:
table_name(column1(column1 comment),column2(column2 comment),
column3(column3 comment) and index keys, and table comment: {table_comment})
"""
return _parse_table_summary(self.db, s... | """Get table summary for table.
example:
table_name(column1(column1 comment),column2(column2 comment),
column3(column3 comment) and index keys, and table comment: {table_comment})
""" | https://github.com/eosphoros-ai/DB-GPT/blob/0310ce9fa333f14954bed4c4994da5ef419c27c7/dbgpt/rag/summary/rdbms_db_summary.py#L52-L59 | 0310ce9fa333f14954bed4c4994da5ef419c27c7 |
DB-GPT | github_2023 | eosphoros-ai | python | __init__ | def __init__(self):
"""Client for vis protocol."""
self._vis_tag: Dict[str, Vis] = {} | """Client for vis protocol.""" | https://github.com/eosphoros-ai/DB-GPT/blob/0310ce9fa333f14954bed4c4994da5ef419c27c7/dbgpt/vis/client.py#L18-L20 | 0310ce9fa333f14954bed4c4994da5ef419c27c7 |
DB-GPT | github_2023 | eosphoros-ai | python | bin_search | async def bin_search(
self, blocks: List[str], model_nam: str, max_new_token: int
) -> int:
"""Binary search to find the split point."""
l, r = 0, len(blocks) - 1
while l < r:
mid = l + r + 1 >> 1
current_tokens = await self._llm_client.count_token(
... | """Binary search to find the split point.""" | https://github.com/eosphoros-ai/DB-GPT/blob/0310ce9fa333f14954bed4c4994da5ef419c27c7/i18n/translate_util.py#L300-L314 | 0310ce9fa333f14954bed4c4994da5ef419c27c7 |
OpenAdapt | github_2023 | OpenAdaptAI | python | stop_recording | def stop_recording(self) -> None:
"""Stop recording."""
Thread(target=stop_record).start() | """Stop recording.""" | https://github.com/OpenAdaptAI/OpenAdapt/blob/acdbb7b2236fcbb6f8da8e0162d394608d49d33e/openadapt/app/tray.py#L255-L257 | acdbb7b2236fcbb6f8da8e0162d394608d49d33e |
Image2Paragraph | github_2023 | showlab | python | get_detection_dataset_dicts | def get_detection_dataset_dicts(
names,
filter_empty=True,
min_keypoints=0,
proposal_files=None,
check_consistency=True,
):
"""
Load and prepare dataset dicts for instance detection/segmentation and semantic segmentation.
Args:
names (str or list[str]): a dataset name or a list ... | """
Load and prepare dataset dicts for instance detection/segmentation and semantic segmentation.
Args:
names (str or list[str]): a dataset name or a list of dataset names
filter_empty (bool): whether to filter out images without instance annotations
min_keypoints (int): filter out imag... | https://github.com/showlab/Image2Paragraph/blob/a24210a6dd4535a1a43af7a6170fb8ad1e3a6013/models/grit_src/third_party/CenterNet2/detectron2/data/build.py#L216-L273 | a24210a6dd4535a1a43af7a6170fb8ad1e3a6013 |
scikit-fingerprints | github_2023 | scikit-fingerprints | python | number_of_rotatable_bonds | def number_of_rotatable_bonds(mol: Mol) -> int:
"""
Number of rotatable bonds.
Calculates the total number of rotatable bonds in the molecule.
Parameters
----------
mol : RDKit ``Mol`` object
The molecule for which the number of rotatable bonds is to be calculated.
Examples
--... | """
Number of rotatable bonds.
Calculates the total number of rotatable bonds in the molecule.
Parameters
----------
mol : RDKit ``Mol`` object
The molecule for which the number of rotatable bonds is to be calculated.
Examples
--------
>>> from rdkit.Chem import MolFromSmiles
... | https://github.com/scikit-fingerprints/scikit-fingerprints/blob/bf4faa208aa115873b138f20543800679bc59da2/skfp/descriptors/constitutional.py#L193-L212 | bf4faa208aa115873b138f20543800679bc59da2 |
CVPR2023-UniDistill | github_2023 | megvii-research | python | _reg_loss | def _reg_loss(self, regr, gt_regr, mask):
"""L1 regression loss
Arguments:
regr (batch x max_objects x dim)
gt_regr (batch x max_objects x dim)
mask (batch x max_objects)
"""
num = mask.float().sum()
mask = mask.unsqueeze(2).expand_as(gt_regr).clone().floa... | """L1 regression loss
Arguments:
regr (batch x max_objects x dim)
gt_regr (batch x max_objects x dim)
mask (batch x max_objects)
""" | https://github.com/megvii-research/CVPR2023-UniDistill/blob/32f02b4304cdf435b83b2265f59fdfed2710c3a5/unidistill/layers/losses/det3d.py#L394-L416 | 32f02b4304cdf435b83b2265f59fdfed2710c3a5 |
h2o-llmstudio | github_2023 | h2oai | python | run_train | def run_train(
cfg: DefaultConfigProblemBase,
model: torch.nn.Module,
optimizer,
scheduler,
epoch_steps,
train_dataloader,
val_dataloader,
val_df: pd.DataFrame,
):
"""Runs the training loop.
Args:
cfg: DefaultConfigProblemBase config object
model: model
t... | """Runs the training loop.
Args:
cfg: DefaultConfigProblemBase config object
model: model
train_dataloader: custom training Dataloader
train_df: train DataFrame
val_dataloader: custom validation Dataloader
val_df: validation DataFrame
Returns:
Validation... | https://github.com/h2oai/h2o-llmstudio/blob/39f5709ff6ad6db08282df0648352b6a88cb749d/llm_studio/train.py#L165-L436 | 39f5709ff6ad6db08282df0648352b6a88cb749d |
langroid | github_2023 | langroid | python | create_custom_chat_agent | def create_custom_chat_agent(
name: str, llm_config: OpenAIGPTConfig, system_message: str
) -> ChatAgent:
"""creates a ChatAgent with the given parameters.
Args:
name (str): The name of the agent.
llm_config (OpenAIGPTConfig): The LLM configuration for the agent.
system_message (str... | """creates a ChatAgent with the given parameters.
Args:
name (str): The name of the agent.
llm_config (OpenAIGPTConfig): The LLM configuration for the agent.
system_message (str): The system message to guide the agent's LLM.
Returns:
ChatAgent: A configured ChatAgent instance.
... | https://github.com/langroid/langroid/blob/8eecdf99b42a0cb488522cc950e0890e3e9b72ed/examples/multi-agent-debate/main_chainlit.py#L89-L120 | 8eecdf99b42a0cb488522cc950e0890e3e9b72ed |
langroid | github_2023 | langroid | python | clear_all_collections | def clear_all_collections(self, really: bool = False, prefix: str = "") -> int:
"""Clear all collections with the given prefix."""
if not really:
logger.warning("Not deleting all collections, set really=True to confirm")
return 0
coll_names = self.list_collections(empty=... | """Clear all collections with the given prefix.""" | https://github.com/langroid/langroid/blob/8eecdf99b42a0cb488522cc950e0890e3e9b72ed/langroid/vector_store/momento.py#L99-L117 | 8eecdf99b42a0cb488522cc950e0890e3e9b72ed |
ChatPLUG | github_2023 | X-PLUG | python | T5EncoderDecoderInitHelper.verify_onnx | @staticmethod
def verify_onnx(
model: T5EncoderDecoderInit,
ort_session: InferenceSession,
device: torch.device,
max_cases=4,
):
"""Compare the result from PyTorch and OnnxRuntime to verify the ONNX model is good."""
ort_inputs = ort_session.get_in... | """Compare the result from PyTorch and OnnxRuntime to verify the ONNX model is good.""" | https://github.com/X-PLUG/ChatPLUG/blob/3f2b8608f59e443214a22d123faaa5930fb3b783/XDPX/xdpx/utils/thirdparty/onnx_transformers/models/t5/t5_encoder_decoder_init.py#L219-L282 | 3f2b8608f59e443214a22d123faaa5930fb3b783 |
stable-diffusion-multi-user | github_2023 | wolverinn | python | forward | def forward(self, x):
"""Forward pass.
Args:
x (tensor): input
Returns:
tensor: interpolated data
"""
x = self.interp(
x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners
)
return x | """Forward pass.
Args:
x (tensor): input
Returns:
tensor: interpolated data
""" | https://github.com/wolverinn/stable-diffusion-multi-user/blob/1d79ad90de9c75692bd8e49d57679697dbefd393/extensions/sd-webui-controlnet/annotator/zoe/zoedepth/models/base_models/midas_repo/midas/blocks.py#L226-L240 | 1d79ad90de9c75692bd8e49d57679697dbefd393 |
stable-diffusion-multi-user | github_2023 | wolverinn | python | UnCLIPPipeline.__call__ | @torch.no_grad()
def __call__(
self,
prompt: Optional[Union[str, List[str]]] = None,
num_images_per_prompt: int = 1,
prior_num_inference_steps: int = 25,
decoder_num_inference_steps: int = 25,
super_res_num_inference_steps: int = 7,
generator: Optional[torch.G... | """
Function invoked when calling the pipeline for generation.
Args:
prompt (`str` or `List[str]`):
The prompt or prompts to guide the image generation. This can only be left undefined if
`text_model_output` and `text_attention_mask` is passed.
num... | https://github.com/wolverinn/stable-diffusion-multi-user/blob/1d79ad90de9c75692bd8e49d57679697dbefd393/repositories/stable-diffusion-stability-ai/ldm/modules/karlo/diffusers_pipeline.py#L241-L512 | 1d79ad90de9c75692bd8e49d57679697dbefd393 |
stable-diffusion-multi-user | github_2023 | wolverinn | python | r1_penalty | def r1_penalty(real_pred, real_img):
"""R1 regularization for discriminator. The core idea is to
penalize the gradient on real data alone: when the
generator distribution produces the true data distribution
and the discriminator is equal to 0 on the data manifold, the
gradient penalt... | """R1 regularization for discriminator. The core idea is to
penalize the gradient on real data alone: when the
generator distribution produces the true data distribution
and the discriminator is equal to 0 on the data manifold, the
gradient penalty ensures that the discriminator cannot c... | https://github.com/wolverinn/stable-diffusion-multi-user/blob/1d79ad90de9c75692bd8e49d57679697dbefd393/sd-docker-slim/repositories/CodeFormer/basicsr/losses/losses.py#L390-L404 | 1d79ad90de9c75692bd8e49d57679697dbefd393 |
nos | github_2023 | autonomi-ai | python | ModelSpec.name | @property
def name(self) -> str:
"""Return the model name (for backwards compatibility)."""
return self.id | """Return the model name (for backwards compatibility).""" | https://github.com/autonomi-ai/nos/blob/2761f7b50fa3173c74ec63a3321527fbb980b9ac/nos/common/spec.py#L449-L452 | 2761f7b50fa3173c74ec63a3321527fbb980b9ac |
Ask-Anything | github_2023 | OpenGVLab | python | overlay_instances | def overlay_instances(
self,
*,
boxes=None,
labels=None,
masks=None,
keypoints=None,
assigned_colors=None,
alpha=0.5,
):
"""
Args:
boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,
or an Nx4 nu... | """
Args:
boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,
or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,
or a :class:`RotatedBoxes`,
or an Nx5 numpy array of (x_center, y_center, width, height, angle_degr... | https://github.com/OpenGVLab/Ask-Anything/blob/c7f879b10533ba7d030c04ac559374663e35e3a4/video_chat_text/video_chat_with_ChatGPT/models/grit_src/third_party/CenterNet2/detectron2/utils/visualizer.py#L607-L747 | c7f879b10533ba7d030c04ac559374663e35e3a4 |
Ask-Anything | github_2023 | OpenGVLab | python | predict_proposals | def predict_proposals(
self,
anchors: List[Boxes],
pred_objectness_logits: List[torch.Tensor],
pred_anchor_deltas: List[torch.Tensor],
image_sizes: List[Tuple[int, int]],
):
"""
Decode all the predicted box regression deltas to proposals. Find the top proposal... | """
Decode all the predicted box regression deltas to proposals. Find the top proposals
by applying NMS and removing boxes that are too small.
Returns:
proposals (list[Instances]): list of N Instances. The i-th Instances
stores post_nms_topk object proposals for imag... | https://github.com/OpenGVLab/Ask-Anything/blob/c7f879b10533ba7d030c04ac559374663e35e3a4/video_chat_text/video_chat_with_StableLM/models/grit_src/third_party/CenterNet2/detectron2/modeling/proposal_generator/rpn.py#L482-L512 | c7f879b10533ba7d030c04ac559374663e35e3a4 |
Ask-Anything | github_2023 | OpenGVLab | python | __init__ | def __init__(self, tensor: torch.Tensor, image_sizes: List[Tuple[int, int]]):
"""
Arguments:
tensor (Tensor): of shape (N, H, W) or (N, C_1, ..., C_K, H, W) where K >= 1
image_sizes (list[tuple[int, int]]): Each tuple is (h, w). It can
be smaller than (H, W) due t... | """
Arguments:
tensor (Tensor): of shape (N, H, W) or (N, C_1, ..., C_K, H, W) where K >= 1
image_sizes (list[tuple[int, int]]): Each tuple is (h, w). It can
be smaller than (H, W) due to padding.
""" | https://github.com/OpenGVLab/Ask-Anything/blob/c7f879b10533ba7d030c04ac559374663e35e3a4/video_chat_text/video_chat_with_StableLM/models/grit_src/third_party/CenterNet2/detectron2/structures/image_list.py#L23-L31 | c7f879b10533ba7d030c04ac559374663e35e3a4 |
Ask-Anything | github_2023 | OpenGVLab | python | swish | def swish(x, inplace: bool = False):
"""Swish - Described in: https://arxiv.org/abs/1710.05941
"""
return x.mul_(x.sigmoid()) if inplace else x.mul(x.sigmoid()) | """Swish - Described in: https://arxiv.org/abs/1710.05941
""" | https://github.com/OpenGVLab/Ask-Anything/blob/c7f879b10533ba7d030c04ac559374663e35e3a4/video_chat_text/video_chat_with_StableLM/models/grit_src/third_party/CenterNet2/projects/CenterNet2/centernet/modeling/backbone/bifpn.py#L40-L43 | c7f879b10533ba7d030c04ac559374663e35e3a4 |
Ask-Anything | github_2023 | OpenGVLab | python | voc_eval | def voc_eval(detpath, annopath, imagesetfile, classname, ovthresh=0.5, use_07_metric=False):
"""rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
classname,
[ovthresh],
... | """rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
classname,
[ovthresh],
[use_07_metric])
Top level function that does the PASCAL VOC evaluation... | https://github.com/OpenGVLab/Ask-Anything/blob/c7f879b10533ba7d030c04ac559374663e35e3a4/video_chat_with_MOSS/models/grit_src/third_party/CenterNet2/detectron2/evaluation/pascal_voc_evaluation.py#L187-L300 | c7f879b10533ba7d030c04ac559374663e35e3a4 |
Ask-Anything | github_2023 | OpenGVLab | python | apply_image | def apply_image(self, img, interp=None):
"""
img should be a numpy array, formatted as Height * Width * Nchannels
"""
if len(img) == 0 or self.angle % 360 == 0:
return img
assert img.shape[:2] == (self.h, self.w)
interp = interp if interp is not None else self... | """
img should be a numpy array, formatted as Height * Width * Nchannels
""" | https://github.com/OpenGVLab/Ask-Anything/blob/c7f879b10533ba7d030c04ac559374663e35e3a4/video_chat_with_StableLM/models/grit_src/third_party/CenterNet2/detectron2/data/transforms/transform.py#L200-L208 | c7f879b10533ba7d030c04ac559374663e35e3a4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.