qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 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), 'in... | 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 s... | 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), 'in... | 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 threadi... | 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 s... |
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), 'in... | 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 s... | 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 p... |
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), 'in... | 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, re... | 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 p... |
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), 'in... | 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 threadi... | 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 i... |
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), 'in... | 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, re... | 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 i... |
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), 'in... | 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 s... | 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 i... |
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), 'in... | 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 threadi... | 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"... |
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/hell... | 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 exclusiv... |
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/hell... | 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[-... | 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 exclusiv... |
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 pare... | 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 dictionar... | *[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 exter... |
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 pare... | 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 dictionar... | >
> 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 ... |
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 pare... | 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 dictionar... | 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... |
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))... | 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 desirab... | 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.i... | 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 th... |
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.ht... | 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.i... |
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.ht... | 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 th... |
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 li... | 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[] = {g... | 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 helpe... |
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 li... | 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 helpe... |
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 li... | 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++")... | ```
#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... |
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 li... | 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++")... | 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 helpe... |
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 li... | 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)); ... | 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 li... | 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 ... | 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 helpe... |
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 li... | 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>
templat... | 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 helpe... |
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 li... | 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) {
s... | 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 li... | 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>
templat... | 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 li... | 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)); ... | ```
#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... |
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 =
... | 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(exam... | 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 ea... |
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:
... | 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 ... | 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()))
... |
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:
... | 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... | 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 ... |
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:
... | 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:
... | 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 ... |
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:
... | 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... | 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()))
... |
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:
... | 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:
... | 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()))
... |
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',... | 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 Request... | 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/>
... |
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 th... | 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 exact... | 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 th... | 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 exact... | 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 ... |
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 th... | 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 ... | 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... | 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)
... |
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... | 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_i... | 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 functo... |
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... | 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_i... | 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... |
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... | 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 functo... | 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... |
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... | 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 attribut... | 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 us... |
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.0... | 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 l... |
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.0... | 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 l... | 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 smalle... |
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.0... | 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 smalle... |
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 jso... | 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}!")
e... | ```
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 ... |
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)() #... |
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 mat... |
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)() #... |
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 mat... |
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 someon... | 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 mig... | ```
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 someon... | 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) # explan... | ```
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 someon... | 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 mig... | 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 someon... | 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 mig... | 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) # explan... |
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 someon... | 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) # explan... | 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... | 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... | 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... |
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 ... | 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,... | 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 13... |
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` evaluat... | 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 specia... | 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` evaluat... | 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 w... | 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 t... | 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 t... | 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... | 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 t... | 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... | ```
(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).
**Ol... | 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 `un... | 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 isLinkInt... |
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 ... | 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
```
Expl... | 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
c... |
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, ... | 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-li... | 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)
```
... |
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, ... | 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-li... | 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, ... | 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... | 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)
```
... |
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, ... | 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... | 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 pass... | 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',... | 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 ... |
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 pass... | 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',... | ```
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-Con... |
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);... | 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.... | 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 `NSIndexP... |
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 timeserie... | 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 "ca... | @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... |
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 sel... | 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 scroll... | 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 sel... | 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 scroll... | 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, ... |
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":
... | 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 actual... | 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="selec... | 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.c... | 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_Ge... |
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, hea... | 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.... | 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.bo... |
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:
t... | 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()`](... | 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 correc... | 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 Framew... | 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 lib... |
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 correc... | 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 requirem... |
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 correc... | 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 u... |
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 correc... | 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 lib... | "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 requirem... |
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 correc... | 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 Framew... | 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 y... |
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 correc... | 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 Framew... | 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 u... |
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 correc... | 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 Framew... | 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 correc... | 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 lib... | 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 u... |
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 correc... | 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 y... |
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 correc... | 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 Framew... | "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 requirem... |
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 th... | 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 f... | 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 op... | 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
"""
ar... |
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 + ext... | 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 eff... | 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 ... |
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/22574... | 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 ... | ```
# 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/22574... | 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/22574... | 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 ... | 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/22574... | 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/22574... | 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 ... | ```
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... | 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 sat... | 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 con... | 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 co... | 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, in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.