qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
You could use [QueueHandler](http://docs.python.org/dev/library/logging.handlers.html#queuehandler) and [QueueListener](http://docs.python.org/dev/library/logging.handlers.html#queuelistener). Taken from the docs: > > Along with the QueueListener class, QueueHandler can be used to let > handlers do their work on a separate thread from the one which does > the logging. This is important in Web applications and also other > service applications where threads servicing clients need to respond > as quickly as possible, while any potentially slow operations (such as > sending an email via SMTPHandler) are done on a separate thread. > > > Alas they are only available from Python 3.2 onward.
Most probably you need to write your own logging handler that would do the sending of the email in the background.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
Here's the implementation I'm using, which I based on [this Gmail adapted SMTPHandler](http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt). I took the part that sends to SMTP and placed it in a different thread. ``` import logging.handlers import smtplib from threading import Thread def smtp_at_your_own_leasure(mailhost, port, username, password, fromaddr, toaddrs, msg): smtp = smtplib.SMTP(mailhost, port) if username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): try: import string # for tls add this line try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) thread = Thread(target=smtp_at_your_own_leasure, args=(self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg)) thread.start() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) ``` Usage example: ``` logger = logging.getLogger() gm = ThreadedTlsSMTPHandler(("smtp.gmail.com", 587), 'bugs@my_company.com', ['admin@my_company.com'], 'Error found!', ('my_company_account@gmail.com', 'top_secret_gmail_password')) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1/0 except: logger.exception('FFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUU-') ```
You could use [QueueHandler](http://docs.python.org/dev/library/logging.handlers.html#queuehandler) and [QueueListener](http://docs.python.org/dev/library/logging.handlers.html#queuelistener). Taken from the docs: > > Along with the QueueListener class, QueueHandler can be used to let > handlers do their work on a separate thread from the one which does > the logging. This is important in Web applications and also other > service applications where threads servicing clients need to respond > as quickly as possible, while any potentially slow operations (such as > sending an email via SMTPHandler) are done on a separate thread. > > > Alas they are only available from Python 3.2 onward.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
You could use [QueueHandler](http://docs.python.org/dev/library/logging.handlers.html#queuehandler) and [QueueListener](http://docs.python.org/dev/library/logging.handlers.html#queuelistener). Taken from the docs: > > Along with the QueueListener class, QueueHandler can be used to let > handlers do their work on a separate thread from the one which does > the logging. This is important in Web applications and also other > service applications where threads servicing clients need to respond > as quickly as possible, while any potentially slow operations (such as > sending an email via SMTPHandler) are done on a separate thread. > > > Alas they are only available from Python 3.2 onward.
As the OP [pointed out](https://stackoverflow.com/a/8616706/7952162), [QueueHandler](https://docs.python.org/dev/library/logging.handlers.html#queuehandler) and [QueueListener](http://docs.python.org/dev/library/logging.handlers.html#queuelistener) can do the trick! I did some research and adapted code found on [this page](https://docs.python.org/3/howto/logging-cookbook.html) to provide you with some sample code: ``` # In your init part, # assuming your logger is given by the "logger" variable # and your config is storded in the "config" dictionary logging_queue = Queue(-1) queue_handler = QueueHandler(logging_queue) queue_handler.setLevel(logging.ERROR) queue_handler.setFormatter(logging_formatter) logger.addHandler(queue_handler) smtp_handler = SMTPHandler(mailhost=(config['MAIL_SERVER'], config['MAIL_PORT']), fromaddr=config['MAIL_SENDER'], toaddrs=[config['ERROR_MAIL']], subject='Application error', credentials=(config['MAIL_USERNAME'], config['MAIL_PASSWORD']), secure=tuple()) smtp_handler.setLevel(logging.ERROR) smtp_handler.setFormatter(logging_formatter) queue_listener = QueueListener(logging_queue, smtp_handler) queue_listener.start() # Let's test it. The warning is not mailed, the error is. logger.warning('Test warning') logger.error('Test error') ``` What I am not sure about is whether it is necessary to use `setLevel` and `setFormatter` twice, probably not.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
The simplest form of asynchronous smtp handler for me is just to override `emit` method and use the original method in a new thread. GIL is not a problem in this case because there is an I/O call to SMTP server which releases GIL. The code is as follows ``` class ThreadedSMTPHandler(SMTPHandler): def emit(self, record): thread = Thread(target=SMTPHandler.emit, args=(self, record)) thread.start() ```
As the OP [pointed out](https://stackoverflow.com/a/8616706/7952162), [QueueHandler](https://docs.python.org/dev/library/logging.handlers.html#queuehandler) and [QueueListener](http://docs.python.org/dev/library/logging.handlers.html#queuelistener) can do the trick! I did some research and adapted code found on [this page](https://docs.python.org/3/howto/logging-cookbook.html) to provide you with some sample code: ``` # In your init part, # assuming your logger is given by the "logger" variable # and your config is storded in the "config" dictionary logging_queue = Queue(-1) queue_handler = QueueHandler(logging_queue) queue_handler.setLevel(logging.ERROR) queue_handler.setFormatter(logging_formatter) logger.addHandler(queue_handler) smtp_handler = SMTPHandler(mailhost=(config['MAIL_SERVER'], config['MAIL_PORT']), fromaddr=config['MAIL_SENDER'], toaddrs=[config['ERROR_MAIL']], subject='Application error', credentials=(config['MAIL_USERNAME'], config['MAIL_PASSWORD']), secure=tuple()) smtp_handler.setLevel(logging.ERROR) smtp_handler.setFormatter(logging_formatter) queue_listener = QueueListener(logging_queue, smtp_handler) queue_listener.start() # Let's test it. The warning is not mailed, the error is. logger.warning('Test warning') logger.error('Test error') ``` What I am not sure about is whether it is necessary to use `setLevel` and `setFormatter` twice, probably not.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
Here's the implementation I'm using, which I based on [this Gmail adapted SMTPHandler](http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt). I took the part that sends to SMTP and placed it in a different thread. ``` import logging.handlers import smtplib from threading import Thread def smtp_at_your_own_leasure(mailhost, port, username, password, fromaddr, toaddrs, msg): smtp = smtplib.SMTP(mailhost, port) if username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): try: import string # for tls add this line try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) thread = Thread(target=smtp_at_your_own_leasure, args=(self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg)) thread.start() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) ``` Usage example: ``` logger = logging.getLogger() gm = ThreadedTlsSMTPHandler(("smtp.gmail.com", 587), 'bugs@my_company.com', ['admin@my_company.com'], 'Error found!', ('my_company_account@gmail.com', 'top_secret_gmail_password')) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1/0 except: logger.exception('FFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUU-') ```
A thing to keep in mind when coding in Python is the GIL (Global Interpreter Lock). This lock prevents more than one process from happening at the same time. there are many number of things that are 'Blocking' activities in Python. They will stop everything until they completed. Currently the only way around the GIL is to either push off the action you are attempting to an outside source like aix and MattH are suggesting, or to implement your code using the multiprocessing module (http://docs.python.org/library/multiprocessing.html) so that one process is handling the sending of messages and the rest is being handled by the other process.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
The simplest form of asynchronous smtp handler for me is just to override `emit` method and use the original method in a new thread. GIL is not a problem in this case because there is an I/O call to SMTP server which releases GIL. The code is as follows ``` class ThreadedSMTPHandler(SMTPHandler): def emit(self, record): thread = Thread(target=SMTPHandler.emit, args=(self, record)) thread.start() ```
A thing to keep in mind when coding in Python is the GIL (Global Interpreter Lock). This lock prevents more than one process from happening at the same time. there are many number of things that are 'Blocking' activities in Python. They will stop everything until they completed. Currently the only way around the GIL is to either push off the action you are attempting to an outside source like aix and MattH are suggesting, or to implement your code using the multiprocessing module (http://docs.python.org/library/multiprocessing.html) so that one process is handling the sending of messages and the rest is being handled by the other process.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
You could use [QueueHandler](http://docs.python.org/dev/library/logging.handlers.html#queuehandler) and [QueueListener](http://docs.python.org/dev/library/logging.handlers.html#queuelistener). Taken from the docs: > > Along with the QueueListener class, QueueHandler can be used to let > handlers do their work on a separate thread from the one which does > the logging. This is important in Web applications and also other > service applications where threads servicing clients need to respond > as quickly as possible, while any potentially slow operations (such as > sending an email via SMTPHandler) are done on a separate thread. > > > Alas they are only available from Python 3.2 onward.
A thing to keep in mind when coding in Python is the GIL (Global Interpreter Lock). This lock prevents more than one process from happening at the same time. there are many number of things that are 'Blocking' activities in Python. They will stop everything until they completed. Currently the only way around the GIL is to either push off the action you are attempting to an outside source like aix and MattH are suggesting, or to implement your code using the multiprocessing module (http://docs.python.org/library/multiprocessing.html) so that one process is handling the sending of messages and the rest is being handled by the other process.
8,616,617
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'Hello Exception!',) gm.setLevel(logging.ERROR) logger.addHandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0 ``` It took more than 1sec to complete, blocking the python script for this whole time. How come? How can I make it not block the script?
2011/12/23
[ "https://Stackoverflow.com/questions/8616617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348545/" ]
Here's the implementation I'm using, which I based on [this Gmail adapted SMTPHandler](http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt). I took the part that sends to SMTP and placed it in a different thread. ``` import logging.handlers import smtplib from threading import Thread def smtp_at_your_own_leasure(mailhost, port, username, password, fromaddr, toaddrs, msg): smtp = smtplib.SMTP(mailhost, port) if username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): try: import string # for tls add this line try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) thread = Thread(target=smtp_at_your_own_leasure, args=(self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg)) thread.start() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) ``` Usage example: ``` logger = logging.getLogger() gm = ThreadedTlsSMTPHandler(("smtp.gmail.com", 587), 'bugs@my_company.com', ['admin@my_company.com'], 'Error found!', ('my_company_account@gmail.com', 'top_secret_gmail_password')) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1/0 except: logger.exception('FFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUU-') ```
Here's the implementation I'm using, which I based on Jonathan Livni code. ``` import logging.handlers import smtplib from threading import Thread # File with my configuration import credentials as cr host = cr.set_logSMTP["host"] port = cr.set_logSMTP["port"] user = cr.set_logSMTP["user"] pwd = cr.set_logSMTP["pwd"] to = cr.set_logSMTP["to"] def smtp_at_your_own_leasure( mailhost, port, username, password, fromaddr, toaddrs, msg ): smtp = smtplib.SMTP(mailhost, port) if username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): try: # import string # <<<CHANGE THIS>>> try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, ",".join(self.toaddrs), # <<<CHANGE THIS>>> self.getSubject(record), formatdate(), msg, ) thread = Thread( target=smtp_at_your_own_leasure, args=( self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg, ), ) thread.start() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) # Test if __name__ == "__main__": logger = logging.getLogger() gm = ThreadedTlsSMTPHandler((host, port), user, to, "Error!:", (user, pwd)) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1 / 0 except: logger.exception("Test ZeroDivisionError: division by zero") ```
10,647,045
When I try to use `ftp.delete()` from ftplib, it raises `error_perm`, resp: ``` >>> from ftplib import FTP >>> ftp = FTP("192.168.0.22") >>> ftp.login("user", "password") '230 Login successful.' >>> ftp.cwd("/Public/test/hello/will_i_be_deleted/") '250 Directory successfully changed.' >>> ftp.delete("/Public/test/hello/will_i_be_deleted/") ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ftplib.py", line 520, in delete resp = self.sendcmd('DELE ' + filename) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ftplib.py", line 243, in sendcmd return self.getresp() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ftplib.py", line 218, in getresp raise error_perm, resp ftplib.error_perm: 550 Delete operation failed. ``` The directory exists, and "user" has sufficient permissions to delete the folder. The site is actually a NAS (WD MyBookWorld) that supports ftp. Changing to parent directory and using command `ftp.delete("will_i_be_deleted")` does not work either. "will\_i\_be\_deleted" is an empty directory. ftp settings for WD MyBookWorld: ``` Service - Enable; Enable Anonymous - No; Port (Default 21) - Default ```
2012/05/18
[ "https://Stackoverflow.com/questions/10647045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402511/" ]
You need to use the `rmd` command, i.e `ftp.rmd("/Public/test/hello/will_i_be_deleted/")` `rmd` is for removing directories, `delete`is for removing files.
The only method that works for me is that I can rename with the ftp.rename() command: e.g. ``` ftp.mkd("/Public/Trash/") ftp.rename("/Public/test/hello/will_i_be_deleted","/Public/Trash/will_i_be_deleted") ``` and then to manually delete the contents of Trash from time to time. I do not know if this is an exclusive problem for the WD MyBookWorld ftp capabilities or not, but at least I got a workaround.
10,647,045
When I try to use `ftp.delete()` from ftplib, it raises `error_perm`, resp: ``` >>> from ftplib import FTP >>> ftp = FTP("192.168.0.22") >>> ftp.login("user", "password") '230 Login successful.' >>> ftp.cwd("/Public/test/hello/will_i_be_deleted/") '250 Directory successfully changed.' >>> ftp.delete("/Public/test/hello/will_i_be_deleted/") ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ftplib.py", line 520, in delete resp = self.sendcmd('DELE ' + filename) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ftplib.py", line 243, in sendcmd return self.getresp() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ftplib.py", line 218, in getresp raise error_perm, resp ftplib.error_perm: 550 Delete operation failed. ``` The directory exists, and "user" has sufficient permissions to delete the folder. The site is actually a NAS (WD MyBookWorld) that supports ftp. Changing to parent directory and using command `ftp.delete("will_i_be_deleted")` does not work either. "will\_i\_be\_deleted" is an empty directory. ftp settings for WD MyBookWorld: ``` Service - Enable; Enable Anonymous - No; Port (Default 21) - Default ```
2012/05/18
[ "https://Stackoverflow.com/questions/10647045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402511/" ]
My solution to fix this ftplib.error\_perm: 550 issue is to cwd to root directory of FTP server, and delete files by their full path as below. ``` ftp.cwd(‘.’) directory = '/Public/test/hello/will_i_be_deleted/' # delete files in dir files = list(ftp.nlst(directory)) for f in files: if f[-3:] == "/.." or f[-2:] == '/.': continue ftp.delete(f) # delete this dir ftp.rmd(directory) ```
The only method that works for me is that I can rename with the ftp.rename() command: e.g. ``` ftp.mkd("/Public/Trash/") ftp.rename("/Public/test/hello/will_i_be_deleted","/Public/Trash/will_i_be_deleted") ``` and then to manually delete the contents of Trash from time to time. I do not know if this is an exclusive problem for the WD MyBookWorld ftp capabilities or not, but at least I got a workaround.
56,581,237
How efficient is python (cpython I guess) when allocating resources for a newly created instance of a class? I have a situation where I will need to instantiate a node class millions of times to make a tree structure. Each of the node objects *should* be lightweight, just containing a few numbers and references to parent and child nodes. For example, will python need to allocate memory for all the "double underscore" properties of each instantiated object (e.g. the docstrings, `__dict__`, `__repr__`, `__class__`, etc, etc), either to create these properties individually or store pointers to where they are defined by the class? Or is it efficient and does not need to store anything except the custom stuff I defined that needs to be stored in each object?
2019/06/13
[ "https://Stackoverflow.com/questions/56581237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1394763/" ]
Superficially it's quite simple: Methods, class variables, and the class docstring are stored in the class (function docstrings are stored in the function). Instance variables are stored in the instance. The instance also references the class so you can look up the methods. Typically all of them are stored in dictionaries (the `__dict__`). So yes, the short answer is: Python doesn't store methods in the instances, but all instances need to have a reference to the class. For example if you have a simple class like this: ```py class MyClass: def __init__(self): self.a = 1 self.b = 2 def __repr__(self): return f"{self.__class__.__name__}({self.a}, {self.b})" instance_1 = MyClass() instance_2 = MyClass() ``` Then in-memory it looks (very simplified) like this: [![enter image description here](https://i.stack.imgur.com/JhLI3.png)](https://i.stack.imgur.com/JhLI3.png) Going deeper ------------ However there are a few things that important when going deeper in CPython: * Having a dictionary as abstraction leads to quite a bit of overhead: You need a reference to the instance dictionary (bytes) and each entry in the dictionary stores the hash (8bytes), a pointer to a key (8bytes) and a pointer to the stored attribute (another 8 bytes). Also dictionaries generally over-allocate so that adding another attribute doesn't trigger a dictionary-resize. * Python doesn't have "value-types", even an integer will be an instance. That means that you don't need 4 bytes to store an integer - Python needs (on my computer) 24bytes to store the integer 0 and at least 28 bytes to store integers different from zero. However references to other objects just require 8 bytes (pointer). * CPython uses reference counting so each instance needs a reference count (8bytes). Also most of CPythons classes participate in the cyclic garbage collector, which incurs an overhead of another 24bytes per instance. In addition to these classes that can be weak-referenced (most of them) also have a `__weakref__` field (another 8 bytes). At this point it's also necessary to point out that CPython optimizes for a few of these "problems": * Python uses [Key-Sharing Dictionaries](https://www.python.org/dev/peps/pep-0412/) to avoid some of the memory overheads (hash and key) of instance dictionaries. * You can use `__slots__` in classes to avoid `__dict__` and `__weakref__`. This can give a significantly less memory-footprint per instance. * Python interns some values, for example if you create a small integer it will not create a new integer instance but return a reference to an already existing instance. Given all that and that several of these points (especially the points about optimizing) are implementation-details it's hard to give an canonical answer about the effective memory-requirements of Python classes. Reducing the memory footprint of instances ------------------------------------------ However in case you want to reduce the memory-footprint of your instances definitely give `__slots__` a try. They do have draw-backs but in case they don't apply to you they are a very good way to reduce the memory. ```py class Slotted: __slots__ = ('a', 'b') def __init__(self): self.a = 1 self.b = 1 ``` If that's not enough and you operate with lots of "value types" you could also go a step further and create extension classes. These are classes that are defined in C but are wrapped so that you can use them in Python. For convenience I'm using the IPython bindings for Cython here to simulate an extension class: ```py %load_ext cython ``` ```py %%cython cdef class Extensioned: cdef long long a cdef long long b def __init__(self): self.a = 1 self.b = 1 ``` Measuring the memory usage -------------------------- The remaining interesting question after all this theory is: How can we measure the memory? I also use a normal class: ```py class Dicted: def __init__(self): self.a = 1 self.b = 1 ``` I'm generally using [`psutil`](https://psutil.readthedocs.io/en/latest/) (even though it's a proxy method) for measuring memory impact and simply measure how much memory it used before and after. The measurements are a bit offset because I need to keep the instances in memory somehow, otherwise the memory would be reclaimed (immediately). Also this is only an approximation because Python actually does quite a bit of memory housekeeping especially when there are lots of create/deletes. ```py import os import psutil process = psutil.Process(os.getpid()) runs = 10 instances = 100_000 memory_dicted = [0] * runs memory_slotted = [0] * runs memory_extensioned = [0] * runs for run_index in range(runs): for store, cls in [(memory_dicted, Dicted), (memory_slotted, Slotted), (memory_extensioned, Extensioned)]: before = process.memory_info().rss l = [cls() for _ in range(instances)] store[run_index] = process.memory_info().rss - before l.clear() # reclaim memory for instances immediately ``` The memory will not be exactly identical for each run because Python re-uses some memory and sometimes also keeps memory around for other purposes but it should at least give a reasonable hint: ``` >>> min(memory_dicted) / 1024**2, min(memory_slotted) / 1024**2, min(memory_extensioned) / 1024**2 (15.625, 5.3359375, 2.7265625) ``` I used the `min` here mostly because I was interested what the minimum was and I divided by `1024**2` to convert the bytes to MegaBytes. Summary: As expected the normal class with dict will need more memory than classes with slots but extension classes (if applicable and available) can have an even lower memory footprint. Another tools that could be very handy for measuring memory usage is [`memory_profiler`](https://pypi.org/project/memory-profiler/), although I haven't used it in a while.
*[edit] It is not easy to get an accurate measurement of memory usage by a python process; **I don't think my answer completely answers the question**, but it is one approach that may be useful in some cases.* *Most approaches use proxy methods (create n objects and estimate the impact on the system memory), and external libraries attempting to wrap those methods. For instance, threads can be found [here](https://stackoverflow.com/questions/9850995/tracking-maximum-memory-usage-by-a-python-function), [here](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python), and [there](https://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended) [/edit]* On `cPython 3.7`, The minimum size of a regular class instance is 56 bytes; with `__slots__` (no dictionary), 16 bytes. ``` import sys class A: pass class B: __slots__ = () pass a = A() b = B() sys.getsizeof(a), sys.getsizeof(b) ``` ### output: ``` 56, 16 ``` Docstrings, class variables, & type annotations are not found at the instance level: ``` import sys class A: """regular class""" a: int = 12 class B: """slotted class""" b: int = 12 __slots__ = () a = A() b = B() sys.getsizeof(a), sys.getsizeof(b) ``` ### output: ``` 56, 16 ``` *[edit ]In addition, see [@LiuXiMin answer](https://stackoverflow.com/questions/56581237/what-resources-does-an-instance-of-a-class-use/56598070#56598070) for **a measure of the size of the class definition**. [/edit]*
56,581,237
How efficient is python (cpython I guess) when allocating resources for a newly created instance of a class? I have a situation where I will need to instantiate a node class millions of times to make a tree structure. Each of the node objects *should* be lightweight, just containing a few numbers and references to parent and child nodes. For example, will python need to allocate memory for all the "double underscore" properties of each instantiated object (e.g. the docstrings, `__dict__`, `__repr__`, `__class__`, etc, etc), either to create these properties individually or store pointers to where they are defined by the class? Or is it efficient and does not need to store anything except the custom stuff I defined that needs to be stored in each object?
2019/06/13
[ "https://Stackoverflow.com/questions/56581237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1394763/" ]
Superficially it's quite simple: Methods, class variables, and the class docstring are stored in the class (function docstrings are stored in the function). Instance variables are stored in the instance. The instance also references the class so you can look up the methods. Typically all of them are stored in dictionaries (the `__dict__`). So yes, the short answer is: Python doesn't store methods in the instances, but all instances need to have a reference to the class. For example if you have a simple class like this: ```py class MyClass: def __init__(self): self.a = 1 self.b = 2 def __repr__(self): return f"{self.__class__.__name__}({self.a}, {self.b})" instance_1 = MyClass() instance_2 = MyClass() ``` Then in-memory it looks (very simplified) like this: [![enter image description here](https://i.stack.imgur.com/JhLI3.png)](https://i.stack.imgur.com/JhLI3.png) Going deeper ------------ However there are a few things that important when going deeper in CPython: * Having a dictionary as abstraction leads to quite a bit of overhead: You need a reference to the instance dictionary (bytes) and each entry in the dictionary stores the hash (8bytes), a pointer to a key (8bytes) and a pointer to the stored attribute (another 8 bytes). Also dictionaries generally over-allocate so that adding another attribute doesn't trigger a dictionary-resize. * Python doesn't have "value-types", even an integer will be an instance. That means that you don't need 4 bytes to store an integer - Python needs (on my computer) 24bytes to store the integer 0 and at least 28 bytes to store integers different from zero. However references to other objects just require 8 bytes (pointer). * CPython uses reference counting so each instance needs a reference count (8bytes). Also most of CPythons classes participate in the cyclic garbage collector, which incurs an overhead of another 24bytes per instance. In addition to these classes that can be weak-referenced (most of them) also have a `__weakref__` field (another 8 bytes). At this point it's also necessary to point out that CPython optimizes for a few of these "problems": * Python uses [Key-Sharing Dictionaries](https://www.python.org/dev/peps/pep-0412/) to avoid some of the memory overheads (hash and key) of instance dictionaries. * You can use `__slots__` in classes to avoid `__dict__` and `__weakref__`. This can give a significantly less memory-footprint per instance. * Python interns some values, for example if you create a small integer it will not create a new integer instance but return a reference to an already existing instance. Given all that and that several of these points (especially the points about optimizing) are implementation-details it's hard to give an canonical answer about the effective memory-requirements of Python classes. Reducing the memory footprint of instances ------------------------------------------ However in case you want to reduce the memory-footprint of your instances definitely give `__slots__` a try. They do have draw-backs but in case they don't apply to you they are a very good way to reduce the memory. ```py class Slotted: __slots__ = ('a', 'b') def __init__(self): self.a = 1 self.b = 1 ``` If that's not enough and you operate with lots of "value types" you could also go a step further and create extension classes. These are classes that are defined in C but are wrapped so that you can use them in Python. For convenience I'm using the IPython bindings for Cython here to simulate an extension class: ```py %load_ext cython ``` ```py %%cython cdef class Extensioned: cdef long long a cdef long long b def __init__(self): self.a = 1 self.b = 1 ``` Measuring the memory usage -------------------------- The remaining interesting question after all this theory is: How can we measure the memory? I also use a normal class: ```py class Dicted: def __init__(self): self.a = 1 self.b = 1 ``` I'm generally using [`psutil`](https://psutil.readthedocs.io/en/latest/) (even though it's a proxy method) for measuring memory impact and simply measure how much memory it used before and after. The measurements are a bit offset because I need to keep the instances in memory somehow, otherwise the memory would be reclaimed (immediately). Also this is only an approximation because Python actually does quite a bit of memory housekeeping especially when there are lots of create/deletes. ```py import os import psutil process = psutil.Process(os.getpid()) runs = 10 instances = 100_000 memory_dicted = [0] * runs memory_slotted = [0] * runs memory_extensioned = [0] * runs for run_index in range(runs): for store, cls in [(memory_dicted, Dicted), (memory_slotted, Slotted), (memory_extensioned, Extensioned)]: before = process.memory_info().rss l = [cls() for _ in range(instances)] store[run_index] = process.memory_info().rss - before l.clear() # reclaim memory for instances immediately ``` The memory will not be exactly identical for each run because Python re-uses some memory and sometimes also keeps memory around for other purposes but it should at least give a reasonable hint: ``` >>> min(memory_dicted) / 1024**2, min(memory_slotted) / 1024**2, min(memory_extensioned) / 1024**2 (15.625, 5.3359375, 2.7265625) ``` I used the `min` here mostly because I was interested what the minimum was and I divided by `1024**2` to convert the bytes to MegaBytes. Summary: As expected the normal class with dict will need more memory than classes with slots but extension classes (if applicable and available) can have an even lower memory footprint. Another tools that could be very handy for measuring memory usage is [`memory_profiler`](https://pypi.org/project/memory-profiler/), although I haven't used it in a while.
> > Is it efficient and does not need to store anything except the custom stuff I defined that needs to be stored in each object? > > > Almost yes, except some certain space. Class in Python is already an instance of `type`, called metaclass. When new an instance of class object, the `custom stuff` are just those things in `__init__`. The attributes and methods defined in class won't spend more space. As for the some certain space, just refer Reblochon Masque's answer, very good and impressive. Maybe I can give one simple but illustrative example: ``` class T(object): def a(self): print(self) t = T() t.a() # output: <__main__.T object at 0x1060712e8> T.a(t) # output: <__main__.T object at 0x1060712e8> # as you see, t.a() equals T.a(t) import sys sys.getsizeof(T) # output: 1056 sys.getsizeof(T()) # output: 56 ```
56,581,237
How efficient is python (cpython I guess) when allocating resources for a newly created instance of a class? I have a situation where I will need to instantiate a node class millions of times to make a tree structure. Each of the node objects *should* be lightweight, just containing a few numbers and references to parent and child nodes. For example, will python need to allocate memory for all the "double underscore" properties of each instantiated object (e.g. the docstrings, `__dict__`, `__repr__`, `__class__`, etc, etc), either to create these properties individually or store pointers to where they are defined by the class? Or is it efficient and does not need to store anything except the custom stuff I defined that needs to be stored in each object?
2019/06/13
[ "https://Stackoverflow.com/questions/56581237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1394763/" ]
Superficially it's quite simple: Methods, class variables, and the class docstring are stored in the class (function docstrings are stored in the function). Instance variables are stored in the instance. The instance also references the class so you can look up the methods. Typically all of them are stored in dictionaries (the `__dict__`). So yes, the short answer is: Python doesn't store methods in the instances, but all instances need to have a reference to the class. For example if you have a simple class like this: ```py class MyClass: def __init__(self): self.a = 1 self.b = 2 def __repr__(self): return f"{self.__class__.__name__}({self.a}, {self.b})" instance_1 = MyClass() instance_2 = MyClass() ``` Then in-memory it looks (very simplified) like this: [![enter image description here](https://i.stack.imgur.com/JhLI3.png)](https://i.stack.imgur.com/JhLI3.png) Going deeper ------------ However there are a few things that important when going deeper in CPython: * Having a dictionary as abstraction leads to quite a bit of overhead: You need a reference to the instance dictionary (bytes) and each entry in the dictionary stores the hash (8bytes), a pointer to a key (8bytes) and a pointer to the stored attribute (another 8 bytes). Also dictionaries generally over-allocate so that adding another attribute doesn't trigger a dictionary-resize. * Python doesn't have "value-types", even an integer will be an instance. That means that you don't need 4 bytes to store an integer - Python needs (on my computer) 24bytes to store the integer 0 and at least 28 bytes to store integers different from zero. However references to other objects just require 8 bytes (pointer). * CPython uses reference counting so each instance needs a reference count (8bytes). Also most of CPythons classes participate in the cyclic garbage collector, which incurs an overhead of another 24bytes per instance. In addition to these classes that can be weak-referenced (most of them) also have a `__weakref__` field (another 8 bytes). At this point it's also necessary to point out that CPython optimizes for a few of these "problems": * Python uses [Key-Sharing Dictionaries](https://www.python.org/dev/peps/pep-0412/) to avoid some of the memory overheads (hash and key) of instance dictionaries. * You can use `__slots__` in classes to avoid `__dict__` and `__weakref__`. This can give a significantly less memory-footprint per instance. * Python interns some values, for example if you create a small integer it will not create a new integer instance but return a reference to an already existing instance. Given all that and that several of these points (especially the points about optimizing) are implementation-details it's hard to give an canonical answer about the effective memory-requirements of Python classes. Reducing the memory footprint of instances ------------------------------------------ However in case you want to reduce the memory-footprint of your instances definitely give `__slots__` a try. They do have draw-backs but in case they don't apply to you they are a very good way to reduce the memory. ```py class Slotted: __slots__ = ('a', 'b') def __init__(self): self.a = 1 self.b = 1 ``` If that's not enough and you operate with lots of "value types" you could also go a step further and create extension classes. These are classes that are defined in C but are wrapped so that you can use them in Python. For convenience I'm using the IPython bindings for Cython here to simulate an extension class: ```py %load_ext cython ``` ```py %%cython cdef class Extensioned: cdef long long a cdef long long b def __init__(self): self.a = 1 self.b = 1 ``` Measuring the memory usage -------------------------- The remaining interesting question after all this theory is: How can we measure the memory? I also use a normal class: ```py class Dicted: def __init__(self): self.a = 1 self.b = 1 ``` I'm generally using [`psutil`](https://psutil.readthedocs.io/en/latest/) (even though it's a proxy method) for measuring memory impact and simply measure how much memory it used before and after. The measurements are a bit offset because I need to keep the instances in memory somehow, otherwise the memory would be reclaimed (immediately). Also this is only an approximation because Python actually does quite a bit of memory housekeeping especially when there are lots of create/deletes. ```py import os import psutil process = psutil.Process(os.getpid()) runs = 10 instances = 100_000 memory_dicted = [0] * runs memory_slotted = [0] * runs memory_extensioned = [0] * runs for run_index in range(runs): for store, cls in [(memory_dicted, Dicted), (memory_slotted, Slotted), (memory_extensioned, Extensioned)]: before = process.memory_info().rss l = [cls() for _ in range(instances)] store[run_index] = process.memory_info().rss - before l.clear() # reclaim memory for instances immediately ``` The memory will not be exactly identical for each run because Python re-uses some memory and sometimes also keeps memory around for other purposes but it should at least give a reasonable hint: ``` >>> min(memory_dicted) / 1024**2, min(memory_slotted) / 1024**2, min(memory_extensioned) / 1024**2 (15.625, 5.3359375, 2.7265625) ``` I used the `min` here mostly because I was interested what the minimum was and I divided by `1024**2` to convert the bytes to MegaBytes. Summary: As expected the normal class with dict will need more memory than classes with slots but extension classes (if applicable and available) can have an even lower memory footprint. Another tools that could be very handy for measuring memory usage is [`memory_profiler`](https://pypi.org/project/memory-profiler/), although I haven't used it in a while.
The most basic object in CPython is just a [type reference and reference count](https://docs.python.org/3/c-api/structures.html#c.PyObject). Both are word-sized (i.e. 8 byte on a 64 bit machine), so the minimal size of an instance is 2 words (i.e. 16 bytes on a 64 bit machine). ``` >>> import sys >>> >>> class Minimal: ... __slots__ = () # do not allow dynamic fields ... >>> minimal = Minimal() >>> sys.getsizeof(minimal) 16 ``` **Each instance needs space for `__class__` and a hidden reference count.** --- The type reference (roughly `object.__class__`) means that *instances fetch content from their class*. Everything you define on the class, not the instance, does not take up space per instance. ``` >>> class EmptyInstance: ... __slots__ = () # do not allow dynamic fields ... foo = 'bar' ... def hello(self): ... return "Hello World" ... >>> empty_instance = EmptyInstance() >>> sys.getsizeof(empty_instance) # instance size is unchanged 16 >>> empty_instance.foo # instance has access to class attributes 'bar' >>> empty_instance.hello() # methods are class attributes! 'Hello World' ``` Note that methods too are *functions on the class*. Fetching one via an instance invokes the [function's data descriptor protocol](https://docs.python.org/3/reference/datamodel.html#implementing-descriptors) to create a temporary method object by partially binding the instance to the function. As a result, *methods do not increase instance size*. **Instances do not need space for class attributes, including `__doc__` and *any* methods.** --- The only thing that increases the size of instances is content stored on the instance. There are three ways to achieve this: `__dict__`, `__slots__` and [container types](https://docs.python.org/3/c-api/structures.html#c.PyVarObject). All of these store content assigned to the instance in some way. * By default, instances have a [`__dict__` field](https://docs.python.org/3/library/stdtypes.html#object.__dict__) - a reference to a mapping that stores attributes. Such classes *also* have some other default fields, like `__weakref__`. ``` >>> class Dict: ... # class scope ... def __init__(self): ... # instance scope - access via self ... self.bar = 2 # assign to instance ... >>> dict_instance = Dict() >>> dict_instance.foo = 1 # assign to instance >>> sys.getsizeof(dict_instance) # larger due to more references 56 >>> sys.getsizeof(dict_instance.__dict__) # __dict__ takes up space as well! 240 >>> dict_instance.__dict__ # __dict__ stores attribute names and values {'bar': 2, 'foo': 1} ``` **Each instance using `__dict__` uses space for the `dict`, the attribute names and values.** * Adding a [`__slots__` field to the class](https://docs.python.org/3/reference/datamodel.html#slots) generates instances with a fixed data layout. This restricts the allowed attributes to those declared, but takes up little space on the instance. The `__dict__` and `__weakref__` slots are only created on request. ``` >>> class Slots: ... __slots__ = ('foo',) # request accessors for instance data ... def __init__(self): ... # instance scope - access via self ... self.foo = 2 ... >>> slots_instance = Slots() >>> sys.getsizeof(slots_instance) # 40 + 8 * fields 48 >>> slots_instance.bar = 1 AttributeError: 'Slots' object has no attribute 'bar' >>> del slots_instance.foo >>> sys.getsizeof(slots_instance) # size is fixed 48 >>> Slots.foo # attribute interface is descriptor on class <member 'foo' of 'Slots' objects> ``` **Each instance using `__slots__` uses space only for the attribute values.** * Inheriting from a container type, such as `list`, `dict` or `tuple`, allows to store items (`self[0]`) instead of attributes (`self.a`). This uses a compact internal storage *in addition* to either `__dict__` or `__slots__`. Such classes are rarely constructed manually - helpers such as `typing.NamedTuple` are often used. ``` >>> from typing import NamedTuple >>> >>> class Named(NamedTuple): ... foo: int ... >>> named_instance = Named(2) >>> sys.getsizeof(named_instance) 56 >>> named_instance.bar = 1 AttributeError: 'Named' object has no attribute 'bar' >>> del named_instance.foo # behaviour inherited from container AttributeError: can't delete attribute >>> Named.foo # attribute interface is descriptor on class <property at 0x10bba3228> >>> Named.__len__ # container interface/metadata such as length exists <slot wrapper '__len__' of 'tuple' objects> ``` **Each instance of a derived container behaves like the base type, plus potential `__slots__` or `__dict__`.** **The most lightweight instances use `__slots__` to only store attribute values.** --- Note that a part of the `__dict__` overhead is commonly optimised by Python interpreters. CPython is capable of [sharing keys between instances](https://www.python.org/dev/peps/pep-0412/), which can [considerably reduce the size per instance](https://stackoverflow.com/questions/42419011/why-is-the-dict-of-instances-so-much-smaller-in-size-in-python-3). PyPy uses an optimises key-shared representation that [completely eliminates the difference](https://morepypy.blogspot.com/2010/11/efficiently-implementing-python-objects.html) between `__dict__` and `__slots__`. It is not possible to accurately measure the memory consumption of objects in all but the most trivial cases. Measuring the size of isolated objects misses related structures, such as `__dict__` using memory for *both* a pointer on the instance *and* an external `dict`. Measuring groups of objects miscounts shared objects (interned strings, small integers, ...) and lazy objects (e.g. the `dict` of `__dict__` only exists when accessed). Note that PyPy [does not implement `sys.getsizeof`](http://doc.pypy.org/en/latest/cpython_differences.html) [to avoid its misuse](https://stackoverflow.com/questions/42562838/is-there-any-alternative-to-sys-getsizeof-in-pypy). In order to measure memory consumption, a full program measurement should be used. For example, one can use [`resource`](https://docs.python.org/3/library/resource.html#resource.getrusage) or [`psutils` to get the own memory consumption while spawning objects](https://dev.nextthought.com/blog/2018/08/cpython-vs-pypy-memory-usage.html). I have created one such [measurement script for *number of fields*, *number of instances* and *implementation variant*](https://gist.github.com/maxfischer2781/d6b617771e76ddd518f1de8b1221e57e). Values shown are *bytes/field* for an instance count of 1000000, on CPython 3.7.0 and PyPy3 3.6.1/7.1.1-beta0. ``` # fields | 1 | 4 | 8 | 16 | 32 | 64 | ---------------+-------+-------+-------+-------+-------+-------+ python3: slots | 48.8 | 18.3 | 13.5 | 10.7 | 9.8 | 8.8 | python3: dict | 170.6 | 42.7 | 26.5 | 18.8 | 14.7 | 13.0 | pypy3: slots | 79.0 | 31.8 | 30.1 | 25.9 | 25.6 | 24.1 | pypy3: dict | 79.2 | 31.9 | 29.9 | 27.2 | 24.9 | 25.0 | ``` For CPython, `__slots__` save about 30%-50% of memory versus `__dict__`. For PyPy, consumption is comparable. Interestingly, PyPy is worse than CPython with `__slots__`, and stays stable for extreme field counts.
13,876,441
Hej, I'm using the latest version (1.2.0) of matplotlib distributed with macports. I run into an AssertionError (I guess stemming from internal test) running this code ``` #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt X,Y = np.meshgrid(np.arange(0, 2*np.pi, .2), np.arange(0, 2*np.pi, .2)) U = np.cos(X) V = np.sin(Y) Q = plt.quiver(U, V) plt.quiverkey(Q, 0.5, .9, 1., 'Label') plt.gca().add_patch(plt.Circle((10, 10), 1)) plt.savefig('test.pdf') ``` Three parts of this code are required for me to reproduce the error: 1. The quiver plot has to have a key created with quiver key 2. have to add an additional patch to the current axes 3. I have to save the figure as a PDF (I can display it just fine) The bug is not dependent on the backend. The traceback I get reads ``` Traceback (most recent call last): File "./test_quiver.py", line 15, in <module> plt.savefig('test.pdf') File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/pyplot.py", line 472, in savefig return fig.savefig(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 1363, in savefig self.canvas.print_figure(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 2093, in print_figure **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1845, in print_pdf return pdf.print_pdf(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_pdf.py", line 2301, in print_pdf self.figure.draw(renderer) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 999, in draw func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes.py", line 2086, in draw a.draw(renderer) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/quiver.py", line 306, in draw self.vector.draw(renderer) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/collections.py", line 755, in draw return Collection.draw(self, renderer) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/collections.py", line 259, in draw self._offset_position) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_pdf.py", line 1548, in draw_path_collection output(*self.gc.pop()) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_pdf.py", line 2093, in pop assert self.parent is not None AssertionError ``` In case it's important: I'm on Mac OS X 10.7.5, using python 2.7.3 and matplotlib 1.2.0. Do you also get this error? Is it a bug in matplotlib? Is it system dependent? Is there some workaround?
2012/12/14
[ "https://Stackoverflow.com/questions/13876441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932593/" ]
You can save as eps or svg and convert to pdf. I found that the best way to produce small pdf files is to save as eps in matplotlib and then use epstopdf. svg also works fine, you can use Inkscape to convert to pdf. A side-effect of svg is that the text is converted to paths (no embedded fonts), which might be desirable in some circumstances.
The matplotlib (v 1.2.1) distributed with Ubuntu 13.04 (raring) also has this bug. I don't know if it's still a problem in newer versions. Another workaround (seems to work for me) is to completely delete the `draw_path_collection` function in `.../matplotlib/backends/backend_pdf.py`.
892,196
buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!
2009/05/21
[ "https://Stackoverflow.com/questions/892196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105167/" ]
If you want the Python standard library to do the work for you (recommended!), use [smtplib](http://docs.python.org/library/smtplib.html). To see whether sending the mail worked, just open your inbox ;) If you want to implement the protocol yourself (is this homework?), then read up on the [SMTP protocol](http://www.ietf.org/rfc/rfc0821.txt) and use e.g. the [socket](http://docs.python.org/library/socket.html) module.
Depends what you mean by "received". It's possible to verify "delivery" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept the mail and then either filter it or send a bounce notice at a later time.
892,196
buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!
2009/05/21
[ "https://Stackoverflow.com/questions/892196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105167/" ]
Create mail messages (possibly with multipart attachments) with [email](http://docs.python.org/library/email.html). > > The `email` package is a library for managing email messages, including MIME and other RFC 2822-based message documents. > > > Send mail using [smtplib](http://docs.python.org/library/smtplib.html) > > The `smtplib` module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. > > > If you are interested in browsing a remote mailbox (for example, to see if the message you sent have arrived), you need a mail service accessible via a known protocol. An popular example is the [`imaplib`](http://docs.python.org/library/imaplib.html) module, implementing the [`IMAP4` protocol](http://en.wikipedia.org/wiki/IMAP4). `IMAP` is [supported by `gmail`](http://mail.google.com/support/bin/topic.py?hl=en&topic=12806). > > This (`imaplib`) module defines three classes, IMAP4, IMAP4\_SSL and IMAP4\_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4. > > >
If you want the Python standard library to do the work for you (recommended!), use [smtplib](http://docs.python.org/library/smtplib.html). To see whether sending the mail worked, just open your inbox ;) If you want to implement the protocol yourself (is this homework?), then read up on the [SMTP protocol](http://www.ietf.org/rfc/rfc0821.txt) and use e.g. the [socket](http://docs.python.org/library/socket.html) module.
892,196
buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!
2009/05/21
[ "https://Stackoverflow.com/questions/892196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105167/" ]
Create mail messages (possibly with multipart attachments) with [email](http://docs.python.org/library/email.html). > > The `email` package is a library for managing email messages, including MIME and other RFC 2822-based message documents. > > > Send mail using [smtplib](http://docs.python.org/library/smtplib.html) > > The `smtplib` module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. > > > If you are interested in browsing a remote mailbox (for example, to see if the message you sent have arrived), you need a mail service accessible via a known protocol. An popular example is the [`imaplib`](http://docs.python.org/library/imaplib.html) module, implementing the [`IMAP4` protocol](http://en.wikipedia.org/wiki/IMAP4). `IMAP` is [supported by `gmail`](http://mail.google.com/support/bin/topic.py?hl=en&topic=12806). > > This (`imaplib`) module defines three classes, IMAP4, IMAP4\_SSL and IMAP4\_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4. > > >
Depends what you mean by "received". It's possible to verify "delivery" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept the mail and then either filter it or send a bounce notice at a later time.
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
There is no specific feature for it right now but there are some workarounds you can use. Using initialization list ========================= One workaround uses the fact, that subexpressions of [initialization lists](http://en.cppreference.com/w/cpp/language/list_initialization) are evaluated in order. `int a[] = {get1(), get2()}` will execute `get1` before executing `get2`. Maybe [fold expressions](http://en.cppreference.com/w/cpp/language/fold) will come handy for similar techniques in the future. To call `do()` on every argument, you can do something like this: ``` template <class... Args> void doSomething(Args... args) { int x[] = {args.do()...}; } ``` However, this will only work when `do()` is returning an `int`. You can use the [comma operator](http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator) to support operations which do not return a proper value. ``` template <class... Args> void doSomething(Args... args) { int x[] = {(args.do(), 0)...}; } ``` To do more complex things, you can put them in another function: ``` template <class Arg> void process(Arg arg, int &someOtherData) { // You can do something with arg here. } template <class... Args> void doSomething(Args... args) { int someOtherData; int x[] = {(process(args, someOtherData), 0)...}; } ``` Note that with generic [lambdas](http://en.cppreference.com/w/cpp/language/lambda) (C++14), you can define a function to do this boilerplate for you. ``` template <class F, class... Args> void do_for(F f, Args... args) { int x[] = {(f(args), 0)...}; } template <class... Args> void doSomething(Args... args) { do_for([&](auto arg) { // You can do something with arg here. }, args...); } ``` Using recursion =============== Another possibility is to use recursion. Here is a small example that defines a similar function `do_for` as above. ``` template <class F, class First, class... Rest> void do_for(F f, First first, Rest... rest) { f(first); do_for(f, rest...); } template <class F> void do_for(F f) { // Parameter pack is empty. } template <class... Args> void doSomething(Args... args) { do_for([&](auto arg) { // You can do something with arg here. }, args...); } ```
You can use multiple variadic templates, this is a bit messy, but it works and is easy to understand. You simply have a function with the variadic template like so: ``` template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } ``` And a helper function like so: ``` void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` Now when you call "function" the "helperFunction" will be called and isolate the first passed parameter from the rest, this variable can b used to call another function (or something). Then "function" will be called again and again until there are no more variables left. Note you might have to declare helperClass before "function". The final code will look like this: ``` void helperFunction(); template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args); template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` The code is not tested.
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
You can't iterate, but you can recurse over the list. Check the printf() example on wikipedia: <http://en.wikipedia.org/wiki/C++0x#Variadic_templates>
You can use multiple variadic templates, this is a bit messy, but it works and is easy to understand. You simply have a function with the variadic template like so: ``` template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } ``` And a helper function like so: ``` void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` Now when you call "function" the "helperFunction" will be called and isolate the first passed parameter from the rest, this variable can b used to call another function (or something). Then "function" will be called again and again until there are no more variables left. Note you might have to declare helperClass before "function". The final code will look like this: ``` void helperFunction(); template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args); template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` The code is not tested.
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
Range based for loops are wonderful: ``` #include <iostream> #include <any> template <typename... Things> void printVariadic(Things... things) { for(const auto p : {things...}) { std::cout << p.type().name() << std::endl; } } int main() { printVariadic(std::any(42), std::any('?'), std::any("C++")); } ``` For me, [this](http://coliru.stacked-crooked.com/a/a04e4f4863f7cd70) produces the output: ``` i c PKc ``` [Here](http://coliru.stacked-crooked.com/a/b5cc4e21c2de8bd6)'s an example without `std::any`, which might be easier to understand for those not familiar with `std::type_info`: ``` #include <iostream> template <typename... Things> void printVariadic(Things... things) { for(const auto p : {things...}) { std::cout << p << std::endl; } } int main() { printVariadic(1, 2, 3); } ``` As you might expect, this produces: ``` 1 2 3 ```
``` #include <iostream> template <typename Fun> void iteratePack(const Fun&) {} template <typename Fun, typename Arg, typename ... Args> void iteratePack(const Fun &fun, Arg &&arg, Args&& ... args) { fun(std::forward<Arg>(arg)); iteratePack(fun, std::forward<Args>(args)...); } template <typename ... Args> void test(const Args& ... args) { iteratePack([&](auto &arg) { std::cout << arg << std::endl; }, args...); } int main() { test(20, "hello", 40); return 0; } ``` Output: ``` 20 hello 40 ```
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
Range based for loops are wonderful: ``` #include <iostream> #include <any> template <typename... Things> void printVariadic(Things... things) { for(const auto p : {things...}) { std::cout << p.type().name() << std::endl; } } int main() { printVariadic(std::any(42), std::any('?'), std::any("C++")); } ``` For me, [this](http://coliru.stacked-crooked.com/a/a04e4f4863f7cd70) produces the output: ``` i c PKc ``` [Here](http://coliru.stacked-crooked.com/a/b5cc4e21c2de8bd6)'s an example without `std::any`, which might be easier to understand for those not familiar with `std::type_info`: ``` #include <iostream> template <typename... Things> void printVariadic(Things... things) { for(const auto p : {things...}) { std::cout << p << std::endl; } } int main() { printVariadic(1, 2, 3); } ``` As you might expect, this produces: ``` 1 2 3 ```
You can use multiple variadic templates, this is a bit messy, but it works and is easy to understand. You simply have a function with the variadic template like so: ``` template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } ``` And a helper function like so: ``` void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` Now when you call "function" the "helperFunction" will be called and isolate the first passed parameter from the rest, this variable can b used to call another function (or something). Then "function" will be called again and again until there are no more variables left. Note you might have to declare helperClass before "function". The final code will look like this: ``` void helperFunction(); template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args); template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` The code is not tested.
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
This is not how one would typically use Variadic templates, not at all. Iterations over a variadic pack is not possible, as per the language rules, so you need to turn toward recursion. ``` class Stock { public: bool isInt(size_t i) { return _indexes.at(i).first == Int; } int getInt(size_t i) { assert(isInt(i)); return _ints.at(_indexes.at(i).second); } // push (a) template <typename... Args> void push(int i, Args... args) { _indexes.push_back(std::make_pair(Int, _ints.size())); _ints.push_back(i); this->push(args...); } // push (b) template <typename... Args> void push(float f, Args... args) { _indexes.push_back(std::make_pair(Float, _floats.size())); _floats.push_back(f); this->push(args...); } private: // push (c) void push() {} enum Type { Int, Float; }; typedef size_t Index; std::vector<std::pair<Type,Index>> _indexes; std::vector<int> _ints; std::vector<float> _floats; }; ``` Example (in action), suppose we have `Stock stock;`: * `stock.push(1, 3.2f, 4, 5, 4.2f);` is resolved to (a) as the first argument is an `int` * `this->push(args...)` is expanded to `this->push(3.2f, 4, 5, 4.2f);`, which is resolved to (b) as the first argument is a `float` * `this->push(args...)` is expanded to `this->push(4, 5, 4.2f);`, which is resolved to (a) as the first argument is an `int` * `this->push(args...)` is expanded to `this->push(5, 4.2f);`, which is resolved to (a) as the first argument is an `int` * `this->push(args...)` is expanded to `this->push(4.2f);`, which is resolved to (b) as the first argument is a `float` * `this->push(args...)` is expanded to `this->push();`, which is resolved to (c) as there is no argument, thus ending the recursion Thus: * Adding another type to handle is as simple as adding another overload, changing the first type (for example, `std::string const&`) * If a completely different type is passed (say `Foo`), then no overload can be selected, resulting in a compile-time error. One caveat: Automatic conversion means a `double` would select overload (b) and a `short` would select overload (a). If this is not desired, then SFINAE need be introduced which makes the method slightly more complicated (well, their signatures at least), example: ``` template <typename T, typename... Args> typename std::enable_if<is_int<T>::value>::type push(T i, Args... args); ``` Where `is_int` would be something like: ``` template <typename T> struct is_int { static bool constexpr value = false; }; template <> struct is_int<int> { static bool constexpr value = true; }; ``` --- Another alternative, though, would be to consider a variant type. For example: ``` typedef boost::variant<int, float, std::string> Variant; ``` It exists already, with all utilities, it can be stored in a `vector`, copied, etc... and seems really much like what you need, even though it does not use Variadic Templates.
You can't iterate, but you can recurse over the list. Check the printf() example on wikipedia: <http://en.wikipedia.org/wiki/C++0x#Variadic_templates>
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
If you want to wrap arguments to `any`, you can use the following setup. I also made the `any` class a bit more usable, although it isn't technically an `any` class. ``` #include <vector> #include <iostream> struct any { enum type {Int, Float, String}; any(int e) { m_data.INT = e; m_type = Int;} any(float e) { m_data.FLOAT = e; m_type = Float;} any(char* e) { m_data.STRING = e; m_type = String;} type get_type() const { return m_type; } int get_int() const { return m_data.INT; } float get_float() const { return m_data.FLOAT; } char* get_string() const { return m_data.STRING; } private: type m_type; union { int INT; float FLOAT; char *STRING; } m_data; }; template <class ...Args> void foo_imp(const Args&... args) { std::vector<any> vec = {args...}; for (unsigned i = 0; i < vec.size(); ++i) { switch (vec[i].get_type()) { case any::Int: std::cout << vec[i].get_int() << '\n'; break; case any::Float: std::cout << vec[i].get_float() << '\n'; break; case any::String: std::cout << vec[i].get_string() << '\n'; break; } } } template <class ...Args> void foo(Args... args) { foo_imp(any(args)...); //pass each arg to any constructor, and call foo_imp with resulting any objects } int main() { char s[] = "Hello"; foo(1, 3.4f, s); } ``` It is however possible to write functions to access the nth argument in a variadic template function and to apply a function to each argument, which might be a better way of doing whatever you want to achieve.
You can use multiple variadic templates, this is a bit messy, but it works and is easy to understand. You simply have a function with the variadic template like so: ``` template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } ``` And a helper function like so: ``` void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` Now when you call "function" the "helperFunction" will be called and isolate the first passed parameter from the rest, this variable can b used to call another function (or something). Then "function" will be called again and again until there are no more variables left. Note you might have to declare helperClass before "function". The final code will look like this: ``` void helperFunction(); template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args); template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` The code is not tested.
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
If your inputs are all of the same type, see `OMGtechy`'s great answer. For mixed-types we can use [fold expressions](https://en.cppreference.com/w/cpp/language/fold) (introduced in `c++17`) with a callable (in this case, a [lambda](https://en.cppreference.com/w/cpp/language/lambda)): ``` #include <iostream> template <class ... Ts> void Foo (Ts && ... inputs) { int i = 0; ([&] { // Do things in your "loop" lambda ++i; std::cout << "input " << i << " = " << inputs << std::endl; } (), ...); } int main () { Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3); } ``` [Live demo](https://godbolt.org/z/Erv61TTbb) (Thanks to [glades](https://stackoverflow.com/users/11770390/glades) for pointing out in the comments that I didn't need to explicitly pass `inputs` to the lambda. This made it a lot neater.) --- If you need `return`/`break`s in your loop, here are some workarounds: * [Demo using try/throw](https://godbolt.org/z/xKo5j47he). Note that `throw`s [can cause tremendous slow down](https://youtu.be/GC4cp4U2f2E?t=1512) of this function; so only use this option if speed isn't important, or the `break`/`return`s are genuinely *exceptional*. * [Demo using variable/if switches](https://godbolt.org/z/jj4M3M65q). These latter answers are honestly a code smell, but shows it's general-purpose.
You can use multiple variadic templates, this is a bit messy, but it works and is easy to understand. You simply have a function with the variadic template like so: ``` template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } ``` And a helper function like so: ``` void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` Now when you call "function" the "helperFunction" will be called and isolate the first passed parameter from the rest, this variable can b used to call another function (or something). Then "function" will be called again and again until there are no more variables left. Note you might have to declare helperClass before "function". The final code will look like this: ``` void helperFunction(); template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args); template <typename ...ArgsType > void function(ArgsType... Args){ helperFunction(Args...); } void helperFunction() {} template <typename T, typename ...ArgsType > void helperFunction(T t, ArgsType... Args) { //do what you want with t function(Args...); } ``` The code is not tested.
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
You can create a container of it by initializing it with your parameter pack between {}. As long as the type of params... is homogeneous or at least convertable to the element type of your container, it will work. (tested with g++ 4.6.1) ``` #include <array> template <class... Params> void f(Params... params) { std::array<int, sizeof...(params)> list = {params...}; } ```
You can't iterate, but you can recurse over the list. Check the printf() example on wikipedia: <http://en.wikipedia.org/wiki/C++0x#Variadic_templates>
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
If your inputs are all of the same type, see `OMGtechy`'s great answer. For mixed-types we can use [fold expressions](https://en.cppreference.com/w/cpp/language/fold) (introduced in `c++17`) with a callable (in this case, a [lambda](https://en.cppreference.com/w/cpp/language/lambda)): ``` #include <iostream> template <class ... Ts> void Foo (Ts && ... inputs) { int i = 0; ([&] { // Do things in your "loop" lambda ++i; std::cout << "input " << i << " = " << inputs << std::endl; } (), ...); } int main () { Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3); } ``` [Live demo](https://godbolt.org/z/Erv61TTbb) (Thanks to [glades](https://stackoverflow.com/users/11770390/glades) for pointing out in the comments that I didn't need to explicitly pass `inputs` to the lambda. This made it a lot neater.) --- If you need `return`/`break`s in your loop, here are some workarounds: * [Demo using try/throw](https://godbolt.org/z/xKo5j47he). Note that `throw`s [can cause tremendous slow down](https://youtu.be/GC4cp4U2f2E?t=1512) of this function; so only use this option if speed isn't important, or the `break`/`return`s are genuinely *exceptional*. * [Demo using variable/if switches](https://godbolt.org/z/jj4M3M65q). These latter answers are honestly a code smell, but shows it's general-purpose.
You can't iterate, but you can recurse over the list. Check the printf() example on wikipedia: <http://en.wikipedia.org/wiki/C++0x#Variadic_templates>
7,230,621
I'm trying to find a method to iterate over an a pack variadic template argument list. Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list. The general idea is to iterate over the list, store all data of type int into a vector, store all data of type char\* into a vector, and store all data of type float, into a vector. During this process there also needs to be a seperate vector that stores individual chars of what order the arguments went in. As an example, when you push\_back(a\_float), you're also doing a push\_back('f') which is simply storing an individual char to know the order of the data. I could also use a std::string here and simply use +=. The vector was just used as an example. Now the way the thing is designed is the function itself is constructed using a macro, despite the evil intentions, it's required, as this is an experiment. So it's literally impossible to use a recursive call, since the actual implementation that will house all this will be expanded at compile time; and you cannot recruse a macro. Despite all possible attempts, I'm still stuck at figuring out how to actually do this. So instead I'm using a more convoluted method that involves constructing a type, and passing that type into the varadic template, expanding it inside a vector and then simply iterating that. However I do not want to have to call the function like: ``` foo(arg(1), arg(2.0f), arg("three"); ``` So the real question is how can I do without such? To give you guys a better understanding of what the code is actually doing, I've pasted the optimistic approach that I'm currently using. ``` struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char *STRING; }; template<typename T> struct get { T operator()(const any& t) { return T(); } }; template<> struct get<int> { int operator()(const any& t) { return t.INT; } }; template<> struct get<float> { float operator()(const any& t) { return t.FLOAT; } }; template<> struct get<char*> { char* operator()(const any& t) { return t.STRING; } }; #define def(name) \ template<typename... T> \ auto name (T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name,T) get<T>()(args[name]) #define end } any arg(int a) { any arg; arg.INT = a; return arg; } any arg(float f) { any arg; arg.FLOAT = f; return arg; } any arg(char* s) { any arg; arg.STRING = s; return arg; } ``` I know this is nasty, however it's a pure experiment, and will not be used in production code. It's purely an idea. It could probably be done a better way. But an example of how you would use this system: ``` def(foo) int data = get(0, int); std::cout << data << std::endl; end ``` looks a lot like python. it works too, but the only problem is how you call this function. Heres a quick example: ``` foo(arg(1000)); ``` I'm required to construct a new any type, which is highly aesthetic, but thats not to say those macros are not either. Aside the point, I just want to the option of doing: foo(1000); I know it can be done, I just need some sort of iteration method, or more importantly some std::get method for packed variadic template argument lists. Which I'm sure can be done. Also to note, I'm well aware that this is not exactly type friendly, as I'm only supporting int,float,char\* and thats okay with me. I'm not requiring anything else, and I'll add checks to use type\_traits to validate that the arguments passed are indeed the correct ones to produce a compile time error if data is incorrect. This is purely not an issue. I also don't need support for anything other then these POD types. It would be highly apprecaited if I could get some constructive help, opposed to arguments about my purely illogical and stupid use of macros and POD only types. I'm well aware of how fragile and broken the code is. This is merley an experiment, and I can later rectify issues with non-POD data, and make it more type-safe and useable. Thanks for your undertstanding, and I'm looking forward to help.
2011/08/29
[ "https://Stackoverflow.com/questions/7230621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658162/" ]
This is not how one would typically use Variadic templates, not at all. Iterations over a variadic pack is not possible, as per the language rules, so you need to turn toward recursion. ``` class Stock { public: bool isInt(size_t i) { return _indexes.at(i).first == Int; } int getInt(size_t i) { assert(isInt(i)); return _ints.at(_indexes.at(i).second); } // push (a) template <typename... Args> void push(int i, Args... args) { _indexes.push_back(std::make_pair(Int, _ints.size())); _ints.push_back(i); this->push(args...); } // push (b) template <typename... Args> void push(float f, Args... args) { _indexes.push_back(std::make_pair(Float, _floats.size())); _floats.push_back(f); this->push(args...); } private: // push (c) void push() {} enum Type { Int, Float; }; typedef size_t Index; std::vector<std::pair<Type,Index>> _indexes; std::vector<int> _ints; std::vector<float> _floats; }; ``` Example (in action), suppose we have `Stock stock;`: * `stock.push(1, 3.2f, 4, 5, 4.2f);` is resolved to (a) as the first argument is an `int` * `this->push(args...)` is expanded to `this->push(3.2f, 4, 5, 4.2f);`, which is resolved to (b) as the first argument is a `float` * `this->push(args...)` is expanded to `this->push(4, 5, 4.2f);`, which is resolved to (a) as the first argument is an `int` * `this->push(args...)` is expanded to `this->push(5, 4.2f);`, which is resolved to (a) as the first argument is an `int` * `this->push(args...)` is expanded to `this->push(4.2f);`, which is resolved to (b) as the first argument is a `float` * `this->push(args...)` is expanded to `this->push();`, which is resolved to (c) as there is no argument, thus ending the recursion Thus: * Adding another type to handle is as simple as adding another overload, changing the first type (for example, `std::string const&`) * If a completely different type is passed (say `Foo`), then no overload can be selected, resulting in a compile-time error. One caveat: Automatic conversion means a `double` would select overload (b) and a `short` would select overload (a). If this is not desired, then SFINAE need be introduced which makes the method slightly more complicated (well, their signatures at least), example: ``` template <typename T, typename... Args> typename std::enable_if<is_int<T>::value>::type push(T i, Args... args); ``` Where `is_int` would be something like: ``` template <typename T> struct is_int { static bool constexpr value = false; }; template <> struct is_int<int> { static bool constexpr value = true; }; ``` --- Another alternative, though, would be to consider a variant type. For example: ``` typedef boost::variant<int, float, std::string> Variant; ``` It exists already, with all utilities, it can be stored in a `vector`, copied, etc... and seems really much like what you need, even though it does not use Variadic Templates.
``` #include <iostream> template <typename Fun> void iteratePack(const Fun&) {} template <typename Fun, typename Arg, typename ... Args> void iteratePack(const Fun &fun, Arg &&arg, Args&& ... args) { fun(std::forward<Arg>(arg)); iteratePack(fun, std::forward<Args>(args)...); } template <typename ... Args> void test(const Args& ... args) { iteratePack([&](auto &arg) { std::cout << arg << std::endl; }, args...); } int main() { test(20, "hello", 40); return 0; } ``` Output: ``` 20 hello 40 ```
13,736,191
I'm stuck on this [exercise](http://www.codecademy.com/courses/python-beginner-en-qzsCL/0?curriculum_id=4f89dab3d788890003000096#!/exercises/3). Its asking me to print out from the list that has dictionaries in it but I don't even know how to. I can't find how to do something like this on google...
2012/12/06
[ "https://Stackoverflow.com/questions/13736191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1260452/" ]
This is a more efficient answer that I found: ``` for persons in students: for grades in persons: print persons[grades] ```
Next time you should specify more carefully what your question is. Below is the loop that the exercise is asking for. ``` for s in students: print s['name'] print s['homework'] print s['quizzes'] print s['tests'] ```
29,384,129
Basically I have a matrix in python 'example' (although much larger). I need to product the array 'example\_what\_I\_want' with some python code. I guess a for loop is in order- but how can I do this? ``` example= [1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25] example_what_I_want = [25,24,23,22,21], [16,17,18,19,20], [15,14,13,12,11], [6,7,8,9,10], [5,4,3,2,1] ``` So it increments in kind of snake fashion. And the first row must be reversed! and then follow that pattern. thanks!
2015/04/01
[ "https://Stackoverflow.com/questions/29384129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285950/" ]
I'm assuming `example` is actually: ``` example = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]] ``` In which case you could do: ``` swapped_example = [sublst if idx%2 else sublst[::-1] for idx,sublst in enumerate(example)][::-1] ``` Which will give you: ``` In [5]: swapped_example Out[5]: [[25, 24, 23, 22, 21], [16, 17, 18, 19, 20], [15, 14, 13, 12, 11], [6, 7, 8, 9, 10], [5, 4, 3, 2, 1]] ```
Or, you can use iter. ``` a = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]] b = [] rev_a = iter(a[::-1]) while rev_a: try: b.append(rev_a.next()[::-1]) b.append(rev_a.next()) except StopIteration: break print b ``` Modified (Did not know that earlier. @Adam), ``` a = iter(a) while a: try: b.insert(0, a.next()[::-1]) b.insert(0, a.next()) except StopIteration: break print b[::-1] ```
61,882,136
working on a coding program that I think I have licked and I'm getting the correct values for. However the test conditions are looking for the values formatted in a different way. And I'm failing at figuring out how to format the return in my function correctly. I get the values correctly when looking for the answer: [4, 15, 7, 19, 1, 20, 13, 9, 4, 14, 9, 7, 8, 20] but the test condition expects should equal '20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20' and for the life of me I haven't been able to figure this out yet. View the original problem here: <https://www.codewars.com/kata/546f922b54af40e1e90001da/train/python> Still very new to Python, but tackling these problems best I can. Code may be ugly, but it's mine =D EDIT: I am looking for a way to reformat my return statement as a string instead of a list of integers. Thanks for the help in advance! Any help is appreciated, even how to post better questions here. Koruptedkernel. ``` import string def alphabet_position(positions): #Declaring final position list. position = [] #Stripping punctuation from the passed string. out1 = positions.translate(str.maketrans("","", string.punctuation)) #Stripping digits from the passed string. out = out1.translate(str.maketrans("","", string.digits)) #Removing Spaces from the passed string. outter = out.replace(" ","") #reducing to lowercase. mod_text = str.lower(outter) #For loop to iterate through alphabet and report index location to position list. for letter in mod_text: #Declare list of letters (lower) in the alphabet (US). alphabet = list('abcdefghijklmnopqrstuvwxyz') position.append(alphabet.index(letter) + 1) return(position) #Call the function with text. alphabet_position("The sunset sets at twelve o'clock.") ```
2020/05/19
[ "https://Stackoverflow.com/questions/61882136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13571383/" ]
The `try-except` indention creates the problem: ``` def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: # <--- spelling corrected from exept to except print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() ```
There were three mistakes in your code 1. Indentation of try-except block 2. Spelling of except 3. at one place you have used myTime and at another mytime. ``` import time import winsound print("Made by Ethan") def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(myTime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() myAlarm() ```
61,882,136
working on a coding program that I think I have licked and I'm getting the correct values for. However the test conditions are looking for the values formatted in a different way. And I'm failing at figuring out how to format the return in my function correctly. I get the values correctly when looking for the answer: [4, 15, 7, 19, 1, 20, 13, 9, 4, 14, 9, 7, 8, 20] but the test condition expects should equal '20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20' and for the life of me I haven't been able to figure this out yet. View the original problem here: <https://www.codewars.com/kata/546f922b54af40e1e90001da/train/python> Still very new to Python, but tackling these problems best I can. Code may be ugly, but it's mine =D EDIT: I am looking for a way to reformat my return statement as a string instead of a list of integers. Thanks for the help in advance! Any help is appreciated, even how to post better questions here. Koruptedkernel. ``` import string def alphabet_position(positions): #Declaring final position list. position = [] #Stripping punctuation from the passed string. out1 = positions.translate(str.maketrans("","", string.punctuation)) #Stripping digits from the passed string. out = out1.translate(str.maketrans("","", string.digits)) #Removing Spaces from the passed string. outter = out.replace(" ","") #reducing to lowercase. mod_text = str.lower(outter) #For loop to iterate through alphabet and report index location to position list. for letter in mod_text: #Declare list of letters (lower) in the alphabet (US). alphabet = list('abcdefghijklmnopqrstuvwxyz') position.append(alphabet.index(letter) + 1) return(position) #Call the function with text. alphabet_position("The sunset sets at twelve o'clock.") ```
2020/05/19
[ "https://Stackoverflow.com/questions/61882136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13571383/" ]
Try/except blocks also need to be indented in Python: ```py def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() ```
The `try-except` indention creates the problem: ``` def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: # <--- spelling corrected from exept to except print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() ```
61,882,136
working on a coding program that I think I have licked and I'm getting the correct values for. However the test conditions are looking for the values formatted in a different way. And I'm failing at figuring out how to format the return in my function correctly. I get the values correctly when looking for the answer: [4, 15, 7, 19, 1, 20, 13, 9, 4, 14, 9, 7, 8, 20] but the test condition expects should equal '20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20' and for the life of me I haven't been able to figure this out yet. View the original problem here: <https://www.codewars.com/kata/546f922b54af40e1e90001da/train/python> Still very new to Python, but tackling these problems best I can. Code may be ugly, but it's mine =D EDIT: I am looking for a way to reformat my return statement as a string instead of a list of integers. Thanks for the help in advance! Any help is appreciated, even how to post better questions here. Koruptedkernel. ``` import string def alphabet_position(positions): #Declaring final position list. position = [] #Stripping punctuation from the passed string. out1 = positions.translate(str.maketrans("","", string.punctuation)) #Stripping digits from the passed string. out = out1.translate(str.maketrans("","", string.digits)) #Removing Spaces from the passed string. outter = out.replace(" ","") #reducing to lowercase. mod_text = str.lower(outter) #For loop to iterate through alphabet and report index location to position list. for letter in mod_text: #Declare list of letters (lower) in the alphabet (US). alphabet = list('abcdefghijklmnopqrstuvwxyz') position.append(alphabet.index(letter) + 1) return(position) #Call the function with text. alphabet_position("The sunset sets at twelve o'clock.") ```
2020/05/19
[ "https://Stackoverflow.com/questions/61882136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13571383/" ]
As flakes mentioned, your `try` block and `except` block need to be indented. Another error is that `except` is misspelled as `exept`. ``` import time import winsound print("Made by Ethan") def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() myAlarm() ```
The `try-except` indention creates the problem: ``` def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: # <--- spelling corrected from exept to except print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() ```
61,882,136
working on a coding program that I think I have licked and I'm getting the correct values for. However the test conditions are looking for the values formatted in a different way. And I'm failing at figuring out how to format the return in my function correctly. I get the values correctly when looking for the answer: [4, 15, 7, 19, 1, 20, 13, 9, 4, 14, 9, 7, 8, 20] but the test condition expects should equal '20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20' and for the life of me I haven't been able to figure this out yet. View the original problem here: <https://www.codewars.com/kata/546f922b54af40e1e90001da/train/python> Still very new to Python, but tackling these problems best I can. Code may be ugly, but it's mine =D EDIT: I am looking for a way to reformat my return statement as a string instead of a list of integers. Thanks for the help in advance! Any help is appreciated, even how to post better questions here. Koruptedkernel. ``` import string def alphabet_position(positions): #Declaring final position list. position = [] #Stripping punctuation from the passed string. out1 = positions.translate(str.maketrans("","", string.punctuation)) #Stripping digits from the passed string. out = out1.translate(str.maketrans("","", string.digits)) #Removing Spaces from the passed string. outter = out.replace(" ","") #reducing to lowercase. mod_text = str.lower(outter) #For loop to iterate through alphabet and report index location to position list. for letter in mod_text: #Declare list of letters (lower) in the alphabet (US). alphabet = list('abcdefghijklmnopqrstuvwxyz') position.append(alphabet.index(letter) + 1) return(position) #Call the function with text. alphabet_position("The sunset sets at twelve o'clock.") ```
2020/05/19
[ "https://Stackoverflow.com/questions/61882136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13571383/" ]
Try/except blocks also need to be indented in Python: ```py def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() ```
There were three mistakes in your code 1. Indentation of try-except block 2. Spelling of except 3. at one place you have used myTime and at another mytime. ``` import time import winsound print("Made by Ethan") def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(myTime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() myAlarm() ```
61,882,136
working on a coding program that I think I have licked and I'm getting the correct values for. However the test conditions are looking for the values formatted in a different way. And I'm failing at figuring out how to format the return in my function correctly. I get the values correctly when looking for the answer: [4, 15, 7, 19, 1, 20, 13, 9, 4, 14, 9, 7, 8, 20] but the test condition expects should equal '20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20' and for the life of me I haven't been able to figure this out yet. View the original problem here: <https://www.codewars.com/kata/546f922b54af40e1e90001da/train/python> Still very new to Python, but tackling these problems best I can. Code may be ugly, but it's mine =D EDIT: I am looking for a way to reformat my return statement as a string instead of a list of integers. Thanks for the help in advance! Any help is appreciated, even how to post better questions here. Koruptedkernel. ``` import string def alphabet_position(positions): #Declaring final position list. position = [] #Stripping punctuation from the passed string. out1 = positions.translate(str.maketrans("","", string.punctuation)) #Stripping digits from the passed string. out = out1.translate(str.maketrans("","", string.digits)) #Removing Spaces from the passed string. outter = out.replace(" ","") #reducing to lowercase. mod_text = str.lower(outter) #For loop to iterate through alphabet and report index location to position list. for letter in mod_text: #Declare list of letters (lower) in the alphabet (US). alphabet = list('abcdefghijklmnopqrstuvwxyz') position.append(alphabet.index(letter) + 1) return(position) #Call the function with text. alphabet_position("The sunset sets at twelve o'clock.") ```
2020/05/19
[ "https://Stackoverflow.com/questions/61882136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13571383/" ]
As flakes mentioned, your `try` block and `except` block need to be indented. Another error is that `except` is misspelled as `exept`. ``` import time import winsound print("Made by Ethan") def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(mytime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() myAlarm() ```
There were three mistakes in your code 1. Indentation of try-except block 2. Spelling of except 3. at one place you have used myTime and at another mytime. ``` import time import winsound print("Made by Ethan") def myAlarm(): try: myTime = list(map(int, input("Enter time in hr min sec\n") .split())) if len(myTime) == 3: total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2] time.sleep(total_secounds) frequency = 2500 duration = 10 winsound.Beep(frequency, duration) else: print("Please enter time in correct format as mentioned\n") myAlarm() except Exception as e: print("This is the exception\n ", e, "So!, please enter correct details") myAlarm() myAlarm() ```
39,026,950
I'm trying to set up a django app that connects to a remote MySQL db. I currently have Django==1.10 and MySQL-python==1.2.5 installed in my venv. In settings.py I have added the following to the DATABASES variable: ``` 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': 'db_host', 'PORT': 'db_port', } ``` I get the error ``` from django.contrib.sites.models import RequestSite ``` when I run python manage.py migrate I am a complete beginner when it comes to django. Is there some step I am missing? edit: I have also installed mysql-connector-c via brew install edit2: realized I just need to connect to a db by importing MySQLdb into a file. sorry for the misunderstanding.
2016/08/18
[ "https://Stackoverflow.com/questions/39026950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3861295/" ]
The error you're seeing has nothing to do with your database settings (assuming your real code has the actual database name, username, and password) or connection. You are not importing the RequestSite from the correct spot. Change (wherever you have this set) from: ``` from django.contrib.sites.models import RequestSite ``` to: ``` from django.contrib.sites.requests import RequestSite ```
This is documentation you should look at this for connecting to databases and how django does it, from what you gave us, as long as your parameters are correct you should be connecting to the database but a good confirmation of this would be the inspectdb tool. <https://docs.djangoproject.com/en/1.10/ref/databases/> This shows you how to import your models from the sql database: <https://docs.djangoproject.com/en/1.10/howto/legacy-databases/> To answer your question in the comments " Auto-generate the models Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command: ``` python manage.py inspectdb ``` Save this as a file by using standard Unix output redirection: ``` python manage.py inspectdb > models.py ``` "
50,322,384
I am new to machine learning and the sklearn package. when trying to import sklearn, I am getting an error saying it cannot find a DLL. I installed sklearn through pip, have un-installed everything including python and re-installed it all and still am having the same issue. only one version of python is installed on this machine. I am running python 3.6.1 and have visual studio 2017 community installed as well. All packages are up to date. The traceback is as follows. (removed username from all the paths) code being ran: ``` import numpy as np from sklearn import cross_validation, neighbors import pandas as pd Traceback (most recent call last): File "C:/Users/Public/Documents/Machine learning project/Classification/KNN.py", line 2, in <module> from sklearn import cross_validation, neighbors File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\sklearn\__init__.py", line 134, in <module> from .base import clone File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\sklearn\base.py", line 11, in <module> from scipy import sparse File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\scipy\sparse\__init__.py", line 229, in <module> from .csr import * File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\scipy\sparse\csr.py", line 15, in <module> from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, get_csr_submatrix, csr_sample_values ImportError: DLL load failed: %1 is not a valid Win32 application. ```
2018/05/14
[ "https://Stackoverflow.com/questions/50322384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9785849/" ]
Check the version of python that you are using. Is it 64 bit or 32 bit? The only time I have seen that error is when there was a mismatch between the package type and the Python version. If there is nothing wrong there you can try the following: ``` import imp imp.find_module("sklearn") ``` This will tell you exactly what is being loaded and the path it is being loaded from. If that is loading the correct package, I'd say try and install the package binary manually instead of going through pip. However I did just test it and saw it working on my system.
Although it is difficult to guess the issue you are experiencing based on what is provided, try the following: ``` from sklearn.model_selection import cross_validate from sklearn.neighbors import KNeighborsClassifier ```
50,322,384
I am new to machine learning and the sklearn package. when trying to import sklearn, I am getting an error saying it cannot find a DLL. I installed sklearn through pip, have un-installed everything including python and re-installed it all and still am having the same issue. only one version of python is installed on this machine. I am running python 3.6.1 and have visual studio 2017 community installed as well. All packages are up to date. The traceback is as follows. (removed username from all the paths) code being ran: ``` import numpy as np from sklearn import cross_validation, neighbors import pandas as pd Traceback (most recent call last): File "C:/Users/Public/Documents/Machine learning project/Classification/KNN.py", line 2, in <module> from sklearn import cross_validation, neighbors File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\sklearn\__init__.py", line 134, in <module> from .base import clone File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\sklearn\base.py", line 11, in <module> from scipy import sparse File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\scipy\sparse\__init__.py", line 229, in <module> from .csr import * File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\scipy\sparse\csr.py", line 15, in <module> from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, get_csr_submatrix, csr_sample_values ImportError: DLL load failed: %1 is not a valid Win32 application. ```
2018/05/14
[ "https://Stackoverflow.com/questions/50322384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9785849/" ]
Check the version of python that you are using. Is it 64 bit or 32 bit? The only time I have seen that error is when there was a mismatch between the package type and the Python version. If there is nothing wrong there you can try the following: ``` import imp imp.find_module("sklearn") ``` This will tell you exactly what is being loaded and the path it is being loaded from. If that is loading the correct package, I'd say try and install the package binary manually instead of going through pip. However I did just test it and saw it working on my system.
I totally assent to using **from sklearn.model\_selection import cross\_validate** but the process fails when you attempt to train the dataset. I will rather recommend importing the below library since your aim is to perform train\_test\_split functionality: ``` from sklearn.model_selection import train_test_split as tts ... ... ... train_feats, test_feats, train_labels, test_labels = tts(features, labels, test_size=0.2) ```
50,322,384
I am new to machine learning and the sklearn package. when trying to import sklearn, I am getting an error saying it cannot find a DLL. I installed sklearn through pip, have un-installed everything including python and re-installed it all and still am having the same issue. only one version of python is installed on this machine. I am running python 3.6.1 and have visual studio 2017 community installed as well. All packages are up to date. The traceback is as follows. (removed username from all the paths) code being ran: ``` import numpy as np from sklearn import cross_validation, neighbors import pandas as pd Traceback (most recent call last): File "C:/Users/Public/Documents/Machine learning project/Classification/KNN.py", line 2, in <module> from sklearn import cross_validation, neighbors File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\sklearn\__init__.py", line 134, in <module> from .base import clone File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\sklearn\base.py", line 11, in <module> from scipy import sparse File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\scipy\sparse\__init__.py", line 229, in <module> from .csr import * File "C:\Users\\AppData\Roaming\Python\Python36\site-packages\scipy\sparse\csr.py", line 15, in <module> from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, get_csr_submatrix, csr_sample_values ImportError: DLL load failed: %1 is not a valid Win32 application. ```
2018/05/14
[ "https://Stackoverflow.com/questions/50322384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9785849/" ]
I totally assent to using **from sklearn.model\_selection import cross\_validate** but the process fails when you attempt to train the dataset. I will rather recommend importing the below library since your aim is to perform train\_test\_split functionality: ``` from sklearn.model_selection import train_test_split as tts ... ... ... train_feats, test_feats, train_labels, test_labels = tts(features, labels, test_size=0.2) ```
Although it is difficult to guess the issue you are experiencing based on what is provided, try the following: ``` from sklearn.model_selection import cross_validate from sklearn.neighbors import KNeighborsClassifier ```
54,717,221
I'm trying to write a Python operator in an airflow DAG and pass certain parameters to the Python callable. My code looks like below. ``` def my_sleeping_function(threshold): print(threshold) fmfdependency = PythonOperator( task_id='poke_check', python_callable=my_sleeping_function, provide_context=True, op_kwargs={'threshold': 100}, dag=dag) end = BatchEndOperator( queue=QUEUE, dag=dag) start.set_downstream(fmfdependency) fmfdependency.set_downstream(end) ``` But I keep getting the below error. > > TypeError: my\_sleeping\_function() got an unexpected keyword argument 'dag\_run' > > > Not able to figure out why.
2019/02/15
[ "https://Stackoverflow.com/questions/54717221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4017926/" ]
Add \*\*kwargs to your operator parameters list after your threshold param
This is how you can pass arguments for a Python operator in Airflow. ``` from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import PythonOperator from time import sleep from datetime import datetime def my_func(*op_args): print(op_args) return op_args[0] with DAG('python_dag', description='Python DAG', schedule_interval='*/5 * * * *', start_date=datetime(2018, 11, 1), catchup=False) as dag: dummy_task = DummyOperator(task_id='dummy_task', retries=3) python_task = PythonOperator(task_id='python_task', python_callable=my_func, op_args=['one', 'two', 'three']) dummy_task >> python_task ```
55,052,883
I may may need help phrasing this question better. I'm writing an async api interface, via python3.7, & with a class (called `Worker()`). `Worker` has a few blocking methods I want to run using `loop.run_in_executor()`. I'd like to build a decorator I can just add above all of the non-`async` methods in `Worker`, but I keep running into problems. I am being told that I need to `await` `wraps()` in the decorator below: ```py def run_method_in_executor(func, *, loop=None): async def wraps(*args): _loop = loop if loop is not None else asyncio.get_event_loop() return await _loop.run_in_executor(executor=None, func=func, *args) return wraps ``` which throws back: `RuntimeWarning: coroutine 'run_method_in_executor.<locals>.wraps' was never awaited` I'm not seeing how I could properly `await` `wraps()` since the containing function & decorated functions aren't asynchronous. Not sure if this is due to misunderstanding `asyncio`, or misunderstanding decorators. Any help (or help clarifying) would be greatly appreciated!
2019/03/07
[ "https://Stackoverflow.com/questions/55052883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6293857/" ]
Not\_a\_Golfer answered my question in the comments. Changing the inner `wraps()` function from a coroutine into a generator solved the problem: ```py def run_method_in_executor(func, *, loop=None): def wraps(*args): _loop = loop if loop is not None else asyncio.get_event_loop() yield _loop.run_in_executor(executor=None, func=func, *args) return wraps ``` **Edit:** This has been really useful for IO, but I haven't figured out how to `await` the yielded executor function, which means it *will* create a race condition if I'm relying on a decorated function to update some value used by any of my other async functions.
Here is a complete example for Python 3.6+ which does not use interfaces deprecated by 3.8. Returning the value of `loop.run_in_executor` effectively converts the wrapped function to an *awaitable* which executes in a thread, so you can `await` its completion. ```py #!/usr/bin/env python3 import asyncio import functools import time def run_in_executor(_func): @functools.wraps(_func) def wrapped(*args, **kwargs): loop = asyncio.get_event_loop() func = functools.partial(_func, *args, **kwargs) return loop.run_in_executor(executor=None, func=func) return wrapped @run_in_executor def say(text=None): """Block, then print.""" time.sleep(1.0) print(f'say {text} at {time.monotonic():.3f}') async def main(): print(f'beginning at {time.monotonic():.3f}') await asyncio.gather(say('asdf'), say('hjkl')) await say(text='foo') await say(text='bar') if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` ```none beginning at 3461039.617 say asdf at 3461040.618 say hjkl at 3461040.618 say foo at 3461041.620 say bar at 3461042.621 ```
55,052,883
I may may need help phrasing this question better. I'm writing an async api interface, via python3.7, & with a class (called `Worker()`). `Worker` has a few blocking methods I want to run using `loop.run_in_executor()`. I'd like to build a decorator I can just add above all of the non-`async` methods in `Worker`, but I keep running into problems. I am being told that I need to `await` `wraps()` in the decorator below: ```py def run_method_in_executor(func, *, loop=None): async def wraps(*args): _loop = loop if loop is not None else asyncio.get_event_loop() return await _loop.run_in_executor(executor=None, func=func, *args) return wraps ``` which throws back: `RuntimeWarning: coroutine 'run_method_in_executor.<locals>.wraps' was never awaited` I'm not seeing how I could properly `await` `wraps()` since the containing function & decorated functions aren't asynchronous. Not sure if this is due to misunderstanding `asyncio`, or misunderstanding decorators. Any help (or help clarifying) would be greatly appreciated!
2019/03/07
[ "https://Stackoverflow.com/questions/55052883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6293857/" ]
Not\_a\_Golfer answered my question in the comments. Changing the inner `wraps()` function from a coroutine into a generator solved the problem: ```py def run_method_in_executor(func, *, loop=None): def wraps(*args): _loop = loop if loop is not None else asyncio.get_event_loop() yield _loop.run_in_executor(executor=None, func=func, *args) return wraps ``` **Edit:** This has been really useful for IO, but I haven't figured out how to `await` the yielded executor function, which means it *will* create a race condition if I'm relying on a decorated function to update some value used by any of my other async functions.
since the release of [PEP-612](https://peps.python.org/pep-0612/) in Python 3.10 there is a way to create a decorator that also keeps the typechecker happy ``` from typing import Awaitable, Callable, ParamSpec, TypeVar R = TypeVar("R") P = ParamSpec("P") def make_async(_func: Callable[P, R]) -> Callable[P, Awaitable[R]]: async def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: func = functools.partial(_func, *args, **kwargs) return await asyncio.get_event_loop().run_in_executor(executor=None, func=func) return wrapped ```
55,052,883
I may may need help phrasing this question better. I'm writing an async api interface, via python3.7, & with a class (called `Worker()`). `Worker` has a few blocking methods I want to run using `loop.run_in_executor()`. I'd like to build a decorator I can just add above all of the non-`async` methods in `Worker`, but I keep running into problems. I am being told that I need to `await` `wraps()` in the decorator below: ```py def run_method_in_executor(func, *, loop=None): async def wraps(*args): _loop = loop if loop is not None else asyncio.get_event_loop() return await _loop.run_in_executor(executor=None, func=func, *args) return wraps ``` which throws back: `RuntimeWarning: coroutine 'run_method_in_executor.<locals>.wraps' was never awaited` I'm not seeing how I could properly `await` `wraps()` since the containing function & decorated functions aren't asynchronous. Not sure if this is due to misunderstanding `asyncio`, or misunderstanding decorators. Any help (or help clarifying) would be greatly appreciated!
2019/03/07
[ "https://Stackoverflow.com/questions/55052883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6293857/" ]
Here is a complete example for Python 3.6+ which does not use interfaces deprecated by 3.8. Returning the value of `loop.run_in_executor` effectively converts the wrapped function to an *awaitable* which executes in a thread, so you can `await` its completion. ```py #!/usr/bin/env python3 import asyncio import functools import time def run_in_executor(_func): @functools.wraps(_func) def wrapped(*args, **kwargs): loop = asyncio.get_event_loop() func = functools.partial(_func, *args, **kwargs) return loop.run_in_executor(executor=None, func=func) return wrapped @run_in_executor def say(text=None): """Block, then print.""" time.sleep(1.0) print(f'say {text} at {time.monotonic():.3f}') async def main(): print(f'beginning at {time.monotonic():.3f}') await asyncio.gather(say('asdf'), say('hjkl')) await say(text='foo') await say(text='bar') if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` ```none beginning at 3461039.617 say asdf at 3461040.618 say hjkl at 3461040.618 say foo at 3461041.620 say bar at 3461042.621 ```
since the release of [PEP-612](https://peps.python.org/pep-0612/) in Python 3.10 there is a way to create a decorator that also keeps the typechecker happy ``` from typing import Awaitable, Callable, ParamSpec, TypeVar R = TypeVar("R") P = ParamSpec("P") def make_async(_func: Callable[P, R]) -> Callable[P, Awaitable[R]]: async def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: func = functools.partial(_func, *args, **kwargs) return await asyncio.get_event_loop().run_in_executor(executor=None, func=func) return wrapped ```
40,535,066
I'm trying to override a python class (first time doing this), and I can't seem to override this method. When I run this, my recv method doesn't run. It runs the superclasses's method instead. What am I doing wrong here? (This is python 2.7 by the way.) ``` import socket class PersistentSocket(socket.socket): def recv(self, count): print("test") return super(self.__class__, self).recv(count) if __name__ == '__main__': s = PersistentSocket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 2300)) print(s.recv(1) ```
2016/11/10
[ "https://Stackoverflow.com/questions/40535066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2100448/" ]
The socket type (officially `socket.SocketType`, though `socket.socket` happens to be the same object) makes the strange choice of implementing `recv` and a few other methods as instance attributes, rather than as normal methods in the class dict. In `socket.SocketType.__init__`, it sets a `self.recv` instance attribute that overrides the `recv` method you tried to define.
Picking on the explanation from @user2357112, one thing that seems to have helped is to do a `delattr(self, 'recv')` on the class constructor (inheriting from `socket.SocketType`) and then define you own `recv` method; for example: ``` class PersistentSocket(socket.SocketType): def __init__(self): """As usual.""" delattr(self, 'recv') def recv(self, buffersize=1024, flags=0): """Your own implementation here.""" return None ```
37,598,337
I want to apply a fee to an amount according with this scale: ``` AMOUNT FEE ------- --- 0 24.04 € 6010.12 0.00450 30050.61 0.00150 60101.21 0.00100 150253.03 0.00050 601012.11 0.00030 ``` From 0 to 6010.13€ is a fix fee of 24.04€ My code: ``` def fee(amount): scale = [[0, 24.04], [6010.12, 0.00450], [30050.61, 0.00150], [60101.21, 0.00100], [150253.03, 0.00050], [601012.11, 0.00030]] if amount <= scale[1][0]: fee = scale[0][1] else: for i in range(0, 5): if amount >= scale[i][0] and amount < scale[i+1][0]: fee = amount * scale[i][1] break return fee print(fee(601012.12)) ``` This code works fine from 0€ to 601012.11€, but for 601012.12€ or greater fails. > > > ``` > return fee UnboundLocalError: local variable 'fee' referenced before assignment > > ``` > > I suppose that the problem is here: `amount < scale[i+1][0]` when i=4 the `fee` variable isn't assigned. Are there any methods more pythonic to select range limits of a scale?
2016/06/02
[ "https://Stackoverflow.com/questions/37598337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3160820/" ]
I think a better way would be to use a while loop to check if `amount` is lesser then `scale[i+1][0]` so that you may just use `scale[i][1]`. And also give an else to handle anything greater than `scale[len(scale)][0]`.
You aren't handling that one case. You should just add another `if` statement outside the loop (similar to the `if ammount <= scale[1][0]` you used, because values in both of these ranges are not handled by the loop): ``` if ammount >= scale[len(scale) - 1][0]: fee = scale[len(scale) - 1][1] ``` Btw, there's a little inconsistency with the `<=` for the first `if`, but `>=` and `<` for the second, in the loop. I doubt I can make better than this: ``` for i in range(-1, len(scale) - 1): if((i == -1 or ammount >= scale[i][0]) and (i == len(scale) or ammount < scale[i + 1][0])): fee = ammount * scale[i][1] return fee ``` `scale[-1][0]` and `scale[len(scale)][0]` cannot be executed, so they're short-circuited.
37,598,337
I want to apply a fee to an amount according with this scale: ``` AMOUNT FEE ------- --- 0 24.04 € 6010.12 0.00450 30050.61 0.00150 60101.21 0.00100 150253.03 0.00050 601012.11 0.00030 ``` From 0 to 6010.13€ is a fix fee of 24.04€ My code: ``` def fee(amount): scale = [[0, 24.04], [6010.12, 0.00450], [30050.61, 0.00150], [60101.21, 0.00100], [150253.03, 0.00050], [601012.11, 0.00030]] if amount <= scale[1][0]: fee = scale[0][1] else: for i in range(0, 5): if amount >= scale[i][0] and amount < scale[i+1][0]: fee = amount * scale[i][1] break return fee print(fee(601012.12)) ``` This code works fine from 0€ to 601012.11€, but for 601012.12€ or greater fails. > > > ``` > return fee UnboundLocalError: local variable 'fee' referenced before assignment > > ``` > > I suppose that the problem is here: `amount < scale[i+1][0]` when i=4 the `fee` variable isn't assigned. Are there any methods more pythonic to select range limits of a scale?
2016/06/02
[ "https://Stackoverflow.com/questions/37598337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3160820/" ]
You aren't handling that one case. You should just add another `if` statement outside the loop (similar to the `if ammount <= scale[1][0]` you used, because values in both of these ranges are not handled by the loop): ``` if ammount >= scale[len(scale) - 1][0]: fee = scale[len(scale) - 1][1] ``` Btw, there's a little inconsistency with the `<=` for the first `if`, but `>=` and `<` for the second, in the loop. I doubt I can make better than this: ``` for i in range(-1, len(scale) - 1): if((i == -1 or ammount >= scale[i][0]) and (i == len(scale) or ammount < scale[i + 1][0])): fee = ammount * scale[i][1] return fee ``` `scale[-1][0]` and `scale[len(scale)][0]` cannot be executed, so they're short-circuited.
First of all, you should try to avoid naming different things the same. That makes harder to see what the problem is. What happens is this: if the amount is below the second entry in the scale table, you return the first entry. If not, you look in the table and check if the amount is bigger than the current and smaller than the next threshold. That works up until the last one, your `range(0, 5)` will yield `0, 1, 2, 3, 4`, not reaching the last one and breaking. In that case, no `fee` is defined when you try to return it, raising the UnboundLocalError. I would fix by checking the upper bound too: ``` def fee(amount): scale = [[0, 24.04], [6010.12, 0.00450], [30050.61, 0.00150], [60101.21, 0.00100], [150253.03, 0.00050], [601012.11, 0.00030]] if amount <= scale[1][0]: return scale[0][1] elif amount >= scale[-1][0]: return scale[-1][1] else: for i in range(0, 5): if amount >= scale[i][0] and amount < scale[i + 1][0]: return amount * scale[i][1] ```
37,598,337
I want to apply a fee to an amount according with this scale: ``` AMOUNT FEE ------- --- 0 24.04 € 6010.12 0.00450 30050.61 0.00150 60101.21 0.00100 150253.03 0.00050 601012.11 0.00030 ``` From 0 to 6010.13€ is a fix fee of 24.04€ My code: ``` def fee(amount): scale = [[0, 24.04], [6010.12, 0.00450], [30050.61, 0.00150], [60101.21, 0.00100], [150253.03, 0.00050], [601012.11, 0.00030]] if amount <= scale[1][0]: fee = scale[0][1] else: for i in range(0, 5): if amount >= scale[i][0] and amount < scale[i+1][0]: fee = amount * scale[i][1] break return fee print(fee(601012.12)) ``` This code works fine from 0€ to 601012.11€, but for 601012.12€ or greater fails. > > > ``` > return fee UnboundLocalError: local variable 'fee' referenced before assignment > > ``` > > I suppose that the problem is here: `amount < scale[i+1][0]` when i=4 the `fee` variable isn't assigned. Are there any methods more pythonic to select range limits of a scale?
2016/06/02
[ "https://Stackoverflow.com/questions/37598337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3160820/" ]
I think a better way would be to use a while loop to check if `amount` is lesser then `scale[i+1][0]` so that you may just use `scale[i][1]`. And also give an else to handle anything greater than `scale[len(scale)][0]`.
First of all, you should try to avoid naming different things the same. That makes harder to see what the problem is. What happens is this: if the amount is below the second entry in the scale table, you return the first entry. If not, you look in the table and check if the amount is bigger than the current and smaller than the next threshold. That works up until the last one, your `range(0, 5)` will yield `0, 1, 2, 3, 4`, not reaching the last one and breaking. In that case, no `fee` is defined when you try to return it, raising the UnboundLocalError. I would fix by checking the upper bound too: ``` def fee(amount): scale = [[0, 24.04], [6010.12, 0.00450], [30050.61, 0.00150], [60101.21, 0.00100], [150253.03, 0.00050], [601012.11, 0.00030]] if amount <= scale[1][0]: return scale[0][1] elif amount >= scale[-1][0]: return scale[-1][1] else: for i in range(0, 5): if amount >= scale[i][0] and amount < scale[i + 1][0]: return amount * scale[i][1] ```
60,011,277
New to coding and running through the exercises in Python Crash Course version 2. One of the exercises involves creating a file called "remember\_me.py" and as far as I can tell, I'm entering the code as it exists in the book almost verbatim, but getting an error: ``` """Exercise for Python Crash Course.""" import json #Load the username, if it has been stored previously. #Otherwise, prompt for the username and store it. filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: username = input("What is your name?\n") with open(filename, 'w') as f: json.dump(username, f) print(f"We'll remember you when you come back, {username}!") else: print(f"Welcome back, {username}!") ``` Whenever I try to run it, I get the following traceback (I replaced the username with "me" here): ``` Traceback (most recent call last): File "C:\Users\me\Desktop\python_work\remember_me.py", line 9, in <module> username = json.load(f) File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ``` Any ideas what I'm doing wrong? I've tried just starting from scratch and re-typing, but apparently I'm making the same error!
2020/01/31
[ "https://Stackoverflow.com/questions/60011277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12821839/" ]
``` import json filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: username = input("What is your name? ") with open(filename, 'w') as f: json.dump(username, f) print(f"We'll remember you when you come back, {username}!") except json.decoder.JSONDecodeError: # This error is for when the json file is EMPTY. username = input("What is your name? ") with open(filename, 'w') as f: json.dump(username, f) print(f"We'll remember you when you come back, {username}!") else: print(f"Welcome back, {username}!") ```
``` def get_stored_number(): try: with open(filename) as f: username = json.load(f) except FileNotFoundError: return None **except json.decoder.JSONDecodeError: return None** else: return username number() ``` Solve this problem adding except for blank file username.json
5,238,785
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
2011/03/08
[ "https://Stackoverflow.com/questions/5238785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650556/" ]
``` getattr(obj, "name")(args) ``` ​​​​
hmmm... getattr(obj, funcname)(\*args, \*\*kwargs) ? ``` >>> s = "Abc" >>> s.upper() 'ABC' >>> getattr(s, "upper")() 'ABC' >>> getattr(s, "lower")() 'abc' ```
5,238,785
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
2011/03/08
[ "https://Stackoverflow.com/questions/5238785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650556/" ]
``` getattr(obj, "name")(args) ``` ​​​​
Apart from the already mentioned `getattr()` builtin: As an alternative to an if-elif-else loop you can use a dictionary to map your "cases" to the desired functions/methods: ``` # given func_a, func_b and func_default already defined function_dict = { 'a': func_a, 'b': func_b } x = 'a' function_dict(x)() # -> func_a() function_dict.get('xyzzy', func_default)() # fallback to -> func_c ``` Concerning methods instead of plain functions: * you can just turn the above example into `method_dict` using for example `lambda obj: obj.method_a()` instead of `function_a` etc., and then do `method_dict[case](obj)` * you can use `getattr()` as other answers have already mentioned, but you only need it if you really need to get the method from its name. * [operator.methodcaller()](http://docs.python.org/library/operator.html#operator.methodcaller) from the stdlib is a nice shortcut in some cases: based on a method name, and optionally some arguments, it creates a function that calls the method with that name on another object (and if you provided any extra arguments when creating the methodcaller, it will call the method with these arguments)
5,238,785
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
2011/03/08
[ "https://Stackoverflow.com/questions/5238785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650556/" ]
``` getattr(obj, "name")(args) ``` ​​​​
Or, if you prefer, `operator.methodcaller('foo')` is a function which calls `foo` on whatever you pass it. In other words, ``` import operator fooer = operator.methodcaller("foo") fooer(bar) ``` is equivalent to ``` bar.foo() ``` (I think this is probably the adjoint or dual in a suitable category. If you're mathematically inclined.)
5,238,785
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
2011/03/08
[ "https://Stackoverflow.com/questions/5238785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650556/" ]
hmmm... getattr(obj, funcname)(\*args, \*\*kwargs) ? ``` >>> s = "Abc" >>> s.upper() 'ABC' >>> getattr(s, "upper")() 'ABC' >>> getattr(s, "lower")() 'abc' ```
Apart from the already mentioned `getattr()` builtin: As an alternative to an if-elif-else loop you can use a dictionary to map your "cases" to the desired functions/methods: ``` # given func_a, func_b and func_default already defined function_dict = { 'a': func_a, 'b': func_b } x = 'a' function_dict(x)() # -> func_a() function_dict.get('xyzzy', func_default)() # fallback to -> func_c ``` Concerning methods instead of plain functions: * you can just turn the above example into `method_dict` using for example `lambda obj: obj.method_a()` instead of `function_a` etc., and then do `method_dict[case](obj)` * you can use `getattr()` as other answers have already mentioned, but you only need it if you really need to get the method from its name. * [operator.methodcaller()](http://docs.python.org/library/operator.html#operator.methodcaller) from the stdlib is a nice shortcut in some cases: based on a method name, and optionally some arguments, it creates a function that calls the method with that name on another object (and if you provided any extra arguments when creating the methodcaller, it will call the method with these arguments)
5,238,785
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
2011/03/08
[ "https://Stackoverflow.com/questions/5238785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650556/" ]
hmmm... getattr(obj, funcname)(\*args, \*\*kwargs) ? ``` >>> s = "Abc" >>> s.upper() 'ABC' >>> getattr(s, "upper")() 'ABC' >>> getattr(s, "lower")() 'abc' ```
Or, if you prefer, `operator.methodcaller('foo')` is a function which calls `foo` on whatever you pass it. In other words, ``` import operator fooer = operator.methodcaller("foo") fooer(bar) ``` is equivalent to ``` bar.foo() ``` (I think this is probably the adjoint or dual in a suitable category. If you're mathematically inclined.)
47,608,612
Whilst I was learning pygame, I stumbled across a line of code that I did not understand: ``` if y == 0 or y == height-1: var1 *= -1 ``` I understand what if statements are in python and the usage of logic gates, what I don't understand is the small piece of statement after the if statement: "var1 \*= 1" Can someone explain this syntax? I do not understand the code and thought it would return a syntax error if we type anything beyond a colon.
2017/12/02
[ "https://Stackoverflow.com/questions/47608612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687842/" ]
Actually there is no rule that you cannot write something after a colon in Python. In fact, you could write multiple statements after an if condition as well, like: `if True: print("foo"); print("bar")`. However for stylistic reasons generally it is recommended to write it in a new line after the colon. Exceptions might be when the content of the block is very simple and one line. `*=` means to assign the variable on the left to the value of itself multiplied by the expression on the right.
``` var *= -1 ``` is equivalent to ``` var = var * (-1) ``` So it means that the sign of var will change . --- ``` if condition: statement ``` is equivalent to ``` if condition: statement ```
47,608,612
Whilst I was learning pygame, I stumbled across a line of code that I did not understand: ``` if y == 0 or y == height-1: var1 *= -1 ``` I understand what if statements are in python and the usage of logic gates, what I don't understand is the small piece of statement after the if statement: "var1 \*= 1" Can someone explain this syntax? I do not understand the code and thought it would return a syntax error if we type anything beyond a colon.
2017/12/02
[ "https://Stackoverflow.com/questions/47608612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687842/" ]
We can write stuff after colons. Another common thing is to use semicolon to chain operations or imports. But those syntax are highly discouraged for readability. I'd write it like this: ``` if (y == 0 or y == height-1): var1 *= -1 ``` Or if you have more complex relations: ``` cond1 = (y == 0) # explanation1 cond2 = (y == height-1) # explanation2 if (cond1 or cond2): var1 *= -1 ```
``` var *= -1 ``` is equivalent to ``` var = var * (-1) ``` So it means that the sign of var will change . --- ``` if condition: statement ``` is equivalent to ``` if condition: statement ```
47,608,612
Whilst I was learning pygame, I stumbled across a line of code that I did not understand: ``` if y == 0 or y == height-1: var1 *= -1 ``` I understand what if statements are in python and the usage of logic gates, what I don't understand is the small piece of statement after the if statement: "var1 \*= 1" Can someone explain this syntax? I do not understand the code and thought it would return a syntax error if we type anything beyond a colon.
2017/12/02
[ "https://Stackoverflow.com/questions/47608612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687842/" ]
Actually there is no rule that you cannot write something after a colon in Python. In fact, you could write multiple statements after an if condition as well, like: `if True: print("foo"); print("bar")`. However for stylistic reasons generally it is recommended to write it in a new line after the colon. Exceptions might be when the content of the block is very simple and one line. `*=` means to assign the variable on the left to the value of itself multiplied by the expression on the right.
In general ``` if condition is true: statement else: another statement ``` So,according to your statement: ``` if y == 0 or y == height-1: var = var * (-1) ```
47,608,612
Whilst I was learning pygame, I stumbled across a line of code that I did not understand: ``` if y == 0 or y == height-1: var1 *= -1 ``` I understand what if statements are in python and the usage of logic gates, what I don't understand is the small piece of statement after the if statement: "var1 \*= 1" Can someone explain this syntax? I do not understand the code and thought it would return a syntax error if we type anything beyond a colon.
2017/12/02
[ "https://Stackoverflow.com/questions/47608612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687842/" ]
Actually there is no rule that you cannot write something after a colon in Python. In fact, you could write multiple statements after an if condition as well, like: `if True: print("foo"); print("bar")`. However for stylistic reasons generally it is recommended to write it in a new line after the colon. Exceptions might be when the content of the block is very simple and one line. `*=` means to assign the variable on the left to the value of itself multiplied by the expression on the right.
We can write stuff after colons. Another common thing is to use semicolon to chain operations or imports. But those syntax are highly discouraged for readability. I'd write it like this: ``` if (y == 0 or y == height-1): var1 *= -1 ``` Or if you have more complex relations: ``` cond1 = (y == 0) # explanation1 cond2 = (y == height-1) # explanation2 if (cond1 or cond2): var1 *= -1 ```
47,608,612
Whilst I was learning pygame, I stumbled across a line of code that I did not understand: ``` if y == 0 or y == height-1: var1 *= -1 ``` I understand what if statements are in python and the usage of logic gates, what I don't understand is the small piece of statement after the if statement: "var1 \*= 1" Can someone explain this syntax? I do not understand the code and thought it would return a syntax error if we type anything beyond a colon.
2017/12/02
[ "https://Stackoverflow.com/questions/47608612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687842/" ]
We can write stuff after colons. Another common thing is to use semicolon to chain operations or imports. But those syntax are highly discouraged for readability. I'd write it like this: ``` if (y == 0 or y == height-1): var1 *= -1 ``` Or if you have more complex relations: ``` cond1 = (y == 0) # explanation1 cond2 = (y == height-1) # explanation2 if (cond1 or cond2): var1 *= -1 ```
In general ``` if condition is true: statement else: another statement ``` So,according to your statement: ``` if y == 0 or y == height-1: var = var * (-1) ```
59,338,922
I'm looking for a convention stating how different types of methods (i.e. `@staticmethod` or `@classmethod`) inside the Python class definition should be arranged. [PEP-8](https://www.python.org/dev/peps/pep-0008) does not provide any information about such topic. For example, Java programming language has some [code conventions](https://www.oracle.com/technetwork/java/codeconventions-141855.html#1852) referring to order in which static and instance variables are appearing in the class definition block. Is there any standard for Python 3 declaring such recommendations?
2019/12/14
[ "https://Stackoverflow.com/questions/59338922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7217645/" ]
The lack of answers so far just triggered me to simply write down the way I do it: ``` class thing(object): info = 'someinfo' # this can be useful to provide information about the class, # either as text or otherwise, in case you have multiple similar # but different classes. # It's also useful if there are some fixed numbers defining # the class' behaviour but you don't want to bury them somewhere # in the code (and haven't gotten around to putting them into # a separate file or look-up table, as you probably should) @staticmethod def stat(arg1, arg2): '''similarly, static methods are for stuff that is specific to the class but still useful without an instance''' pass # e.g.: some preprocessor for input needed to instantiate the class, or a computation specific to the type of thing represented by the class return(arg1 + arg2) @classmethod def classy(cls, str1) '''class methods get access to other class stuff. So, basically, they can do less-trivial things''' return(cls.stat(str1, cls.info) def __init__(self, arg): # ...and here starts the regular class-internal stuff self.arg = arg def simplething(self, arg): '''I like to put the simple things first which don't call other instance methods...''' return(arg * self.arg) def complicated(self, arg1, arg2): '''...before the methods which call the other methods above them''' return(self.simplething(arg1) / simplething(arg2)) ``` In short: anything that is useful before the class has been created goes above the `__init__()` definition, first the class-global definitions, then static methods, then class methods, and after `__init__()`, all methods in a hierarchical order. The benefit (to me) of doing it this way is that when I'm scrolling through the code and get to some method that calls other methods from the class, I've already seen those methods. I suppose there is no objectively "best" way of doing this, since you could arrange things the other way round just as well and still know where to look first. To me, it makes more intuitive sense to me this way round. It also has the advantage that at some point during development, I'm more likely to add higher-level methods to the bottom than to squeeze low-level ones in at the top. Another way to do it might be to sort things by "relevance". I.e.: The things which a user of the class is expected to need most often could be at the top. That might be good if you have lots of people using your code but not modifying it (much). I do see some people organizing not their classes but modules of functions that way: The function you're most likely to call directly is at the top, and the function it calls are below. But for the internals of a class whose methods are rarely executed in order, that kind of order can be hard to determine and may make it harder to find the definite list of static or class methods. ...definitely not a standard, but maybe a little orientation for those looking for it, or at least a starting point to explain why your order is better than mine :)
I think the way to declare `@staticmethod` and `@classmethod` on python is by adding that method statement (`@staticmethod` or `@classmethod`) directly above of your function. The usage of `@classmethod` is like instance function, it requires some argument like `class` or `cls` (u can change the parameter name so it's up to u). Whether for the `@static method`, it doesn't require self or class argument like instance method or class method. These two methods are bound to the class not to the object of the class so that `@staticmethod` cannot access or modify that because `@staticmethod` doesn't know about the state of the class, but for the `@classmethod` can access or modify class state because it has access into it (look at cls argument when calling `@classmethod`) but remember, if u are changing some state through `@classmethod`, It will change all the state of all instances of the class. U can see the differences on the example below. Example : ``` @classmethod def something(cls, arg1, arg2, ....): #this is class method @staticmethod def something2(arg1, arg2, ...): #this is static method ``` for further explanations, maybe you can see this links : Static and class method explanation : [link](https://www.geeksforgeeks.org/class-method-vs-static-method-python/) Class or static variable explanation : [link](https://www.geeksforgeeks.org/g-fact-34-class-or-static-variables-in-python/) \*I edited my answer because I seem not answer your question There isn't any strict rules / standard to arrange it and luckily in python, u don't have to specify what types of method do u want to define (in java like public void ... or private int..., etc). 1. Name of Class The first order comes the name of classes and then u can have attribute references and instantiation just like java. U can specify the scope of the attribute too (like private etc). 2. Instantiation Then u can declare instantiation just like java by declaring `def __init__(self, ...)`. If u declare instantiation, then it will automatically invokes `__init__` when u declare new class instance. If u not declare this, python will keep to call this function because it automatically inherit from base class and won't do anything 3. Function / Method After that, u can declare function. U can define `instance method` or `@classmethod` or `@staticmethod` and do something. Its method has its own advantages so it depends on how u need it. Python supports inheritance and multiple inheritance too. For further explanation u can see this link [link](https://docs.python.org/3/tutorial/classes.html). Hope it helps.
51,928,090
I am trying to separate the pixel values of an image in python which are in a numpy array of 'object' data-type in a single quote like this: ``` ['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 .... 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] ``` The shape of the numpy array is coming as 1. There are a total of 784 numbers but I cannot access them individually. I wanted something like: `[238, 236, 237, ......, 70, 75, 90]` of dtype int or float. There are 1000 such numpy arrays like the one above. Thanks in advance.
2018/08/20
[ "https://Stackoverflow.com/questions/51928090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9804344/" ]
You can use `str.split` **Ex:** ``` l = ['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] print( list(map(int, l[0].split())) ) ``` **Output:** ``` [238, 236, 237, 238, 240, 240, 239, 241, 241, 243, 240, 239, 231, 212, 190, 173, 148, 122, 104, 92, 143, 136, 132, 127, 124, 119, 110, 104, 112, 119, 78, 20, 17, 19, 20, 23, 26, 31, 30, 30, 32, 33, 29, 30, 34, 39, 49, 62, 70, 75, 90] ```
I believe using [`np.ndarray.item()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html) is idiomatic to retrieve a single item from a numpy array. ``` import numpy as np your_numpy_array = np.asarray(['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] ) values = your_numpy_array.item().split(' ') new_numpy_array = np.asarray(values, dtype='int') ``` Note that `values` here is a list of strings. `np.asarray` can construct an array of integers from list of string values, we just need to specify the `dtype` (as suggested by [hpaulj](https://stackoverflow.com/users/901925))
37,335,027
The following python code has a bug: ``` class Location(object): def is_nighttime(): return ... if location.is_nighttime: close_shades() ``` The bug is that the programmer forgot to call `is_nighttime` (or forgot to use a `@property` decorator on the method), so the method is cast by `bool` evaluated as `True` without being called. Is there a way to prevent the programmer from doing this, both in the case above, and in the case where `is_nighttime` is a standalone function instead of a method? For example, something in the following spirit? ``` is_nighttime.__bool__ = TypeError ```
2016/05/19
[ "https://Stackoverflow.com/questions/37335027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205529/" ]
In theory, you could wrap the function in a function-like object with a `__call__` that delegates to the function and a `__bool__` that raises a TypeError. It'd be really unwieldy and would probably cause more bad interactions than it'd catch - for example, these objects won't work as methods unless you add more special handling for that - but you could do it: ``` class NonBooleanFunction(object): """A function wrapper that prevents a function from being interpreted as a boolean.""" def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __bool__(self): raise TypeError __nonzero__ = __bool__ @NonBooleanFunction def is_nighttime(): return True # We're at the Sun-Earth L2 point or something. if is_nighttime: # TypeError! ``` There's still a lot of stuff you can't catch: ``` nighttime_list.append(is_nighttime) # No TypeError ._. ``` And you have to remember to explicitly apply this to any functions you don't want being treated as booleans. You also can't do much about functions and methods you don't control; for example, you can't apply this to `str.islower` to catch things like `if some_string.islower:`. If you want to catch things like this, I recommend using static analysis tools instead. I think IDEs like PyCharm might warn you, and there should be linting tools that can catch this. --- If you want these things to work as methods, here's the extra handling for that: ``` import functools class NonBooleanFunction(object): ... # other methods omitted for brevity def __get__(self, instance, owner): if instance is None: return self return NonBooleanFunction(functools.partial(self.func, instance)) ```
Short answer: `if is_nighttime():`, with parenthesis to call it. Longer answer: `is_nighttime` points to a function, which is a non-None type. `if` looks for a condition which is a boolean, and casts the symbol `is_nighttime` to boolean. As it is not zero and not None, it is True.
37,335,027
The following python code has a bug: ``` class Location(object): def is_nighttime(): return ... if location.is_nighttime: close_shades() ``` The bug is that the programmer forgot to call `is_nighttime` (or forgot to use a `@property` decorator on the method), so the method is cast by `bool` evaluated as `True` without being called. Is there a way to prevent the programmer from doing this, both in the case above, and in the case where `is_nighttime` is a standalone function instead of a method? For example, something in the following spirit? ``` is_nighttime.__bool__ = TypeError ```
2016/05/19
[ "https://Stackoverflow.com/questions/37335027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205529/" ]
This is something you can approach with *static code analysis.* For instance, [`pylint`](https://docs.pylint.org/en/latest/index.html) has a [related warning](https://docs.pylint.org/en/latest/features.html): > > `using-constant-test (W0125):` > > > Using a conditional statement with a > constant value Emitted when a conditional statement (If or ternary if) > uses a constant value for its test. This might not be what the user > intended to do. > > > Demo: If `is_nightmare` is not called: ``` $ pylint test.py ************* Module test C: 1, 0: Missing module docstring (missing-docstring) C: 1, 0: Missing function docstring (missing-docstring) W: 4, 0: Using a conditional statement with a constant value (using-constant-test) ``` If called: ``` $ pylint test.py ************* Module test C: 1, 0: Missing module docstring (missing-docstring) C: 1, 0: Missing function docstring (missing-docstring) ```
Short answer: `if is_nighttime():`, with parenthesis to call it. Longer answer: `is_nighttime` points to a function, which is a non-None type. `if` looks for a condition which is a boolean, and casts the symbol `is_nighttime` to boolean. As it is not zero and not None, it is True.
15,663,899
It turns out building the following string in python... ``` # global variables cr = '\x0d' # segment terminator lf = '\x0a' # data element separator rs = '\x1e' # record separator sp = '\x20' # white space a = 'hello' b = 'world' output = a + rs + b ``` ...is not the same as it may be in C#. How do I accomplish the same in C#?
2013/03/27
[ "https://Stackoverflow.com/questions/15663899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687137/" ]
It is known as [type cast](http://en.wikipedia.org/wiki/Type_conversion) or type conversion. It is used when you want to cast one of type of data to another type of data.
``` (some_type) *apointer ``` This mean that you cast the `apointer` content to the `some_type` type
15,663,899
It turns out building the following string in python... ``` # global variables cr = '\x0d' # segment terminator lf = '\x0a' # data element separator rs = '\x1e' # record separator sp = '\x20' # white space a = 'hello' b = 'world' output = a + rs + b ``` ...is not the same as it may be in C#. How do I accomplish the same in C#?
2013/03/27
[ "https://Stackoverflow.com/questions/15663899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687137/" ]
``` (uv_stream_t*)&server ``` is a cast. It is used here as a polymorphism emulation in C. uv\_tcp\_t may be declared like: ``` typedef struct uv_tcp_t { uv_stream_t base; //base has to be first member for byte reinterpretation to work /*...snip...*/ } uv_tcp_t; ``` This allows `uv_listen` to operate on uv\_tcp\_t as if it was an uv\_stream\_t variable. It is common, and (AFAIK) perfectly valid C.
It is known as [type cast](http://en.wikipedia.org/wiki/Type_conversion) or type conversion. It is used when you want to cast one of type of data to another type of data.
15,663,899
It turns out building the following string in python... ``` # global variables cr = '\x0d' # segment terminator lf = '\x0a' # data element separator rs = '\x1e' # record separator sp = '\x20' # white space a = 'hello' b = 'world' output = a + rs + b ``` ...is not the same as it may be in C#. How do I accomplish the same in C#?
2013/03/27
[ "https://Stackoverflow.com/questions/15663899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687137/" ]
``` (uv_stream_t*)&server ``` is a cast. It is used here as a polymorphism emulation in C. uv\_tcp\_t may be declared like: ``` typedef struct uv_tcp_t { uv_stream_t base; //base has to be first member for byte reinterpretation to work /*...snip...*/ } uv_tcp_t; ``` This allows `uv_listen` to operate on uv\_tcp\_t as if it was an uv\_stream\_t variable. It is common, and (AFAIK) perfectly valid C.
``` (some_type) *apointer ``` This mean that you cast the `apointer` content to the `some_type` type
60,212,670
I have a form on an HTML page with an `input type="text"` that I'm replacing with a `textarea`. Now the form no longer works. When I try to submit it, I get an error "UnboundLocalError: local variable 'updated\_details' referenced before assignment" referring to my python code (I didn't change the python at all). **Old line in HTML** ``` <input type="text" name="comments" id="comments" placeholder="Write stuff here." style="height:150px"> </input> ``` **New Line in HTML** ``` <textarea name="comments" id="comments" placeholder="Write stuff here" </input> </textarea> ``` **Full HTML form** ``` <form action = "/insert_vote" method = "post" onsubmit=""> <div id="vote-form" action = "/insert_vote" method = "post" onsubmit=""> <div class="smalltext"> {% for dict_item in vote_choices %} <input type="radio" name="options" padding="10px" margin="10px" id="{{ dict_item['id'] }}" value="{{ dict_item['id'] }}"> {{ dict_item['choice'] }} </input><br> {% endfor %} </div> <br> <div class="mediumlefttext"> Why did you make that choice? </div> <!-- <input type="text" name="comments" id="comments" placeholder="Write stuff here." style="height:150px"> </input> <br>--> <textarea name="comments" id="comments" placeholder="Write stuff here" </input> </textarea> <!--<button onclick="javascript:login();" size="large" type="submit" value="Submit" scope="public_profile,email" returnscopes="true" onlogin="checkLoginState();">Submit</button>--> <input type="text" name="user_id" id="user_id" style="display:none;"> <input type="submit" value="Submit"> </div> </form> ``` **Python** ``` @app.route('/insert_vote', methods=['GET', 'POST']) def insert_vote(): posted = 1 global article, user_id print ("insert_vote", "this should be the facebook user id", user_id) if request.method == 'POST' or request.method == 'GET': if not request.form['options'] or request.form['comments']: flash('Please enter all the fields', 'error') else: rate = 0 # rate of votes protection against no votes vote_choice_id = int(request.form['options']) comments = request.form['comments'] # user_id = request.form['user_id'] #user_id = 1 av_obj = ArticleVote(user_id, article.id, vote_choice_id, comments) db.session.add(av_obj) try: db.session.commit() except exc.SQLAlchemyError: flash('User has already voted on this article.') posted = 0 if posted == 1: flash('Record was successfully added') else: db.session.rollback() a_obj = article # this is the current global article avs_obj = retrieve_article_vote_summary(a_obj.id) # vote_summary is a list of [tuples('True', numOfTrue), etc] total_votes = avs_obj.getTotalVotes() vote_choice_list = VoteChoice.getVoteChoiceList() vote_choices = [] for item in vote_choice_list: # looping over VoteChoice objects num = avs_obj.getVoteCount(item.choice) if total_votes > 0: rate = num / total_votes vote_choices.append([item.choice, item.color, num, rate*100, total_votes]) details = avs_obj.getVoteDetails() # 10/02 - retrieve array of tuples [(user, VoteChoice, Comments)] details_count = 0 for detail in details: details_count += 1 return redirect('/results/' + str(article.id)) ``` ... ``` @app.route('/results/<int:id>') def results(id): rate = 0 # either 0 or num/total article_list_of_one = Article.query.filter_by(id=id) a_obj = article_list_of_one[0] avs_obj = retrieve_article_vote_summary(a_obj.id) # vote_summary is a list of [tuples('True', numOfTrue), etc] total_votes = avs_obj.getTotalVotes() vote_choices = [] vote_choice_list = VoteChoice.getVoteChoiceList() for item in vote_choice_list: # looping over VoteChoice objects num = avs_obj.getVoteCount(item.choice) if total_votes > 0: # protecting against no votes rate = num/total_votes vote_choices.append([item.choice, item.color, num, rate*100, total_votes]) details = avs_obj.getVoteDetails() # 10/02 - retrieve array of tuples [(user, VoteChoice, Comments)] print("Inside results(" + str(id) + "):") details_count = 0 for detail in details: updated_details = [(user, VoteChoice, Comments, User.query.filter_by(name=user).first().fb_pic) for (user, VoteChoice, Comments) in details] #print(" " + str(details_count) + ": " + details[0] + " " + details[1] + " " + details[2]) # details_count += 1 return render_template('results.html', title=a_obj.title, id=id, image_url=a_obj.image_url, url=a_obj.url, vote_choices=vote_choices, home_data=Article.query.all(), vote_details=updated_details) ```
2020/02/13
[ "https://Stackoverflow.com/questions/60212670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12555158/" ]
Since you want to test `if(getStatisticsLinks) { ... }` and narrow the type to `LinkInterface` when test passes, this is actually very easy. Your function never returns `true`, only `false`, so the return type can be `LinkInterface | false` instead of `LinkInterface | boolean`. That said, I would suggest returning `undefined` rather than `false` here, since that's a more usual way to indicate the absence of a result. The `if` condition still works in the same way, since `undefined` is falsey. It also simplifies the implementation: ```js function getLinkInterfaceForRel(links: LinkInterface[], targetRel: string): LinkInterface | undefined { targetRel = targetRel.toLowerCase(); // could also use .find(...) here, which returns undefined if no match is found return links.filter(el => el.rel.toLowerCase() === targetRel)[0]; } ``` [Playground Link](http://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgDKgNYElzXk5AbwFgAoZC5KCAGwC5kBnMKUAczMuQAtqYHmrEB3KUAthDDcA9gBMBLdmQC+ZMjACuIBGGDSQyNpPQhsuWIggAxaVABKtABQ1MjBibOQLSANoBdABpkMDgoIzAHeiZFYQBKd0wcL3wUAB9kLVkIGFAIWSJOSmowDSgDF1NGADockFlHWmQAXgA+ZFoq6hoqsGlUaQB3aABhOEYIR1jmpqbg0PDInr7BkbGJ2NiAbhU1UhpJZFCoBNMkvEt-ZuQfQopCKloGAHIYaWknoN5s54AjUI-kBIpHJfnAAF5PZDKAJkPzbUhkBD6ZiGSQAZRCumYwAQjA8jCu4Q8Z281lskUcRyCTwA4pIAPoYuBY3S4p5bMjAGDIRzhJksnF41xTEiiCgAenFwQAngAHFDAAnE8wpW7IJEgRjSfZVGjSNi89GYxWsoWVDmkVSkIA)
You will need to write your own typeguard to "narrow down" the type, such that the TypeScript compiler knows that `getStatisticsLinks` is of type `LinkInterface` when it is being used in `this.service.get(getStatisticsLinks.href).subscribe(.....);`. This is one way you can write the type guard: ``` function isLinkInterface(obj: LinkInterface | boolean): pet is LinkInterface { return (obj as LinkInterface).href !== undefined; } ``` And then, this is how you can use it: ``` const getStatisticsLinks = getLinkInterfaceForRel(this.question.links, 'Get_Statistics'); if (getStatisticsLinks && isLinkInterface(getStatisticsLinks)) { this.service.get(getStatisticsLinks.href).subscribe(..); } ``` The `isLinkInterface()` type guard will return `true` only if `getStatisticsLinks` is of type `LinkInterface` (because it has the href property), and then `this.service.get()` will be called conditionally.
69,188,407
I try to use a loop to do some operations on the Pandas numeric and category columns. ``` df = sns.load_dataset('diamonds') print(df.dtypes,'\n') carat float64 cut category color category clarity category depth float64 table float64 price int64 x float64 y float64 z float64 dtype: object ``` In the following codes, I just simply cut and paste 'float64' and 'category' from the preceding step output. ``` for i in df.columns: if df[i].dtypes in ['float64']: print(i) for i in df.columns: if df[i].dtypes in ['category']: print(i) ``` I found that it works for 'float64' but generates an error for 'category'. Why is this ? Thanks very much !!! ``` carat depth table x y z --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-74-8e6aa9d4726e> in <module> 4 5 for i in df.columns: ----> 6 if df[i].dtypes in ['category']: 7 print(i) TypeError: data type 'category' not understood ```
2021/09/15
[ "https://Stackoverflow.com/questions/69188407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15670527/" ]
Solution ======== Try using `pd.api.types.is_categorical_dtype`: ``` for i in df.columns: if pd.api.types.is_categorical_dtype(df[i]): print(i) ``` Or check the `dtype` name: ``` for i in df.columns: if df[i].dtype.name == 'category': print(i) ``` Output: ``` cut color clarity ``` Explanation: ============ This is a bug in Pandas, [here](https://github.com/pandas-dev/pandas/issues/16697) is the GitHub issue, one sentence is: > > `df.dtypes[colname] == 'category'` evaluates as `True` for categorical columns and raises `TypeError: data type "category"` not understood for `np.float64` columns. > > > So actually, it works, it does give `True` for categorical columns, but the problem here is that the numpy `float64` dtype checking isn't cooperated with pandas dtypes, such as `category`. If you make order the columns differently, having the first 3 columns as categorical dtype columns, it will show those column names, but once float columns come, it will raise error due to numpy and pandas type issue: ``` >>> df = df.iloc[:, 1:] >>> df cut color clarity depth table price x y z 0 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 1 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 2 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 3 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 4 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 ... ... ... ... ... ... ... ... ... ... 53935 Ideal D SI1 60.8 57.0 2757 5.75 5.76 3.50 53936 Good D SI1 63.1 55.0 2757 5.69 5.75 3.61 53937 Very Good D SI1 62.8 60.0 2757 5.66 5.68 3.56 53938 Premium H SI2 61.0 58.0 2757 6.15 6.12 3.74 53939 Ideal D SI2 62.2 55.0 2757 5.83 5.87 3.64 [53940 rows x 9 columns] >>> for i in df.columns: if df[i].dtypes in ['category']: print(i) cut color clarity Traceback (most recent call last): File "<pyshell#138>", line 2, in <module> if df[i].dtypes in ['category']: TypeError: data type 'category' not understood >>> ``` As you can see, it did output the columns, but once `np.float64` dtyped columns appear, the numpy `__eq__` magic method would throw an error from numpy backend.
If you have only one possibility in your list, go with @U12-Forward's solution. Yet, if you want to match several types, you can just convert your type to check to its string representation: ``` for i in df.columns: if str(df[i].dtypes) in ['category', 'othertype']: print(i) ``` Output: ``` cut color clarity ```
48,477,200
I'm having a problem trying to extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that. Instead, I get this error message, but I'm not able to solve it: ``` Traceback (most recent call last): File "python", line 45, in <module> IndexError: list index out of range ``` This is my current code: ``` class Queue(): def __init__(self): self.items = [] def empty(self): if self.items == []: return True else: return False def insert(self, value): self.items.append(value) def extract(self): try: return self.items.pop(0) except: raise ValueError("Empty queue") def last(self): if self.empty(): return None else: return self.items[0] import random def randomlist(n2,a2,b2): list = [0] * n2 for i in range(n2): list[i] = random.randint(a2,b2) return list queue1=Queue() for i in range (0,10): queue1.insert(randomlist(10,1,70)[i]) if queue1.empty()==False : print("These are the numbers of your queue:\n",queue1.items) test1=True while test1==True: s=(input("Input a number:\n")) if s.isdigit()==True : test1=False s2=int(s) else: print("Wrong, try again\n") for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) break if queue1.empty()==True : print ("Queue is empty now", cola1.items) ```
2018/01/27
[ "https://Stackoverflow.com/questions/48477200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9147054/" ]
Modifying a list while going through it is a bad idea. ``` for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) ``` This code modifies your queue - items, it shortens the items-list but you still itereate over the full range if no items is found. So your internal list will get shorter and shorter and your range (i) advances towards i. Somewhen you access an `items[i]` that is no longer in your queue. Solution (Edited thanks to [Stefan Pochmann's](https://stackoverflow.com/users/1672429/stefan-pochmann) comment): ``` for _ in range(len(queue1.items)): # no hardcoded length anymore item = queue1.extract() # pop item if item == s2 : # check item for break criteria print ("Remaining numbers:\n",queue1.items) break ```
You can try replacing the last part of your code i.e. ``` for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) break if queue1.empty()==True : print ("Queue is empty now", cola1.items) ``` with ``` poptill = -1 # index till where we should pop for i in range(0,len(queue1.items)): # this loop finds the index to pop queue till if queue1.items[i]==s2: poptill = i break if poptill != -1: # if item to pop was found in queue i = 0 while i <= poptill: # this loop empties the queue till that index queue1.extract() i += 1 if queue1.empty()==True : print ("Queue is empty now", queue1.items) else: print ("Remaining numbers:\n",queue1.items) else: # else item was not found in list for i in range(0,len(queue1.items)): # this loop empties the queue queue1.extract() print ("no item found, so emptied the list, numbers:\n",queue1.items) ``` Here we find the index location till where we should pop in the first loop, and then pop the queue till that index in the second loop, finally if the item to pop was not found in list we empty list in the third loop.
48,477,200
I'm having a problem trying to extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that. Instead, I get this error message, but I'm not able to solve it: ``` Traceback (most recent call last): File "python", line 45, in <module> IndexError: list index out of range ``` This is my current code: ``` class Queue(): def __init__(self): self.items = [] def empty(self): if self.items == []: return True else: return False def insert(self, value): self.items.append(value) def extract(self): try: return self.items.pop(0) except: raise ValueError("Empty queue") def last(self): if self.empty(): return None else: return self.items[0] import random def randomlist(n2,a2,b2): list = [0] * n2 for i in range(n2): list[i] = random.randint(a2,b2) return list queue1=Queue() for i in range (0,10): queue1.insert(randomlist(10,1,70)[i]) if queue1.empty()==False : print("These are the numbers of your queue:\n",queue1.items) test1=True while test1==True: s=(input("Input a number:\n")) if s.isdigit()==True : test1=False s2=int(s) else: print("Wrong, try again\n") for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) break if queue1.empty()==True : print ("Queue is empty now", cola1.items) ```
2018/01/27
[ "https://Stackoverflow.com/questions/48477200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9147054/" ]
Modifying a list while going through it is a bad idea. ``` for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) ``` This code modifies your queue - items, it shortens the items-list but you still itereate over the full range if no items is found. So your internal list will get shorter and shorter and your range (i) advances towards i. Somewhen you access an `items[i]` that is no longer in your queue. Solution (Edited thanks to [Stefan Pochmann's](https://stackoverflow.com/users/1672429/stefan-pochmann) comment): ``` for _ in range(len(queue1.items)): # no hardcoded length anymore item = queue1.extract() # pop item if item == s2 : # check item for break criteria print ("Remaining numbers:\n",queue1.items) break ```
The test code operates from 0 to 10, but when you extract an element, that decreases the size of the queue. So if the queue is originally 10 element long, the index `i` you provide will eventually be `>=` the length of the queue. Hence an `IndexError`. Try one of the other suggested code segments.
48,477,200
I'm having a problem trying to extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that. Instead, I get this error message, but I'm not able to solve it: ``` Traceback (most recent call last): File "python", line 45, in <module> IndexError: list index out of range ``` This is my current code: ``` class Queue(): def __init__(self): self.items = [] def empty(self): if self.items == []: return True else: return False def insert(self, value): self.items.append(value) def extract(self): try: return self.items.pop(0) except: raise ValueError("Empty queue") def last(self): if self.empty(): return None else: return self.items[0] import random def randomlist(n2,a2,b2): list = [0] * n2 for i in range(n2): list[i] = random.randint(a2,b2) return list queue1=Queue() for i in range (0,10): queue1.insert(randomlist(10,1,70)[i]) if queue1.empty()==False : print("These are the numbers of your queue:\n",queue1.items) test1=True while test1==True: s=(input("Input a number:\n")) if s.isdigit()==True : test1=False s2=int(s) else: print("Wrong, try again\n") for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) break if queue1.empty()==True : print ("Queue is empty now", cola1.items) ```
2018/01/27
[ "https://Stackoverflow.com/questions/48477200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9147054/" ]
> > extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that. > > > ``` while not queue.empty(): if queue.extract() == target: print('Found! Remaining numbers:', queue.items) break else: print('Not found! Remaining numbers:', queue.items) ```
You can try replacing the last part of your code i.e. ``` for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) break if queue1.empty()==True : print ("Queue is empty now", cola1.items) ``` with ``` poptill = -1 # index till where we should pop for i in range(0,len(queue1.items)): # this loop finds the index to pop queue till if queue1.items[i]==s2: poptill = i break if poptill != -1: # if item to pop was found in queue i = 0 while i <= poptill: # this loop empties the queue till that index queue1.extract() i += 1 if queue1.empty()==True : print ("Queue is empty now", queue1.items) else: print ("Remaining numbers:\n",queue1.items) else: # else item was not found in list for i in range(0,len(queue1.items)): # this loop empties the queue queue1.extract() print ("no item found, so emptied the list, numbers:\n",queue1.items) ``` Here we find the index location till where we should pop in the first loop, and then pop the queue till that index in the second loop, finally if the item to pop was not found in list we empty list in the third loop.
48,477,200
I'm having a problem trying to extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that. Instead, I get this error message, but I'm not able to solve it: ``` Traceback (most recent call last): File "python", line 45, in <module> IndexError: list index out of range ``` This is my current code: ``` class Queue(): def __init__(self): self.items = [] def empty(self): if self.items == []: return True else: return False def insert(self, value): self.items.append(value) def extract(self): try: return self.items.pop(0) except: raise ValueError("Empty queue") def last(self): if self.empty(): return None else: return self.items[0] import random def randomlist(n2,a2,b2): list = [0] * n2 for i in range(n2): list[i] = random.randint(a2,b2) return list queue1=Queue() for i in range (0,10): queue1.insert(randomlist(10,1,70)[i]) if queue1.empty()==False : print("These are the numbers of your queue:\n",queue1.items) test1=True while test1==True: s=(input("Input a number:\n")) if s.isdigit()==True : test1=False s2=int(s) else: print("Wrong, try again\n") for i in range (0,10) : if queue1.items[i]!=s2 : queue1.extract() elif queue1.items[i]==s2 : queue1.extract() print ("Remaining numbers:\n",queue1.items) break if queue1.empty()==True : print ("Queue is empty now", cola1.items) ```
2018/01/27
[ "https://Stackoverflow.com/questions/48477200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9147054/" ]
> > extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that. > > > ``` while not queue.empty(): if queue.extract() == target: print('Found! Remaining numbers:', queue.items) break else: print('Not found! Remaining numbers:', queue.items) ```
The test code operates from 0 to 10, but when you extract an element, that decreases the size of the queue. So if the queue is originally 10 element long, the index `i` you provide will eventually be `>=` the length of the queue. Hence an `IndexError`. Try one of the other suggested code segments.
50,151,490
I've been trying to send free sms using way2sms. I found this link where it seemed to work on python 3: <https://github.com/shubhamc183/way2sms> I've saved this file as way2sms.py: ``` import requests from bs4 import BeautifulSoup class sms: def __init__(self,username,password): ''' Takes username and password as parameters for constructors and try to log in ''' self.url='http://site24.way2sms.com/Login1.action?' self.cred={'username': username, 'password': password} self.s=requests.Session() # Session because we want to maintain the cookies ''' changing s.headers['User-Agent'] to spoof that python is requesting ''' self.s.headers['User-Agent']="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0" self.q=self.s.post(self.url,data=self.cred) self.loggedIn=False # a variable of knowing whether logged in or not if "http://site24.way2sms.com/main.action" in self.q.url: # http status 200 == OK print("Successfully logged in..!") self.loggedIn=True else: print("Can't login, once check credential..!") self.loggedIn=False self.jsid=self.s.cookies.get_dict()['JSESSIONID'][4:] # JSID is the main KEY as JSID are produced every time a session satrts def msgSentToday(self): ''' Returns number of SMS sent today as there is a limit of 100 messages everyday..! ''' if self.loggedIn == False: print("Can't perform since NOT logged in..!") return -1 self.msg_left_url='http://site24.way2sms.com/sentSMS?Token='+self.jsid self.q=self.s.get(self.msg_left_url) self.soup=BeautifulSoup(self.q.text,'html.parser') #we want the number of messages sent which is present in the self.t=self.soup.find("div",{"class":"hed"}).h2.text # div element with class "hed" -> h2 self.sent=0 for self.i in self.t: if self.i.isdecimal(): self.sent=10*self.sent+int(self.i) return self.sent def send(self,mobile_no,msg): ''' Sends the message to the given mobile number ''' if self.loggedIn == False: print("Can't perform since NOT logged in..!") return False if len(msg)>139 or len(mobile_no)!=10 or not mobile_no.isdecimal(): #checks whether the given message is of length more than 139 return False #or the mobile_no is valid self.payload={'ssaction':'ss', 'Token':self.jsid, #inorder to visualize how I came to these payload, 'mobile':mobile_no, #must see the NETWORK section in Inspect Element 'message':msg, #while messagin someone from your browser 'msgLen':'129' } self.msg_url='http://site24.way2sms.com/smstoss.action' self.q=self.s.post(self.msg_url,data=self.payload) if self.q.status_code==200: return True else: return False def sendLater(self, mobile_no, msg, date, time): #Function for future SMS feature. #date must be in dd/mm/yyyy format #time must be in 24hr format. For ex: 18:05 if self.loggedIn == False: print("Can't perform since NOT logged in..!") return False if len(msg)>139 or len(mobile_no)!=10 or not mobile_no.isdecimal(): return False dateparts = date.split('/') #These steps to check for valid date and time and formatting timeparts = time.split(':') if int(dateparts[0])<1 or int(dateparts[0])>32 or int(dateparts[1])>12 or int(dateparts[1])<1 or int(dateparts[2])<2017 or int(timeparts[0])<0 or int(timeparts[0])>23 or int(timeparts[1])>59 or int(timeparts[1])<0: return False date = dateparts[0].zfill(2) + "/" + dateparts[1].zfill(2) + "/" + dateparts[2] time = timeparts[0].zfill(2) + ":" + timeparts[1].zfill(2) self.payload={'Token':self.jsid, 'mobile':mobile_no, 'sdate':date, 'stime':time, 'message':msg, 'msgLen':'129' } self.msg_url='http://site24.way2sms.com/schedulesms.action' self.q=self.s.post(self.msg_url, data=self.payload) if self.q.status_code==200: return True else: return False def logout(self): self.s.get('http://site24.way2sms.com/entry?ec=0080&id=dwks') self.s.close() # close the Session self.loggedIn=False ``` And saved another file as smsing.py: ``` import way2sms q=way2sms.sms(1234567890,'password') #username = 1234567890 q.send('0987654321','hello') #receiver ph no.:0987654321, message=hello n=q.msgSentToday() q.logout() ``` -I've tried to pass username as string and otherwise. Password if not given as string shows error. My username and password both are correct. When I execute smsing.py... displays: ``` >>>Can't login, once check credential..! Can't perform since NOT logged in..! Can't perform since NOT logged in..! ``` With such simple code I thought it would be easy. But I am not able to find where I am going wrong. Is it because I am using Windows 7?? Can anybody please help me.?
2018/05/03
[ "https://Stackoverflow.com/questions/50151490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5250206/" ]
To send `sms` using `way2sms` account, you may use below code snippet. Before that you would be required to create an API `Key` from [here](https://smsapi.engineeringtgr.com/) ``` import requests url = "https://smsapi.engineeringtgr.com/send/" params = dict( Mobile='login username', Password='login password', Key='generated from above sms api', Message='Your message Here', To='recipient') resp = requests.get(url, params) print(resp, resp.text) ``` **N.B: There is a limit of approx 20 sms per day**
First of all make sure you have all the dependencies like requests and bs4, if not trying downloading them using pip3 since this code work on Python3 **not** python2. I have update the [repository](https://github.com/shubhamc183/way2sms). > > The mobilenumber should also be in String format > > > So, instead of ``` q=way2sms.sms(1234567890,'password') #username = 1234567890 ``` use ``` q=way2sms.sms('1234567890','password') #username = 1234567890 ```
50,151,490
I've been trying to send free sms using way2sms. I found this link where it seemed to work on python 3: <https://github.com/shubhamc183/way2sms> I've saved this file as way2sms.py: ``` import requests from bs4 import BeautifulSoup class sms: def __init__(self,username,password): ''' Takes username and password as parameters for constructors and try to log in ''' self.url='http://site24.way2sms.com/Login1.action?' self.cred={'username': username, 'password': password} self.s=requests.Session() # Session because we want to maintain the cookies ''' changing s.headers['User-Agent'] to spoof that python is requesting ''' self.s.headers['User-Agent']="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0" self.q=self.s.post(self.url,data=self.cred) self.loggedIn=False # a variable of knowing whether logged in or not if "http://site24.way2sms.com/main.action" in self.q.url: # http status 200 == OK print("Successfully logged in..!") self.loggedIn=True else: print("Can't login, once check credential..!") self.loggedIn=False self.jsid=self.s.cookies.get_dict()['JSESSIONID'][4:] # JSID is the main KEY as JSID are produced every time a session satrts def msgSentToday(self): ''' Returns number of SMS sent today as there is a limit of 100 messages everyday..! ''' if self.loggedIn == False: print("Can't perform since NOT logged in..!") return -1 self.msg_left_url='http://site24.way2sms.com/sentSMS?Token='+self.jsid self.q=self.s.get(self.msg_left_url) self.soup=BeautifulSoup(self.q.text,'html.parser') #we want the number of messages sent which is present in the self.t=self.soup.find("div",{"class":"hed"}).h2.text # div element with class "hed" -> h2 self.sent=0 for self.i in self.t: if self.i.isdecimal(): self.sent=10*self.sent+int(self.i) return self.sent def send(self,mobile_no,msg): ''' Sends the message to the given mobile number ''' if self.loggedIn == False: print("Can't perform since NOT logged in..!") return False if len(msg)>139 or len(mobile_no)!=10 or not mobile_no.isdecimal(): #checks whether the given message is of length more than 139 return False #or the mobile_no is valid self.payload={'ssaction':'ss', 'Token':self.jsid, #inorder to visualize how I came to these payload, 'mobile':mobile_no, #must see the NETWORK section in Inspect Element 'message':msg, #while messagin someone from your browser 'msgLen':'129' } self.msg_url='http://site24.way2sms.com/smstoss.action' self.q=self.s.post(self.msg_url,data=self.payload) if self.q.status_code==200: return True else: return False def sendLater(self, mobile_no, msg, date, time): #Function for future SMS feature. #date must be in dd/mm/yyyy format #time must be in 24hr format. For ex: 18:05 if self.loggedIn == False: print("Can't perform since NOT logged in..!") return False if len(msg)>139 or len(mobile_no)!=10 or not mobile_no.isdecimal(): return False dateparts = date.split('/') #These steps to check for valid date and time and formatting timeparts = time.split(':') if int(dateparts[0])<1 or int(dateparts[0])>32 or int(dateparts[1])>12 or int(dateparts[1])<1 or int(dateparts[2])<2017 or int(timeparts[0])<0 or int(timeparts[0])>23 or int(timeparts[1])>59 or int(timeparts[1])<0: return False date = dateparts[0].zfill(2) + "/" + dateparts[1].zfill(2) + "/" + dateparts[2] time = timeparts[0].zfill(2) + ":" + timeparts[1].zfill(2) self.payload={'Token':self.jsid, 'mobile':mobile_no, 'sdate':date, 'stime':time, 'message':msg, 'msgLen':'129' } self.msg_url='http://site24.way2sms.com/schedulesms.action' self.q=self.s.post(self.msg_url, data=self.payload) if self.q.status_code==200: return True else: return False def logout(self): self.s.get('http://site24.way2sms.com/entry?ec=0080&id=dwks') self.s.close() # close the Session self.loggedIn=False ``` And saved another file as smsing.py: ``` import way2sms q=way2sms.sms(1234567890,'password') #username = 1234567890 q.send('0987654321','hello') #receiver ph no.:0987654321, message=hello n=q.msgSentToday() q.logout() ``` -I've tried to pass username as string and otherwise. Password if not given as string shows error. My username and password both are correct. When I execute smsing.py... displays: ``` >>>Can't login, once check credential..! Can't perform since NOT logged in..! Can't perform since NOT logged in..! ``` With such simple code I thought it would be easy. But I am not able to find where I am going wrong. Is it because I am using Windows 7?? Can anybody please help me.?
2018/05/03
[ "https://Stackoverflow.com/questions/50151490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5250206/" ]
To send `sms` using `way2sms` account, you may use below code snippet. Before that you would be required to create an API `Key` from [here](https://smsapi.engineeringtgr.com/) ``` import requests url = "https://smsapi.engineeringtgr.com/send/" params = dict( Mobile='login username', Password='login password', Key='generated from above sms api', Message='Your message Here', To='recipient') resp = requests.get(url, params) print(resp, resp.text) ``` **N.B: There is a limit of approx 20 sms per day**
``` import requests url = "https://www.fast2sms.com/dev/bulk" payload = "sender_id=FSTSMS&message=Good morning , this is prasad sending from python.&language=english&route=p&numbers=9052766763,7013514480" headers = { 'authorization': "your app key", 'Content-Type': "application/x-www-form-urlencoded", 'Cache-Control': "no-cache", } response = requests.request("POST", url, data=payload, headers=headers) print(response.text) ```
38,885,431
I'm really stuck on this one, but I am a python (and Raspberry Pi) newbie. All I want is to output the `print` output from my python script. The problem is (I believe) that a function in my python script takes half a second to execute and PHP misses the output. This is my php script: ``` <?php error_reporting(E_ALL); ini_set('display_errors', 1); $cmd = escapeshellcmd('/var/www/html/weathertest.py'); $output = shell_exec($cmd); echo $output; //$handle = popen('/var/www/html/weathertest.py', 'r'); //$output = fread($handle, 1024); //var_dump($output); //pclose($handle); //$cmd = "python /var/www/html/weathertest.py"; //$var1 = system($cmd); //echo $var1; echo 'end'; ?> ``` I've included the commented blocks to show what else I've tried. All three output "static text end" This is the python script: ``` #!/usr/bin/env python import sys import Adafruit_DHT import time print 'static text ' humidity, temperature = Adafruit_DHT.read(11, 4) time.sleep(3) print 'Temp: {0:0.1f}C Humidity: {1:0.1f}%'.format(temperature, humidity) ``` The py executes fine on the command line. I've added the 3 second delay to make the script feel longer for my own testing. Given that I always get `static text` as an output, I figure my problem is with PHP not waiting for the Adafruit command. BUT the STRANGEST thing for me is that all three of my PHP attempts work correctly if I execute the PHP script on the command line i.e. `php /var/www/html/test.php` - I then get the desired output: ``` static text Temp: 23.0C Humidity 34.0% end ``` So I guess there's two questions: 1. How to make PHP wait for Python completion. 2. Why does the PHP command line differ from the browser?
2016/08/11
[ "https://Stackoverflow.com/questions/38885431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066625/" ]
Following code example may help you understand what you need to do: 1. Create an array of index paths 2. Add the 20 data objects which you received from the server in your data source. 3. Now since your data source and array of index paths are on the same page, begin table view updates and insert the rows. That's it. :) Created a dummy project to answer. When you run the project and scroll, you'll see that the rows are added dynamically. <https://github.com/harsh62/stackoverflow_insert_dynamic_rows> ``` func insertRows() { let newData = ["Steve", "Bill", "Linus", "Bret"] let olderCount: Int = self.names.count names += newData var indexPaths = [NSIndexPath]() for i in 0..<newData.count {//hardcoded 20, this should be the number of new results received indexPaths.append(NSIndexPath(forRow: olderCount + i, inSection: 0)) } // tell the table view to update (at all of the inserted index paths) self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Top) self.tableView.endUpdates() } ```
When you call `insertRowsAtIndexPaths`, the number of row present in your data source must be equal to the previous count plus the number of rows being inserted. But you appear to be inserting one `NSIndexPath` in the table, but your `names` array presumably has 20 more items. So, make sure that the number of `NSIndexPath` items in the array passed to `insertRowsAtIndexPaths` is equal to the number of rows that have been added to `names`.
67,039,337
Here's my [small CSV file](https://github.com/gusbemacbe/aparecida-covid-19-tracker/blob/main/data/aparecida-small-sample.csv), which is totally encoded in UTF-8, and the date is totally correct. I repaired the erros from: * [Is there a function to get the difference between two values on a pandas dataframe timeseries?](https://stackoverflow.com/questions/63488407/is-there-a-function-to-get-the-difference-between-two-values-on-a-pandas-datafra) * [I can't convert the Pandas Dataframe type to datetime](https://stackoverflow.com/questions/50415981/i-cant-convert-the-pandas-dataframe-type-to-datetime) * [Pandas Python: KeyError Date](https://stackoverflow.com/questions/59617059/pandas-python-keyerror-date) ```py import datetime import altair as alt import operator import pandas as pd s = pd.read_csv('data/aparecida-small-sample.csv', parse_dates=['date']) city = s[s['city'] == 'Aparecida'] base = alt.Chart(city).mark_bar().encode(x = 'date').properties(width = 500) confirmed = alt.value("#106466") death = alt.value("#D8B08C") recovered = alt.value("#87C232") # Convert to date s['date'] = pd.to_datetime(s['date']) s = s.set_index('date') # Take `totalCases` value from CSV file, to differentiate new cases between each 2 days cases = s['totalCases'].resample('2d', on='date').last().diff() # Load the chart base.encode(y = cases, color = confirmed).properties(title = "Daily new cases") ``` The error was `KeyError: Date` which appointed `s['date'] = pd.to_datetime(s['date'])`, which is totally correct. I do not know why it insists it is incorrect. The entire error message: ``` KeyError: 'date' --------------------------------------------------------------------------- KeyError Traceback (most recent call last) /usr/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3079 try: -> 3080 return self._engine.get_loc(casted_key) 3081 except KeyError as err: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'date' The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) <ipython-input-37-df3f26429754> in <module> ----> 1 s['date'] = pd.to_datetime(s['date']) 2 s = s.set_index('date') 3 4 # s.groupby(['date'])[['totalCases']].resample('2d').last().diff() 5 cases = s['totalCases'].resample('2d', on='date').last().diff() /usr/lib/python3.9/site-packages/pandas/core/frame.py in __getitem__(self, key) 3022 if self.columns.nlevels > 1: 3023 return self._getitem_multilevel(key) -> 3024 indexer = self.columns.get_loc(key) 3025 if is_integer(indexer): 3026 indexer = [indexer] /usr/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3080 return self._engine.get_loc(casted_key) 3081 except KeyError as err: -> 3082 raise KeyError(key) from err 3083 3084 if tolerance is not None: KeyError: 'date' ``` Another error message after correcting `full_grouped` to `s`; ``` KeyError: 'The grouper name date is not found' --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-3-df3f26429754> in <module> 3 4 # s.groupby(['date'])[['totalCases']].resample('2d').last().diff() ----> 5 cases = s['totalCases'].resample('2d', on='date').last().diff() 6 # cases = s.groupby(['date'])[['totalCases']].resample('2d', on='date').last().diff() 7 /usr/lib/python3.9/site-packages/pandas/core/generic.py in resample(self, rule, axis, closed, label, convention, kind, loffset, base, on, level, origin, offset) 8367 8368 axis = self._get_axis_number(axis) -> 8369 return get_resampler( 8370 self, 8371 freq=rule, /usr/lib/python3.9/site-packages/pandas/core/resample.py in get_resampler(obj, kind, **kwds) 1309 """ 1310 tg = TimeGrouper(**kwds) -> 1311 return tg._get_resampler(obj, kind=kind) 1312 1313 /usr/lib/python3.9/site-packages/pandas/core/resample.py in _get_resampler(self, obj, kind) 1464 1465 """ -> 1466 self._set_grouper(obj) 1467 1468 ax = self.ax /usr/lib/python3.9/site-packages/pandas/core/groupby/grouper.py in _set_grouper(self, obj, sort) 363 else: 364 if key not in obj._info_axis: --> 365 raise KeyError(f"The grouper name {key} is not found") 366 ax = Index(obj[key], name=key) 367 KeyError: 'The grouper name date is not found' ```
2021/04/10
[ "https://Stackoverflow.com/questions/67039337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8041366/" ]
Based on your posted code I made some changes: 1. I have put in a print statement for the DataFrame after read. This should show the datatypes for each column in the DataFrame. For the date - field it should be "datetime64[ns]". 2. Afterwards you don't have to parse it again as a date. 3. Some code changes for the "cases" - field and to visualize it. ```py import datetime import altair as alt import operator import pandas as pd s = pd.read_csv('./data/aparecida-small-sample.csv', parse_dates=['date']) print(s.dtypes) confirmed = alt.value("#106466") death = alt.value("#D8B08C") recovered = alt.value("#87C232") # Take `totalCases` value from CSV file, to differentiate new cases between each 2 days city = s[s['city'] == 'Aparecida'] # Append dataframe with the new information city['daily_cases'] = city['totalCases'].diff() # Initiate chart with data base = alt.Chart(city).mark_point().encode( alt.X('date:T'), alt.Y('daily_cases:Q') ) # Load the chart base.properties(title = "Daily new cases") ``` The results of the code changes: [![enter image description here](https://i.stack.imgur.com/Hy0Ka.png)](https://i.stack.imgur.com/Hy0Ka.png)
@Gustavo Reis according to your question in the answered segment: ```py city['daily_cases'] = city['totalCases'] city['daily_deaths'] = city['totalDeaths'] city['daily_recovered'] = city['totalRecovered'] tempCityDailyCases = city[['date','daily_cases']] tempCityDailyCases["title"] = "Daily Cases" tempCityDailyDeaths = city[['date','daily_deaths']] tempCityDailyDeaths["title"] = "Daily Deaths" tempCityDailyRecovered = city[['date','daily_recovered']] tempCityDailyRecovered["title"] = "Daily Recovered" tempCity = tempCityDailyCases.append(tempCityDailyDeaths) tempCity = tempCity.append(tempCityDailyRecovered) ## Initiate chart with data totalCases = alt.Chart(tempCity).mark_bar().encode(alt.X('date:T', title=None), alt.Y('daily_cases:Q', title = None)) # color='#106466' totalDeaths = alt.Chart(tempCity).mark_bar().encode(alt.X('date:T', title=None), alt.Y('daily_deaths:Q', title = None)) # color = '#DC143C' totalRecovered = alt.Chart(tempCity).mark_bar().encode(alt.X('date:T', title=None), alt.Y('daily_recovered:Q', title = None)) # color = '#87C232' (totalCases + totalRecovered + totalDeaths).encode(color=alt.Color('title', scale=alt.Scale(range=['#106466','#DC143C','#87C232']), legend=alt.Legend(title="Art of cases") )).properties(title = "New total toll", width = 800) ``` [![enter image description here](https://i.stack.imgur.com/2u7sh.png)](https://i.stack.imgur.com/2u7sh.png)
42,015,768
How would I modify this program so that my list doesn't keep spitting out the extra text per line? The program should only output the single line that the user wants to display rather than the quotes that were added to the list before. The program will read a textfile indicated by the user, then it will display the selected line for the user and exit up a '0' input. This is in python ``` import string count = 0 #reads file def getFile(): while True: inName = input("Please enter file name: ") try: inputFile = open(inName, 'r') except: print ("I cannot open that file. Please try again.") else: break return inputFile inputFile = getFile() inputList = inputFile.readlines() for line in inputList: count = count + 1 print("There are", count, "lines.") while True: lineChoice = int(input("Please select line[0 to exit]: ")) if lineChoice == 0: break elif lineChoice > 0 and lineChoice <= count: print(inputList[:lineChoice - 1]) else: print("Invalid selection[0 to exit]") ``` Output: ``` Please enter file name: quotes.txt There are 16 lines. Please select line[0 to exit]: 1 [] Please select line[0 to exit]: 2 ['Hakuna Matata!\n'] Please select line[0 to exit]: 3 ['Hakuna Matata!\n', 'All our dreams can come true, if we have the courage to pursue them.\n'] Please select line[0 to exit]: ```
2017/02/03
[ "https://Stackoverflow.com/questions/42015768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151347/" ]
As far as disk storage and ram memory are concerned, `'\n` is just another character. As far as tcl/tk and Python's `tkinter` wrapper are concerned, newlines are very important. Since tk's Text widget is intended to display text to humans, and since vertical scrolling is much more useful for this than horizontal scrolling, it is optimized for the former. A hundred 1000 char lines (100,000 chars total) bogs down vertical scrolling, whereas 300,000 50 char lines (15,000,000 chars total) is no problem. IDLE uses `tkinter` and the main windows are based on tk's Text widget. So if you to view text in IDLE, keep lines lengths sensible. I do not know about other IDEs that use other GUI frameworks. But even if they handle indefinitely long lines better, horizontal scrolling of a 100000 char line is pretty obnoxious.
You shouldn't have to worry about a limit. As for a new line, you can use an `if` with `\n` or a `for` loop depending on what you're going for.
42,015,768
How would I modify this program so that my list doesn't keep spitting out the extra text per line? The program should only output the single line that the user wants to display rather than the quotes that were added to the list before. The program will read a textfile indicated by the user, then it will display the selected line for the user and exit up a '0' input. This is in python ``` import string count = 0 #reads file def getFile(): while True: inName = input("Please enter file name: ") try: inputFile = open(inName, 'r') except: print ("I cannot open that file. Please try again.") else: break return inputFile inputFile = getFile() inputList = inputFile.readlines() for line in inputList: count = count + 1 print("There are", count, "lines.") while True: lineChoice = int(input("Please select line[0 to exit]: ")) if lineChoice == 0: break elif lineChoice > 0 and lineChoice <= count: print(inputList[:lineChoice - 1]) else: print("Invalid selection[0 to exit]") ``` Output: ``` Please enter file name: quotes.txt There are 16 lines. Please select line[0 to exit]: 1 [] Please select line[0 to exit]: 2 ['Hakuna Matata!\n'] Please select line[0 to exit]: 3 ['Hakuna Matata!\n', 'All our dreams can come true, if we have the courage to pursue them.\n'] Please select line[0 to exit]: ```
2017/02/03
[ "https://Stackoverflow.com/questions/42015768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151347/" ]
As far as disk storage and ram memory are concerned, `'\n` is just another character. As far as tcl/tk and Python's `tkinter` wrapper are concerned, newlines are very important. Since tk's Text widget is intended to display text to humans, and since vertical scrolling is much more useful for this than horizontal scrolling, it is optimized for the former. A hundred 1000 char lines (100,000 chars total) bogs down vertical scrolling, whereas 300,000 50 char lines (15,000,000 chars total) is no problem. IDLE uses `tkinter` and the main windows are based on tk's Text widget. So if you to view text in IDLE, keep lines lengths sensible. I do not know about other IDEs that use other GUI frameworks. But even if they handle indefinitely long lines better, horizontal scrolling of a 100000 char line is pretty obnoxious.
To answer your question, no, there's no limit on the length of the dictionary or list (or any other object). I've stored all the words of an entire book in a list. They are just streams of input. As far as how your code is written, it's not Pythonic to write beyond 80 characters/columns per line, because, ultimately, humans must read it. But if it makes you feel any better, you can break dictionaries and lists up onto multiple lines, and even leave comments between the items: ``` >>> my_dict = {'a': 1, # comment 1 'b': 2, # comment 2 'c': 3, # comment 3 'd': 4 } ``` You can also break any statement with a backslash: ``` >>> my_string = "my \ string" >>> print(my_string) 'my string' ``` Lastly, you can use triple quotes for very long strings, that may span multiple lines. Note, newlines will be included in your string. ``` >>> my_very_long_string = '''This is a long string. Rather than using multiple print statements, I only used one.''' >>> print(my_very_long_string) 'This is a long string.\nRather than using multiple print statements,\nI only used one.' ``` In the last (multi-line string) example, this is how a "file" (stream) actually looks when it is not being formatted to be presented on multiple lines in an editor.
49,658,679
I have a nested json and i want to find a record whose value is equal to a given number. I'm using pymongo in python wih equal operator but getting some errors: ``` from pymongo import MongoClient import datetime import json import pprint def connectDatabase(service): try: if service=="mongodb": host = 'mongodb://connecion_string.mlab.com:31989' database = 'xxx' user = 'xxx' password = 'xxx' client = MongoClient(host) client.xxx.authenticate(user, password, mechanism='SCRAM-SHA-1') db = client.xxx new_posts = [{"author": "Mike", "text": "Another post!", "tags": [ { "CSPAccountNo": "414693" }, { "CSPAccountNo": "349903" }] }] result=db.posts1.insert_many(new_posts) print (xxx.posts1.find( {"CSPAccountNo": { $eq: "414693" } } ) except Exception as e: print(e) pass print (connectDatabase("mongodb")) ``` Error: ``` File "mongo.py", line 35 print (cstore.posts1.find( {"CSPAccountNo": { $eq: "414693" } } ) ^ SyntaxError: invalid syntax ``` I'm very new to Mongodb. Any help would be appreciated
2018/04/04
[ "https://Stackoverflow.com/questions/49658679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7422128/" ]
In Python you have to use Python syntax, not JS syntax like in the Mongo shell. That means that dictionary keys need quotes: ``` print(cstore.posts1.find( {"CSPAccountNo": { "$eq": "414693" } } ) ``` (Note, in your code you never actually insert the `new_posts` into the collection, so your find call might not actually find anything.)
It should be ``` print (xxx.posts1.find( {"tags.CSPAccountNo": { $eq: "414693" } } ) ```
60,928,238
I'm using selenium in python and I'm looking to select the option Male from the below: ``` <div class="formelementcontent"> <select aria-disabled="false" class="Width150" id="ctl00_Gender" name="ctl00$Gender" onchange="javascript: return doSearch();" style="display: none;"> <option selected="selected" title="" value=""> </option> <option title="Male" value="MALE"> Male </option> <option title="Female" value="FEM"> Female </option> </select> ``` Before selecting from the dropdown, I need to switch to iframe ``` driver.switch_to.frame(iframe) ``` I've tried many options and searched extensively. This gets me most of the way. ``` driver.find_element_by_id("ctl00_Gender-button").click() WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "ctl00_Gender"))) select=Select(driver.find_element_by_id("ctl00_Gender")) check=select.select_by_visible_text('Male') ``` If I use WebDriverWait it times out. I've tried selecting by visible text and index, both give: > > ElementNotInteractableException: Element could not be scrolled into view > > >
2020/03/30
[ "https://Stackoverflow.com/questions/60928238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11483107/" ]
As per the HTML you have shared the `<select>` tag is having the value of *style* attribute set as **`display: none;`**. So using [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) it would be tough interacting with this [WebElement](https://stackoverflow.com/questions/52782684/what-is-the-difference-between-webdriver-and-webelement-in-selenium/52805139#52805139). If you access the [DOM Tree](https://javascript.info/dom-nodes) of the webpage through [google-chrome-devtools](/questions/tagged/google-chrome-devtools "show questions tagged 'google-chrome-devtools'"), presumably you will find a couple of `<li>` nodes equivalent to the `<option>` nodes within an `<ul>` node. You may be required to interact with those. You can find find a couple of relevant detailed discussions in: * [select kendo dropdown using selenium python](https://stackoverflow.com/questions/58767150/select-kendo-dropdown-using-selenium-python/58767346#58767346) * [How to test non-standard drop down lists through a crawler using Selenium and Python](https://stackoverflow.com/questions/44224924/how-to-test-non-standard-drop-down-lists-through-a-crawler-using-selenium-and-py/44235532#44235532) * [How to select an option from a dropdown of non select tag?](https://stackoverflow.com/questions/57399713/how-to-select-an-option-from-a-dropdown-of-non-select-tag/57402060#57402060)
Try below solutions: **Solution 1:** ``` select = Select(driver.find_element_by_id('ctl00_Gender')) select.select_by_value('MALE') ``` **Note** add below imports to your solution : ``` from selenium.webdriver.support.ui import Select ``` **Solution 2:** ``` driver.find_element_by_xpath("//select[@id='ctl00_Gender']/option[text()='Male']").click() ```
52,672,810
I have a Node.js API using Express.js with body parser which receives a BSON binary file from a python client. Python client code: ``` data = bson.BSON.encode({ "some_meta_data": 12, "binary_data": binary_data }) headers = {'content-type': 'application/octet-stream'} response = requests.put(endpoint_url, headers=headers, data=data) ``` Now I have an endpoint in my Node.js API where I want to deserialize the BSON data as explained in the documentation: <https://www.npmjs.com/package/bson>. What I am struggling with is how to get the binary BSON file from the request. Here is the API endpoint: ``` exports.updateBinary = function(req, res){ // How to get the binary data which bson deserializes from the req? let bson = new BSON(); let data = bson.deserialize(???); ... } ```
2018/10/05
[ "https://Stackoverflow.com/questions/52672810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531894/" ]
You'll want to use <https://www.npmjs.com/package/raw-body> to grab the raw contents of the body. And then pass the [`Buffer`](https://nodejs.org/api/buffer.html) object to `bson.deserialize(..)`. Quick dirty example below: ``` const getRawBody = require("raw-body"); app.use(async (req, res, next) => { if (req.headers["content-type"] === "application/octet-stream") { req.body = await getRawBody(req) } next() }) ``` Then just simply do: ``` exports.updateBinary = (req, res) => { const data = new BSON().deserialize(req.body) } ```
You could as well use the [body-parser](https://github.com/expressjs/body-parser) package: ``` const bodyParser = require('body-parser') app.use(bodyParser.raw({type: 'application/octet-stream', limit : '100kb'})) app.use((req, res, next) => { if (Buffer.isBuffer(req.body)) { req.body = JSON.parse(req.body) } }) ```
73,428,442
I need to get the absolute path of a file in python, i already tried `os.path.abspath(filename)` in my code like this: ```py def encrypt(filename): with open(filename, 'rb') as toencrypt: content = toencrypt.read() content = Fernet(key).encrypt(content) with open(filename, "wb") as toencrypt: toencrypt.write(content) def checkfolder(folder): for file in os.listdir(folder): fullpath = os.path.abspath(file) if file != "decrypt.py" and file != "encrypt.py" and file != "key.txt" and not os.path.isdir(file): print(fullpath) encrypt(fullpath) elif os.path.isdir(file) and not file.startswith("."): checkfolder(fullpath) ``` the problem is that `os.path.abspath(filename)` doesn't really get the absolute path, it just attach the current working directory to the filename which in this case is completely useless. how can i do this?
2022/08/20
[ "https://Stackoverflow.com/questions/73428442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19400931/" ]
If you want to control something over time in Pygame you have two options: 1. Use [`pygame.time.get_ticks()`](https://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks) to measure time and and implement logic that controls the object depending on the time. 2. Use the timer event. Use [`pygame.time.set_timer()`](https://www.pygame.org/docs/ref/time.html#pygame.time.set_timer) to repeatedly create a [`USEREVENT`](https://www.pygame.org/docs/ref/event.html) in the event queue. Change object states when the event occurs. For a timer event you need to define a unique user events id. The ids for the user events have to be between `pygame.USEREVENT` (24) and `pygame.NUMEVENTS` (32). In this case `pygame.USEREVENT+1` is the event id for the timer event. Receive the event in the event loop: ```py def spawn_ship(): # [...] def main(): spawn_ship_interval = 5000 # 5 seconds spawn_ship_event_id = pygame.USEREVENT + 1 # 1 is just as an example pygame.time.set_timer(spawn_ship_event_id, spawn_ship_interval) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == spawn_ship_event_id: spawn_ship() ``` Also see [Spawning multiple instances of the same object concurrently in python](https://stackoverflow.com/questions/62112754/spawning-multiple-instances-of-the-same-object-concurrently-in-python/62112894#62112894) and [How to run multiple while loops at a time in Pygame](https://stackoverflow.com/questions/65263318/how-to-run-multiple-while-loops-at-a-time-in-pygame/65263396#65263396).
You could try making spawn\_ship async, then use a thread so it doesn't affect the main loop ```py import threading def main(): threading.Timer(5.0, spawn_ship).start() async def spawn_ship(): # ... ```
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match. Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together.
What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all. (Personally I use a separate form-reading library, data access layer and template engine, none of which know about each other or need to start fiddling with the WSGI `environ`.)
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used. nginx/fcgi is the fastest, but its a bit of a headache.
"it seems too simple when working with a number of middleware packages." How big a number? You won't be working with hundreds or thousands. It will be (a) a small number (under a dozen) and (b) the "right" order isn't magical. Each piece of middleware will have a very, very specific job and very specific requirements for what must come before it. It's much less confusing than you're assuming.
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used. nginx/fcgi is the fastest, but its a bit of a headache.
If you liked the Do-It-Yourself-Framework tutorial mentioned before, but you want to manage these things in a config file, [Paste Deploy](http://pythonpaste.org/deploy/) would be the obvious answer. (It is mentioned in the tutorial, but only very briefly in the very last paragraph). This is what the Pylons framework uses, by the way (and Turbogears 2, which is built upon Pylons, also).
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all. (Personally I use a separate form-reading library, data access layer and template engine, none of which know about each other or need to start fiddling with the WSGI `environ`.)
"it seems too simple when working with a number of middleware packages." How big a number? You won't be working with hundreds or thousands. It will be (a) a small number (under a dozen) and (b) the "right" order isn't magical. Each piece of middleware will have a very, very specific job and very specific requirements for what must come before it. It's much less confusing than you're assuming.
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match. Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together.
My advice is to read the [PEP](http://www.python.org/dev/peps/pep-0333/) on WSGI, specifically the part on [middleware](http://www.python.org/dev/peps/pep-0333/#middleware-components-that-play-both-sides). If you have a question about anything with the words "standard" and "WSGI" in it, the answer is either there, or you're asking the wrong question.
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match. Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together.
If you liked the Do-It-Yourself-Framework tutorial mentioned before, but you want to manage these things in a config file, [Paste Deploy](http://pythonpaste.org/deploy/) would be the obvious answer. (It is mentioned in the tutorial, but only very briefly in the very last paragraph). This is what the Pylons framework uses, by the way (and Turbogears 2, which is built upon Pylons, also).
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match. Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together.
I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used. nginx/fcgi is the fastest, but its a bit of a headache.
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all. (Personally I use a separate form-reading library, data access layer and template engine, none of which know about each other or need to start fiddling with the WSGI `environ`.)
If you liked the Do-It-Yourself-Framework tutorial mentioned before, but you want to manage these things in a config file, [Paste Deploy](http://pythonpaste.org/deploy/) would be the obvious answer. (It is mentioned in the tutorial, but only very briefly in the very last paragraph). This is what the Pylons framework uses, by the way (and Turbogears 2, which is built upon Pylons, also).
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used. nginx/fcgi is the fastest, but its a bit of a headache.
My advice is to read the [PEP](http://www.python.org/dev/peps/pep-0333/) on WSGI, specifically the part on [middleware](http://www.python.org/dev/peps/pep-0333/#middleware-components-that-play-both-sides). If you have a question about anything with the words "standard" and "WSGI" in it, the answer is either there, or you're asking the wrong question.
1,633,342
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application. I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand. Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use: `Spawning-->memento-->AuthKit-->(?)-->MyApp` how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`? So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application? **Edit** Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on: ``` app = ObjectPublisher(Root()) wrapped_app = AuthMiddleware(app) from paste.evalexception import EvalException exc_wrapped_app = EvalException(wrapped_app) ``` Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages. **Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?**
2009/10/27
[ "https://Stackoverflow.com/questions/1633342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match. Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together.
"it seems too simple when working with a number of middleware packages." How big a number? You won't be working with hundreds or thousands. It will be (a) a small number (under a dozen) and (b) the "right" order isn't magical. Each piece of middleware will have a very, very specific job and very specific requirements for what must come before it. It's much less confusing than you're assuming.
32,295,943
I am trying to sort a list in python with integers and a float using "a.sort([1])" (I am sorting it from the second element of the list) but it keeps on saying "TypeError: must use keyword argument for key function". What should I do? Also my list looks like this: ["bob","2","6","8","5.3333333333333"]
2015/08/30
[ "https://Stackoverflow.com/questions/32295943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4464968/" ]
[Paul's answer](https://stackoverflow.com/a/32296030/21945) does a nice job of explaining how to use `sort` correctly. I want to point out, however, that sorting strings of numbers is not the same as sorting numeric values (ints and floats etc.). Sorting by strings will use character collating sequence to determine the order, e.g. ``` >>> l = ['100','1','2','99'] >>> sorted(l) ['1', '100', '2', '99'] ``` but this is probably not what you want; 100 is greater than 2 and so should appear further back in the list than 2. You can sort by numeric value, but retain strings for the list items using the `key` parameter to `sort()`: ``` >>> sorted(l, key=lambda x: float(x)) ['1', '2', '99', '100'] ``` Here the `key` is a lambda function that converts its argument to a float. The `sort()` routine will use the converted value as the sort key, not the string value that is actually contained in the list. To sort from the second list item on, do this: ``` >>> a = ["bob", "2", "6", "8", "5.3333333333333"] >>> a[1:] = sorted(a[1:], key=lambda x: float(x)) >>> a ['bob', '2', '5.3333333333333', '6', '8'] ```
try to do "a.sort()". it will sort your list. sort cant get 1 as argument. read more here: <http://www.tutorialspoint.com/python/list_sort.htm> if you trying to sort every element except the first one try to do: ``` a[1:] = sorted(a[1:]) ```
66,831,049
I am trying to document the Reports, Visuals and measures used in a PBIX file. I have a PBIX file(containing some visuals and pointing to Tabular Model in Live Mode), I then exported it as a PBIT, renamed to zip. Now in this zip file we have a folder called Report, within that we have a file called Layout. The layout file looks like a JSON file but when I try to read it via python, ``` import json # Opening JSON file f = open("C://Layout",) # returns JSON object as # a dictionary #f1 = str.replace("\'", "\"") data = json.load(f) ``` I get below issue, ``` JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) ``` Renaming it to Layout.json doesn't help either and gives the same issue. Is there a easy way or a parser to specifically parse this Layout file and get below information out of it ``` Report Name | Visual Name | Column or Measure Name ```
2021/03/27
[ "https://Stackoverflow.com/questions/66831049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6668031/" ]
Not sure if you have come across an answer for your question yet, but I have been looking into something similar. Here is what I have had to do in order to get the file to parse correctly. Big items here to not is the encoding and all the whitespace replacements. data will then contain the parsed object. ``` with open('path/to/Layout', 'r', encoding="cp1252") as json_file: data_str = json_file.read().replace(chr(0), "").replace(chr(28), "").replace(chr(29), "").replace(chr(25), "") data = json.loads(data_str) ```
This script may help: <https://github.com/grenzi/powerbi-model-utilization> a portion of the script is: ``` def get_layout_from_pbix(pbixpath): """ get_layout_from_pbix loads a pbix file, grabs the layout from it, and returns json :parameter pbixpath: file to read :return: json goodness """ archive = zipfile.ZipFile(pbixpath, 'r') bytes_read = archive.read('Report/Layout') s = bytes_read.decode('utf-16-le') json_obj = json.loads(s, object_hook=parse_pbix_embedded_json) return json_obj ```
48,097,949
Hi am running the following model with statsmodel and it works fine. ``` from statsmodels.formula.api import ols from statsmodels.iolib.summary2 import summary_col #for summary stats of large tables time_FE_str = ' + C(hour_of_day) + C(day_of_week) + C(week_of_year)' weather_2_str = ' + C(weather_index) + rain + extreme_temperature + wind_speed' model = ols("activity_count ~ C(city_id)"+weather_2_str+time_FE_str, data=df) results = model.fit() print summary_col(results).tables print 'F-TEST:' hypotheses = '(C(weather_index) = 0), (rain=0), (extreme_temperature=0), (wind_speed=0)' f_test = results.f_test(hypotheses) ``` However, I do not know how to formulate the hypthosis for the F-test if I want to include the categorical variable `C(weather_index)`. I tried all for me imaginable versions but I always get an error. Did someone face this issue before? Any ideas? ``` F-TEST: Traceback (most recent call last): File "C:/VK/scripts_python/predict_activity.py", line 95, in <module> f_test = results.f_test(hypotheses) File "C:\Users\Niko\Anaconda2\envs\gl-env\lib\site-packages\statsmodels\base\model.py", line 1375, in f_test invcov=invcov, use_f=True) File "C:\Users\Niko\Anaconda2\envs\gl-env\lib\site-packages\statsmodels\base\model.py", line 1437, in wald_test LC = DesignInfo(names).linear_constraint(r_matrix) File "C:\Users\Niko\Anaconda2\envs\gl-env\lib\site-packages\patsy\design_info.py", line 536, in linear_constraint return linear_constraint(constraint_likes, self.column_names) File "C:\Users\Niko\Anaconda2\envs\gl-env\lib\site-packages\patsy\constraint.py", line 391, in linear_constraint tree = parse_constraint(code, variable_names) File "C:\Users\Niko\Anaconda2\envs\gl-env\lib\site-packages\patsy\constraint.py", line 225, in parse_constraint return infix_parse(_tokenize_constraint(string, variable_names), File "C:\Users\Niko\Anaconda2\envs\gl-env\lib\site-packages\patsy\constraint.py", line 184, in _tokenize_constraint Origin(string, offset, offset + 1)) patsy.PatsyError: unrecognized token in constraint (C(weather_index) = 0), (rain=0), (extreme_temperature=0), (wind_speed=0) ^ ```
2018/01/04
[ "https://Stackoverflow.com/questions/48097949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7969556/" ]
The methods t\_test, wald\_test and f\_test are for hypothesis test on the parameters directly and not for a entire categorical or composite effect. Results.summary() shows the parameter names that patsy created for the categorical variables. Those can be used to create contrast or restrictions for the categorical effects. As alternative anova\_lm directly computes the hypothesis test that a term,e.g. A categorical variable has no effect.
Leave out the `C()`! I tried making an analysis of these data. ``` Area Clover_yield Yarrow_stems A 19.0 220 A 76.7 20 A 11.4 510 A 25.1 40 A 32.2 120 A 19.5 300 A 89.9 60 A 38.8 10 A 45.3 70 A 39.7 290 B 16.5 460 B 1.8 320 B 82.4 0 B 54.2 80 B 27.4 0 B 25.8 450 B 69.3 30 B 28.7 250 B 52.6 20 B 34.5 100 C 49.7 0 C 23.3 220 C 38.9 160 C 79.4 0 C 53.2 120 C 30.1 150 C 4.0 450 C 20.7 240 C 29.8 250 C 68.5 0 ``` When I used the linear model in the first call to `ols` shown in the code I eventually ran into the snag you experienced. However, when I omitted mention of the fact that *Area* assumes discrete levels I was able to calculate F-tests on contrasts. ``` import pandas as pd from statsmodels.formula.api import ols df = pd.read_csv('clover.csv', sep='\s+') model = ols('Clover_yield ~ C(Area) + Yarrow_stems', data=df) model = ols('Clover_yield ~ Area + Yarrow_stems', data=df) results = model.fit() print (results.summary()) print (results.f_test(['Area[T.B] = Area[T.C], Yarrow_stems=150'])) ``` Here is the output. Notice that, the summary indicates the names that can be used in formulating contrasts for factors, in our case `Area[T.B]` and `Area[T.C]`. ``` OLS Regression Results ============================================================================== Dep. Variable: Clover_yield R-squared: 0.529 Model: OLS Adj. R-squared: 0.474 Method: Least Squares F-statistic: 9.726 Date: Thu, 04 Jan 2018 Prob (F-statistic): 0.000177 Time: 17:26:03 Log-Likelihood: -125.61 No. Observations: 30 AIC: 259.2 Df Residuals: 26 BIC: 264.8 Df Model: 3 Covariance Type: nonrobust ================================================================================ coef std err t P>|t| [0.025 0.975] -------------------------------------------------------------------------------- Intercept 57.5772 6.337 9.086 0.000 44.551 70.603 Area[T.B] 0.3205 7.653 0.042 0.967 -15.411 16.052 Area[T.C] -0.5432 7.653 -0.071 0.944 -16.274 15.187 Yarrow_stems -0.1086 0.020 -5.401 0.000 -0.150 -0.067 ============================================================================== Omnibus: 0.459 Durbin-Watson: 2.312 Prob(Omnibus): 0.795 Jarque-Bera (JB): 0.449 Skew: 0.260 Prob(JB): 0.799 Kurtosis: 2.702 Cond. No. 766. ============================================================================== Warnings: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. <F test: F=array([[ 27873807.59795523]]), p=4.939796675253845e-83, df_denom=26, df_num=2> ``` As mentioned in my comment, I'm not clear what you intended to test. **Edit**: Prompted by user333700's comment, I've tried running this code again, with two slighly different statements, `model = ols('Clover_yield ~ C(Area) + Yarrow_stems', data=df)` and `print (results.f_test(['C(Area)[T.B] = C(Area)[T.C], Yarrow_stems=150']))`. 'C(Area)[T.B]' and 'C(Area)[T.C]' came from the summary with the changed model. Thus, it doesn't matter, for this type of analysis, whether you declare with C() or not. You must simply remember to use the appropriate form for the dummy variables, as mentioned in the summary.
8,919,080
This is what my problem is: I need to make a random string 50 characters long, made up of `1`s and `0`s. I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know([1](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), [2](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), etc). But what I really want is **the most** Pythonic way of doing this. Currently, I'm leaning towards `''.join(( random.choice([0,1]) for i in xrange(50) ))` Is there a more pythonic way of doing this? Is there a built-in that does something like this, perhaps in `itertools`?
2012/01/18
[ "https://Stackoverflow.com/questions/8919080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198633/" ]
For Python2.7 or better: ``` In [83]: import random In [84]: '{:050b}'.format(random.randrange(1<<50)) Out[84]: '10011110110110000011111000011100101111101001001011' ``` (In Python2.6, use `'{0:050b}'` instead of `'{:050b}'`.) --- **Explanation**: The `string.format` method can convert integers into their binary string representations. The basic format code to do this is `'{:b}'`: ``` In [91]: '{:b}'.format(10) Out[91]: '1010' ``` To make a string of width 50, use the format code `'{:50b}'`: ``` In [92]: '{:50b}'.format(10) Out[92]: ' 1010' ``` and to fill in the whitespace with zeros, use `{:050b}`: ``` In [93]: '{:050b}'.format(10) Out[93]: '00000000000000000000000000000000000000000000001010' ``` The [syntax for str.format](http://docs.python.org/library/string.html#format-string-syntax) is a bit daunting at first. Here is my cheat sheet: ``` http://docs.python.org/library/string.html#format-string-syntax replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}" field_name ::= (identifier|integer)("."attribute_name|"["element_index"]")* attribute_name ::= identifier element_index ::= integer conversion ::= "r" | "s" format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= <a character other than '}'> align ::= "<" | ">" | "=" | "^" "=" forces the padding to be placed after the sign (if any) but before the digits. (for numeric types) "<" left justification ">" right justification "^" center justification sign ::= "+" | "-" | " " "+" places a plus/minus sign for all numbers "-" places a sign only for negative numbers " " places a leading space for positive numbers # for integers with type b,o,x, tells format to prefix output with 0b, 0o, or 0x. 0 enables zero-padding. equivalent to 0= fill align. width ::= integer , tells format to use a comma for a thousands separator precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" c convert integer to corresponding unicode character n uses a locale-aware separator % multiplies number by 100, display in 'f' format, with percent sign ```
``` # Choose a number in [0, 1L << 50), and format it as binary. # The [2:] lops off the prefix "0b" bit_str = bin(random.randint(0, (1L << 50) - 1))[2:] # We then need to pad to 50 bits. fifty_random_bits = '%s%s' % ('0' * (50 - len(bit_str)), bit_str) ```
8,919,080
This is what my problem is: I need to make a random string 50 characters long, made up of `1`s and `0`s. I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know([1](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), [2](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), etc). But what I really want is **the most** Pythonic way of doing this. Currently, I'm leaning towards `''.join(( random.choice([0,1]) for i in xrange(50) ))` Is there a more pythonic way of doing this? Is there a built-in that does something like this, perhaps in `itertools`?
2012/01/18
[ "https://Stackoverflow.com/questions/8919080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198633/" ]
``` # Choose a number in [0, 1L << 50), and format it as binary. # The [2:] lops off the prefix "0b" bit_str = bin(random.randint(0, (1L << 50) - 1))[2:] # We then need to pad to 50 bits. fifty_random_bits = '%s%s' % ('0' * (50 - len(bit_str)), bit_str) ```
``` from random import choice from itertools import repeat # map or generator expression, take your pick "".join( map( choice, repeat( "01", 50))) "".join( choice(x) for x in repeat("01", 50)) ``` Change the inputs to `repeat` to generalize.
8,919,080
This is what my problem is: I need to make a random string 50 characters long, made up of `1`s and `0`s. I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know([1](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), [2](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), etc). But what I really want is **the most** Pythonic way of doing this. Currently, I'm leaning towards `''.join(( random.choice([0,1]) for i in xrange(50) ))` Is there a more pythonic way of doing this? Is there a built-in that does something like this, perhaps in `itertools`?
2012/01/18
[ "https://Stackoverflow.com/questions/8919080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198633/" ]
For Python2.7 or better: ``` In [83]: import random In [84]: '{:050b}'.format(random.randrange(1<<50)) Out[84]: '10011110110110000011111000011100101111101001001011' ``` (In Python2.6, use `'{0:050b}'` instead of `'{:050b}'`.) --- **Explanation**: The `string.format` method can convert integers into their binary string representations. The basic format code to do this is `'{:b}'`: ``` In [91]: '{:b}'.format(10) Out[91]: '1010' ``` To make a string of width 50, use the format code `'{:50b}'`: ``` In [92]: '{:50b}'.format(10) Out[92]: ' 1010' ``` and to fill in the whitespace with zeros, use `{:050b}`: ``` In [93]: '{:050b}'.format(10) Out[93]: '00000000000000000000000000000000000000000000001010' ``` The [syntax for str.format](http://docs.python.org/library/string.html#format-string-syntax) is a bit daunting at first. Here is my cheat sheet: ``` http://docs.python.org/library/string.html#format-string-syntax replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}" field_name ::= (identifier|integer)("."attribute_name|"["element_index"]")* attribute_name ::= identifier element_index ::= integer conversion ::= "r" | "s" format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= <a character other than '}'> align ::= "<" | ">" | "=" | "^" "=" forces the padding to be placed after the sign (if any) but before the digits. (for numeric types) "<" left justification ">" right justification "^" center justification sign ::= "+" | "-" | " " "+" places a plus/minus sign for all numbers "-" places a sign only for negative numbers " " places a leading space for positive numbers # for integers with type b,o,x, tells format to prefix output with 0b, 0o, or 0x. 0 enables zero-padding. equivalent to 0= fill align. width ::= integer , tells format to use a comma for a thousands separator precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" c convert integer to corresponding unicode character n uses a locale-aware separator % multiplies number by 100, display in 'f' format, with percent sign ```
That looks pretty pythonic to me. You can lose the brackets if you wish to save on characters: ``` ''.join( random.choice(['0','1']) for i in xrange(50) ) ```
8,919,080
This is what my problem is: I need to make a random string 50 characters long, made up of `1`s and `0`s. I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know([1](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), [2](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), etc). But what I really want is **the most** Pythonic way of doing this. Currently, I'm leaning towards `''.join(( random.choice([0,1]) for i in xrange(50) ))` Is there a more pythonic way of doing this? Is there a built-in that does something like this, perhaps in `itertools`?
2012/01/18
[ "https://Stackoverflow.com/questions/8919080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198633/" ]
That looks pretty pythonic to me. You can lose the brackets if you wish to save on characters: ``` ''.join( random.choice(['0','1']) for i in xrange(50) ) ```
``` from random import choice from itertools import repeat # map or generator expression, take your pick "".join( map( choice, repeat( "01", 50))) "".join( choice(x) for x in repeat("01", 50)) ``` Change the inputs to `repeat` to generalize.
8,919,080
This is what my problem is: I need to make a random string 50 characters long, made up of `1`s and `0`s. I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know([1](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), [2](https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits), etc). But what I really want is **the most** Pythonic way of doing this. Currently, I'm leaning towards `''.join(( random.choice([0,1]) for i in xrange(50) ))` Is there a more pythonic way of doing this? Is there a built-in that does something like this, perhaps in `itertools`?
2012/01/18
[ "https://Stackoverflow.com/questions/8919080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198633/" ]
For Python2.7 or better: ``` In [83]: import random In [84]: '{:050b}'.format(random.randrange(1<<50)) Out[84]: '10011110110110000011111000011100101111101001001011' ``` (In Python2.6, use `'{0:050b}'` instead of `'{:050b}'`.) --- **Explanation**: The `string.format` method can convert integers into their binary string representations. The basic format code to do this is `'{:b}'`: ``` In [91]: '{:b}'.format(10) Out[91]: '1010' ``` To make a string of width 50, use the format code `'{:50b}'`: ``` In [92]: '{:50b}'.format(10) Out[92]: ' 1010' ``` and to fill in the whitespace with zeros, use `{:050b}`: ``` In [93]: '{:050b}'.format(10) Out[93]: '00000000000000000000000000000000000000000000001010' ``` The [syntax for str.format](http://docs.python.org/library/string.html#format-string-syntax) is a bit daunting at first. Here is my cheat sheet: ``` http://docs.python.org/library/string.html#format-string-syntax replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}" field_name ::= (identifier|integer)("."attribute_name|"["element_index"]")* attribute_name ::= identifier element_index ::= integer conversion ::= "r" | "s" format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= <a character other than '}'> align ::= "<" | ">" | "=" | "^" "=" forces the padding to be placed after the sign (if any) but before the digits. (for numeric types) "<" left justification ">" right justification "^" center justification sign ::= "+" | "-" | " " "+" places a plus/minus sign for all numbers "-" places a sign only for negative numbers " " places a leading space for positive numbers # for integers with type b,o,x, tells format to prefix output with 0b, 0o, or 0x. 0 enables zero-padding. equivalent to 0= fill align. width ::= integer , tells format to use a comma for a thousands separator precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" c convert integer to corresponding unicode character n uses a locale-aware separator % multiplies number by 100, display in 'f' format, with percent sign ```
``` from random import choice from itertools import repeat # map or generator expression, take your pick "".join( map( choice, repeat( "01", 50))) "".join( choice(x) for x in repeat("01", 50)) ``` Change the inputs to `repeat` to generalize.
47,355,844
I'm trying to run a python script in a Docker container, and i don't know why, python can't find any of the python's module. I thaught it has something to do with the PYTHONPATH env variable, so i tried to add it in the Dockerfile like this : `ENV PYTHONPATH $PYTHONPATH` But it didn't work. this is what my Dockerfile looks like: ``` FROM ubuntu:16.04 MAINTAINER SaveMe SaveMe@Desperate.com ADD . /app WORKDIR /app RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get install -y locales # Set the locale RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \ locale-gen ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8 ENV PYTHONPATH ./app #Install dependencies RUN echo "===> Installing sudo to emulate normal OS behavior..." RUN apt-get install -y software-properties-common RUN apt-add-repository universe RUN add-apt-repository ppa:jonathonf/python-3.6 RUN (apt-get update && apt-get upgrade -y -q && apt-get dist-upgrade - y -q && apt-get -y -q autoclean && apt-get -y -q autoremove) RUN apt-get install -y libxml2-dev libxslt-dev RUN apt-get install -y python3.6 python3.6-dev python3.6-venv openssl ca-certificates python3-pip RUN apt-get install -y python3-dev python-dev libffi-dev gfortran RUN apt-get install -y swig RUN apt-get install -y sshpass openssh-client rsync python-pip python- dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev zlib1g-dev libpulse-dev RUN pip install --upgrade pip RUN pip install bugsnag #Install python package + requirements.txt RUN pip3 install -r requirements.txt CMD ["python3.6", "import_emails.py"] ``` when i'm trying to run: `sudo docker run <my_container>` i got this Traceback: ``` Traceback (most recent call last): File "import_emails.py", line 9, in <module> import bugsnag ModuleNotFoundError: No module named 'bugsnag' ``` As you can see i'm using python3.6 for this project. Any lead on how to solve this ?
2017/11/17
[ "https://Stackoverflow.com/questions/47355844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8538327/" ]
Inside the container, when I `pip install bugsnag`, I get the following: ``` root@af08af24a458:/app# pip install bugsnag Requirement already satisfied: bugsnag in /usr/local/lib/python2.7/dist-packages Requirement already satisfied: webob in /usr/local/lib/python2.7/dist-packages (from bugsnag) Requirement already satisfied: six<2,>=1.9 in /usr/local/lib/python2.7/dist-packages (from bugsnag) ``` You probably see the problem here. You're installing the package for python2.7, which is the OS default, instead of python3.6, which is what you're trying to use. Check out this answer for help resolving this issue: ["ModuleNotFoundError: No module named <package>" in my Docker container](https://stackoverflow.com/questions/47355844/modulenotfounderror-no-module-named-package-in-my-docker-container) Alternatively, this is a problem `virtualenv` and similar tools are meant to solve, you could look into that as well.
since you're using py3, try using pip3 to install bugsnag instead of pip
33,617,221
I am trying to speed up some heavy simulations by using python's multiprocessing module on a machine with 24 cores that runs Suse Linux. From reading through the documentation, I understand that this only makes sense if the individual calculations take much longer than the overhead for creating the pool etc. What confuses me is that the execution time of some of the individual processes is much longer with multiprocessing than when I just run a single process. In my actual simulations the the time increases from around 300s to up to 1500s. Interestingly this gets worse when I use more processes. The following example illustrates the problem with a slightly shorter dummy loop: ```py from time import clock,time import multiprocessing import os def simulate(params): t1 = clock() result = 0 for i in range(10000): for j in range(10000): result+=i*j pid = os.getpid() print 'pid: ',pid,' sim time: ',clock() - t1, 'seconds' return result if __name__ == '__main__': for n_procs in [1,5,10,20]: print n_procs,' processes:' t1 = time() result = multiprocessing.Pool(processes = n_procs).map(simulate,range(20)) print 'total: ',time()-t1 ``` This produces the following output: ``` 1 processes: pid: 1872 sim time: 8.1 seconds pid: 1872 sim time: 7.92 seconds pid: 1872 sim time: 7.93 seconds pid: 1872 sim time: 7.89 seconds pid: 1872 sim time: 7.87 seconds pid: 1872 sim time: 7.74 seconds pid: 1872 sim time: 7.83 seconds pid: 1872 sim time: 7.84 seconds pid: 1872 sim time: 7.88 seconds pid: 1872 sim time: 7.82 seconds pid: 1872 sim time: 8.83 seconds pid: 1872 sim time: 7.91 seconds pid: 1872 sim time: 7.97 seconds pid: 1872 sim time: 7.84 seconds pid: 1872 sim time: 7.87 seconds pid: 1872 sim time: 7.91 seconds pid: 1872 sim time: 7.86 seconds pid: 1872 sim time: 7.9 seconds pid: 1872 sim time: 7.96 seconds pid: 1872 sim time: 7.97 seconds total: 159.337743998 5 processes: pid: 1906 sim time: 8.66 seconds pid: 1907 sim time: 8.74 seconds pid: 1908 sim time: 8.75 seconds pid: 1905 sim time: 8.79 seconds pid: 1909 sim time: 9.52 seconds pid: 1906 sim time: 7.72 seconds pid: 1908 sim time: 7.74 seconds pid: 1907 sim time: 8.26 seconds pid: 1905 sim time: 8.45 seconds pid: 1909 sim time: 9.25 seconds pid: 1908 sim time: 7.48 seconds pid: 1906 sim time: 8.4 seconds pid: 1907 sim time: 8.23 seconds pid: 1905 sim time: 8.33 seconds pid: 1909 sim time: 8.15 seconds pid: 1908 sim time: 7.47 seconds pid: 1906 sim time: 8.19 seconds pid: 1907 sim time: 8.21 seconds pid: 1905 sim time: 8.27 seconds pid: 1909 sim time: 8.1 seconds total: 35.1368539333 10 processes: pid: 1918 sim time: 8.79 seconds pid: 1920 sim time: 8.81 seconds pid: 1915 sim time: 14.78 seconds pid: 1916 sim time: 14.78 seconds pid: 1914 sim time: 14.81 seconds pid: 1922 sim time: 14.81 seconds pid: 1913 sim time: 14.98 seconds pid: 1921 sim time: 14.97 seconds pid: 1917 sim time: 15.13 seconds pid: 1919 sim time: 15.13 seconds pid: 1920 sim time: 8.26 seconds pid: 1918 sim time: 8.34 seconds pid: 1915 sim time: 9.03 seconds pid: 1921 sim time: 9.03 seconds pid: 1916 sim time: 9.39 seconds pid: 1913 sim time: 9.27 seconds pid: 1914 sim time: 12.12 seconds pid: 1922 sim time: 12.17 seconds pid: 1917 sim time: 12.15 seconds pid: 1919 sim time: 12.17 seconds total: 27.4067809582 20 processes: pid: 1941 sim time: 8.63 seconds pid: 1939 sim time: 10.32 seconds pid: 1931 sim time: 12.35 seconds pid: 1936 sim time: 12.23 seconds pid: 1937 sim time: 12.82 seconds pid: 1942 sim time: 12.73 seconds pid: 1932 sim time: 13.01 seconds pid: 1946 sim time: 13.0 seconds pid: 1945 sim time: 13.74 seconds pid: 1944 sim time: 14.03 seconds pid: 1929 sim time: 14.44 seconds pid: 1943 sim time: 14.75 seconds pid: 1935 sim time: 14.8 seconds pid: 1930 sim time: 14.79 seconds pid: 1927 sim time: 14.85 seconds pid: 1934 sim time: 14.8 seconds pid: 1928 sim time: 14.83 seconds pid: 1940 sim time: 14.88 seconds pid: 1933 sim time: 15.05 seconds pid: 1938 sim time: 15.06 seconds total: 15.1311581135 ``` What I do not understand is that *some* of the processes become much slower above a certain number of CPUs. I should add that nothing else is running on this machine. Is this expected? Am I doing something wrong?
2015/11/09
[ "https://Stackoverflow.com/questions/33617221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5543796/" ]
Cores are shared resource like anything else on computer. OS will usually balance load. Meaning it will spread threads on as many cores as possible.`*` Guiding metric will be core load. So if there are less thread counts then core count some cores will sit idle. (Thread architecture prevent splitting onto multiple cores). If there are more threads then cores. OS will assign many threads to single core, and will multitask between those threads on that core. Switching from one thread to other on single core have some cost associated. Shifting task from core to another have even greater cost. (Quite significant in terms of both cores resources) OS will generally avoid such actions. **So getting back to Your story.** **Performance rouse with thread count up to core count** because there where idling cores that got new work. Few last cores though where busy with OS work anyway, so those added very little to actual performance. **Overall performance still improved** after thread count passed core count. Just because OS can switch active thread if previous got stuck on long running task (like I/O), so another one can use CPU time. **Perofrmance would decrease** if thread count would significantly pass core count. As too many threads would fight for same resource (CPU time), and switching costs would aggregate to substantial portion of CPU cycles. However from Your listing its still not happened. **As for seemingly long execution time?** It was long! Just threads did not spent it all working. OS switched them off and on to maximize CPU usage whenever anyone of them got stuck on external work (I/O), and then some more switching to more evenly spread CPU time across threads assigned to core. `*` OS may also go for least power usage, maximized I/O usage, etc. Especially Linux is very flexible here. But its out of scope ;) Read on various schedulers in Linux if interested.
This is the best answer I could come up with after looking through different questions and documentations: It is pretty widely known that `multiprocessing` in general adds some sort of overhead when it comes to run time performance. This is/can be a result of a lot of different factors such as allocating RAM space, initializing the process, waiting for termination, [etc,etc,etc](https://stackoverflow.com/questions/26630245/testing-python-multiprocessing-low-speed-because-of-overhead). This then explains the increase in time from switching to parallel processing from singular. The increase in time as the amount of processes increases can sort of be explained by the way that mutliprocessing works. The comment by ali\_m [in this link](https://stackoverflow.com/questions/28789377/python-multiprocessing-run-time-per-process-increases-with-number-of-processes) was the best that I could find that explains why this happens: > > For starters, if your threads share CPU cache you're likely to suffer a lot more cache misses, which can cause a big degradation in performance > > > This is is alike to when you try to run a lot of different programs on your computer at once: your programs start to 'lag' and slow down because your CPU can only handle so many requests at a time. Another good link that I found was [this](https://community.oracle.com/message/3777500). Although this was a question about SQL servers and using queries, the same idea can be applied to it (regarding the amount of overhead as the amount of processes/queries increase) This is not, by far, a complete answer but this is my slight understanding on why you are getting the results as you are. Conclusion? the results you are getting or both normal and expected for multiprocessing