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 |
|---|---|---|---|---|---|
41,850,558 | I have a model called "document-detail-sample" and when you call it with a GET, something like this, **GET** `https://url/document-detail-sample/` then you get every "document-detail-sample".
Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy.
But... th... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41850558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050960/"
] | You could use `@list_route` decorator
```
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
... | Assuming you don't need pagination, just override the `list` method like so
```
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
def list(self, request):
return Response(self.get_queryset().val... |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can do something like this:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--foo',dest='foo',default=None)
parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--bar',dest='bar',default=None)... | I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default) |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can also use this module: [docopt](https://github.com/docopt/docopt) | I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default) |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can do something like this:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--foo',dest='foo',default=None)
parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--bar',dest='bar',default=None)... | You can also use this module: [docopt](https://github.com/docopt/docopt) |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing c... | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | Try this
```
stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)')
```
* output
```
"The dog walked (ABC) in the park"
``` | Not a one liner, but it does the trick and is (hopefully!) intuitive.
```
library(stringr)
add_brackets = function(text) {
brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters
brackets_new = paste0(brackets, ")") # adds in the closing brackets
str_replace(text, ... |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing c... | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | Try this
```
stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)')
```
* output
```
"The dog walked (ABC) in the park"
``` | You might also use gsub, and first use the word boundary and then the negative lookahead.
In the replacement use the first capture group followed by `)`
```
text = "The dog walked (ABC in the park"
gsub('(\\([A-Z]+)\\b(?!\\))', '\\1\\)', text, perl=T)
```
Output
```
[1] "The dog walked (ABC) in the park"
``` |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing c... | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | You might also use gsub, and first use the word boundary and then the negative lookahead.
In the replacement use the first capture group followed by `)`
```
text = "The dog walked (ABC in the park"
gsub('(\\([A-Z]+)\\b(?!\\))', '\\1\\)', text, perl=T)
```
Output
```
[1] "The dog walked (ABC) in the park"
``` | Not a one liner, but it does the trick and is (hopefully!) intuitive.
```
library(stringr)
add_brackets = function(text) {
brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters
brackets_new = paste0(brackets, ")") # adds in the closing brackets
str_replace(text, ... |
67,609,973 | I chose to use Python 3.8.1 Azure ML in Azure Machine learning studio, but when i run the command
`!python train.py`, it uses python Anconda 3.6.9, when i downloaded python 3.8 and run the command `!python38 train.py` in the same dir as before, the response was `python3.8: can't open file` .
Any idea?
Also Python 3 in ... | 2021/05/19 | [
"https://Stackoverflow.com/questions/67609973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14915505/"
] | You should try adding a new Python 3.8 Kernel. Here and instructions how to add a new Kernel: <https://learn.microsoft.com/en-us/azure/machine-learning/how-to-access-terminal#add-new-kernels> | Yeah I understand your pain point, and I agree that calling bash commands in a notebook cell should execute in the same conda environment as the one associated with the selected kernel of the notebook. I think this is bug, I'll flag it to the notebook feature team, but I encourage you to open a priority support ticket ... |
58,483,706 | I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe.
I have tried .merge and .join, both of which was not able to get my desired outbcome.
let us suppose I have the below scenario:
```
lt = list(['a','b','c','... | 2019/10/21 | [
"https://Stackoverflow.com/questions/58483706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11378087/"
] | If you don't mind the order of the columns changing, this is just a right join. The only caveat is that those are performed on rows rather than columns, so you need to transpose first:
```py
In [44]: df.T.join(df1.T, how='right').T
Out[44]:
a a a b b b c d
0 10 10 10 11 11 11 12 12
1 15 15 ... | Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html)
```py
pd.concat([df, df1], axis=0, join='inner', sort=False)
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` |
58,483,706 | I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe.
I have tried .merge and .join, both of which was not able to get my desired outbcome.
let us suppose I have the below scenario:
```
lt = list(['a','b','c','... | 2019/10/21 | [
"https://Stackoverflow.com/questions/58483706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11378087/"
] | What you can do is to use the columns of `df` and select the corresponding columns in `df1`, like so:
```py
lt = list(['a','b','c','d','a','b','a','b'])
df = pd.DataFrame(columns = lt)
data = [[10,11,12,12], [15,14,12,10]]
df1 = pd.DataFrame(data, columns = ['a','b','c','d'])
df2 = df1[df.columns]
print(df2)
```
... | Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html)
```py
pd.concat([df, df1], axis=0, join='inner', sort=False)
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 ... | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | ```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
``` | I needed this solution and wrote the following based on the answer from @root
```
def is_method_static(cls, method_name):
# http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static
for c in cls.mro():
if method_name in c.__dict__:
return isinstance(c.__dict__[method_nam... |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 ... | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | ```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
``` | For Python 3.2 or newer, use [`inspect.getattr_static()`](https://docs.python.org/3/library/inspect.html#inspect.getattr_static) to retrieve the attribute without invoking the descriptor protocol:
>
> Retrieve attributes without triggering dynamic lookup via the descriptor protocol, `__getattr__()` or `__getattribute... |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 ... | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | For Python 3.2 or newer, use [`inspect.getattr_static()`](https://docs.python.org/3/library/inspect.html#inspect.getattr_static) to retrieve the attribute without invoking the descriptor protocol:
>
> Retrieve attributes without triggering dynamic lookup via the descriptor protocol, `__getattr__()` or `__getattribute... | I needed this solution and wrote the following based on the answer from @root
```
def is_method_static(cls, method_name):
# http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static
for c in cls.mro():
if method_name in c.__dict__:
return isinstance(c.__dict__[method_nam... |
46,132,431 | I have written code to generate numbers from 0500000000 to 0500000100:
```
def generator(nums):
count = 0
while count < 100:
gg=print('05',count, sep='')
count += 1
g = generator(10)
```
as I use linux, I thought I may be able to use this command `python pythonfilename.py >> file.txt`
Yet,... | 2017/09/09 | [
"https://Stackoverflow.com/questions/46132431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548783/"
] | Here I've assumed we're laying out two general images, rather than plots. If your images are actually plots you've created, then you can lay them out as a single image for display using `gridExtra::grid.arrange` for grid graphics or `par(mfrow=c(1,2))` for base graphics and thereby avoid the complications of laying out... | Put them in the same code chunk and do not use align. Let them use html.
THis has worked for me.
```
````{r echo=FALSE, fig.height=3.0, fig.width=3.0}
#type your code here
ggplot(anscombe, aes(x=x1 , y=y1)) + geom_point()
+geom_smooth(method="lm") +
ggtitle("Results for x1 and y1 ")
ggplot(anscombe, aes(x=... |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the followin... | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | Use `BeautifulSoup` to parse HTML
**Ex:**
```
from bs4 import BeautifulSoup
text="""<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
... | You can use `HTMLParser` as demonstrated below:
```
from HTMLParser import HTMLParser
s = \
"""
<html>
<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td... |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the followin... | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | Use `BeautifulSoup` to parse HTML
**Ex:**
```
from bs4 import BeautifulSoup
text="""<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
... | If you do not want to use external library, you can use `re` module to remove tables:
```
output = re.sub('<table.+?</table>','',text,flags=re.DOTALL)
```
printing output give:
```
Hi Team from the following Server :
<p> </p>
<p>Please archive the following Project Areas :</p>
```
(and 2 empty lines which... |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the followin... | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | If you do not want to use external library, you can use `re` module to remove tables:
```
output = re.sub('<table.+?</table>','',text,flags=re.DOTALL)
```
printing output give:
```
Hi Team from the following Server :
<p> </p>
<p>Please archive the following Project Areas :</p>
```
(and 2 empty lines which... | You can use `HTMLParser` as demonstrated below:
```
from HTMLParser import HTMLParser
s = \
"""
<html>
<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td... |
38,776,104 | I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use
```
$ python myfile.py &> out.txt
```
to do the same task that I want, but I need to do it from the Python script itself.
I looked into the questions [Redirect subprocess stder... | 2016/08/04 | [
"https://Stackoverflow.com/questions/38776104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461999/"
] | This works
```
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
``` | A SyntaxError in a Python file like the above is raised before your program even begins to run:
Python files are compiled just like in any other compiled language - if the parser or compiler can't find sense in your Python file, no executable bytecode is generated, therefore the program does not run.
The correct way t... |
57,843,695 | I haven't changed my system configuration, But I'm spotting this error for the first time today.
I've reported it here: <https://github.com/jupyter/notebook/issues/4871>
```
> jupyter notebook
[I 10:44:20.102 NotebookApp] JupyterLab extension loaded from /usr/local/anaconda3/lib/python3.7/site-packages/jupyterlab
[I ... | 2019/09/08 | [
"https://Stackoverflow.com/questions/57843695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435129/"
] | I fixed this by updating both jupyter on pip and pip3 (just to be safe) and this fixed the problem
using both
>
> `pip install --upgrade jupyter`
>
>
>
and
>
> `pip3 install --upgrade jupyter --no-cache-dir`
>
>
>
I believe you can do this in the terminal as well as in conda's terminal (since conda envs al... | As per [Where does Jupyter install site-packages on macOS?](https://stackoverflow.com/questions/57843888/where-does-jupyter-install-site-packages-on-macos), I locate where on my system `jupyter` is searching for this missing file:
```
> find / -path '*/static/components' 2>/dev/null
/usr/local/anaconda3/pkgs/notebook... |
44,175,800 | Simple question: given a string
```
string = "Word1 Word2 Word3 ... WordN"
```
is there a pythonic way to do this?
```
firstWord = string.split(" ")[0]
otherWords = string.split(" ")[1:]
```
Like an unpacking or something?
Thank you | 2017/05/25 | [
"https://Stackoverflow.com/questions/44175800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131783/"
] | Since Python 3 and [PEP 3132](https://www.python.org/dev/peps/pep-3132/), you can use extended unpacking.
This way, you can unpack arbitrary string containing any number of words. The first will be stored into the variable `first`, and the others will belong to the list (possibly empty) `others`.
```
first, *others =... | From [Extended Iterable Unpacking](https://www.python.org/dev/peps/pep-3132/).
Many algorithms require splitting a sequence in a "first, rest" pair, if you're using Python2.x, you need to try this:
```
seq = string.split()
first, rest = seq[0], seq[1:]
```
and it is replaced by the cleaner and probably more efficie... |
28,717,067 | I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it w... | 2015/02/25 | [
"https://Stackoverflow.com/questions/28717067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529171/"
] | Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop.
A much better way to do this would be simply run a COUNT query, get the single result with `fetchone(... | In python you should check for `None` not `NULL`. In your code you can just check for object, if it is not None then control should go inside `if` otherwise `else` will be executed
```
for row in rows:
if row:
print('Available')
else:
print('No available copies of the said book in the library')... |
28,717,067 | I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it w... | 2015/02/25 | [
"https://Stackoverflow.com/questions/28717067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529171/"
] | Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop.
A much better way to do this would be simply run a COUNT query, get the single result with `fetchone(... | First of all NULL in python is called None.
Next:
according to documentation:
"The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.
"
enpty list is not None
```
>>> row = []
>>> row is None
False
```
So you need to... |
65,995,857 | I'm quite new to coding and I'm working on a math problem in python.
To solve it, I would like to extract the first 7 numbers from a string of one hundred 50-digit number (take first 7 numbers, skip 43 numbers, and then take the first 7 again). The numbers aren't separated in any way (just one long string).
Then I want... | 2021/02/01 | [
"https://Stackoverflow.com/questions/65995857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15117090/"
] | Python allows you to iterate over a range with custom step sizes. So that should be allow you to do something like:
```py
your_list = []
for idx in range(0, len(string), 50): # Indexes 0, 50, 100, so on
first_seven_digits = string[idx:idx+7] # Say, "1234567"
str_to_int = int(first_seven_digits) # Converts to t... | first of all your number string is 4999 characters long so you'll have to add one. secondly if you want to use numpy you could make a 100 by 50 array by reshaping the original 5000 long array. like this
```
arr = np.array(list(number)).reshape(100, 50)
```
than you can slice the arr in a way that the first 7 element... |
21,307,128 | Since I have to mock a static method, I am using **Power Mock** to test my application.
My application uses \**Camel 2.1*\*2.
I define routes in *XML* that is read by *camel-spring* context.
There were no issues when `Junit` alone was used for testing.
While using power mock, I get the error listed at the end of the po... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21307128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2345966/"
] | This error message usually means that your specified truststore can not be read. What I would check:
* Is the path correct? (I'm sure you checked this...)
* Has the user who started the JVM enough access privileges to read the
trustore?
* When do you set the system properties? Are they already set when the webservice ... | ```
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
```
>
> * In my case, I have 2 duplicate Java installations (OpenJDK and
> JDK-17).
> * I installed JDK-17 after configuring environment variable for OpenJDK and... |
49,059,660 | I am looking for a simple way to constantly monitor a log file, and send me an email notification every time thhis log file has changed (new lines have been added to it).
The system runs on a Raspberry Pi 2 (OS Raspbian /Debian Stretch) and the log monitors a GPIO python script running as daemon.
I need something ver... | 2018/03/01 | [
"https://Stackoverflow.com/questions/49059660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9431262/"
] | You asked for simple:
```
#!/bin/bash
cur_line_count="$(wc -l myfile.txt)"
while true
do
new_line_count="$(wc -l myfile.txt)"
if [ "$cur_line_count" != "$new_line_count" ]
then
python ./sendmail.py
fi
cur_line_count="$new_line_count"
sleep 5
done
``` | I've done this a bunch of different ways. If you run a cron job every minute that counts the number of lines (wc -l) compares that to a stored count (e.g. in /tmp/myfilecounter) and sends the emails when the numbers are different.
If you have inotify, there are more direct ways to get "woken up" when the file changes,... |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How co... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | If you are set on using the class, one way would be to use [`__getattribute__()`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__)
```
print([Numbers().__getattribute__(a) for a in alist])
#[4, 3, 5, 1, 2]
```
But a much better (and more pythonic IMO) way would be to use a `dict`:
```
Num... | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ... |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How co... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | Most objects (and hence classes) in python have the `__dict__` field, which is a mapping from attribute names to their values. You can access this field using the built-in [`vars`](https://docs.python.org/3/library/functions.html#vars), so
```
values = [vars(Numbers)[a] for a in alist]
```
will give you what you wan... | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ... |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How co... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | While I totally agree that using a `dict` for `Numbers` would be easier and straight forward, but showing you the `Enum` way as your class involves magic numbers and sort of a valid use case for using enums.
A similar implementation using `Enum` would be:
```
from enum import Enum
class Numbers(Enum):
One = 1
... | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ... |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]... | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat... | Well, the problem is with:
```
reviews["review"]
```
The above is a Series. In your first snippet, you are doing this:
```
reviews["review"][1].split("disappointed")
```
That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example... |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]... | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat... | You can use `.str` to use string methods on series of strings:
```
reviews["review"].str.split("disappointed")
``` |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]... | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat... | pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made
```
len(reviews['review'].str.split('disappointed')) - 1
```
[pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/p... |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]... | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made
```
len(reviews['review'].str.split('disappointed')) - 1
```
[pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/p... | Well, the problem is with:
```
reviews["review"]
```
The above is a Series. In your first snippet, you are doing this:
```
reviews["review"][1].split("disappointed")
```
That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example... |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]... | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made
```
len(reviews['review'].str.split('disappointed')) - 1
```
[pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/p... | You can use `.str` to use string methods on series of strings:
```
reviews["review"].str.split("disappointed")
``` |
72,329,252 | Let's say we have following list. This list contains response times of a REST server in a traffic run.
[1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
I need following output
Percentage of the requests served within a certain time (ms)
50% 3
60% 4
70% 5
80% 6
90% 7
100% 9
How can we get it done in python? This is apache bench... | 2022/05/21 | [
"https://Stackoverflow.com/questions/72329252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137009/"
] | You can try something like this:
```
responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
for time in range(3,10):
percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes))
print(f'{percentage*100}%')
```
>
> *"So basically lets say at 50%, we need to find point in list below which 50% of the... | You basically need to compute the cumulative ratio of the sorted response times.
```py
from collections import Counter
values = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
frequency = Counter(values) # {1: 2, 2: 1, 3: 2, ...}
total = 0
n = len(values)
for time in sorted(frequency):
total += frequency[time]
print(time, f'... |
50,239,640 | In python have three one dimensional arrays of different shapes (like the ones given below)
```
a0 = np.array([5,6,7,8,9])
a1 = np.array([1,2,3,4])
a2 = np.array([11,12])
```
I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these ass... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50239640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761166/"
] | You can use `numpy` stack functions to speed up:
```
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
``` | One way to do this would be a simple list comprehension:
```
result = np.array([[i, arr_v] for i, arr in enumerate([a0, a1, a2])
for arr_v in arr])
>>> result
array([[ 0, 5],
[ 0, 6],
[ 0, 7],
[ 0, 8],
[ 0, 9],
[ 1, 1],
[ 1, 2],
[ 1... |
50,239,640 | In python have three one dimensional arrays of different shapes (like the ones given below)
```
a0 = np.array([5,6,7,8,9])
a1 = np.array([1,2,3,4])
a2 = np.array([11,12])
```
I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these ass... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50239640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761166/"
] | You can use `numpy` stack functions to speed up:
```
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
``` | Here's an almost vectorized approach -
```
L = [a0,a1,a2] # list of all arrays
lens = [len(i) for i in L] # only looping part*
out = np.dstack(( np.repeat(np.arange(len(L)), lens), np.concatenate(L)))
```
\*The looping part is simply to get the lengths of the arrays, which should have negligible impact on the total ... |
45,939,564 | I am accessing a python file via python.
The google sheets looks like the following:
[](https://i.stack.imgur.com/eIW7v.png)
But when I access it via:
```
self.probe=[]
self.scope = ['https://spreadsheets.google.com/feeds']
self.creds = S... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45939564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3554329/"
] | I'm not familiar with gspread, which appears to be a third-party client for the Google Sheets API, but it looks like you should be using [`get_all_values`](https://github.com/burnash/gspread#getting-all-values-from-a-worksheet-as-a-list-of-lists) rather than `get_all_records`. That will give you a list of lists, rather... | Python dictionaries are unordered. There is the [OrderedDict](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict) in collections, but hard to say more about what the best course of action should be without more insight into why you need this dictionary ordered... |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib mak... | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib mak... | I have applied the following fix and it worked for my CentOS 7.x server.
Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example:
```
def check_sqlite_version():
# if Database.sqlite_version_info < (3, 8, 3):
# 2018-07-07, edit
if Database.sqlite_version_info < (3, ... |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following comman... | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib mak... |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following comman... | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps:
1. Download latest sqlite3 from official site. (<https://www.sqlite.... | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following comman... | I have applied the following fix and it worked for my CentOS 7.x server.
Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example:
```
def check_sqlite_version():
# if Database.sqlite_version_info < (3, 8, 3):
# 2018-07-07, edit
if Database.sqlite_version_info < (3, ... |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps:
1. Download latest sqlite3 from official site. (<https://www.sqlite.... | I have applied the following fix and it worked for my CentOS 7.x server.
Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example:
```
def check_sqlite_version():
# if Database.sqlite_version_info < (3, 8, 3):
# 2018-07-07, edit
if Database.sqlite_version_info < (3, ... |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following comman... | This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps:
1. Download latest sqlite3 from official site. (<https://www.sqlite.... |
46,143,091 | I'm pretty new to python so it's a basic question.
I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to th... | 2017/09/10 | [
"https://Stackoverflow.com/questions/46143091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252187/"
] | You could try adding a composite index
```
create index test on screenshot (DateTaken, id)
``` | Try running this query:
```
SELECT COUNT(*) as total
FROM screenshot
WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10';
```
The reference to `ID` in the `SELECT` could be affecting the use of the index. |
46,143,091 | I'm pretty new to python so it's a basic question.
I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to th... | 2017/09/10 | [
"https://Stackoverflow.com/questions/46143091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252187/"
] | There is no problem. Your index is fine. To explain...
The `5730138` in `EXPLAIN` is an *estimate*. It can be larger or smaller than the actual value, sometimes by a large amount. Do not be bothered by it.
You have 2.8M of screenshots in that date range, correct? Well, it could take 15 seconds to scan the index to co... | Try running this query:
```
SELECT COUNT(*) as total
FROM screenshot
WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10';
```
The reference to `ID` in the `SELECT` could be affecting the use of the index. |
71,568,396 | We are using a beam multi-language pipeline using python and java(ref <https://beam.apache.org/documentation/sdks/python-multi-language-pipelines/>). We are creating a cross-language pipeline using java. We have some external jar files that required a java library path. Code gets compiled properly and is able to create... | 2022/03/22 | [
"https://Stackoverflow.com/questions/71568396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648514/"
] | A Worksheet Change Event: Monitor Change in Column's Data
---------------------------------------------------------
* I personally would go with JvdV's suggestion in the comments.
* On each manual change of a cell, e.g. in column `A`, it will check the formula
`=SUM(A2:ALastRow)` in cell `A1` and if it is not correct ... | Use a nested function as below:
=SUM(OFFSET(A2,,,COUNTA(A2:A26))) |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po... | If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows ... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po... | It allows you to write single-threaded asynchronous code and implement concurrency in Python. Basically, `asyncio` provides an event loop for asynchronous programming. For example, if we need to make requests without blocking the main thread, we can use the `asyncio` library.
The asyncio module allows for the implemen... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | How does asyncio work?
======================
Before answering this question we need to understand a few base terms, skip these if you already know any of them.
[Generators](https://wiki.python.org/moin/Generators)
-----------------------------------------------------
Generators are objects that allow us to suspend ... | Talking about `async/await` and `asyncio` is not the same thing. The first is a fundamental, low-level construct (coroutines) while the later is a library using these constructs. Conversely, there is no single ultimate answer.
The following is a general description of how `async/await` and `asyncio`-like libraries wor... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | How does asyncio work?
======================
Before answering this question we need to understand a few base terms, skip these if you already know any of them.
[Generators](https://wiki.python.org/moin/Generators)
-----------------------------------------------------
Generators are objects that allow us to suspend ... | If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows ... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | Talking about `async/await` and `asyncio` is not the same thing. The first is a fundamental, low-level construct (coroutines) while the later is a library using these constructs. Conversely, there is no single ultimate answer.
The following is a general description of how `async/await` and `asyncio`-like libraries wor... | What is asyncio?
----------------
Asyncio stands for **asynchronous input output** and refers to a programming paradigm which achieves high concurrency using a single thread or event loop.
Asynchronous programming is a type of parallel programming in which a unit of work is allowed to run separately from the primary a... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | What is asyncio?
----------------
Asyncio stands for **asynchronous input output** and refers to a programming paradigm which achieves high concurrency using a single thread or event loop.
Asynchronous programming is a type of parallel programming in which a unit of work is allowed to run separately from the primary a... | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | Talking about `async/await` and `asyncio` is not the same thing. The first is a fundamental, low-level construct (coroutines) while the later is a library using these constructs. Conversely, there is no single ultimate answer.
The following is a general description of how `async/await` and `asyncio`-like libraries wor... | If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows ... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | How does asyncio work?
======================
Before answering this question we need to understand a few base terms, skip these if you already know any of them.
[Generators](https://wiki.python.org/moin/Generators)
-----------------------------------------------------
Generators are objects that allow us to suspend ... | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | How does asyncio work?
======================
Before answering this question we need to understand a few base terms, skip these if you already know any of them.
[Generators](https://wiki.python.org/moin/Generators)
-----------------------------------------------------
Generators are objects that allow us to suspend ... | It allows you to write single-threaded asynchronous code and implement concurrency in Python. Basically, `asyncio` provides an event loop for asynchronous programming. For example, if we need to make requests without blocking the main thread, we can use the `asyncio` library.
The asyncio module allows for the implemen... |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | How does asyncio work?
======================
Before answering this question we need to understand a few base terms, skip these if you already know any of them.
[Generators](https://wiki.python.org/moin/Generators)
-----------------------------------------------------
Generators are objects that allow us to suspend ... | What is asyncio?
----------------
Asyncio stands for **asynchronous input output** and refers to a programming paradigm which achieves high concurrency using a single thread or event loop.
Asynchronous programming is a type of parallel programming in which a unit of work is allowed to run separately from the primary a... |
36,590,875 | How to obtain absolute path via relative path for 'other' project files, not those python file in the project, like Java?
```
D:\Workspaces\ABCPythonProject\
|- src
| |-- com/abc
| |-- conf.py
| |-- abcd.py
| |-- defg.py
| |-- installation.rst
|- resources
| |-- a.txt
| |-- b.txt
| |--... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762932/"
] | For images you'll have to use:
```
<img src="url">
``` | It should be in following way,
```
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['u_id'] . '</td>';
echo '<td>'. $row['u_role'] . '</td>';
echo '<td>'. $row['u_name'] . '</td>';
echo '<td>'. $row['u_passw'] . '</td>';
echo '<td>'. $row['u_init'] . '</td>';
echo '<td>'. $row['c_name... |
36,590,875 | How to obtain absolute path via relative path for 'other' project files, not those python file in the project, like Java?
```
D:\Workspaces\ABCPythonProject\
|- src
| |-- com/abc
| |-- conf.py
| |-- abcd.py
| |-- defg.py
| |-- installation.rst
|- resources
| |-- a.txt
| |-- b.txt
| |--... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762932/"
] | For images you'll have to use:
```
<img src="url">
``` | ```
echo '<td><img src="'. $row['u_pic'] . '" width=45 height=45></img></td>';
``` |
36,590,875 | How to obtain absolute path via relative path for 'other' project files, not those python file in the project, like Java?
```
D:\Workspaces\ABCPythonProject\
|- src
| |-- com/abc
| |-- conf.py
| |-- abcd.py
| |-- defg.py
| |-- installation.rst
|- resources
| |-- a.txt
| |-- b.txt
| |--... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762932/"
] | ```
echo '<td><img src="'. $row['u_pic'] . '" width=45 height=45></img></td>';
``` | It should be in following way,
```
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['u_id'] . '</td>';
echo '<td>'. $row['u_role'] . '</td>';
echo '<td>'. $row['u_name'] . '</td>';
echo '<td>'. $row['u_passw'] . '</td>';
echo '<td>'. $row['u_init'] . '</td>';
echo '<td>'. $row['c_name... |
36,215,958 | I want to filter the moment of a day only with hour and minutes.
For example, a function that return true if now is between the 9.15 and 11.20 of the day.
I tried with datetime but with the minutes is littlebit complicated.
```
#!/usr/bin/python
import datetime
n = datetime.datetime.now()
sta = datetime.time(19,18... | 2016/03/25 | [
"https://Stackoverflow.com/questions/36215958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341022/"
] | You can use tuple comparisons to do any subinterval comparisons pretty easily:
```
>>> def f(dt):
... return (9, 15) <= (dt.hour, dt.minute) < (11, 21)
...
>>> d = datetime.datetime.now()
>>> str(d)
'2016-03-25 09:50:51.782718'
>>> f(d)
True
>>> f(d + datetime.timedelta(hours=2)
False
```
This accepts any dateti... | You'll need to use the combine class method:
```
import datetime
def between():
now = datetime.datetime.now()
start = datetime.datetime.combine(now.date(), datetime.time(9, 15))
end = datetime.datetime.combine(now.date(), datetime.time(11, 20))
return start <= now < end
``` |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | You want *inter-process communication*. Sockets are the first thing that comes to mind; you'd need to set up a socket to *listen* for a connection (on the same machine) in PHP and set up a socket to *connect* to the listening socket in Python and *send* it its status.
Have a look at [this socket programming overview](... | I think you would have to use a meta refresh and maybe have the python write the status to a file and then have the php read from it.
You could use AJAX as well to make it more dynamic.
Also, probably shouldn't use exec()...that opens up a world of vulnerabilities. |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | I think you would have to use a meta refresh and maybe have the python write the status to a file and then have the php read from it.
You could use AJAX as well to make it more dynamic.
Also, probably shouldn't use exec()...that opens up a world of vulnerabilities. | Unfortunately my friend, I do believe you'll need to use Sockets as you requested. :( I have little experience working with them, but [This Python Tutorial on Sockets/Network Programming](http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf) may help you get the Python socket interaction you need. (Beau Martinez's l... |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | I think you would have to use a meta refresh and maybe have the python write the status to a file and then have the php read from it.
You could use AJAX as well to make it more dynamic.
Also, probably shouldn't use exec()...that opens up a world of vulnerabilities. | You could use a queuing service like [Gearman](http://gearman.org/), with a client in PHP and a worker in Python or vice versa.
Someone has created an example setup here.
<https://github.com/dbaltas/gearman-python-worker> |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | You want *inter-process communication*. Sockets are the first thing that comes to mind; you'd need to set up a socket to *listen* for a connection (on the same machine) in PHP and set up a socket to *connect* to the listening socket in Python and *send* it its status.
Have a look at [this socket programming overview](... | Unfortunately my friend, I do believe you'll need to use Sockets as you requested. :( I have little experience working with them, but [This Python Tutorial on Sockets/Network Programming](http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf) may help you get the Python socket interaction you need. (Beau Martinez's l... |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | You want *inter-process communication*. Sockets are the first thing that comes to mind; you'd need to set up a socket to *listen* for a connection (on the same machine) in PHP and set up a socket to *connect* to the listening socket in Python and *send* it its status.
Have a look at [this socket programming overview](... | You could use a queuing service like [Gearman](http://gearman.org/), with a client in PHP and a worker in Python or vice versa.
Someone has created an example setup here.
<https://github.com/dbaltas/gearman-python-worker> |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | You could use a queuing service like [Gearman](http://gearman.org/), with a client in PHP and a worker in Python or vice versa.
Someone has created an example setup here.
<https://github.com/dbaltas/gearman-python-worker> | Unfortunately my friend, I do believe you'll need to use Sockets as you requested. :( I have little experience working with them, but [This Python Tutorial on Sockets/Network Programming](http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf) may help you get the Python socket interaction you need. (Beau Martinez's l... |
31,480,921 | I can't seem to get the interactive tooltips powered by mpld3 to work with the fantastic lmplot-like scatter plots from seaborn.
I'd love any pointer on how to get this to work! Thanks!
Example Code:
```
# I'm running this in an ipython notebook.
%matplotlib inline
import matplotlib.pyplot as plt, mpld3
mpld3.enable... | 2015/07/17 | [
"https://Stackoverflow.com/questions/31480921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270151/"
] | I don't think that there is an easy way to do this currently. I can get some of the tooltips to show by replacing your `tooltip` constructor with the following:
```
ax = plt.gca()
pts = ax.get_children()[3]
tooltip = mpld3.plugins.PointLabelTooltip(pts, labels=list(data.label))
```
This only works for the points out... | Your code works for me on `ipython` (no notepad) when saving the figure to file with `mpld3.save_html(fig,"./out.html")`. May be an issue with `ipython` `notepad`/`mpld3` compatibility or `mpld3.display` (which causes an error for me, although I think this is related to an old version of matplotlib on my computer).
T... |
31,480,921 | I can't seem to get the interactive tooltips powered by mpld3 to work with the fantastic lmplot-like scatter plots from seaborn.
I'd love any pointer on how to get this to work! Thanks!
Example Code:
```
# I'm running this in an ipython notebook.
%matplotlib inline
import matplotlib.pyplot as plt, mpld3
mpld3.enable... | 2015/07/17 | [
"https://Stackoverflow.com/questions/31480921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270151/"
] | I was able to get the tooltips to work by using the standard matplotlib scatter on top of the seaborn plot and very low alpha (you can't use zero)
```
data_tip_points = ax.scatter(x_points, y_points, alpha=0.001)
tooltip = plugins.PointLabelTooltip(data_tip_points, labels)
```
It's a bit of a hack, but it works as s... | Your code works for me on `ipython` (no notepad) when saving the figure to file with `mpld3.save_html(fig,"./out.html")`. May be an issue with `ipython` `notepad`/`mpld3` compatibility or `mpld3.display` (which causes an error for me, although I think this is related to an old version of matplotlib on my computer).
T... |
31,480,921 | I can't seem to get the interactive tooltips powered by mpld3 to work with the fantastic lmplot-like scatter plots from seaborn.
I'd love any pointer on how to get this to work! Thanks!
Example Code:
```
# I'm running this in an ipython notebook.
%matplotlib inline
import matplotlib.pyplot as plt, mpld3
mpld3.enable... | 2015/07/17 | [
"https://Stackoverflow.com/questions/31480921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270151/"
] | I don't think that there is an easy way to do this currently. I can get some of the tooltips to show by replacing your `tooltip` constructor with the following:
```
ax = plt.gca()
pts = ax.get_children()[3]
tooltip = mpld3.plugins.PointLabelTooltip(pts, labels=list(data.label))
```
This only works for the points out... | I was able to get the tooltips to work by using the standard matplotlib scatter on top of the seaborn plot and very low alpha (you can't use zero)
```
data_tip_points = ax.scatter(x_points, y_points, alpha=0.001)
tooltip = plugins.PointLabelTooltip(data_tip_points, labels)
```
It's a bit of a hack, but it works as s... |
28,180,252 | I am trying to create a quiver plot from a NetCDF file in Python using this code:
```
import matplotlib.pyplot as plt
import numpy as np
import netCDF4 as Dataset
ncfile = netCDF4.Dataset('30JUNE2012_0300UTC.cdf', 'r')
dbZ = ncfile.variables['MAXDBZF']
data = dbZ[0,0]
U = ncfile.variables['UNEW'][:]
V = ncfile.varia... | 2015/01/27 | [
"https://Stackoverflow.com/questions/28180252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4500459/"
] | `ValueError: too many values to unpack` is because the line `379` of your program is trying to assign two variables (`nr`, `nc`) from `U.shape` when there are not enough variables to assign these values to.
Look above on line `377` - that is correctly assigning two values (`1` and `U.shape[0]` to `nr` and `nc` but lin... | Probably more useful to solve future problems rather then author's but still:
The problem was likely that the netcdf file had a time dimension, therefore U and V where 3 dimensional arrays - you should choose the time slice or aggregate the data across the time dimension. |
36,486,120 | I'm trying to centre and normalise a data set in python with the following code
```
mean = np.mean(train, axis=0)
std = np.std(train, axis=0)
norm_train = (train - mean) / std
```
The problem is that I get a devision by zero error. Two of the values in the data set end up having a zero std. The data set if of shape ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36486120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531296/"
] | Since the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) is calculated by taking the sum of the *squared* deviations from the mean, a zero standard deviation can only be possible when all the values of a variable are the same (all equal to the mean). In this case, those variables have no discrim... | You could just replace the 0 std to 1 for that feature. This would basically mean that the scaled value would be zero for all the data points for that feature. This makes sense as this implies that the feature values do not deviate even a bit form the mean(as the values is constant, the constant is the mean.)
FYI- Thi... |
36,486,120 | I'm trying to centre and normalise a data set in python with the following code
```
mean = np.mean(train, axis=0)
std = np.std(train, axis=0)
norm_train = (train - mean) / std
```
The problem is that I get a devision by zero error. Two of the values in the data set end up having a zero std. The data set if of shape ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36486120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531296/"
] | Since the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) is calculated by taking the sum of the *squared* deviations from the mean, a zero standard deviation can only be possible when all the values of a variable are the same (all equal to the mean). In this case, those variables have no discrim... | One standard is to include an epsilon variable that prevents divide by zero. In theory, it is not needed because it doesn't make logical sense to do such calculations. In reality, machines are just calculators and divide by zero becomes either NaN or +/-Inf.
In short, define your function like this:
```
def z_norm(ar... |
36,486,120 | I'm trying to centre and normalise a data set in python with the following code
```
mean = np.mean(train, axis=0)
std = np.std(train, axis=0)
norm_train = (train - mean) / std
```
The problem is that I get a devision by zero error. Two of the values in the data set end up having a zero std. The data set if of shape ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36486120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531296/"
] | Since the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) is calculated by taking the sum of the *squared* deviations from the mean, a zero standard deviation can only be possible when all the values of a variable are the same (all equal to the mean). In this case, those variables have no discrim... | Going back to its definition, the idea behind the z\_score is to give the distance between an element and the mean of the sample in terms of standard deviations. If all elements are the same, it means that their distance to the mean is 0, and therefore the zscore is 0 time the standard deviation, since all your data po... |
36,486,120 | I'm trying to centre and normalise a data set in python with the following code
```
mean = np.mean(train, axis=0)
std = np.std(train, axis=0)
norm_train = (train - mean) / std
```
The problem is that I get a devision by zero error. Two of the values in the data set end up having a zero std. The data set if of shape ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36486120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531296/"
] | One standard is to include an epsilon variable that prevents divide by zero. In theory, it is not needed because it doesn't make logical sense to do such calculations. In reality, machines are just calculators and divide by zero becomes either NaN or +/-Inf.
In short, define your function like this:
```
def z_norm(ar... | You could just replace the 0 std to 1 for that feature. This would basically mean that the scaled value would be zero for all the data points for that feature. This makes sense as this implies that the feature values do not deviate even a bit form the mean(as the values is constant, the constant is the mean.)
FYI- Thi... |
36,486,120 | I'm trying to centre and normalise a data set in python with the following code
```
mean = np.mean(train, axis=0)
std = np.std(train, axis=0)
norm_train = (train - mean) / std
```
The problem is that I get a devision by zero error. Two of the values in the data set end up having a zero std. The data set if of shape ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36486120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531296/"
] | One standard is to include an epsilon variable that prevents divide by zero. In theory, it is not needed because it doesn't make logical sense to do such calculations. In reality, machines are just calculators and divide by zero becomes either NaN or +/-Inf.
In short, define your function like this:
```
def z_norm(ar... | Going back to its definition, the idea behind the z\_score is to give the distance between an element and the mean of the sample in terms of standard deviations. If all elements are the same, it means that their distance to the mean is 0, and therefore the zscore is 0 time the standard deviation, since all your data po... |
3,950,368 | >
> **Possible Duplicate:**
>
> [What do I use for a max-heap implementation in Python?](https://stackoverflow.com/questions/2501457/what-do-i-use-for-a-max-heap-implementation-in-python)
>
>
>
Python has a min heap implemented in the heapq module. However, if one would want a max heap, would one have to build... | 2010/10/16 | [
"https://Stackoverflow.com/questions/3950368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475790/"
] | You could multiply your numbers by -1 and use the min heap. | No need to implement a max heap from scratch. You can easily employ a bit of math to turn your min heap into a max heap!
See [this](http://www.mail-archive.com/python-list@python.org/msg238926.html) and [this](http://code.activestate.com/recipes/502295/) - but really [this SO answer](https://stackoverflow.com/question... |
55,522,649 | I have installed numpy but when I import it, it doesn't work.
```
from numpy import *
arr=array([1,2,3,4])
print(arr)
```
Result:
```
C:\Users\YUVRAJ\PycharmProjects\mycode2\venv\Scripts\python.exe C:/Users/YUVRAJ/PycharmProjects/mycode2/numpy.py
Traceback (most recent call last):
File "C:/Users/YUVRAJ/PycharmPr... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55522649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11313285/"
] | The problem is you named your script as `numpy.py`, which is a conflict with the module numpy that you need to use. Just rename your script to something else and will be fine. | Instead of using `from numpy import *`
Try using this:
```
import numpy
from numpy import array
```
And then add your code:
```
arr=array([1,2,3,4])
print(arr)
```
---
**EDIT:** Even though this is the accepted answer, this may not work under all circumstances. If this doesn't work, see [adrtam's answer](https:... |
24,703,432 | I am attempting to catch messages by topic by using the message\_callback\_add() function in [this library](https://pypi.python.org/pypi/paho-mqtt#usage-and-api). Below is my entire module that I am using to deal with my mqtt subscribe and publishing needs. I have been able to test that the publish works, but I can't s... | 2014/07/11 | [
"https://Stackoverflow.com/questions/24703432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851048/"
] | I called `loop_start` in the wrong place.
I moved the call to right after the connect statement and it now works.
Here is the snippet:
```
client_uniq = "pubclient_"+str(mypid)
mqttclient = paho.Client(client_uniq, False) #nocleanstart
mqttclient.connect(broker, port, 60)
mqttclient.loop_start()
mqttclient.subscri... | `loop_start()` will return immediately, so your program will quit before it gets chance to do anything.
You've also called `subscribe()` before `message_callback_add()` which doesn't make sense, although in this specific example it probably doesn't matter. |
23,190,348 | Has the alsaaudio library been ported to python3? i have this working on python 2.7 but not on python 3.
is there another library for python 3 if the above cannot be used? | 2014/04/21 | [
"https://Stackoverflow.com/questions/23190348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612242/"
] | I have compiled alsaaudio for python3 manually.
You can install it by following the steps given below.
1. Make sure that **gcc, python3-dev, libasound2-dev** packages are installed in your machine (install them using synaptic if you are using Ubuntu).
2. Download and extract the following package
<http://sourceforg... | It's now called pyalsaaudio.
For me pip install pyalsaaudio worked. |
66,929,254 | Is there a library for interpreting python code within a python program?
Sample usage might look like this..
```
code = """
def hello():
return 'hello'
hello()
"""
output = Interpreter.run(code)
print(output)
```
which then outputs
`hello` | 2021/04/03 | [
"https://Stackoverflow.com/questions/66929254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12594122/"
] | found this example from grepper
```
the_code = '''
a = 1
b = 2
return_me = a + b
'''
loc = {}
exec(the_code, globals(), loc)
return_workaround = loc['return_me']
print(return_workaround)
```
apparently you can pass global and local scope into `exec`. In your use case, you would just use a named variable instead of ... | You can use the `exec` function. You can't get the return value from the code variable. Instead you can print it there itself.
```
code = """
def hello():
print('hello')
hello()
"""
exec(code)
``` |
65,697,374 | So I am a beginner at python, and I was trying to install packages using pip. But any time I try to install I keep getting the error:
>
> ERROR: Could not install packages due to an EnvironmentError: [WinError 2] The system cannot find the file specified: 'c:\python38\Scripts\sqlformat.exe' -> 'c:\python38\Scripts\sq... | 2021/01/13 | [
"https://Stackoverflow.com/questions/65697374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14996295/"
] | Try running command line as administrator. The issue looks like its about permission. To run as administrator. Type cmd on search bar and right click on icon of command prompt. There you will find an option of run as administrator. Click the option and then try to install package | Looks like a permissions error. You might try starting the installation with admin rights or install the package only for your current user with:
```
pip install --user package
``` |
65,697,374 | So I am a beginner at python, and I was trying to install packages using pip. But any time I try to install I keep getting the error:
>
> ERROR: Could not install packages due to an EnvironmentError: [WinError 2] The system cannot find the file specified: 'c:\python38\Scripts\sqlformat.exe' -> 'c:\python38\Scripts\sq... | 2021/01/13 | [
"https://Stackoverflow.com/questions/65697374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14996295/"
] | Try running command line as administrator. The issue looks like its about permission. To run as administrator. Type cmd on search bar and right click on icon of command prompt. There you will find an option of run as administrator. Click the option and then try to install package | Looks like the issue is with permissions . Try running the same command on the terminal as a "administrator". Let me know if that fixes this issue. |
59,662,028 | I am trying to retrieve app related information from Google Play store using selenium and BeautifulSoup. When I try to retrieve the information, I got webdriver exception error. I checked the chrome version and chrome driver version (both are compatible). Here is the weblink that is causing the issue, code to retrieve ... | 2020/01/09 | [
"https://Stackoverflow.com/questions/59662028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293224/"
] | I think this is due to the chromedriver encoding problem.
See <https://bugs.chromium.org/p/chromium/issues/detail?id=723592#c9> for additional information about this bug.
Instead of selenium you can get page source using BeautifulSoup as follows.
```
import requests
from bs4 import BeautifulSoup
r = requests.get('ht... | try this
```
driver = webdriver.Chrome('path')
driver.get('https://play.google.com/store/apps/details?id=com.tudasoft.android.BeMakeup&hl=en&showAllReviews=true')
# retrieve data you want, for example
review_user_list = driver.find_elements_by_class_name("X43Kjb")
``` |
59,662,028 | I am trying to retrieve app related information from Google Play store using selenium and BeautifulSoup. When I try to retrieve the information, I got webdriver exception error. I checked the chrome version and chrome driver version (both are compatible). Here is the weblink that is causing the issue, code to retrieve ... | 2020/01/09 | [
"https://Stackoverflow.com/questions/59662028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293224/"
] | try this
```
driver = webdriver.Chrome('path')
driver.get('https://play.google.com/store/apps/details?id=com.tudasoft.android.BeMakeup&hl=en&showAllReviews=true')
# retrieve data you want, for example
review_user_list = driver.find_elements_by_class_name("X43Kjb")
``` | You can use [urllib](/questions/tagged/urllib "show questions tagged 'urllib'") with [beautifulsoup](/questions/tagged/beautifulsoup "show questions tagged 'beautifulsoup'") as follows:
* Code Block:
```
# -*- coding: UTF-8 -*
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
url = "https://pl... |
59,662,028 | I am trying to retrieve app related information from Google Play store using selenium and BeautifulSoup. When I try to retrieve the information, I got webdriver exception error. I checked the chrome version and chrome driver version (both are compatible). Here is the weblink that is causing the issue, code to retrieve ... | 2020/01/09 | [
"https://Stackoverflow.com/questions/59662028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293224/"
] | I think this is due to the chromedriver encoding problem.
See <https://bugs.chromium.org/p/chromium/issues/detail?id=723592#c9> for additional information about this bug.
Instead of selenium you can get page source using BeautifulSoup as follows.
```
import requests
from bs4 import BeautifulSoup
r = requests.get('ht... | You can use [urllib](/questions/tagged/urllib "show questions tagged 'urllib'") with [beautifulsoup](/questions/tagged/beautifulsoup "show questions tagged 'beautifulsoup'") as follows:
* Code Block:
```
# -*- coding: UTF-8 -*
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
url = "https://pl... |
36,781,198 | I'm sending an integer from python using pySerial.
```
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600);
ser.write(b'5');
```
When i compile,the receiver LED on arduino blinks.However I want to cross check if the integer is received by arduino. I cannot use Serial.println() because the port is busy. I... | 2016/04/21 | [
"https://Stackoverflow.com/questions/36781198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6237876/"
] | A simple way to do it using the standard library :
```
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class Example {
private static final int POOL_SIZE = 5;
private st... | I would recommend reading up on specific tutorials, such as the Java Language Tutorial (available as a book - at least, it used to be - as well as on the Java website <https://docs.oracle.com/javase/tutorial/essential/concurrency/>)
However as others have cautioned, getting into threading is a challenge and requires g... |
34,685,486 | After installing my python project with `setup.py` and executing it in terminal I get the following error:
```
...
from ui.mainwindow import MainWindow
File "/usr/local/lib/python2.7/dist-packages/EpiPy-0.1-py2.7.egg/epipy/ui/mainwindow.py", line 9, in <module>
from model.sir import SIR
ImportError: No module na... | 2016/01/08 | [
"https://Stackoverflow.com/questions/34685486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2609713/"
] | What I would do is to use absolute imports everywhere (from epipy import ...). That's what is recommanded in [PEP 328](https://docs.python.org/2.5/whatsnew/pep-328.html).
Your imports won't work anymore if the project is not installed. You can add the project directory to your PYTHONPATH, install the package, or, what... | I had a similar issue with one of my projects.
I've been able to solve my issue by adding this line at the start of my module (before all imports besides sys & os, which are required for this insert), so that it would include the parent folder and by that it will be able to see the parent folder (turns out it doesn't d... |
42,968,543 | I have a file displayed as follows. I want to delete the lines start from `>rev_` until the next line with `>`, not delete the `>` line. I want a python code to realize it.
input file:
```
>name1
fgrsagrhshsjtdkj
jfsdljgagdahdrah
gsag
>rev_name1 # delete from here
jfdsfjdlsgrgagrehdsah
fsagasfd ... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42968543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4672728/"
] | I'd recommend at least trying to come up with a solution on your own before asking us on here. Ask yourself questions regarding what different ways I can work towards a solution, will parsing character by character/line by line/regex be sufficient for this problem.
But in this case since determining when to start and... | The code also can be as follows:
```
with open("human.fasta") as inf, open("human_norev.fasta",'w') as outf:
del_start = False
for line in inf:
if line.startswith('>rev_'):
del_start = True
elif line.startswith('>'):
del_start = False
if not del_start:
... |
42,968,543 | I have a file displayed as follows. I want to delete the lines start from `>rev_` until the next line with `>`, not delete the `>` line. I want a python code to realize it.
input file:
```
>name1
fgrsagrhshsjtdkj
jfsdljgagdahdrah
gsag
>rev_name1 # delete from here
jfdsfjdlsgrgagrehdsah
fsagasfd ... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42968543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4672728/"
] | Your code isn't working because (among other things) you're not marking lines that neither start with `>rev` nor with `>`. Also, you'd need another loop for outputting all the lines that have been marked for output - right now you're only outputting the last one.
Alec's answer is nice, but I'll suggest a different app... | The code also can be as follows:
```
with open("human.fasta") as inf, open("human_norev.fasta",'w') as outf:
del_start = False
for line in inf:
if line.startswith('>rev_'):
del_start = True
elif line.startswith('>'):
del_start = False
if not del_start:
... |
49,396,554 | Okay, so I have the following issue. I have a Mac, so the the default Python 2.7 is installed for the OS's use. However, I also have Python 3.6 installed, and I want to install a package using Pip that is only compatible with python version 3. How can I install a package with Python 3 and not 2? | 2018/03/21 | [
"https://Stackoverflow.com/questions/49396554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9525828/"
] | To download use
```
pip3 install package
```
and to run the file
```
python3 file.py
``` | Why do you ask such a thing here?
<https://docs.python.org/3/using/mac.html>
>
> 4.3. Installing Additional Python Packages
> There are several methods to install additional Python packages:
>
>
> Packages can be installed via the standard Python distutils mode (python setup.py install).
> Many packages can also... |
49,396,554 | Okay, so I have the following issue. I have a Mac, so the the default Python 2.7 is installed for the OS's use. However, I also have Python 3.6 installed, and I want to install a package using Pip that is only compatible with python version 3. How can I install a package with Python 3 and not 2? | 2018/03/21 | [
"https://Stackoverflow.com/questions/49396554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9525828/"
] | To download use
```
pip3 install package
```
and to run the file
```
python3 file.py
``` | Just a suggestion, before you run any command that you don't know what is it, please use `which your_cmd` or `whereis your_cmd` to find its path. |
57,754,497 | So I think tensorflow.keras and the independant keras packages are in conflict and I can't load my model, which I have made with transfer learning.
Import in the CNN ipynb:
```
!pip install tensorflow-gpu==2.0.0b1
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
```
Loading this pretraine... | 2019/09/02 | [
"https://Stackoverflow.com/questions/57754497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10780811/"
] | Yes, there is a conflict between `tf.keras` and `keras` packages, you trained the model using `tf.keras` but then you are loading it with the `keras` package. That is not supported, you should use only one version of this package.
The specific problem is that you are using TensorFlow 2.0, but the standalone `keras` pa... | Try to replace
```
from keras.models import load_model
model =load_model('Leavesnet Model.h5')
```
with
`model = tf.keras.models.load_model(model_path)`
It works for me, and I am using:
tensorflow version: 2.0.0
keras version: 2.3.1
You can check the following:
<https://www.tensorflow.org/api_docs/python/tf/keras... |
57,754,497 | So I think tensorflow.keras and the independant keras packages are in conflict and I can't load my model, which I have made with transfer learning.
Import in the CNN ipynb:
```
!pip install tensorflow-gpu==2.0.0b1
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
```
Loading this pretraine... | 2019/09/02 | [
"https://Stackoverflow.com/questions/57754497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10780811/"
] | Yes, there is a conflict between `tf.keras` and `keras` packages, you trained the model using `tf.keras` but then you are loading it with the `keras` package. That is not supported, you should use only one version of this package.
The specific problem is that you are using TensorFlow 2.0, but the standalone `keras` pa... | I think downgrading your **keras** or **tensorflow** will not be that much suitable because you need to retrain your model for various dependencies. Why not try to load the weights instead of loading the model?
here is a piece of code
```
import tensorflow as tf
{your code here}
#save the weights
model.save_weights(... |
57,754,497 | So I think tensorflow.keras and the independant keras packages are in conflict and I can't load my model, which I have made with transfer learning.
Import in the CNN ipynb:
```
!pip install tensorflow-gpu==2.0.0b1
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
```
Loading this pretraine... | 2019/09/02 | [
"https://Stackoverflow.com/questions/57754497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10780811/"
] | Try to replace
```
from keras.models import load_model
model =load_model('Leavesnet Model.h5')
```
with
`model = tf.keras.models.load_model(model_path)`
It works for me, and I am using:
tensorflow version: 2.0.0
keras version: 2.3.1
You can check the following:
<https://www.tensorflow.org/api_docs/python/tf/keras... | I think downgrading your **keras** or **tensorflow** will not be that much suitable because you need to retrain your model for various dependencies. Why not try to load the weights instead of loading the model?
here is a piece of code
```
import tensorflow as tf
{your code here}
#save the weights
model.save_weights(... |
66,196,791 | So take a triangle formatted as a nested list.
e.g.
```
t = [[5],[3, 6],[8, 14, 7],[4, 9, 2, 0],[9, 11, 5, 2, 9],[1, 3, 8, 5, 3, 2]]
```
and define a path to be the sum of elements from each row of the triangle,
moving 1 to the left or right as you go down rows. Or in python
the second index either stays the same o... | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15208320/"
] | We can simplify the expression a bit by including all the rows in the second argument to reduce - there's no reason to pass the last row as third parameter (the starting value) of `reduce`.
Then, it really helps to give your variables meaningful names, which the original code badly fails to do.
So, this becomes:
```... | you can spell out the lambda function so it can print. does this help you understand?
```
t = [[5],[3, 6],[8, 14, 7],[4, 9, 2, 0],[9, 11, 5, 2, 9],[1, 3, 8, 5, 3, 2]]
def g( xs, ys):
ans=[a + max(b, c) for (a, b, c) in zip(ys, xs, xs[1:])]
print(ans)
return ans
def maxPathSum(rows):
return reduce(
... |
2,291,176 | I need to arrange some kind of encrpytion for generating user specific links. Users will be clicking this link and at some other view, related link with the crypted string will be decrypted and result will be returned.
For this, I need some kind of encryption function that consumes a number(or a string) that is the pr... | 2010/02/18 | [
"https://Stackoverflow.com/questions/2291176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151937/"
] | There are no encryption algorithms, per se, built in to Python. However, you might want to look at the [Python Cryptography Toolkit](http://www.dlitz.net/software/pycrypto/) (PyCrypt). I've only tinkered with it, but it's referenced in Python's documentation on [cryptographic services](http://docs.python.org/library/cr... | Django has features for this now. See <https://docs.djangoproject.com/en/dev/topics/signing/>
Quoting that page:
"Django provides both a low-level API for signing values and a high-level API for setting and reading signed cookies, one of the most common uses of signing in Web applications.
You may also find signin... |
11,632,154 | In python if I have two dictionaries, specifically Counter objects that look like so
```
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
```
Can I combine these dictionaries so that the results is a dictionary of lists, as follows:
```
c3 =... | 2012/07/24 | [
"https://Stackoverflow.com/questions/11632154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/801348/"
] | ```
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
for k,v in c.iteritems():
c3.setdefault(k, []).append(v)
```
`c3` is now: `{'item1': [4, 6], 'item2': [2, 2], 'item3': ... | Or with a list comprehension:
```
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
merged = {}
for k in set().union(c1, c2):
merged[k] = [d[k] for d in [c1, c2] if k in d]
>>> merged
{'item2': [2, 2], 'item3... |
11,632,154 | In python if I have two dictionaries, specifically Counter objects that look like so
```
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
```
Can I combine these dictionaries so that the results is a dictionary of lists, as follows:
```
c3 =... | 2012/07/24 | [
"https://Stackoverflow.com/questions/11632154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/801348/"
] | ```
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
for k,v in c.iteritems():
c3.setdefault(k, []).append(v)
```
`c3` is now: `{'item1': [4, 6], 'item2': [2, 2], 'item3': ... | You can use `defaultdict`:
```
>>> from collections import Counter, defaultdict
>>> c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
>>> c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
>>> c3 = defaultdict(list)
>>> for c in c1, c2:
... for k, v in c.items():
... c3[k].append(v)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.