Saravanan666/pypi-org huggingface dataset:
Package: py-cache
Method _cacheWhyIf you want to _cache the calls to a specific method or function you could use the pythonfunctools._cachedecorator.
If this has not enough configuration options for your taste, or you work with arguments which are not hashable this _
cache decorator could be useful.AdvantagesWorks with non hashable objectsSet expiry after timeSet expiry after a scheduleSet maximal _cache size per methodWorks with sync and async functionsProperly testedUsageCacheUse a cache which expires after a certain amount of time:frompycacheimportcache# The format for schedule_type is <hh:mm:ss># This _cache would expire every 10 seconds@cache(expires_at="*:*:10")defplease_cache():pass# This _cache would expire every 5 minutes and 10 seconds@cache(expires_every="*:5:10")defplease_cache():passUse a _cache which expires every time at a certain time (A bit like a cron job).frompycacheimportcache# The format for _schedule_str is <hh:mm:ss># This _cache would expire every day at 15:10:05@cache(expires_at="15:10:05")defplease_cache():pass# This _cache would expire every hour 8 minutes after a full hour@cache(expires_at="*:08:00")defplease_cache():passLimit the number of _cache entriesfrompycacheimportcache# This would result in only one _cache entry@cache(expires_every="*:*:10",max_cache_size=1)defplease_cache(data:str):pass# Gets placed in _cacheplease_cache("hello")# Gets called from _cacheplease_cache("hello")# Gets placed in _cache and "hello" gets removedplease_cache("world")# Is not found in _cache, because "world" is the only _cache entry,# because the _cache size is oneplease_cache("hello")Schedulefrompycacheimportschedule,add_schedule,ScheduleSubscriptionimportasyncio# Gets called every 10 seconds@schedule(call_every="*:*:10")defschedule_me():pass# Gets called every at 10 am@schedule(call_every="10:00:00")defschedule_me():pass# Gets called 3 times@schedule(call_every="10:00:00",stop_after=3)defschedule_me():pass# Call with args and keyword args@schedule(call_every="10:00:00",args=(3,),kwargs={"hello":"world"})defschedule_me(three:int,hello:str):pass# Pass an event loop@schedule(call_every="10:00:00",event_loop=your_event_loop)asyncdefschedule_me():passdefschedule_programmatically():pass# Call this every five secondsschedule_subscription:ScheduleSubscription=add_schedule(schedule_programmatically,call_every="*:*:5")# Stop the schedule callschedule_subscription.stop()# Start the schedule againschedule_subscription.stop()
Package: pycacher
pycacher [![Build Status](https://secure.travis-ci.org/garindra/pycacher.png)](https://secure.travis-ci.org/garindra/pycacher.png)=======Python module for easy function caching decoration, batching, and many more.Complete documentation on:[http://pycacher.readthedocs.org](http://pycacher.readthedocs.org) (still empty)###PyPi Page[http://pypi.python.org/pypi/pycacher](http://pypi.python.org/pypi/pycacher)###InstallationThis package is officially hosted on PyPI, so what you need to do is simply:pip install pycacher###Examples:##### #1 Caching function decorator:from pycacher import Cachercacher = Cacher('localhost', 11211)@cacher.cache()def expensive_function(a, b):return a + bexpensive_function(1, 2) # will actually executeexpensive_function(1, 2) # will get the value from the cache##### #2 Batching:batcher = cacher.create_batcher()batcher.add('test-1')batcher.add('test-2')batcher.add('test-3')batcher.batch()batcher.get_values()>> {'test-1':'test-value-1', 'test-2':'test-value-2', 'test-3' : None}##### #3 Batching Context Manager:batcher = cacher.create_batcher()with batcher:#expensive_function is a pycacher-decorated function.expensive_function.register(1, 2)expensive_function.register(1, 3)#batches the cache key of both those 2 function register calls.batcher.batch()with batcher:expensive_function(1, 2) #will get its value directly from the batched valueexpensive_function(1, 3)You can see more advanced examples on the [documentation](http://pycacher.readthedocs.org).###Prerequisites`pycacher` is currently well tested on Python 2.5, 2.6 and 2.7.###Run unit testsIf you have the `nose` Python unit tester library installed and want to run the unit test suite for this library, then simply run this command:nosetests###Travis CIYou can track the project's CI status on Travis at : [http://travis-ci.org/#!/garindra/pycacher](http://travis-ci.org/#!/garindra/pycacher)###LicenseMIT 2.0###Authors:- Garindra Prahandono (garindraprahandono@gmail.com)
Package: pycachera
PyCacheraA powerful python decorator to cache functionsInstallationIn command line:pip install pycacheraUsageImport the pycachera as:from pycachera import cacheFor caching a function@cache()
def sum(a,b):
   return a+bFor caching a class attributes.class Math:
   def __init__(self):
       pass
   
   @cache()
   def sum(a,b):
      return a + bFor caching to a specific directory.@cache(cachefolder='/home/user/scratch')
def sum(a,b):
   return a+bFor caching with a specific key@cache(cachekey='This a custom cache')
def sum(a,b):
   return a+bFor printing the info@cache(verbose=True)
def sum(a,b):
   return a+bWhile debugging your script if you want to ignore the cached values you can recache@cache(recache=True)
def sum(a,b):
   return a+bWhen you use cache with a class attribute, and if you want to consider some attributes of that class for caching,class Math:
   def __init__(self,c):
       self.c = c
   
   @cache(extrarg=['c'])
   def sum(a,b):
      return a + bTo cache a class property,class math:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    
    @property
    @cache(extrarg=['a','b'],verbose=True)
    def add(self):
        return self.a + self.bWhen using mpi4py.MPI,@cache(with_mpi=True)
def sum(a,b):
   return a+bAPIvisitpycachera.readthedocs.io
Package: pycaches
A bunch of caches.Features✓ Ease of usecachedecorator✓ Support for non-Hashablekeys (dictionaries, lists, sets)✓ Different cache replacement policies (random, LRU)✓ Time-based item expiration□ Cache hit/miss statistics□ Rich configuration, sane defaults□ Optional persistencyInstallationRecommended way is to usepoetry:poetryinstallpycachesBut you also can install library with pip:pipinstallpycachesUsagecachedecoratorfrompycachesimportcache@cache()defexample():print("Hi, I will be called once!")example()# Prints "Hi, I will be called once!"example()# Is not calledimporttimefrompycachesimportcache@cache()deflong_computation(x):print("Performing long computation...")time.sleep(1)returnx+1long_computation(5)# Sleeps for 1 second and returns 6long_computation(5)# Immediately returns 6long_computation(6)# Sleeps for 1 second and returns 7long_computation(6)# Immediately returns 7long_computation(6)# And againCacheclassimporttimefromdatetimeimporttimedeltafrompycachesimportCachecache=Cache()cache.save("a",1)cache.save("b",2)cache.save("c",3,expire_in=timedelta(seconds=10))cache.has("c")# returns Truecache.get("a")# returns 1time.sleep(10)cache.has("c")# Falsecache.get("c")# raises KeyErrorDifferent cache replacement policiesfrompycachesimportCachefrompycaches.policiesimportLRU"""LRU stands for Least Recently Used.So LRU policy removes Least Recently Used item from cacheif it's size exceed max_items."""cache=Cache(max_items=2,replacement_policy=LRU())cache.save("a",1)cache.save("b",2)cache.save("c",3)cache.has("a")# returns Falsecache.has("b")# returns Truecache.save("d",4)cache.has("b")# returns FalseDisabledeepcopyfor keysfrompycachesimportcache"""Cache class and cache decorator accepts `copy_keys` argument.If you can garantee that keys will not change even if they are mutable,you may set it to `True` to speed things up."""@cache(copy_keys=False)deffaster_caching(x):returnxfaster_caching({1,2,3})# returns {1, 2, 3}ContributionJust clone repository, make your changes and create a pull request.Do not forget to make sure code quality is high: run linters, typecheckers, check code coverage, etc. You can do it all withmake:make lint:pylintandpycodestylemake typecheck:mypymake test:pytestmake coverage:pytestwithpytest-covmake quality:radonmake build:setup.pyAnd justmakeormake allto run all these targets.
Package: py-cachify
Py-Cachifypy-cachify is a library that provides small but useful cache utilities.Some parts were heavily inspired bydouglasfarinelli's python-cachelocklib,
which is sadly no longer maintained.py-cachify works well in both sync and async environments, has 100% test coverage,
is backend agnostic (you can provide your own client as long as it matches the signature), and supports Python from 3.8 and upward.It offers cache-based locks and decorators for securing function executions and storing their results in the cache.Table of ContentsDocumentationInstallationExamplesContributingLicenseDocumentationDetailed documentation can be found athttps://py-cachify.readthedocs.io/en/latest/.InstallationTo install:pipinstallpy-cachify# or if using poetrypoetryaddpy-cachifyExamplesTo start working with it, you'll have to initialize it usinginit_cachify:frompy_cachifyimportinit_cachifyinit_cachify()By default, it will use an in-memory cache.If you want to use Redis:frompy_cachifyimportinit_cachifyfromredis.asyncioimportfrom_urlasasync_from_urlfromredisimportfrom_urlinit_cachify(sync_client=from_url(redis_url),async_clien=async_from_url(async_redis_client))Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async.Once initialized you can use everything that the library provides straight up without being worried about managing the cache yourself.If you forgot to callinit_cachifytheCachifyInitErrorwill be raised during runtime.frompy_cachifyimportonce# Make sure there is just one copy of a function running at a time@once(key='long_running_function')asyncdeflong_running_function()->str:# Executing long-running operation...passFor more detailed documentation and examples please visithttps://py-cachify.readthedocs.io/en/latest/.ContributingIf you'd like to contribute, please first discuss the changes using Issues, and then don't hesitate to shoot a PR which will be reviewed shortly.LicenseThis project is licensed under the MIT License - see theLICENSEfile for details.
Package: pycachu
A tool to provide a LRU cache on files.It has been created to store gigabytes of Thumbor thumbnails on a DigitalOcean server.Usagefrom pycachu import Pycachu

# Initialize the cache
# The dir has to exist
p = Pycachu('/storage/pycachu', 20 * (1024 ** 3))

# Get a file
f = p.get('/some/file')

if f is not None:
    yield f
    f.close()
else:
    content = generate_file_content()
    p.put('/some/file', content)
    content.seek(0)
    yield content
    content.close()PerformanceThe performance is not exceptional, but operations basically take a constant time independently of
the number of files in the cache, which is not too bad.Rough benchmarking gave about 170 get per second.
Package: pycachuser
PycachuAn interactive cache that saves user-submitted credentials and tokens in a yaml file, and passwords in the OS keychain using the keyring moduleInstallpip install pycachuserGetting StartedOnce you have imported the module:import pycachuYou can create a cache. This should always be the first step.cache = pycachu.Cache("file_name")This will create a yaml file with the specified name. The file will be created at your current directory location by default, but you can specify a path also:cache = pycachu.Cache("file_name", path="~/")NOTE: The trialing / is not added for you,make sure to include it on the path.Getting a tokenWhen you wish to grab a token, just use the following:token = cache.get_token("key")The token will be requested by the user at runtime then saved to the cache yaml file. On running a second time, the token will be grabbed directly from the cache with no user input.This creates a Token object. You can grab the token with .tokenprint(token.token)You can specify your own terminal output for the user, and hide the user input:token = pycachu.Token(cache, "key", user_prompt="Submit the token: ", hide_input=True)All kwargs to the Token initiator are carried in Cache.get_token(). This is just a demonstration of the other (more convoluted) method for creating a Token.Getting a credentialWhen you wish to grab a credential, just use the following:credential = cache.get_credential("key")The user will then be asked for the username and password, if already not saved in the cache. The password will be stored in the OS keychain using Keyring.This creates a Credential object. You can grab the credentials with .username and .password.print(credential.username, credential.password)You can specify your own terminal output for the name and password, and hide the username input (the password input is hidden by default):credential = pycachu.Credential(
    cache,
    "key",
    username_prompt="Submit the username: ",
    password_prompt="And now the password: ",
    hide_username=True,
    hide_password=False,
)All kwargs to the Credential initiator are carried in Cache.get_credential(). This is just a demonstration of the other (more convoluted) method for creating a Credential.Oh no! My token/credential didn't workRaise a cache error to remove the cache object from the cachetoken1.error()
raise pycachu.CacheTokenError(token2)

credential1.error()
raise pycachu.CacheCredentialError(credential2)This will raise an exception and also remove the token/credential from the cache to be re-entered on next runtime.If you don't want to raise an Exception, both object have a remove() function:token.remove()
credential.remove()ValidatorsValidators are also imported, these are used to match the input to a set regular expression. By default all inputs use thepycachu.validators.NotEmpty()but you can specify any of the other validators, or create your own Validator class.
Package: pycactus
CactusAdapter to run an Azure Function Application with a WSGI Web Server.How it worksGiven the path of a folder containing a Function App, it builds a WSGI App parsing the Function settings. The app simply calls the Function main according to the route/methods settings.Supported FunctionThis software is meant to support only Function which use binding httpTrigger as input and http as output. No other binding types. This is not an Azure emulator.Function App structureV1FunctionApp
|-- host.json
|-- function_1
|	|-- function.json
|	|-- __init__.py
|-- function_2
|	|-- function.json
|	|-- __init__.pyV2FunctionApp
|-- host.json
|-- local.settings.json
|-- function_app.pyInstallingpip install pycactus
pip install pycactus[flask] # to use Flask as web frameworkHow to runCreate a file "wsgi.py"from cactus.appfactory import build_app
app = build_app("YourFunctionAppFolder")Or, to use Flask as web framework:from cactus.flask import build_app
app = build_app("YourFunctionAppFolder")Or, for V2 projects:from cactus.flask import build_app_v2
app = build_app_v2("YourFunctionAppFolder")Run it with a WSGI Web Servergunicorn wsgi:app
uwsgi --http localhost:7071 --module wsgi:appCheckout theexamplesfor more.Using Flask blueprintsfrom cactus.flask import build_blueprint
from cactus.route_info import parse_project

app = flask.Flask(__name__)
b = build_blueprint("myfunctionapp", parse_project("/path"))
app.register_blueprint(b)Or, for V2 projects:from cactus.flask import build_blueprint
from cactus.route_info import parse_project_v2

app = flask.Flask(__name__)
b = build_blueprint("myfunctionapp", parse_project_v2("/path"))
app.register_blueprint(b)TestingThis module is tested usingFirWSGI client.# Create a virtual environment 
python3 -m venv venv
source venv/bin/activate
# Install requirements
pip install -r requirements -r test-requirements
# Run tests with coverage
python -m pytest tests --cov=cactus
Package: pycades
pycadesДанный проект создан для удобной установки pycades в свой проект, пока только для linux системpycades представляет собой расширение для Python3, которое реализует интерфейс, аналогичныйCAdESCOM.Источник расширенияGitHubpip install pycadesЕсли не установлены зависимости КриптоПро CSP, то библиотека начинает вести себя непредсказуемо и
некоторые методы перестают работать, для лучшей работы желательно установить все зависимостис оф сайтаили найти вгите /libs(можно ограничиться КриптоПро CSP,/libs/linux-amd64_debчерез install.sh)Официальная документацияПример использованияНесколько примеровбольше можно посмотреть в директории стестамиЗагрузка сертификата из фала:frompycadesimportpycadesif__name__=="__main__":withopen('./certs/Kornevoy-sertifikat-GUTS-2022.CER',"rb")asf:cert=pycades.Certificate()cert.Import(f.read())print(cert.IsValid().Result)Получение данных сертификата:frompycadesimportpycadesdeftest_get_info_method(cert):# Возвращает имя субъекта.assertcert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME)=='Минцифры России'# Возвращает имя издателя сертификата.assertcert.GetInfo(pycades.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME)=='Минцифры России'# Возвращает адрес электронной почты субъектаassertcert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)=='dit@digital.gov.ru'# Возвращает адрес электронной почты издателя сертификата.assertcert.GetInfo(pycades.CAPICOM_CERT_INFO_ISSUER_EMAIL_NAME)=='dit@digital.gov.ru'# Возвращает UPN субъекта сертификатаassertcert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_UPN)==''# Возвращает UPN издателя сертификатаassertcert.GetInfo(pycades.CAPICOM_CERT_INFO_ISSUER_UPN)==''# Возвращает DNS-имя субъекта сертификата. .assertcert.GetInfo(pycades.CAPICOM_CERT_INFO_SUBJECT_DNS_NAME)=='Минцифры России'# Возвращает DNS-имя издателя сертификата.assertcert.GetInfo(pycades.CAPICOM_CERT_INFO_ISSUER_DNS_NAME)=='Минцифры России'deftest_get_base_info(cert):# Дата, с которой сертификат действителен.assertcert.ValidFromDate=='08.01.2022 13:32:39'# Дата, до которой сертификат действителенassertcert.ValidToDate=='08.01.2040 13:32:39'# Серийный номер.assertcert.SerialNumber=='00951FA3477C61043AADFA858627823442'name=('CN=Минцифры России, ИНН ЮЛ=7710474375, ОГРН=1047702026701, O=Минцифры ''России, STREET="Пресненская набережная, дом 10, строение 2", L=г. Москва, ''S=77 Москва, C=RU, E=dit@digital.gov.ru')# Издатель сертификата.assertcert.IssuerName==name# Имя субъекта.assertcert.SubjectName==name# Отпечаток.assertcert.Thumbprint=='2F0CB09BE3550EF17EC4F29C90ABD18BFCAAD63A'# Версия сертификата.assertcert.Version==3
Package: pycad-medic
Welcome to PYCAD, a comprehensive library designed to simplify and streamline medical imaging tasks. From data preprocessing to advanced visualization, PYCAD empowers professionals, researchers, and enthusiasts to harness the power of modern algorithms and techniques with ease.InstallationClone the repository:pipinstallpycad-medicFor more installation instructions, please seethis.Features & UsageImage File Conversion: Between NIFTI and DICOM formats.Visualization: Upcoming feature to visualize medical imaging data.Data Preprocessing: Including data splitting and annotation conversion.Dataset Creation: Configurations for YOLOv8.For detailed usage and examples, refer to thetutorialsdirectory anddocumentation.What is New?The latest release contains some new exciting features, if you want to know more about the new features you can read therelease features documentation.Contributions & SupportWe value contributions from the community! If you find a bug, want to propose a feature, or simply have a question, feel free to open an issue on our GitHub repository.For deeper insights and support, consider booking apremium sessionwith us.LicensePYCADis licensed under the MIT License. See theLICENSEfile for more details.Connect with UsStay updated with our latest advancements:ðŸ“¹YouTubeðŸ“–BlogðŸ“§NewsletterðŸ’¼Premium SessionsContact & InquiriesFor business inquiries, please reach out to us at:ðŸ“§contact@pycad.coVisitor count
Package: pycaesarcipher
CaesarCipherPython library to encipher & decipher a string using one of the simplest Substitution ciphers - "Caesar's Cipher"In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondenceThis library contains an Encipher method and a Decipher method to encipher & decipher a string, respectively, using a shiftkey.INSTALLATION:python -m pip install pycaesarcipher==1.3 (or) python -m pip install pycaesarcipher==1.4ALGORITHM :Import the moduleCreate an instance of the classcall the function "encipher" or "decipher" as an object along with the instance of the classUSAGE :import pycaesarcipher
variable_name = pycaesarcipher.pycaesarcipher() <br>
new_variable = variable_name.caesar_encipher("string",shiftkey) <br>
another_variable = variable_name.caesar_decipher(new_variable,shiftkey) <br>
print(new_variable) <br>EXAMPLE PROGRAM:import pycaesarcipher
word = pycaesarcipher.pycaesarcipher()
new = word.caesar_encipher("i love python",12)
word2 = word.caesar_decipher("u xahq bkftaz",12)
print(new," is the enciphered text.\n")
print(word2," is the deciphered text.")
Package: pycafee
pycafeePyCafeeis a Python library developed to help scientists evaluate their experimental data. We use Python's main scientific libraries, such as Numpy, SciPy, matplotlib, Statsmodel, Pandas, among others, as a motor to power the experimental data analysis, adding features that helps researchers make better conclusions. So, get a cup of coffee |cup_coffee| (or tea, or chocolate, or chimarrão, or any other beverage that makes you feel comfy) and let's understand your data!This project is under active development.
Package: pycaged
pycagedEste é um módulo para extrair relatórios a partir dos microdados do CAGED. Consolidando os dados do CAGED antigo com o novo. (As ressalvas metodológicas do Ministério da Economia devem ser consideradas)InstalaçãoInstale no prompt de comando (Windows) com o comando:pipinstallpycagedUso no pythonimportpycaged#Ano (int), mes(str), uf(int, código ibge da UF)pycaged.SubclasseMunicipios(ano,mes,uf)#<---- Nível mais desagregado"Retorna o dataframe com dados CAGED dos municípios da UF selecionada a nível Subclasse de classificação de emprego (CNAE 2.0)"#Ano (int), mes(str), uf(int, código ibge da UF)pycaged.ClasseMunicipios(ano,mes,uf)"Retorna o dataframe com dados CAGED dos municípios da UF selecionada a nível de Classe de classificação de emprego (CNAE 2.0)"#Ano (int), mes(str), uf(int, código ibge da UF)pycaged.SecaoMunicipios(ano,mes,uf)#<----- Nível menos agregado"Retorna o dataframe com dados CAGED dos municípios da UF selecionada a nível de Seção de classificação de emprego (CNAE 2.0)"ContributingContribuições serão bem-vindas.LicençaMITExtraindo bases de dados completas## Extração de dados completos
É possível fazer uma iteração com os dados completos dos municípios de um estado desde 2015:
 ESTE PROCESSO PODE LEVAR ENTRE 40 E 100 MINUTOS
        __________________________________________
 
 ```python
 #Exemplo : Criando uma tabela para uma sequência de anos
CAGEDMun = pd.DataFrame(columns = [], index = None)
mes = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]
ano = 2015

#Iteração para os anos e meses (usamos Alagoas, 27, como exemplo)
while ano < 2022:
    for i in mes:
        data = pycaged.SecaoMunicipios(ano, i, 27)
    
#Consolidando dados na tabela final
        CAGEDMun = CAGEDMun.append(data, ignore_index = True)
    ano += 1
    
CAGEDMun.to_csv('CAGEDMun.csv', encoding = 'iso-8859-1')Dicionário de Dados:Admitidos/Desligados: Contratação (1), Demissão(2)Sexo: Masculino (1), Feminino (2)Classificação de Setores CNAE 2.0:https://docs.google.com/spreadsheets/d/1bMFKpREb4YlW2ZzW1WVLdMN59ol-iLw5/export?format=xlsxCódigos IBGE por Estado:https://www.oobj.com.br/bc/article/quais-os-c%C3%B3digos-de-cada-uf-no-brasil-465.html