Saravanan666/pypi-org huggingface dataset:
Package: simple-mock
simple_mockIntroductionThe motivation behind this library is to provide easy way of mocking to python functions while doing the unittest.This library is based on "mock" module in pythonInstallationInstall viapip:$ pip install simple_mockInstall from source:$ git clone https://github.com/satyavls/simple_mock.git
$ cd simple_mock
$ python setup.py installUsage# example - mocking single function to return some value or exceptionimportunittestfromsimple_mockimportSimpleMock# import of function that needs to be patch in test case filefromadd_moduleimportadd_numclassTestAddNum(unittest.TestCase):defsetUp(self):# create simple mock objectself.simple_mock=SimpleMock()deftearDown(self):self.simple_mock.clear_all_patch()deftest_add_num(self):"""This is example where add_num function is patched to return the 45 value"""# patch the add_num function to return 45 valuepatched_add_func=self.simple_mock.patch_func(func='add_num',exptd_ret_val=45)self.assertEqual(add_num(2,2),45)deftest_add_num_exception(self):"""This is exmaple where add_num function is patched to return exception"""# Patch the add_num function to return ValueErrorpatched_add_func=self.simple_mock.patch_func(func='add_num',exptd_err=ValueError,err_msg="exception raise in add_num")self.assertRaises(ValueError,add_num)if__name__=='__main__':unittest.main()Referherefor more detailed examplesContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests or examples are appropriate.LicenseMIT
Package: simple-model-logging
based Django 2.x to logging model instances update## Installation`pip install simple-model-logging`Add `simple-model-logging` to your `INSTALLED_APPS`.## Usage#### Low-level usefrom datetime import datetimefrom django.db import modelsfrom .simple_model_logging import SystemUserLogMixinclass AbstractModel(models.Model):"""base model"""STATUS_TYPE = (('1', 'NORMAL'),('2', 'DELETE'),('3', 'DISABLE'))create_time = models.DateTimeField('create_time', default=datetime.now)update_time = models.DateTimeField('update_time', default=datetime.now)update_time = models.DateTimeField('update_time', default=None, null=True, blank=True)data_status = models.CharField('data_status', max_length=1, choices=STATUS_TYPE, default='1')def delete(self, using=None, keep_parents=False):# logging deleteSystemUserLogMixin.log_delete(self)# override delete methodself.delete_time = datetime.now()self.data_status = '2'self.save()def save(self, *args, **kw):log = SystemUserLogMixin()is_insert = Falseif self.id:# updateprint('update model')# logging updatelog.log_update(model=self)else:# insert# set insert signalis_insert = Trueprint('insert model')super(AbstractModel, self).save(*args, **kw)if is_insert:# logging insert# this code can get the record idlog.log_create(model=self)def create(self, *args, **kw):log = SystemUserLogMixin()super(AbstractModel, self).create(*args, **kw)log.log_create(model=self)class Meta:abstract = Trueclass Person(AbstractModel):"""bussiness model extends from AbstractModel.when invoke the model's save(),create(),delete() method will do logging"""pass
Package: simplemonads
simplemonadsLet's make monads easy, fun, and productive.Platform supportJustpip install simplemonadsand you're done. You can also downloadthis single fileinto your project and use it as you wish without dependencies. Works across all platforms, so CPython >= 3.5 (Windows, Linux, Mac, Android, iOS), in asingle standalone htmlfile, multiple files in the browser withdynamic loading, andeven on microcontrollers with micropython.DocsRead the docs here.Example GUI using monads:Success,Failure,Just,Reader, andPrinterimportsimplemonadsassmtry:classDeps(sm.Protocol):"Dependencies for your application"defpopup(self,msg:str)->None:"Display a popup with the specified message."except:pass@sm.runclassTestReader:@classmethoddefmake(cls,create:"sm.Callable[[],sm.Any]")->"sm.Callable[[],Deps]":gui=create()classGuiDeps:defpopup(self,x:str):gui.Popup(x)returnGuiDeps@classmethoddefapp(cls,divide_by_zero:bool=False)->sm.Reader:data=sm.Success(sm.Just(7))double=lambdax:x+(lambday:y*2)triple=lambdax:x+(lambday:y*3)result=data+triple+doubleifdivide_by_zero:result+=lambdax:x+(lambdax:x/0)defeffect(deps:"Deps")->"sm.Monad":msg="Answer to the Universe: "err="Whoops, an error happened: "result|{sm.Success:lambdax:x|{sm.Just:lambdaval:deps.popup(msg+str(val))},sm.Failure:lambdax:deps.popup(err+x),}returnresultreturnsm.Reader(effect)@classmethoddefmain(cls):gui=sm.Success()+(lambdax:__import__("PySimpleGUI"))|{sm.Success:lambdax:x,sm.Failure:lambdax:sm.Printer(),}returncls.app()+cls.make(lambda:gui)
Package: simple-money
A simple interface to work with money-related entities.InstallationThe current stable release:pip install simple_moneyor:easy_install simple_moneyor from source:$ sudo python setup.py installUsageArithmetic operations:>>>Money(100,'EUR')+Money(50,'EUR')150EUR>>>Money(100,'EUR')-Money(50,'EUR')50EUR>>>Money(100,'EUR')*2200EURAlso you can manipulate with money in different currencies:>>>Money(100,'EUR')+Money(50,'USD')100EUR,50USD>>>Money(100,'EUR')-Money(50,'USD')100EUR,-50USD>>>(Money(100,'EUR')-Money(50,'USD'))*2200EUR,-100USDWith multiply currencies you are able to get concrete currency value in the following way:>>>value=Money(100,'EUR')+Money(50,'USD')>>>value.EUR100EUR>>>value.USD50USD
Package: simplemonitor
SimpleMonitor is a Python script which monitors hosts and network connectivity. It is designed to be quick and easy to set up and lacks complex features that can make things like Nagios, OpenNMS and Zenoss overkill for a small business or home network. Remote monitor instances can send their results back to a central location.Requires Python >= 3.6.2.Documentation is here:https://jamesoff.github.io/simplemonitor/
Package: simplemosaic
simplemosaicGetting StartedInstallingpassUsagefrom...importConverter,Mosaic,load_imagesimportcv2ascvimage=Converter.load('default.jpeg')images=load_images('pics')mosaic=Mosaic(image,images,(70,70),ratio=3000).create()cv.imwrite("mosaic.jpg",mosaic)AuthorsJakub Szkodny-szjakub
Package: simplempi
A wrapper around mpi4py that offers simple scattering of iterable objects.This is useful for embarassingly parallel, SPMD, type tasks that simply need to work on a list of things.example usage:parfor_test.py# import the parfor function; note# that this will automatically initialize MPI# also import pprint for parallel-friendly printingfromsimplempi.parforimportparfor,pprint# define a list to loop overmy_list=list(range(10))# define a function that does something with each item in my_listdeffunc(i):returni**2# loop in parallel over my_listforiinparfor(my_list):result=func(i)pprint(f"{i}**2 ={result}")Running this with mpirun on 4 processors shows that the list of 10 numbers gets
scattered as evenly as possible across all 4 processors; it also shows that the order of evaluation in the for loop is not well-defined (which is okay for embarassingly parallel code like this):$mpirun-n4pythonparfor_test.py(rank1/4):0**2=0(rank1/4):4**2=16(rank1/4):8**2=64(rank3/4):2**2=4(rank3/4):6**2=36(rank4/4):3**2=9(rank4/4):7**2=49(rank2/4):1**2=1(rank2/4):5**2=25(rank2/4):9**2=81Alternatively, one can use the object-oriented interface:simpleMPI_test.pyimportsimpleMPI#Initialize MPIsmpi=simpleMPI.simpleMPI()#Make a list of things (20 numbers in this case)testList=range(20)#Scatter the list to all processors (myList differs among processes now)myList=smpi.scatterList(testList)#Print the list contents (as well as the rank of the printing process)smpi.pprint(myList)Running this with mpirun on 6 processors shows that the list of 20 numbers gets
scattered as evenly as possible across all 6 processors:$mpirun-n6pythonsimpleMPI_test.py(rank1/6):[0,6,12,18](rank2/6):[1,7,13,19](rank4/6):[3,9,15](rank6/6):[5,11,17](rank5/6):[4,10,16](rank3/6):[2,8,14]Installpython3 -m pip install simplempi
Package: simple-multiprocessing
simple_multiprocessingDescriptionExecute multiple async tasks (via multiprocessing.Process, or threading.Thread) as simple as possible.Installpipinstallsimple_multiprocessing# orpip3installsimple_multiprocessingUsagefromsimple_multiprocessingimportMultiThread,MultiProcess,Taskimportrandom,timedeftest_func(i:int)->float:print('started:',i)start=time.time()start/iifrandom.random()<0.5:whileTrue:time.sleep(0.01)res=time.time()-startreturnrestasks=[Task(test_func,i)foriinrange(5)]# via threadingresults_via_threading=MultiThread(tasks).solve(timeout=1)fori,rinenumerate(results_via_threading):print(i,type(r),r)# via Multiproccessresults_via_multiprocess=MultiProcess(tasks).solve(timeout=1)fori,rinenumerate(results_via_multiprocess):print(i,type(r),r)Dependenciesnoraise,stopit
Package: simple-music-tools
Simple Music Tools (SMT)Simple Music Tools (SMT) is a collection of simple tools for music analysis, built with Python.InstallationClone this repository to your local machine and install with pip:gitclonehttps://github.com/yyygggg2/smt.gitcdsmt
pipinstallsmtUsageHere is an example of how to use SMT:fromsmtimportintervals# Calculate the top note from a given note and intervalresult=intervals.get_top_note('c','major third')print(result)# Prints: 'e'ContributingWe appreciate and welcome any contributions! Please fork the repository and create a Pull Request with your changes.LicenseThis project is licensed under the terms of the Apache 2.0 license.
Package: simplemysql
An ultra simplistic wrapper for Python MySQLdb with very basic functionalityhttp://nadh.in/code/simplemysqlLicense: GPL v2Installationpip install simplemysqlUsagefrom simplemysql import SimpleMysql

db = SimpleMysql(
                host="localhost",
                db="mydatabase",
                user="username",
                passwd="password"
)

# insert a record to the *books* table
db.insert("books", {"type": "paperback", "name": "Time Machine", "price": 5.55, year: "1997"})

book = db.getOne("books", ["name"], ["year = 1997"])

print "The book's name is " + book.nameQuery methodsinsert(), update(), delete(), getOne(), getAll(), query()insert(table, record{})Inserts a single record into a table.db.insert("food", {"type": "fruit", "name": "Apple", "color": "red"})
db.insert("books", {"type": "paperback", "name": "Time Machine", "price": 5.55})update(table, row{}, condition[])Update one more or rows based on a condition (or no condition).# update all rows
db.update("books", {"discount": 0})

# update rows based on a simple hardcoded condition
db.update("books",
        {"discount": 10},
        ["id=1"]
)

# update rows based on a parametrized condition
db.update("books",
        {"discount": 10},
        ("id=%s AND year=%s", [id, year])
)insertOrUpdate(table, row{}, key)Insert a new row, or update if there is a primary key conflict.# insert a book with id 123. if it already exists, update values
db.insert("books",
                {"id": 123, type": "paperback", "name": "Time Machine", "price": 5.55},
                "id"
)getOne(table, fields[], condition[], order[], limit[])getAll(table, fields[], condition[], order[], limit[])Get a single record or multiple records from a table given a condition (or no condition). The resultant rows are returned as namedtuples. getOne() returns a single namedtuple, and getAll() returns a list of namedtuples.book = db.getOne("books", ["id", "name"])

# get a row based on a simple hardcoded condition
book = db.getOne("books", ["name", "year"], ("id=1"))

# get a row based on a simple hardcoded condition
book = db.getOne("books", ["name", "year"], ("id=1"))

# get multiple rows based on a parametrized condition
books = db.getAll("books",
        ["id", "name"],
        ("year > %s and price < 15", [year, 12.99])
)

# get multiple rows based on a parametrized condition with an order and limit specified
books = db.getAll("books",
        ["id", "name", "year"],
        ("year > %s and price < 15", [year, 12.99]),
        ["year", "DESC"],       # ORDER BY year DESC
        [0, 10]                 # LIMIT 0, 10
)lastId()Get the last insert iddelete(table, fields[], condition[], order[], limit[])Delete one or more records based on a condition (or no condition)# delete all rows
db.delete("books")

# delete rows based on a condition
db.delete("books", ("price > %s AND year < %s", [25, 1999]))query(table)Run a raw SQL query. The MySQLdb cursor is returned.db.query("DELETE FROM books WHERE year > 2005")
Package: simple-namespace
What is this?This is a very simple python tool for creating namespaces. It tries to solve the problem that there isno elegant way to create singleton classesor nested namespaces in python.How do I use this?pip install simple_namespacefromsimple_namespaceimportnamespace@namespacedefMyNamespace():my_value=10defmy_function(arg1):return99returnlocals()# prints 10print(MyNamespace.my_value)
Package: simpleNDB
simpleNDBPurposeProvides a set of wrappers for the Google Cloud Python clients to be used on Python 3 App Engine Standard Edition instances to provide some of the abilities previously provided by the appengine api and ext libraries.Installation$pipinstallsimpleNDBThe full package can be imported as follows:fromsimplendbimportndb,images,usersTo use the individual components, see :NDBUsersImagesBackground and ConceptsI needed to migrate some simple applications running on the  Google Appengine Standard Edition Python 2 version to the Python 3 version.This is a major change to the runtime environment - involving a complete change to the webserver and python run time environments. It also sunsets a number of very usefull APIs that made it very quick and easy to run up a simple web app or web site for groups, for demonstrations and for prototypes :including:NDB- A simple NoSQL Network Database built on Cloud Datastore. Quick and easy to set up a schema.Users- A simple, no setup way to authenticate users against their Google id and get the details. Allows you to create authenticated apps without effort.Blobstore- a handy and simple way of storeing blobs and images.Images- an inbuilt image handler optimised for the environment. Included the native __get_serving_url function that it loosk like will not be resurected :angry:There are, of course, ways to do the same thinsg in the new environment, since all that has gone away is effectively middle ware. Google recommend the following:TheGoogle Cloud Python Clientsto access the datastore databaseTheFirebase Auth APIUsingPillowfor imagesThis is all actually very good, but as one commentor said :this requires the developer to create a lot of boilerplate that the appengine API used to do for usThis library is an attempt to do the boilerplate and make these libraries more of a drop-in replacement for the old libraries. I am not attempting to do afulldrop-in replacement - there are attempts to do this for NDB for instanceseebut that looks like it will take 10 months and I needed somthing in 2 days. Thatsomethingis this library. Quick and not very clean but good for the sort of simple apps that AppEngine SE should be good for.It basically allows developers to migrate basic current apps to use the Google Cloud Clients without completely restructuring the app. There will be some format and type changes and if you want advanced capabilities (like transactions and async operations) you should probable wait for the library linked above or do a proper migration of your app.
Package: simplenet
SimpleNetmaster:A simple neural network in PythonFree software: MITDocumentation:https://simplenet-nn.readthedocs.ioFeaturesSimple interfaceMinimal dependencies (numpy)Runs on Pythonista on iOSAttempts to verify accuracy by comparing results with popular frameworks
Keras and TensorflowIntroductionThis is a simple multilayer perceptron that I decided to build as I learned a
little bit about machine learning and neural networks. It doesn't have many
features.DependenciesPython >= 3.8numpyQuickstartpip3 install simplenetSeeexamples/Development SetupClone the repo:git clone https://github.com/n8henrie/simplenet && cd simplenetMake a virtualenv:python3 -m venv venvsource venv/bin/activatepip install -e .[dev]AcknowledgementsAndrew Ng's Coursera coursesTODOI don't really know any Latex, so if anybody wants to help me fill out some of
the other docstrings with pretty equations, feel free. I'm also not a
mathematician, so if anything doesn't seem quite right, feel free to speak up.Troubleshooting / FAQHow can I install an older / specific version of SimpleNet?Install from a tag:pip install git+git://github.com/n8henrie/simplenet.git@v0.1.0Install from a specific commit:pip install git+git://github.com/n8henrie/simplenet.git@aabc123def456ghi789Changelog0.1.4 :: 20220-06-19Fix README error, version bump for pypi0.1.3 :: 20220-06-19Update dependencies and tests to run on modern python and tensorflowDeprecate python3.5-3.7 due to numpy dependencyUse GitHub Actions instead of TravisAdd an experimental Dockerfile for reproducibility with tests0.1.2 :: 2017-12-12Update initialization (now uses something like Xavier)0.1.0 :: 2017-11-02First release on PyPI / GitHub.
Package: simple-neural
SimpleNNSimpleNN is a simplified framework for building and training neural networks models. Framework is build on modularity and flexibility to enable easy adoption and feature expansions.Currently SimpleNN only supports sequential models. Only sequential execution graphs are supported. This means that the following operations are not supported:Concatenations of any kind (Residual gates or multiple inputs)Addition/Multiplications of layersLoops (RNNs)Originally built as a learning excercise.For complete examples check the /examples directory.Getting StartedInstallpipinstallsimple-neural# Multi class classificationFEATURES=5N_CLASSES=3classDemoNetwork(Network):def__init__(self,*args,**kwargs):super().__init__(*args,**kwargs)self.l1=Dense(FEATURES,64,W_l2=1e-3,b_l2=1e-3)self.activation1=ReLu()self.l2=Dense(32,N_CLASSES)self.output=SoftMaxLoss(loss=CategoricalCrossEntropy())defforward(self,x,targets):# define forward passx=self.l1(x)x=self.activation1(x)x=self.l2(x)returnself.output(x,targets)optimizer=Adam(lr=0.03,decay=5e-7,b1=0.9,b2=0.999)acc=Accuracy()model=DemoNetwork(optimizer=optimizer)model.fit(X,y,epochs=1000,metrics=[acc])Saving/Loading NetworkfromsimplennimportNetwork# serializemodel.save('simplemodel.pkl')# deserializem2=Network.load('simplemodel.pkl')yhat=m2.predict(X)FeaturesLayersDense : simplenn.layers.DenseDropout : simplenn.layers.DropoutActivationsReLu : simplenn.activation.ReLuSigmoid : simplenn.activation.SigmoidSoftMax : simplenn.activation.SoftMaxLinear : simplenn.activation.LinearLossesBinary cross entropy : simplenn.metrics.loss.BinaryCrossEntropyCategorical cross entropy : simplenn.metrics.loss.CategoricalCrossEntropyMean absolute error : simplenn.metrics.loss.MeanAbsoluteErrorMean squared error : simplenn.metrics.loss.MeanSquaredErrorOptimizersStochastic Gradient Descent : simplenn.optimizers.SGDAdaptive Gradient : simplenn.optimizers.AdaGradRoot Mean Squared Propagation : simplenn.optimizers.RMSPropAdaptive Moment Estimation : simplenn.optimizers.AdamMetricsAccuracy : simplenn.metrics.AccuracyMean absolute error : simplenn.metrics.loss.MeanAbsoluteErrorMean squared error : simplenn.metrics.loss.MeanSquaredErrorArea under the curve - receiver operating characteristic : simplenn.metrics.AucROCArea under the curve - precision recall curve : simplenn.metrics.AucPRCTPR (Recall) : simplenn.metrics.TPRFPR : simplenn.metrics.FPR
Package: simplenlg
pySimpleNLGA python port of SimpleNLGThis project is a direct port of the java codeSimpleNLG v4.4.8 (released on Apr 10, 2016)to python.  The port replicates (almost) all the classes and methods in the java API identically.Documentation and UsageThe original project has a wiki tutorial and numerous examples on how to use the code.  Since the API remains same, all of those examples are still valid and provide a great place to start.  In addition, the test directory here has a large number of test cases you can use as examples.The original java code has excellent javadoc documentation availablehere.  Simply download a local copy and openindex.htmlin your browser to view.  The code comments were not ported into python so please use the original documentation.Compatibility and SetupThe project is compatible with python version 3.4+.  It will not work with python v2.x due to a few 3.x specific classes such asEnum.  The code was built and tested under Ubuntu but should be compatible with Mac or Windows.You don't need to install any additional libraries to run the code or execute the unit tests.To install the code with pip do..pip3 install simplenlgCode StatusA few less commonly used components have been omitted.  These include:Sentence "aggregation" componentsThe "xmlrealiser"(s)The java serverThe NIHDBLexicon and MultipleLexicon classesAll implemented components are fully functional.  The original project included about 175 unit-tests, all of which have been ported and pass in python.The java code for SimpleNLG is not really that simple.  It has large if/else statements, regex and other complexities that presented a number of opportunities for errors to creep in during the port.  If you find a bug and are willing to fix it please do the following...Verify the correct behavior in the original java code.Identify the required python code changes needed to fix the issue so the behavior is the same as in java.Write a unit test under tests/misc to cover the changes.Use the provided script to run all unit tests and verify there is no adverse impact to other portions of the code.Submit a Pull Request (PR) here to merge the changes into the main codebase.
Package: simplenlopt
OverviewA simple, SciPy like interface for the excellent nonlinear optimization libraryNLoptto make switching between SciPy and NLopt a piece of cake. SimpleNLopt's functions can act as a drop-in replacement for SciPy functions. Major differences compared to plain NLopt:SciPy like minimize(method='NLopt algorithm') API for NLopt's local optimizersAutomatic numerical approximation of the gradient if analytical gradient is not availableAutomatic handling of constraints via the augmented lagrangian method without boilerplate codeScipy like interfaces to NLopt's global optimizers with hard stopping criteriaSciPy like curve fitting using NLopt's algorithmsDocumentationRefer to the onlinedocumentationfor detailed description of the API and examplesInstallationpipinstallsimplenloptExample: Minimizing the Rosenbrock function in simplenlopt and scipyimportsimplenloptfromscipy.optimizeimportrosen,rosen_derimportscipyimportnumpyasnpx0=np.array([0.5,1.8])res=simplenlopt.minimize(rosen,x0,jac=rosen_der)print("Found optimum: ",res.x)res_scipy=scipy.optimize.minimize(rosen,x0,jac=rosen_der)print("Found optimum: ",res_scipy.x)
Package: simplenlp
This package accomplishes many basic NLP tasks without dependencies on NLTK or parsers, for use in projects such as ConceptNet.Japanese support requires MeCab, a third-party library. More complete analysis is possible if you also install Cabocha and use the language ‘ja_cabocha’, though many applications will not need it. For installation instructions, seehttps://github.com/commonsense/simplenlp/raw/master/simplenlp/ja_cabocha/README.txt. If you don’t need Cabocha, you only need to install the first two (MeCab and IpaDic).Authors: Rob Speer, Kenneth Arnold, and Tyson Roberts
Package: simple-nlp-library
simple_nlp_librarySimple NLP libraryusageinstallationpython3 -m pip install --upgrade simple_nlp_libraryapisemantic_tokensstop_words=preprocessing.stop_words()preprocessing.semantic_tokens(stop_words,"The quick brown fox jumps over the lazy dog")cosine_similaritymetrics.cosine_similarity([1.0,1.0,1.0],[4.0,4.0,4.0])inserting_distancemetrics.inserting_distance("simple","simpler")inserting_similaritymetrics.inserting_similarity("simple","simpler")jaccard_similaritymetrics.jaccard_similarity([1,2,3],[1,2,3,4])embeddingsvectors=embeddings.vectors()vector=vectors["facebook"]sentence similarityvectors=embeddings.vectors()stop_words=preprocessing.stop_words()metrics.cosine_similarity(embeddings.tokens_vector(vectors,preprocessing.semantic_tokens(stop_words,"the slow brown bear jumped over the lazy dog")),embeddings.tokens_vector(vectors,preprocessing.semantic_tokens(stop_words,"the quick red fox jumped over the lazy cat")),)