source
stringlengths
4.8k
15.8k
file_name
stringlengths
9
9
cwe
listlengths
1
1
""" Implementation of the SHA1 hash function and gives utilities to find hash of string or hash of text from a file. Also contains a Test class to verify that the generated hash matches what is returned by the hashlib library Usage: python sha1.py --string "Hello World!!" python sha1.py --file "hello_world.txt"...
916728.py
[ "CWE-327: Use of a Broken or Risky Cryptographic Algorithm" ]
import os import gc import time import numpy as np import torch import torchvision from PIL import Image from einops import rearrange, repeat from omegaconf import OmegaConf import safetensors.torch from ldm.models.diffusion.ddim import DDIMSampler from ldm.util import instantiate_from_config, ismap from modules impo...
177699.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo # The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo # As the LDSR upscaler relies on VQModel & VQModelInterface, the ...
932523.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py, # where the license is as follows: # # Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer # # Permission is hereby granted, free of charge, to any pers...
570756.py
[ "Unknown" ]
#!/usr/bin/python3 import argparse import ctypes import functools import shutil import subprocess import sys import tempfile import threading import traceback import os.path sys.path.insert(0, os.path.dirname(os.path.dirname((os.path.abspath(__file__))))) from youtube_dl.compat import ( compat_input, compat_h...
093118.py
[ "CWE-276: Incorrect Default Permissions" ]
from __future__ import unicode_literals import errno import hashlib import json import os.path import re import ssl import sys import types import unittest import youtube_dl.extractor from youtube_dl import YoutubeDL from youtube_dl.compat import ( compat_open as open, compat_os_name, compat_str, ) from y...
717170.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
# coding: utf-8 from __future__ import unicode_literals import json import re from .common import InfoExtractor from ..utils import ( clean_html, int_or_none, try_get, unified_strdate, unified_timestamp, ) class AmericasTestKitchenIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?(?:ameri...
773378.py
[ "CWE-798: Use of Hard-coded Credentials" ]
#!/usr/bin/env python # Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
627547.py
[ "CWE-676: Use of Potentially Dangerous Function" ]
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
624453.py
[ "CWE-502: Deserialization of Untrusted Data" ]
#! /usr/bin/python3 import argparse import logging import os import sys from collections import namedtuple import torch from modeling_bertabs import BertAbs, build_predictor from torch.utils.data import DataLoader, SequentialSampler from tqdm import tqdm from transformers import BertTokenizer from .utils_summarizati...
884804.py
[ "CWE-676: Use of Potentially Dangerous Function" ]
#!/usr/bin/env python3 import os import shutil import sys from pathlib import Path from subprocess import check_call from tempfile import TemporaryDirectory from typing import Optional SCRIPT_DIR = Path(__file__).parent REPO_DIR = SCRIPT_DIR.parent.parent def read_triton_pin(device: str = "cuda") -> str: trito...
879024.py
[ "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')" ]
#!/usr/bin/env python3 import os import sys from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Dict, Iterable, List, Literal, Set from typing_extensions import TypedDict # Python 3.11+ import generate_binary_build_matrix # type: ignore[import] import jinja2 Arch = Literal...
938702.py
[ "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')" ]
# Helper to get the id of the currently running job in a GitHub Actions # workflow. GitHub does not provide this information to workflow runs, so we # need to figure it out based on what they *do* provide. import argparse import json import operator import os import re import sys import time import urllib import urlli...
948858.py
[ "CWE-939: Improper Authorization in Handler for Custom URL Scheme" ]
import hashlib import time import urllib import uuid from .common import InfoExtractor from .openload import PhantomJSwrapper from ..utils import ( ExtractorError, UserNotLive, determine_ext, int_or_none, js_to_json, parse_resolution, str_or_none, traverse_obj, unescapeHTML, url...
758317.py
[ "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" ]
import functools import hashlib import json import time import urllib.parse from .common import InfoExtractor from ..utils import ( ExtractorError, OnDemandPagedList, int_or_none, jwt_decode_hs256, mimetype2ext, qualities, traverse_obj, try_call, unified_timestamp, ) class IwaraBa...
837764.py
[ "CWE-327: Use of a Broken or Risky Cryptographic Algorithm" ]
import hashlib import random from .common import InfoExtractor from ..utils import ( clean_html, int_or_none, try_get, ) class JamendoIE(InfoExtractor): _VALID_URL = r'''(?x) https?:// (?: licensing\.jamendo\.com/[^/]+| ...
530858.py
[ "CWE-327: Use of a Broken or Risky Cryptographic Algorithm" ]
""" Settings and configuration for Django. Read values from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global_settings.py for a list of all possible variables. """ import importlib import os import time import traceback import warnings f...
359100.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
"Misc. utility functions/classes for admin documentation generator." import re from email.errors import HeaderParseError from email.parser import HeaderParser from inspect import cleandoc from django.urls import reverse from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_sa...
429723.py
[ "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')" ]
""" This module contains the spatial lookup types, and the `get_geo_where_clause` routine for Oracle Spatial. Please note that WKT support is broken on the XE version, and thus this backend will not work on such platforms. Specifically, XE lacks support for an internal JVM, and Java libraries are required to use...
783587.py
[ "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" ]
# Copyright 2024 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
778047.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# Copyright 2024 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
036289.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
102308.py
[ "CWE-502: Deserialization of Untrusted Data" ]
from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from docs_src.security.tutorial005 import ( app, create_access_token, fake_users_db, get_password_hash, verify_password, ) client = TestClient(app) def get_access_token(username="johndoe", password="secret", scope...
545558.py
[ "CWE-798: Use of Hard-coded Credentials" ]
"""Support for Alexa skill auth.""" import asyncio from asyncio import timeout from datetime import datetime, timedelta from http import HTTPStatus import json import logging from typing import Any import aiohttp from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET from homeassistant.core import HomeAs...
695407.py
[ "CWE-532: Insertion of Sensitive Information into Log File" ]
"""The Application Credentials integration. This integration provides APIs for managing local OAuth credentials on behalf of other integrations. Integrations register an authorization server, and then the APIs are used to add one or more client credentials. Integrations may also provide credentials from yaml for backw...
549500.py
[ "CWE-532: Insertion of Sensitive Information into Log File" ]
"""AWS platform for notify component.""" from __future__ import annotations import asyncio import base64 import json import logging from typing import Any from aiobotocore.session import AioSession from homeassistant.components.notify import ( ATTR_DATA, ATTR_TARGET, ATTR_TITLE, ATTR_TITLE_DEFAULT, ...
804802.py
[ "CWE-532: Insertion of Sensitive Information into Log File" ]
from transformers import AutoModel, AutoTokenizer import time import os import json import threading import importlib from toolbox import update_ui, get_conf from multiprocessing import Process, Pipe load_message = "ChatGLMFT尚未加载,加载需要一段时间。注意,取决于`config.py`的配置,ChatGLMFT消耗大量的内存(CPU)或显存(GPU),也许会导致低配计算机卡死 ……" def string...
458056.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# -*- coding: utf-8 -*- # Copyright: (c) 2022, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """Signature verification helpers.""" from __future__ import annotations from ansible.errors import AnsibleError from ansible.galaxy.user_agent import user_agent f...
539416.py
[ "Unknown" ]
# (c) 2013, Jayson Vantuyl <jayson@aggressive.ly> # (c) 2012-17 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations DOCUMENTATION = """ name: sequence author: Jayson Vantuyl (!UNKNOWN) <jayson@aggressive.ly> version...
763767.py
[ "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')" ]
"""Sanity test using validate-modules.""" from __future__ import annotations import collections import contextlib import json import os import tarfile import typing as t from . import ( DOCUMENTABLE_PLUGINS, MULTI_FILE_PLUGINS, SanitySingleVersion, SanityMessage, SanityFailure, SanitySuccess, ...
589414.py
[ "CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')" ]
import os import subprocess import sys import sysconfig import tempfile from contextlib import nullcontext from importlib import resources from pathlib import Path from shutil import copy2 __all__ = ["version", "bootstrap"] _PIP_VERSION = "24.2" # Directory of system wheel packages. Some Linux distribution packaging...
886160.py
[ "Unknown" ]
"""Pop up a reminder of how to call a function. Call Tips are floating windows which display function, class, and method parameter and docstring information when you type an opening parenthesis, and which disappear when you type a closing parenthesis. """ import __main__ import inspect import re import sys import text...
525549.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
import os import pathlib import tempfile import functools import contextlib import types import importlib import inspect import warnings import itertools from typing import Union, Optional, cast from .abc import ResourceReader, Traversable Package = Union[types.ModuleType, str] Anchor = Package def package_to_ancho...
348050.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
""" Title: Multi-GPU distributed training with PyTorch Author: [fchollet](https://twitter.com/fchollet) Date created: 2023/06/29 Last modified: 2023/06/29 Description: Guide to multi-GPU training for Keras models with PyTorch. Accelerator: GPU """ """ ## Introduction There are generally two ways to distribute computa...
422890.py
[ "CWE-676: Use of Potentially Dangerous Function" ]
"""IMDB sentiment classification dataset.""" import json import numpy as np from keras.src.api_export import keras_export from keras.src.utils.file_utils import get_file from keras.src.utils.python_utils import remove_long_seq @keras_export("keras.datasets.imdb.load_data") def load_data( path="imdb.npz", n...
001029.py
[ "CWE-502: Deserialization of Untrusted Data" ]
"""Reuters topic classification dataset.""" import json import numpy as np from keras.src.api_export import keras_export from keras.src.utils.file_utils import get_file from keras.src.utils.python_utils import remove_long_seq @keras_export("keras.datasets.reuters.load_data") def load_data( path="reuters.npz", ...
780018.py
[ "CWE-502: Deserialization of Untrusted Data" ]
from __future__ import annotations import os from xml.etree import ElementTree as ET import numpy as np import svgelements as se import io from manimlib.constants import RIGHT from manimlib.logger import log from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Line from manimlib.mobject...
703706.py
[ "CWE-611: Improper Restriction of XML External Entity Reference" ]
""" =============================== Wikipedia principal eigenvector =============================== A classical way to assert the relative importance of vertices in a graph is to compute the principal eigenvector of the adjacency matrix so as to assign to each vertex the values of the components of the first eigenvect...
502316.py
[ "CWE-939: Improper Authorization in Handler for Custom URL Scheme" ]
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import importlib import inspect import os import warnings from inspect import signature from pkgutil import walk_packages import numpy as np import pytest import sklearn from sklearn.datasets import make_classification # make it possible...
352492.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
"""Module for initialization hooks https://docs.localstack.cloud/references/init-hooks/""" import dataclasses import logging import os.path import subprocess import time from enum import Enum from functools import cached_property from typing import Dict, List, Optional from plux import Plugin, PluginManager from loc...
974666.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
import glob import logging import os import re import shutil import textwrap import threading from typing import List import semver from localstack import config from localstack.constants import ( ELASTICSEARCH_DEFAULT_VERSION, ELASTICSEARCH_DELETE_MODULES, ELASTICSEARCH_PLUGIN_LIST, OPENSEARCH_DEFAUL...
215937.py
[ "CWE-798: Use of Hard-coded Credentials" ]
import io import tarfile import zipfile from subprocess import Popen from typing import IO, Optional try: from typing import Literal except ImportError: from typing_extensions import Literal import glob import logging import os import re import tempfile import time from typing import Union from localstack.co...
124108.py
[ "CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')" ]
"""Scrapy Shell See documentation in docs/topics/shell.rst """ from __future__ import annotations import os import signal from typing import Any, Callable, Dict, Optional, Tuple, Union from itemadapter import is_item from twisted.internet import defer, threads from twisted.python import threadable from w3lib.url i...
671115.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
""" Scheduler queues """ from __future__ import annotations import marshal import pickle # nosec from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Optional, Type, Union from queuelib import queue from scrapy.utils.request import request_from_dict if TYPE_CHECKING: from os import PathLi...
452701.py
[ "CWE-502: Deserialization of Untrusted Data" ]
""" This module provides some useful functions for working with scrapy.http.Request objects """ from __future__ import annotations import hashlib import json import warnings from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Protocol, Tuple, Type, Union, )...
109129.py
[ "CWE-327: Use of a Broken or Risky Cryptographic Algorithm" ]
from encoder.params_data import * from encoder.model import SpeakerEncoder from encoder.audio import preprocess_wav # We want to expose this function from here from matplotlib import cm from encoder import audio from pathlib import Path import numpy as np import torch _model = None # type: SpeakerEncoder _device = N...
770044.py
[ "CWE-502: Deserialization of Untrusted Data" ]
from datetime import datetime from functools import partial from pathlib import Path import torch import torch.nn.functional as F from torch import optim from torch.utils.data import DataLoader from synthesizer import audio from synthesizer.models.tacotron import Tacotron from synthesizer.synthesizer_dataset import S...
508391.py
[ "CWE-676: Use of Potentially Dangerous Function" ]
""" Main entry point for the benchmarking tool. This module provides a command-line interface for running benchmarks using Typer. It allows users to specify the path to an agent, the benchmark(s) to run, and other options such as verbosity. Functions --------- get_agent : function Dynamically imports and returns ...
641969.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
# This is a websocket interpreter, TTS and STT disabled. # It makes a websocket on a port that sends/receives LMC messages in *streaming* format. ### You MUST send a start and end flag with each message! For example: ### """ {"role": "user", "type": "message", "start": True}) {"role": "user", "type": "message", "cont...
262477.py
[ "CWE-942: Permissive Cross-domain Policy with Untrusted Domains" ]
#!/usr/bin python3 """ Handles command line calls to git """ import logging import os import sys from subprocess import PIPE, Popen logger = logging.getLogger(__name__) class Git(): """ Handles calls to github """ def __init__(self) -> None: logger.debug("Initializing: %s", self.__class__.__name__) ...
513433.py
[ "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')" ]
#!/usr/bin/env python3 """ Plugin loader for Faceswap extract, training and convert tasks """ from __future__ import annotations import logging import os import typing as T from importlib import import_module if T.TYPE_CHECKING: from collections.abc import Callable from plugins.extract.detect._base import Det...
335203.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
""" Contains some simple tests. The purpose of this tests is to detect crashes and hangs but NOT to guarantee the corectness of the operations. For this we want another set of testcases using pytest. Due to my lazy coding, DON'T USE PATHES WITH BLANKS ! """ import sys from subprocess import check_call, CalledProcessE...
006394.py
[ "CWE-939: Improper Authorization in Handler for Custom URL Scheme" ]
#!/usr/bin/env python #__all__ = ['pptv_download', 'pptv_download_by_id'] from ..common import * from ..extractor import VideoExtractor import re import time import urllib import random import binascii from xml.dom.minidom import parseString def lshift(a, b): return (a << b) & 0xffffffff def rshift(a, b): ...
454489.py
[ "CWE-939: Improper Authorization in Handler for Custom URL Scheme" ]
import json import shutil import traceback from pathlib import Path import numpy as np from core import pathex from core.cv2ex import * from core.interact import interact as io from core.leras import nn from DFLIMG import * from facelib import XSegNet, LandmarksProcessor, FaceType import pickle def apply_xseg(input_...
494107.py
[ "CWE-502: Deserialization of Untrusted Data" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:46 @Author : alexanderwu @File : run_code.py @Modified By: mashenquan, 2023/11/27. 1. Mark the location of Console logs in the PROMPT_TEMPLATE with markdown code-block formatting to enhance the understanding for the LL...
173324.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
# -*- coding: utf-8 -*- # @Date : 12/23/2023 4:51 PM # @Author : stellahong (stellahong@fuzhi.ai) # @Desc : from __future__ import annotations import asyncio from typing import Any, List, Optional from pydantic import BaseModel, ConfigDict, Field from metagpt.llm import LLM from metagpt.logs import logger fro...
387722.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/4/29 16:19 @Author : alexanderwu @File : test_common.py @Modified by: mashenquan, 2023/11/21. Add unit tests. """ import importlib import os import platform import uuid from pathlib import Path from typing import Any, Set import pytest from pydantic...
082256.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
from __future__ import annotations import importlib import sys from typing import ( TYPE_CHECKING, Literal, overload, ) import warnings from pandas.util._exceptions import find_stack_level from pandas.util.version import Version if TYPE_CHECKING: import types # Update install.rst, actions-310-minim...
946124.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
import numpy as np import pytest import pandas as pd from pandas import ( Index, MultiIndex, ) def test_repr_with_unicode_data(): with pd.option_context("display.encoding", "UTF-8"): d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]} index = pd.DataFrame(d).set_index(["a", "b"])....
222094.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
""" self-contained to write legacy storage pickle files To use this script. Create an environment where you want generate pickles, say its for 0.20.3, with your pandas clone in ~/pandas . activate pandas_0.20.3 cd ~/pandas/pandas $ python -m tests.io.generate_legacy_storage_files \ tests/io/data/legacy_pickle/0....
426331.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
938513.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
# copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
116843.py
[ "CWE-502: Deserialization of Untrusted Data" ]
import torch import ldm_patched.modules.clip_vision import safetensors.torch as sf import ldm_patched.modules.model_management as model_management import ldm_patched.ldm.modules.attention as attention from extras.resampler import Resampler from ldm_patched.modules.model_patcher import ModelPatcher from modules.core im...
791267.py
[ "CWE-502: Deserialization of Untrusted Data" ]
import torch from ldm_patched.ldm.modules.diffusionmodules.util import make_beta_schedule import math import numpy as np class EPS: def calculate_input(self, sigma, noise): sigma = sigma.view(sigma.shape[:1] + (1,) * (noise.ndim - 1)) return noise / (sigma ** 2 + self.sigma_data ** 2) ** 0.5 d...
032394.py
[ "Unknown" ]
import os import einops import torch import numpy as np import ldm_patched.modules.model_management import ldm_patched.modules.model_detection import ldm_patched.modules.model_patcher import ldm_patched.modules.utils import ldm_patched.modules.controlnet import modules.sample_hijack import ldm_patched.modules.samplers...
192634.py
[ "CWE-502: Deserialization of Untrusted Data" ]
import time from abc import abstractmethod from typing import List, Tuple import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import CLIPImageProcessor, CLIPVisionModel from extensions.multimodal.abstract_pipeline import AbstractMultimodalPipeline from modules import share...
490297.py
[ "CWE-502: Deserialization of Untrusted Data" ]
import asyncio import json import logging import os import traceback from collections import deque from threading import Thread import speech_recognition as sr import uvicorn from fastapi import Depends, FastAPI, Header, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.requests import Requ...
204197.py
[ "CWE-942: Permissive Cross-domain Policy with Untrusted Domains" ]
import importlib import traceback from functools import partial from inspect import signature import gradio as gr import extensions import modules.shared as shared from modules.logging_colors import logger state = {} available_extensions = [] setup_called = set() def apply_settings(extension, name): if not has...
813380.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
import argparse import os from threading import Lock from typing import Generator, List, Optional import torch import uvicorn from coati.models import generate_streaming from coati.quant import llama_load_quant, low_resource_init from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware f...
041528.py
[ "CWE-942: Permissive Cross-domain Policy with Untrusted Domains" ]
""" API and LLM warpper class for running LLMs locally Usage: import os model_path = os.environ.get("ZH_MODEL_PATH") model_name = "chatglm2" colossal_api = ColossalAPI(model_name, model_path) llm = ColossalLLM(n=1, api=colossal_api) TEST_PROMPT_CHATGLM="续写文章:惊蛰一过,春寒加剧。先是料料峭峭,继而雨季开始," logger.info(llm(TEST_PROMPT_CHATG...
693973.py
[ "CWE-502: Deserialization of Untrusted Data" ]
import linecache import os import sys import traceback import warnings from pathlib import Path from typing import Any, Dict, Optional, Union import torch import torch.fx import torch.nn as nn from torch.fx.graph import PythonCode try: from torch.fx.graph import _PyTreeCodeGen SUPPORT_PT_CODEGEN = True excep...
514256.py
[ "CWE-502: Deserialization of Untrusted Data" ]
from __future__ import annotations import logging from collections.abc import Iterable from typing import NotRequired, TypedDict from django.db.models.query import QuerySet from django.http import Http404, HttpResponse, StreamingHttpResponse from rest_framework.request import Request from rest_framework.response impo...
610060.py
[ "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')" ]
from __future__ import annotations from collections import defaultdict from collections.abc import Sequence from datetime import timedelta from email.headerregistry import Address from functools import reduce from typing import Any from django.db.models import Q from django.utils import timezone from rest_framework i...
239585.py
[ "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" ]
from typing import Any from django.db.models import Q from drf_spectacular.utils import extend_schema from rest_framework.exceptions import ParseError from rest_framework.request import Request from rest_framework.response import Response from sentry.api.api_publish_status import ApiPublishStatus from sentry.api.base...
557095.py
[ "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" ]
import torch import pytorch_lightning as pl import torch.nn.functional as F from contextlib import contextmanager from ldm.modules.diffusionmodules.model import Encoder, Decoder from ldm.modules.distributions.distributions import DiagonalGaussianDistribution from ldm.util import instantiate_from_config from ldm.modul...
299989.py
[ "CWE-502: Deserialization of Untrusted Data" ]
"""make variations of input image""" import argparse, os import PIL import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange, repeat from torchvision.utils import make_grid from torch import autocast fr...
916680.py
[ "CWE-502: Deserialization of Untrusted Data" ]
#!/usr/bin/env python # vim: set encoding=utf-8 # pylint: disable=wrong-import-position,wrong-import-order """ Main server program. Configuration parameters: path.internal.malformed path.internal.static path.internal.templates path.log.main path.log.queries """ from __future__ import print_funct...
919804.py
[ "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')" ]
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import contextlib import requests from lxml import etree from hashlib import md5 from urllib import parse from odoo import api, fields, models from odoo.addons.account_peppol.tools.demo_utils import handle_demo from odo...
765068.py
[ "CWE-319: Cleartext Transmission of Sensitive Information" ]
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import werkzeug from werkzeug.urls import url_encode from odoo import http, tools, _ from odoo.addons.auth_signup.models.res_users import SignupError from odoo.addons.web.controllers.home import ensure_db,...
511699.py
[ "CWE-532: Insertion of Sensitive Information into Log File" ]
# -*- coding: utf-8 -*- import contextlib import datetime import json import logging import math import os import random import selectors import threading import time from psycopg2 import InterfaceError, sql import odoo from odoo import api, fields, models from odoo.service.server import CommonServer from odoo.tools.m...
969579.py
[ "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" ]
import codecs import io import json import re from pathlib import Path import aiohttp import PyPDF2 import yaml from bs4 import BeautifulSoup from fastapi import FastAPI, Query, Request, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.openapi.utils import get_openapi from fastapi.responses imp...
287641.py
[ "CWE-942: Permissive Cross-domain Policy with Untrusted Domains" ]
""" Basic FastAPI server to serve models using HuggingFace Transformers library. This is an alternative to running the HuggingFace `text-generation-inference` (tgi) server. """ import sys import threading from queue import Queue import fastapi import hf_stopping import hf_streamer import interface import torch import...
672233.py
[ "CWE-942: Permissive Cross-domain Policy with Untrusted Domains" ]
from argparse import Namespace import pytest import torch from model_training.custom_datasets import get_one_dataset from model_training.custom_datasets.formatting import ( QA_SPECIAL_TOKENS, DatasetEntryRm, Role, Utterance, create_dataset_entry_qa, ) from model_training.custom_datasets.ranking_col...
230568.py
[ "CWE-676: Use of Potentially Dangerous Function" ]
import dataclasses import gc import glob import os from accelerate import init_empty_weights from accelerate.utils import set_module_tensor_to_device from huggingface_hub import snapshot_download import torch from torch import Tensor from torch.nn import functional as F import torch.nn as nn from tqdm import tqdm from...
914791.py
[ "CWE-502: Deserialization of Untrusted Data" ]
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
023226.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
218664.py
[ "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')" ]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
409624.py
[ "CWE-489: Active Debug Code" ]
# Copyright (c) SenseTime Research. All rights reserved. import os import argparse import numpy as np import torch from torch.utils.data import DataLoader from torchvision.transforms import transforms from utils.ImagesDataset import ImagesDataset import cv2 import time import copy import imutils # for openpose bod...
192152.py
[ "CWE-676: Use of Potentially Dangerous Function" ]
# Copyright (c) SenseTime Research. All rights reserved. from legacy import save_obj, load_pkl import torch from torch.nn import functional as F import pandas as pd from .edit_config import attr_dict import os def conv_warper(layer, input, style, noise): # the conv should change conv = layer.conv batch, i...
263731.py
[ "CWE-502: Deserialization of Untrusted Data" ]
from enum import Enum import math import numpy as np import torch from torch import nn from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module from pti.pti_models.e4e.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE, _upsample_add from pti.pti_models.e4e.stylegan2.model import EqualLinea...
076051.py
[ "Unknown" ]
import json import random import subprocess import threading import time from typing import NamedTuple import libtmux class InstructionSpec(NamedTuple): instruction: str time_from: float time_to: float class CliDirector: def __init__(self): self.record_start = None self.pause_betwee...
245327.py
[ "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')" ]
""" This module manages and invokes typed commands. """ import functools import inspect import logging import sys import textwrap import types from collections.abc import Callable from collections.abc import Iterable from collections.abc import Sequence from typing import Any from typing import NamedTuple import pypa...
527709.py
[ "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')" ]
#!/usr/bin/env -S python3 -u import datetime import http.client import json import os import re import subprocess import sys import time from pathlib import Path # Security: No third-party dependencies here! root = Path(__file__).absolute().parent.parent def get(url: str) -> http.client.HTTPResponse: assert url...
933962.py
[ "CWE-295: Improper Certificate Validation" ]
import cv2 import math import numpy as np import os.path as osp import torch import torch.utils.data as data from basicsr.data import degradations as degradations from basicsr.data.data_util import paths_from_folder from basicsr.data.transforms import augment from basicsr.utils import FileClient, get_root_logger, imfro...
870482.py
[ "CWE-502: Deserialization of Untrusted Data" ]
import importlib import inspect import re from typing import Any, Callable, Type, Union, get_type_hints from pydantic import BaseModel, parse_raw_as from pydantic.tools import parse_obj_as def name_to_title(name: str) -> str: """Converts a camelCase or snake_case name to title case.""" # If camelCase -> conv...
365412.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .utils.mol_attention import MOLAttention from .utils.basic_layers import Linear from .utils.vc_utils import get_mask_from_lengths class DecoderPrenet(nn.Module): def __init__(self, in_dim, sizes): super().__init__()...
476533.py
[ "Unknown" ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Multi-Head Attention layer definition.""" import math import numpy import torch from torch import nn class MultiHeadedAttention(nn.Module): """Multi-Head Attention laye...
434281.py
[ "Unknown" ]
import importlib import logging import types from dataclasses import dataclass, field from heapq import heappop, heappush from typing import Type, TypeAlias from quivr_core.files.file import FileExtension from .processor_base import ProcessorBase logger = logging.getLogger("quivr_core") _LOWEST_PRIORITY = 100 _reg...
554536.py
[ "CWE-706: Use of Incorrectly-Resolved Name or Reference" ]
import json import os import re import string from collections import Counter from shutil import rmtree from typing import Any, Dict, List, Optional, Tuple import requests import tqdm from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from...
930264.py
[ "CWE-319: Cleartext Transmission of Sensitive Information" ]
"""SQL wrapper around SQLDatabase in langchain.""" from typing import Any, Dict, Iterable, List, Optional, Tuple from sqlalchemy import MetaData, create_engine, insert, inspect, text from sqlalchemy.engine import Engine from sqlalchemy.exc import OperationalError, ProgrammingError class SQLDatabase: """SQL Datab...
885715.py
[ "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" ]