Saravanan666/pypi-org huggingface dataset:
Package: safe-redirect-url
Safe Redirect URLCheck the safety of a redirect URL. Extracted from Django's `url_has_allowed_host_and_scheme`.Documentation:https://frankie567.github.io/safe-redirect-url/Source Code:https://github.com/frankie567/safe-redirect-urlDevelopmentSetup environmentWe useHatchto manage the development environment and production build. Ensure it's installed on your system.Run unit testsYou can run all the tests with:hatchruntestFormat the codeExecute the following command to apply linting and check typing:hatchrunlintPublish a new versionYou can bump the version, create a commit and associated tag with one command:hatchversionpatchhatchversionminorhatchversionmajorYour default Git text editor will open so you can add information about the release.When you push the tag on GitHub, the workflow will automatically publish it on PyPi and a GitHub release will be created as draft.Serve the documentationYou can serve the Mkdocs documentation with:hatchrundocs-serveIt'll automatically watch for changes in your code.LicenseThis project is licensed under the terms of the MIT license.
Package: safe_redis_lock
项目描述一个单机版的redis分布式锁( A single redis distributed lock)项目使用set命令来加锁使用lua脚本来释放锁以保证原子性注意事项,传入的redis连接池需要必须参数一样,同一个redis数据库当block=False的时候如果没有获得锁则返回一个AcquireFailException异常acquire方法返回True时候则说明获得锁成功使用方法一装饰器使用方法新建一个RedisLock对象.使用RedisLock的lock装饰器来装饰需要保证原子性的函数注意该函数不能是阻塞的importthreadingimportredisfromsafe_redis_lockimportRedisLockpool=redis.ConnectionPool(host='127.0.0.1',port=6379,password='lyc',db=0)conn=redis.Redis(connection_pool=pool)conn.set('producer',10000)redis_lock_=RedisLock(lock_timeout=5,pool=pool,block=True)@redis_lock_.lockdefconsumer_pp(conn):num=int(conn.get('producer'))ifnum==0:returnTrueelse:print(f'we consumer one left -->{num}')conn.set('producer',num-1)defconsumer():pool=redis.ConnectionPool(host='127.0.0.1',port=6379,password='lyc',db=0)whileTrue:conn=redis.Redis(connection_pool=pool)ifconsumer_pp(conn):breakdefconsumer_thread():fromthreadingimportThreadforiinrange(20):Thread(target=consumer).start()consumer_thread()使用方法二:fromsafe_redis_lockimportRedisLock,AcquireFailExceptionimportredisimportthreadingimportospool=redis.ConnectionPool(host='127.0.0.1',port=6379,password='lyc',db=0)conn=redis.Redis(connection_pool=pool)conn.set('producer',10000)redis_lock_=RedisLock(lock_timeout=5,pool=pool,block=True)defconsumer_pp(conn):num=int(conn.get('producer'))ifnum==0:returnTrueelse:print(f'we consumer one left -->{num}')conn.set('producer',num-1)defconsumer():pool=redis.ConnectionPool(host='127.0.0.1',port=6379,password='lyc',db=0)whileTrue:conn=redis.Redis(connection_pool=pool)value=f'{threading.current_thread().ident}-{os.getpid()}'get_lock=Falsetry:get_lock=redis_lock_.acquire(value=value)ifget_lock:ifconsumer_pp(conn):breakexceptAcquireFailException:print('can not get the lock')finally:ifget_lock:redis_lock_.release(value)defconsumer_thread():fromthreadingimportThreadforiinrange(20):Thread(target=consumer).start()consumer_thread()
Package: safe-regex
Safe RegexA library to organise the unit tests for your regular expressions.UsagePip this librarypipinstallsafe-regexSeparate your regex from your main code into yaml files with positive and negative examples.  Give these files a.re.yamlextension---pattern:"^[a-z]{3}$"description:a three letter acronymtest_cases:-text:abcmatches:[abc]-text:xyzmatches:[xyz]# These examples do not match anything-text:123-text:r2d2-text:abcdThe change your python code to load the regex from the yaml file.importsafe_regexmy_re=safe_regex.RegularExpression.from_yaml('my_regex',folder="my_folder")# then use as a normal re.Pattern objectre_match_object=my_re.match('cat')Unit testingIn your unit tests loop through your regular expression folder and validate everything.importosfromsafe_regeximportRegularExpression# pytest 6.1 exampledeftest_regex():""" verify all regular expressions are valid """regex_directory="my_folder"forfilenameinos.listdir(regex_directory):iffilename.endswith(".re.yaml"):withopen(os.path.join(regex_directory,filename))asyaml_file:yaml_data=yaml.safe_load(yaml_file)sr=RegularExpression(**yaml_data)sr.test()DebuggingWhen a regular expression's test fails it helpfully prepares a link to regexr.com where you can inspect and debug the problem. For example:https://regexr.com/?expression=%2F%5E%5Ba-z%5D%7B3%7D%2Fgms&text=These+should+all+match%0Aabc%0Axyz%0ANone+of+these+should+match%0A123%0Aabcd%0Ar2d2Configurationrather than passing the folder specifySAFE_REGEX_PATHas an environment variable.DevelopmentDevelopment is being performed on OS X withpyenv(with its.python_versionfile) anddirenv(with its.envrcfile).In order to set up a development environment:brewinstalldirenvpyenvecho-e'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi'>>~/.bash_profileexec"${SHELL}"pyenvinstall$(cat./.python-version)# pyenv install takes a whiledirenvallow# direnv allow triggers the creation and activation of the virtual environmentpipinstall-rrequirements.txtpipinstall-rtests/requirements-testing.txtpipinstall--editable.# Then validate by runningpytest
Package: safer-hist
SAFER STORAGE NAS Historical managementThis project implements a system level API to query and manage the SAFER-STORAGE backup and storage in space and time dimensions (hence the historical dimension). Each command of this API is designed to be either invoked directly from the shell or wrapped into an higher level API, eg. a web-ui back-end.The SAFER-STORAGE backup system is extensively based onZoLsnapshots as found in particulat in theProxmox VEdistribution. Notice that some features may be unavailable depending on which ZoL version is available on the execution platform.InstallThis project usespython v3.7.4. We recommend installing python usingpyenveg. with thepyenv installer, as a regular (non-root) user:$curlhttps://pyenv.run|bash
$pyenvinstall3.7.4
$pyenvlocal3.7.4Note that if python is already installed or you are already pyenv but an older version, version 3.7.4 may not be available. Simply erase your previous pyenv installation an reinstall from scratch (or use vagrant, for a clean fresh start).This package is then available through PyPI using the following command:$pipinstall--upgradesafer_hist_pkgUsagesafer: main commandThe commands of this package are part of a module named safer_hist. For convenience, we also recommend defining the following funtion in your shell (eg. in your.bashrc):functionsafer(){case$1inhelp|lssnaps|genmeta|lsuntil|lsalltime|restore)subcmd=$1shiftpython-msafer_hist${subcmd}"$@";;*)python-msafer_histhelp"$@";;esac}safer genmeta: Snapshot meta-info generationGenerates a snapshot meta file for the snapshot@<snapshot>of the (ZFS) dataset<dataset>. By default the output is written to a file named.zfsmeta_<snapshot>at the root of the dataset. If-ooption is given, output is written to the specied filename or to stdout if-(minus) is given instead of a filename.$safergenmeta[-ofile|-]dataset@snapshotsafer lssnaps: Snapshot listsafer lsuntil: Merge target dir content from snapshots untilsafer lsalltime: Marge target dir content from all snapshotssafer restore: Restore file from snapshotPackaging and deploying to PyPI(reminder, see thistuto)Install building dependencies as follows:$python3-mpipinstall--upgradesetuptoolswheelBuild package as follows:$python3setup.pysdistbdist_wheelUpload to PyPI server:$python3-mtwineuploaddist/*LicenseLicensed under the EUPLAuthor(s)DALLE, Olivier (First.LAST@safer-storage.com)
Package: safer-prompt-toolkit
safer-prompt-toolkita wrapper to prompt-toolkit, designed to provide a fallback for some of prompt-toolkit's functionality when operating from a place where prompt-toolkit can't run.intent:prompt-toolkit is a powerfull, command line UI, built in to almost every python interpreter. I love using it when asking the user for some input. However, prompt toolkit often complains and crashes when asked to run in certain non-terminal invorments (for example pycharms python console). and I find that this to be a major downside to using prompt toolkit as a minor UI part in some major project, that might somtimes be run in some context that is not the terminal.after making several projects that needed this functionality, and after deciding that copy pasting this prompt-toolkit fallback project is tedius and unhealthy, I desided to make this thing a project and upload it ot pypi.Installationpip install safer-prompt-toolkitDocumentationafter installing, you can import like so:importsafer_prompt_toolkitand you can send some prompt via:safer_prompt_toolkit.prompt("some query with validation and completion options")function documentationsafer_prompt_toolkit.prompt(message,max_failcase_completion_lines=3,max_chars_in_completion_line=150,**prompt_toolkit_kwargs)use prompt_toolkit's prompt function with a fail-safeParameters:message - the prompt messege to be printed to the user, (add \n at the end if you want to get the response in a new line)max_failcase_completion_lines - defaults to 3, in case the regular prompt toolkit fails, max_failcase_completion_lines is the maximum amount of lines in the completionmax_chars_in_completion_line - defaults to 150, in case the regular prompt toolkit fails, max_chars_in_completion_line is the maximum amount of chars in a line in the completion**prompt_toolkit_kwargs - any of prompt-toolkits keywords. in case the regular prompt toolkit fails, "validator" and "completer" are used if supplied.returns:the users responseinfo:prompt_toolkit_kwargs allows you to enter some prompt_toolkit.validation.Validator instance. for example 'validator=prompt_toolkit.validation.Validator.DummyValidator()'.prompt_toolkit_kwargs allows you to enter some prompt_toolkit.completion.Completer instance. for example 'completer=prompt_toolkit.completion.Completer.DummyCompleter()'call_example:importsafer_prompt_toolkitimportprompt_toolkit.validation,prompt_toolkit.completionvalidator1=prompt_toolkit.validation.DummyValidator()# Could be any prompt_toolkit.validation.Validator instance.completer1=prompt_toolkit.completion.DummyCompleter()# Could be any prompt_toolkit.completion.Completer instance.response=safer_prompt_toolkit.prompt("some prompt message\n",validator=validator1,completer=completer1)print(f"{response}is the users response.")
Package: safersympify
Safer SympifyConvert unsanitized user input into SymPy expression.This does not prevent all possible attacks. However, this is much safer than usingeval(), which SymPy still does.See SymPy PR12524 for more details:https://github.com/sympy/sympy/pull/12524ExamplesCreate a SymPy expression from user input. 
    This uses pure Python syntax. 
    Whitelisted operators and functions only are allowed.
    >>> expr = SaferSympify().str2sympy('-sqrt(1 + a**b*b)/((a**b)*b+1)')
    >>> expr
    -1/sqrt(a**b*b + 1)

    Get free symbols:
    >>> sorted(expr.free_symbols, key=lambda x: str(x))
    [a, b]

    Evaluate expression:
    >>> expr.evalf(subs={'a': 1, 'b': 3, 'c': 5})  # Note extra values can be passed too
    -0.500000000000000

    Simplify expression:
    >>> expr.simplify()
    -1/sqrt(a**b*b + 1)

    Pretty-print expression as Latex (could be displayed in browser with MathJax)
    >>> sympy.latex(expr)
    '- \\frac{1}{\\sqrt{a^{b} b + 1}}'
Package: safescope
safescopesafescopeis a small python package useful for development in jupyter notebooks.
The goal is to prevent functions from using global variables and instead raise aNameError.
This is achieved by  mimicking a module, and define all functions in that module (namedside_scope).ExampleThe main part ofsafescopeis the decorator@safescope. This mimics writing the function in a fileside_scope.pyand importing this function to the notebook. Hence, functions decorated with@safescopewill not have access to variables declared in the notebook environment.In the example below, onlyfoo(1)will execute, asbar(1)returns aNameError.fromsafescopeimportsafescopex=9deffoo(y):returnx+y@safescopedefbar(y):returnx+yfoo(1)# Returns  10bar(1)# Raise "NameError: name 'x' is not defined"By usingImports, the imports are added to both the main scope and theside_scope, making them available for the functions decorated with@safescope.fromsafescopeimportsafescope,ImportswithImports():importnumpyasnp@safescopedefarange(n):returnnp.arange(n)arange(4)# Returns array([0, 1, 2, 3])Installationsafescopecan either be installed from pypi with pip/pip3:pipinstallsafescopeor from github with:pipinstallgit+git://github.com/havakv/safescope.gitor from source by cloning the repo:gitclonehttps://github.com/havakv/safescope.gitcdsafescope
pythonsetup.pyinstall
Package: safescript
SafeScript v1.0.2SafeScript is a Python module designed to enhance the security of web applications by providing various functions to prevent common security vulnerabilities such as XSS and SQL Injection attacks.Featuressanitize_html: Sanitize HTML content to prevent XSS attacks.escape_html: Escape special characters in HTML content.sanitize_sql: Sanitize SQL input to prevent SQL Injection attacks.prevent_xss_and_sqli: Prevent both XSS and SQL Injection attacks.InstallationYou can install SafeScript using pip:pipinstallsafescriptUsagefromsafescriptimportSafeScript# Example Usageinput_data="<script>alert('XSS Attack')</script>"output=SafeScript.prevent_xss_and_sqli(input_data)print(output)Functionssanitize_html(input_html)Sanitize HTML content to prevent XSS attacks.escape_html(input_html)Escape special characters in HTML content.sanitize_sql(input_sql)Sanitize SQL input to prevent SQL Injection attacks.prevent_xss_and_sqli(input_data)Prevent both XSS and SQL Injection attacks.Version Historyv1.0.2 (Current Version)[List of changes in v1.0.2]v1.0.1Initial release with basic security functions.ContributorsIshan Oshada
Package: safeseqs
ï»¿SafeSeqS - Safe Sequencing SystemPython package for processing of SafeSeqS data (https://www.ncbi.nlm.nih.gov/pubmed/21586637).   The pipeline analyzes multiple
samples in fastq sequencing files to identify mutations present in a small fraction of DNA templates.DocumentationPlease see thedocumentationon github for complete usage details.InstallationUse pip to install the SafeSeqS package:$pipinstallsafeseqsSafeSeqS depends on several other packages and these will be installed automatically by pip if they
are not already installed.
Package: safesort
safesortdoes what it says on the box: guarantees safe sorting of arbitrary
heterogeneous lists across Python 2 and Python 3:>>> list(sorted(["a", 1, None]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
>>> list(safesort(["a", 1, None))
[None, 1, 'a']Three ordering keys are attempted for each comparison:Object:objA > objBType-and-object:(type(objA).__mro__,objA) >(type(objB).__mro__,objB)Type-and-identity:(type(objA).__mro__,id(objA)) >(type(objB).__mro__,id(objB))This guarantees a total ordering which is:As consistent as possibleBroadly sensible: objects with similar types will be grouped togetherFor example:>>> from safesort import safesort
>>> input = ['a', set([]), [], {}, 1, None]
>>> list(safesort(input))
[None, 1, {}, [], set([]), 'a']Installationsafesortcan be installed with Python 2 or Python 3 usingpiporeasy_install:$ pip install safesort
- OR -
$ easy_install safesort
Package: safe_syslog_handler
SafeSysLogHandler recreates the connection to a remote logging server when the connection is lost, avoiding the[errno 32] Broken Pipeerror which would occur when using theSysLogHandler.Free software: Apache Software License 2.0Documentation:https://safe-syslog-handler.readthedocs.io.Instalation$pipinstallsafe_syslog_handlerUsageIf you have some simple logging configured, exemple:from logging import config
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'syslog': {
            'format': '%(asctime)s %(hostname)s %(name)s: #{filename:%(filename)s} #{line:%(lineno)d} #{process:%(process)d} #{thread:%(thread)d} %(message)s\n',
            'datefmt': '%b %d %H:%M:%S',
        },
    },
    'loggers': {
        'my-app': {
            'handlers': ['syslog_handlers', ],
            'level': logging.DEBUG,
            'propagate': True,
        },
    }
}Then you just need to add this:LOGGING['handlers'] = {
    'syslog_handlers': {
        'formatter': 'syslog',
        'class': 'safe_syslog_handler.handlers.SafeSysLogHandler',
        'socktype': socket.SOCK_STREAM,
        'address': ('localhost', 5140),
    }
}You can see an example app in theexamplefolderCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.
Package: safetensors
Installationpip install safetensorsUsageNumpyfromsafetensors.numpyimportsave_file,load_fileimportnumpyasnptensors={"a":np.zeros((2,2)),"b":np.zeros((2,3),dtype=np.uint8)}save_file(tensors,"./model.safetensors")# Now loadingloaded=load_file("./model.safetensors")Torchfromsafetensors.torchimportsave_file,load_fileimporttorchtensors={"a":torch.zeros((2,2)),"b":torch.zeros((2,3),dtype=torch.uint8)}save_file(tensors,"./model.safetensors")# Now loadingloaded=load_file("./model.safetensors")Developing# inside ./safetensors/bindings/python
pip install .[dev]Should be enough to install this library locally.Testing# inside ./safetensors/bindings/python
pip install .[dev]
pytest -sv tests/
Package: safetext
🤔 why safetext?Detect. Filter. Protect.Effortless Profanity Management: Instantly identify and censor profanity with just one line of code.Multilingual Capability: Fluent in five languages, designed for easy expansion.Optimized for Content Moderation: Perfect for efficiently moderating and cleaning up text in various applications.Automated: Smart language detection for quick setup.📦 installationeasily installsafetextwith pip:pipinstallsafetext🎯 quickstartcheck and censor profanity>>>fromsafetextimportSafeText>>>st=SafeText(language='en')>>>results=st.check_profanity(text='Some text with <profanity-word>.')>>>results{'word':'<profanity-word>','index':4,'start':15,'end':31}>>>text=st.censor_profanity(text='Some text with <profanity-word>.')>>>text"Some text with ***."automated language detectionfrom text:>>>fromsafetextimportSafeText>>>eng_text="This story is about to take a dark turn.">>>st=SafeText(language=None)>>>st.set_language_from_text(eng_text)>>>st.language'en'from .srt (subtitle) file:>>>fromsafetextimportSafeText>>>turkish_srt_file_path="turkish.srt">>>st=SafeText(language=None)>>>st.set_language_from_srt(turkish_srt_file_path)>>>st.language'tr'📜 licensesafetextis proudly open-source, available under theMIT License.📞 contactfor inquiries or support, reach out viaemailor visit our websiteSafeVideo.🤝 contribute to safetextjoin our mission in refining content moderation!contribute by:adding new languages: create a folder with the ISO 639-1 code and include awords.txt.enhancing word lists: improve detection accuracy.sharing feedback: your ideas can shapesafetext.see ourcontributing guidelinesfor more.🏆 contributorsmeet our awesome contributors who makesafetextbetter every day!follow us for more!
Package: safety-checker
Safety CheckerSafety checker is a model used in stable diffusion pipeline, aimed to identify NSFW image.Hereis the official description.This project extracts its safety checker into a independent function to provide a conventional way to detect NSFW image in deep neural network.Seetest_imgs.pyto get start.TODOadd standalone safety checker implementation that depends on pytorch only. provide strength config (if possible) for NSFW detectionadd FastAPI integration
Package: safetydance
safetydancesafetydanceis a Python framework for defining type-safe and flexibly composable
application steps with a shared execution context for sharing variables between the
steps. The design of safetydance is partially inspired by<https://cucumber.io>_.Descriptionsafetydancedefines a set of decorators that rewrite functions as steps and scripts.A step should be a function with a name that reads easily, like a short phrase or
sentence. Steps may take arguments and they may access variables defined for the
"context scope". Steps may call other steps, too.A script is a function composing the execution of a series of steps. A script is a step
that defines an execution context. Scripts may also call other scripts. The primary
difference between a script and a step is the implicit definition of the execution
context.TODOWhen a script calls another script the current execution contextmaybe passed as a kwarg to the nested script; by default all scripts execute in their own
execution context; that is, if a step is used by both an originating and a nested script
the context variables it accesses are determined by the calling script's execution
context.Context Scope VariablesA context scope variable is sort of like a global variable. The run of a script defines
a context wherecontext_datavariables are stored for access by steps.Think of a conversation between two friends. Much of the conversation will reference
assumed shared knowledge, or context. Forsafetydance, the context scope provides a
way for steps to share assumed context to make it possible to provide a more
conversational style of programmingFuture WorkMypy extension to validate scripts. For example, prove that a script shouldn't fail
due to missingcontext_datafor any step in the script.Dry run execution of stepsDAG derivation for scriptsParallel evaluation for independent up to a join for DAG legs of a script.Diagram output for script DAGs.Setup for Developmentpoetryinstall
Package: safety-db
What is Safety DB?Safety DB is a database of known security vulnerabilities in Python packages. The data is made available bypyup.ioand synced with this repository once per month. Most of the entries are found by filtering CVEs and changelogs for certain keywords and then manually reviewing them.ToolsSafety CIis a deep GitHub integration that's available on pyup.io. It checks your commits and Pull Requests.Safetyis a command line tool that checks virtualenvironments and requirement files either locally or on a CI server.Safety Djangois a package for Django that warns you in the admin area if your installed Django release is insecure.Safety Bar(alpha) is a macOS menubar application.Apre-commit hookby Lucas Cimon.pipenv checkrelies onsafetyand Safety-DB to check for known vulnerabilities in locked componentsyour tool?Installationpipinstallsafety-dbUsagefromsafety_dbimportINSECURE,INSECURE_FULLWhat is this not?This is not a hall of shame, or a list of packages to avoid. The package maintainers show a great responsibility by documenting and fixing security issues in such a way that they can be listed here. That's extremely valuable when considering using a package in production.Using this dataFor humans:There's a small website available that lets you browse the data:https://pyupio.github.io/safety-db/For robots:Check out thedatadirectory:insecure.jsoncontains just the package name and all insecure releases as a plain list.insecure_full.jsonadditionally contains the CVE description and URLs, or the relevant part of the changelog.The database is licensed underCC BY-NC-SA 4.0. This allows you to use the data in any non commercial project as long as you link back to this repo. If you need a license for a commercial project, please contactsupport@pyup.io.
Package: safety-django
*Note: safety-django is currently in its early stages. It's probably no even installable and likely that there are some false positives and missing packages.*[![PyPi](https://img.shields.io/pypi/v/safety-django.svg)](https://pypi.python.org/pypi/safety-django)[![Travis](https://img.shields.io/travis/pyupio/safety-django.svg)](https://travis-ci.org/pyupio/safety-django)# AboutSafety for Django checks your installed dependencies for known security vulnerabilities and displays them in the admin area.# InstallationInstall `safety-django` with pip:```pip install safety-django```and add it to your `INSTALLED_APPS`, before `django.contrib.admin````INSTALLED_APPS = ['safety_django','django.contrib.admin',]```# Screenshots![secure](secure.png)![insecure](insecure.png)# SupportIf you are using `safety` in one of your projects, please consider getting a paid[pyup.io](https://pyup.io) account. This is what makes projects like this possible.