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 |
|---|---|---|---|---|---|
24,053,152 | I want to convert date like Jun 28 in datetime format like 2014-06-28. I tried following code and many more variation which gives me correct output in ipython but I m unable to save the record in database. It throws error as value has an invalid date format. It must be in YYYY-MM-DD format. Can anyone help me to fix th... | 2014/06/05 | [
"https://Stackoverflow.com/questions/24053152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446107/"
] | Once you have a `date` object, you can use the `strftime()` function to [format](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) it into a string.
Let's say `new_date` is your date object from your question. Then you can do:
```
new_date.strftime('%Y-%m-%d')
```
Btw, you can do the s... | I tried on console:
```
>>import datetime
>>datetime.datetime.strptime("Jun-08-2013", '%b-%d-%Y').date()
datetime.date(2013, 6, 8)
```
There are several errors in the code. So solution should be:
```
m = "Jun"
d = 28
if datetime.datetime.strptime("Aug",'%b').month > datetime.datetime.now().m... |
64,956,344 | I have created a python program that works fine. but I want to make it more neat, I ask the user for numbers, number1, number2 etc. up to 5. I want to just do this with a for loop though, like this
```
for i in range(0,5):
number(i) = int(input("what is the number"))
```
I realise that this code docent actually ... | 2020/11/22 | [
"https://Stackoverflow.com/questions/64956344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14640673/"
] | What your code is, cannot be done per se but it can be done using lists like this:
```
number_list = []
for i in range(5);
number = int(input("What is the number?"))
number_list.append(number)
// Now you can access the list using indexes
for j in len(number_list):
print(number_list[j])
``` | If you want to save also variable names you can use python `dictionaries` like this:
```
number = {}
for i in range(0,5):
number[f'number{i}'] = int(input("what is the number "))
print(number)
```
output:
```
{'number0': 5, 'number1': 4, 'number2': 5, 'number3': 6, 'number4': 3}
``` |
64,956,344 | I have created a python program that works fine. but I want to make it more neat, I ask the user for numbers, number1, number2 etc. up to 5. I want to just do this with a for loop though, like this
```
for i in range(0,5):
number(i) = int(input("what is the number"))
```
I realise that this code docent actually ... | 2020/11/22 | [
"https://Stackoverflow.com/questions/64956344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14640673/"
] | Code:
```
number = []
for i in range(5):
number.append(int(input("what is the number ")))
print(number)
``` | If you want to save also variable names you can use python `dictionaries` like this:
```
number = {}
for i in range(0,5):
number[f'number{i}'] = int(input("what is the number "))
print(number)
```
output:
```
{'number0': 5, 'number1': 4, 'number2': 5, 'number3': 6, 'number4': 3}
``` |
64,956,344 | I have created a python program that works fine. but I want to make it more neat, I ask the user for numbers, number1, number2 etc. up to 5. I want to just do this with a for loop though, like this
```
for i in range(0,5):
number(i) = int(input("what is the number"))
```
I realise that this code docent actually ... | 2020/11/22 | [
"https://Stackoverflow.com/questions/64956344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14640673/"
] | The easiest I could think at the top of my had way would just to create a list and append the items:
```
numbers = []
for i in range(0,5):
numbers += [int(input("what is the number"))]
``` | If you want to save also variable names you can use python `dictionaries` like this:
```
number = {}
for i in range(0,5):
number[f'number{i}'] = int(input("what is the number "))
print(number)
```
output:
```
{'number0': 5, 'number1': 4, 'number2': 5, 'number3': 6, 'number4': 3}
``` |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | as others have said - "no"
Almost all of your time is spent waiting for IO. If this is something that you need to do more than once, *and* you have a machine with tons of ram, you could keep the file in memory. If your machine has 16GB of ram, you'll have 8GB available at /dev/shm to play with.
Another option:
If you... | Note that Python I/O is implemented in C, so there is not much luck speeding it up further. |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | You can't get any faster than the maximum disk read speed.
In order to reach the maximum disk speed you can use the following two tips:
1. Read the file in with a big buffer. This can either be coded "manually" or simply by using io.BufferedReader ( available in python2.6+ ).
2. Do the newline counting in another thr... | **plain "no".**
You've pretty much reached maximum disk speed.
I mean, you could [mmap](http://docs.python.org/library/mmap.html) the file, or read it in binary chunks, and use `.count('\n')` or something. But that is unlikely to give major improvements. |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | **Throw hardware at the problem.**
As gs pointed out, your bottleneck is the hard disk transfer rate. So, no you can't use a better algorithm to improve your time, but you can buy a faster hard drive.
**Edit:** Another good point by gs; you could also use a [RAID](http://en.wikipedia.org/wiki/Redundant_array_of_indep... | The trick is not to make electrons move faster (that's hard to do) but to get more work done per unit of time.
First, be sure your 6GB file read is I/O bound, not CPU bound.
If It's I/O bound, consider the "Fan-Out" design pattern.
* A parent process spawns a bunch of children.
* The parent reads the 6Gb file, and d... |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | If you assume that a disk can read 60MB/s you'd need 6000 / 60 = 100 seconds, which is 1 minute 40 seconds. I don't think that you can get any faster because the disk is the bottleneck. | Note that Python I/O is implemented in C, so there is not much luck speeding it up further. |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | **Throw hardware at the problem.**
As gs pointed out, your bottleneck is the hard disk transfer rate. So, no you can't use a better algorithm to improve your time, but you can buy a faster hard drive.
**Edit:** Another good point by gs; you could also use a [RAID](http://en.wikipedia.org/wiki/Redundant_array_of_indep... | 2 minutes sounds about right to read an entire 6gb file. Theres not really much you can do to the algorithm or the OS to speed things up. I think you have two options:
1. Throw money at the problem and get better hardware. Probably the best option if this project is for your job.
2. Don't read the entire file. I don't... |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | The trick is not to make electrons move faster (that's hard to do) but to get more work done per unit of time.
First, be sure your 6GB file read is I/O bound, not CPU bound.
If It's I/O bound, consider the "Fan-Out" design pattern.
* A parent process spawns a bunch of children.
* The parent reads the 6Gb file, and d... | 2 minutes sounds about right to read an entire 6gb file. Theres not really much you can do to the algorithm or the OS to speed things up. I think you have two options:
1. Throw money at the problem and get better hardware. Probably the best option if this project is for your job.
2. Don't read the entire file. I don't... |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | as others have said - "no"
Almost all of your time is spent waiting for IO. If this is something that you need to do more than once, *and* you have a machine with tons of ram, you could keep the file in memory. If your machine has 16GB of ram, you'll have 8GB available at /dev/shm to play with.
Another option:
If you... | PyPy provides optimised input/output faster up to 7 times. |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | If you assume that a disk can read 60MB/s you'd need 6000 / 60 = 100 seconds, which is 1 minute 40 seconds. I don't think that you can get any faster because the disk is the bottleneck. | 2 minutes sounds about right to read an entire 6gb file. Theres not really much you can do to the algorithm or the OS to speed things up. I think you have two options:
1. Throw money at the problem and get better hardware. Probably the best option if this project is for your job.
2. Don't read the entire file. I don't... |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | If you assume that a disk can read 60MB/s you'd need 6000 / 60 = 100 seconds, which is 1 minute 40 seconds. I don't think that you can get any faster because the disk is the bottleneck. | PyPy provides optimised input/output faster up to 7 times. |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | **plain "no".**
You've pretty much reached maximum disk speed.
I mean, you could [mmap](http://docs.python.org/library/mmap.html) the file, or read it in binary chunks, and use `.count('\n')` or something. But that is unlikely to give major improvements. | This is a bit of an old question, but one idea I've recently tested out in my petabyte project was the speed benefit of compressing data, then using compute to decompress it into memory. I used a gigabyte as a standard, but using [`zlib`](https://docs.python.org/3/library/zlib.html) you can get really impressive file s... |
58,837,883 | I was automating software installation using python's pyautogui model. So, I crop some images from installation screen like for clicking next, accept the terms and conditions. Using image search I am able to locate the image on the screen and able to click on the right areas. Works fine in my system.
However, the scrip... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58837883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2853557/"
] | As far as I can assume! The problem is with image resolution.
In my company, I also have a robot that automates some complex task. All the monitors here are same but still, I was facing some trouble matching images. Cropped image from one PC was not working on another. So what I am doing right now is using "SNIPPING TO... | You can change the resolution if you make script in `1366x768`and trying in 1920x1080 it will never work because you need to add new image
there are two ways you can use:
1:> replace the image
2:> add the x,y position
**Way:**
```
xy = pyautogui.locateCenterOnScreen('your directory', grayscale=True, confidence=.5... |
41,734,584 | I have some background in machine learning and python, but I am just learning TensorFlow. I am going through the [tutorial on deep convolutional neural nets](https://www.tensorflow.org/tutorials/deep_cnn/) to teach myself how to use it for image classification. Along the way there is an exercise, which I am having trou... | 2017/01/19 | [
"https://Stackoverflow.com/questions/41734584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6862133/"
] | I'm also working on this exercise. I'll try and explain my approach properly, rather than just give the solution. It's worth looking back at the mathematics of a fully connected layer (<https://www.tensorflow.org/get_started/mnist/beginners>).
So the linear algebra for a fully connected layer is:
*y = W \* x + b*
wh... | I'll try to answer your question although I'm not 100% I got it right as well.
Looking at the cuda-convnet [architecture](https://github.com/akrizhevsky/cuda-convnet2/blob/master/layers/layers-cifar10-11pct.cfg) we can see that the TensorFlow and cuda-convnet implementations start to differ after the second pooling l... |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic. | Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it. |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.
```
class BaseAccess:
def open(arg):
raise NotImplementedError()
class Pop3Access(BaseAccess):
def open(arg):
...
class AlternateAccess(BaseAccess):
def open(arg)... | Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it. |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | One option is to use [zope interfaces](http://docs.zope.org/zope2/zdgbook/ComponentsAndInterfaces.html#python-interfaces). However, as was stated by [Wai Yip Tung](https://stackoverflow.com/questions/2860106/creating-an-interface-and-swappable-implementations-in-python/2860419#2860419), you do not need to use interface... | Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it. |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.
```
class BaseAccess:
def open(arg):
raise NotImplementedError()
class Pop3Access(BaseAccess):
def open(arg):
...
class AlternateAccess(BaseAccess):
def open(arg)... | Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic. |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic. | One option is to use [zope interfaces](http://docs.zope.org/zope2/zdgbook/ComponentsAndInterfaces.html#python-interfaces). However, as was stated by [Wai Yip Tung](https://stackoverflow.com/questions/2860106/creating-an-interface-and-swappable-implementations-in-python/2860419#2860419), you do not need to use interface... |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.
```
class BaseAccess:
def open(arg):
raise NotImplementedError()
class Pop3Access(BaseAccess):
def open(arg):
...
class AlternateAccess(BaseAccess):
def open(arg)... | One option is to use [zope interfaces](http://docs.zope.org/zope2/zdgbook/ComponentsAndInterfaces.html#python-interfaces). However, as was stated by [Wai Yip Tung](https://stackoverflow.com/questions/2860106/creating-an-interface-and-swappable-implementations-in-python/2860419#2860419), you do not need to use interface... |
6,256,369 | I want to create a "full file name" variable from several other variables, but the string concatenation and string format operations aren't behaving the way I expect.
My code is below:
```
file_date = str(input("Enter file date: "))
root_folder = "\\\\SERVER\\FOLDER\\"
file_prefix = "sample_file_"
file_extension = ... | 2011/06/06 | [
"https://Stackoverflow.com/questions/6256369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467055/"
] | I think the method input used in your example, like so:
```
file_date = str(input("Enter file date: "))
```
may be returning a carriage return character at the end.
This causes the cursor to go back to the start of the line when you try to print it out.
You may want to trim the return value of input(). | Use this line instead to get rid of the line feed:
```
file_date = str(input("Enter file date: ")).rstrip()
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | Worked for me on Ubuntu 18.04 as well:
```
$ sudo apt-get install graphviz
``` | On mac, use Brew to install graphviz and not pip, see links:
graphviz information: <http://www.graphviz.org/download/>
brew installation: <https://brew.sh/>
So typing the following in the terminal after you install brew should work:
```
brew install graphviz
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | For windows users:
1.install Graphviz
2.Add Graphviz path to PATH variable
3.Restart PyCharm or other compiler.
As of version 2.31, the Visual Studio package no longer alters the PATH variable or accesses the registry at all. If you wish to use the command-line interface to Graphviz or are using some other p... | i would suggest avoid graphviz.
use the following alternate approach
```
from sklearn.tree import plot_tree
plt.figure(figsize=(60,30))
plot_tree(dt, filled=True);
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | ```
brew install graphviz
pip install -U pydotplus
```
... worked for me on MacOSX | Worked for me on Ubuntu 18.04 as well:
```
$ sudo apt-get install graphviz
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | cel, answered this in the comment:
>
> Graphviz is not a python tool. The python packages at pypi provide a
> convenient way of using Graphviz in python code. You still have to
> install the Graphviz executables, which are not pythonic, thus not
> shipped with these packages. You can install those e.g. with a
> g... | On Windows 8 this solved the same problem for me:
```
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | On Windows 8 this solved the same problem for me:
```
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
``` | If you are on mac operating system then you might face this issue . I have installed graphviz with pip but dint work . So I had to install it with brew again and worked for me.
**use following command**
>
> brew install graphviz
>
>
> |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | On Windows 8 this solved the same problem for me:
```
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
``` | i would suggest avoid graphviz.
use the following alternate approach
```
from sklearn.tree import plot_tree
plt.figure(figsize=(60,30))
plot_tree(dt, filled=True);
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | ```
brew install graphviz
pip install -U pydotplus
```
... worked for me on MacOSX | I had the same issue when installing pydot and graphviz with pip, then I found the answer [here](https://groups.google.com/forum/#!topic/caffe-users/4r5dxoFpWxk).
In particular, I first uninstalled pydot and graphviz which I separately installed using pip (using `sudo pip uninstall pydot` and the same for `graphviz`).... |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | I was facing the same issues, my problem got resolved using:
1. Run the command `sudo port install graphviz`
2. If error is coming for the port then first install port from below based on the version you are using
<https://guide.macports.org/chunked/installing.macports.html>
3. After installation of port run command ... | i would suggest avoid graphviz.
use the following alternate approach
```
from sklearn.tree import plot_tree
plt.figure(figsize=(60,30))
plot_tree(dt, filled=True);
``` |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | I had the same issue when installing pydot and graphviz with pip, then I found the answer [here](https://groups.google.com/forum/#!topic/caffe-users/4r5dxoFpWxk).
In particular, I first uninstalled pydot and graphviz which I separately installed using pip (using `sudo pip uninstall pydot` and the same for `graphviz`).... | For windows users:
1.install Graphviz
2.Add Graphviz path to PATH variable
3.Restart PyCharm or other compiler.
As of version 2.31, the Visual Studio package no longer alters the PATH variable or accesses the registry at all. If you wish to use the command-line interface to Graphviz or are using some other p... |
27,666,846 | I try to run [this example](http://scikit-learn.org/stable/modules/tree.html) for decision tree learning, but get the following error message:
>
> File "coco.py", line 18, in
> graph.write\_pdf("iris.pdf") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py",
> line 1602, i... | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397694/"
] | Worked for me on Ubuntu 18.04 as well:
```
$ sudo apt-get install graphviz
``` | I did face similar issue and the way it was corrected was by changing the path.
This is what I did :
Copy paste "graphiz" path from your computer to Environment variable>Path from the control panel
Example:
Graphiz path : C:\Apps\Program Files\Continuum\Anaconda2\Library\bin\graphviz)
(I had installed it on Apps... |
3,076,928 | Using sqlite3 and Django I want to change to PostgreSQL and keep all data intact. I used `./manage.py dumpdata > dump.json` to dump the data, and changed settings to use PostgreSQL.
With an empty database `./manage.py loaddata dump.json` resulted in errors about tables not existing, so I ran `./manage.py syncdb` and t... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66107/"
] | The problem is simply that you're getting the content types defined twice - once when you do `syncdb`, and once from the exported data you're trying to import. Since you may well have other items in your database that depend on the original content type definitions, I would recommend keeping those.
So, after running `... | There is a big discussion about it on the [Django ticket 7052](http://code.djangoproject.com/ticket/7052). The right way now is to use the `--natural` parameter, example: `./manage.py dumpdata --natural --format=xml --indent=2 > fixture.xml`
In order for `--natural` to work with your models, they must implement `natur... |
3,076,928 | Using sqlite3 and Django I want to change to PostgreSQL and keep all data intact. I used `./manage.py dumpdata > dump.json` to dump the data, and changed settings to use PostgreSQL.
With an empty database `./manage.py loaddata dump.json` resulted in errors about tables not existing, so I ran `./manage.py syncdb` and t... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66107/"
] | The problem is simply that you're getting the content types defined twice - once when you do `syncdb`, and once from the exported data you're trying to import. Since you may well have other items in your database that depend on the original content type definitions, I would recommend keeping those.
So, after running `... | This worked for me. You probably want to ensure the server is stopped so no new data is lost. Dump it:
```
$ python manage.py dumpdata --exclude auth.permission --exclude contenttypes --natural > db.json
```
Make sure your models don't have signals (e.g. post\_save) or anything that creates models. If you do, commen... |
3,076,928 | Using sqlite3 and Django I want to change to PostgreSQL and keep all data intact. I used `./manage.py dumpdata > dump.json` to dump the data, and changed settings to use PostgreSQL.
With an empty database `./manage.py loaddata dump.json` resulted in errors about tables not existing, so I ran `./manage.py syncdb` and t... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66107/"
] | The problem is simply that you're getting the content types defined twice - once when you do `syncdb`, and once from the exported data you're trying to import. Since you may well have other items in your database that depend on the original content type definitions, I would recommend keeping those.
So, after running `... | I used pgloader, just take a few seconds to migrate successfully:
```
$ pgloader project.load
```
project.load file with:
```
load database
from sqlite:////path/to/dev.db
into postgresql://user:pwd@localhost/db_name
with include drop, create tables, create indexes, reset sequences
set work_mem to '16MB', mai... |
3,076,928 | Using sqlite3 and Django I want to change to PostgreSQL and keep all data intact. I used `./manage.py dumpdata > dump.json` to dump the data, and changed settings to use PostgreSQL.
With an empty database `./manage.py loaddata dump.json` resulted in errors about tables not existing, so I ran `./manage.py syncdb` and t... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66107/"
] | There is a big discussion about it on the [Django ticket 7052](http://code.djangoproject.com/ticket/7052). The right way now is to use the `--natural` parameter, example: `./manage.py dumpdata --natural --format=xml --indent=2 > fixture.xml`
In order for `--natural` to work with your models, they must implement `natur... | This worked for me. You probably want to ensure the server is stopped so no new data is lost. Dump it:
```
$ python manage.py dumpdata --exclude auth.permission --exclude contenttypes --natural > db.json
```
Make sure your models don't have signals (e.g. post\_save) or anything that creates models. If you do, commen... |
3,076,928 | Using sqlite3 and Django I want to change to PostgreSQL and keep all data intact. I used `./manage.py dumpdata > dump.json` to dump the data, and changed settings to use PostgreSQL.
With an empty database `./manage.py loaddata dump.json` resulted in errors about tables not existing, so I ran `./manage.py syncdb` and t... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66107/"
] | There is a big discussion about it on the [Django ticket 7052](http://code.djangoproject.com/ticket/7052). The right way now is to use the `--natural` parameter, example: `./manage.py dumpdata --natural --format=xml --indent=2 > fixture.xml`
In order for `--natural` to work with your models, they must implement `natur... | I used pgloader, just take a few seconds to migrate successfully:
```
$ pgloader project.load
```
project.load file with:
```
load database
from sqlite:////path/to/dev.db
into postgresql://user:pwd@localhost/db_name
with include drop, create tables, create indexes, reset sequences
set work_mem to '16MB', mai... |
74,451,481 | I have built a python script that uses python socket to build a connection between my python application and my python server. I have encrypted the data sent between the two systems. I was wondering if I should think of any other things related to security against hackers. Can they do something that could possibly stea... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513644/"
] | To make this slightly more extensible, you can convert it to an object:
```js
function process(input) {
let data = input.split("\n\n"); // split by double new line
data = data.map(i => i.split("\n")); // split each pair
data = data.map(i => i.reduce((obj, cur) => {
const [key, val] = cur.split(": "); // get ... | These kinds of text extraction are always pretty fragile, so let me know if this works for your real inputs... Anyways, if we split by empty lines (which are really just double line breaks, `\n\n`), and then split each "paragraph" by `\n`, we get chunks of lines we can work with.
Then we can just find the chunk that h... |
73,430,007 | I'm building a website using python and Django, but when I looked in the admin, the names of the model items aren't showing up.
[](https://i.stack.imgur.com/bPvtX.png)
[](https://i.st... | 2022/08/20 | [
"https://Stackoverflow.com/questions/73430007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19771403/"
] | Add [`__str__()`](https://docs.python.org/3/reference/datamodel.html#object.__str__) method in the model itself instead of admin.py, so:
```py
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField()
email ... | You need to specify a `def __str__(self)` method.
Example:
```
class Author(models..):
....
def __str__(self):
return self.first_name + ' ' + self.last_name
``` |
57,124,038 | I am a beginner with Python and I am learning how to treat images.
Given a square image (NxN), I would like to make it into a (N+2)x(N+2) image with a new layer of zeros around it. I would prefer not to use numpy and only stick with the basic python programming. Any idea on how to do so ?
Right now, I used .extend ... | 2019/07/20 | [
"https://Stackoverflow.com/questions/57124038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10154400/"
] | We can create a padding function that adds layers of zeros around an image (padding it).
```
def pad(img,layers):
#img should be rectangular
return [[0]*(len(img[0])+2*layers)]*layers + \
[[0]*layers+r+[0]*layers for r in img] + \
[[0]*(len(img[0])+2*layers)]*layers
```
We can test w... | Im assuming that by image we're talking about a matrix, in that case you could do this:
```
img = [[5, 5, 5], [5, 5, 5], [5, 5, 5]]
row_len = len(img)
col_len = len(img[0])
new_image = list()
for n in range(col_len+2): # Adding two more rows
if n == 0 or n == col_len + 1:
new_image.append([0] * (row_len ... |
53,440,086 | I am trying to right click with mouse and click save as Image in selenium python.
I was able to perform right click with follwing method, however the next action to perform right click does not work any more. How can I solve this problem?
```
from selenium.webdriver import ActionChains
from selenium.webdriver.common... | 2018/11/23 | [
"https://Stackoverflow.com/questions/53440086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8263870/"
] | You can do the same functionality using pyautogui. Assuming you are using Windows.
-->pyautogui.position()
(187, 567) #prints the current cursor position
-->pyautogui.moveTo(100, 200)#move to location where right click is req.
-->pyautogui.click(button='right')
-->pyautogui.hotkey('ctrl', 'c') - Ctrl+C in keyboard(C... | You have to first move to the element where you want to perform the context click
```py
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
driver.get(url)
# get the image source
img = driver.find_element_by_xpath('//img')
actionChains = ActionCh... |
53,440,086 | I am trying to right click with mouse and click save as Image in selenium python.
I was able to perform right click with follwing method, however the next action to perform right click does not work any more. How can I solve this problem?
```
from selenium.webdriver import ActionChains
from selenium.webdriver.common... | 2018/11/23 | [
"https://Stackoverflow.com/questions/53440086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8263870/"
] | The problem is that the send\_keys() method, after having created the context menu, sends the keys to the window, and not to the menu. So, there is no way to access the menu items.
I had a similar problem with downloading a canvas created in a webpage. Finally, I was able to download the image executing a javascript. ... | You can do the same functionality using pyautogui. Assuming you are using Windows.
-->pyautogui.position()
(187, 567) #prints the current cursor position
-->pyautogui.moveTo(100, 200)#move to location where right click is req.
-->pyautogui.click(button='right')
-->pyautogui.hotkey('ctrl', 'c') - Ctrl+C in keyboard(C... |
53,440,086 | I am trying to right click with mouse and click save as Image in selenium python.
I was able to perform right click with follwing method, however the next action to perform right click does not work any more. How can I solve this problem?
```
from selenium.webdriver import ActionChains
from selenium.webdriver.common... | 2018/11/23 | [
"https://Stackoverflow.com/questions/53440086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8263870/"
] | The problem is that the send\_keys() method, after having created the context menu, sends the keys to the window, and not to the menu. So, there is no way to access the menu items.
I had a similar problem with downloading a canvas created in a webpage. Finally, I was able to download the image executing a javascript. ... | You have to first move to the element where you want to perform the context click
```py
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
driver.get(url)
# get the image source
img = driver.find_element_by_xpath('//img')
actionChains = ActionCh... |
32,406,711 | I'm trying to write a python script using BeautifulSoup that crawls through a webpage <http://tbc-python.fossee.in/completed-books/> and collects necessary data from it. Basically it has to fetch all the `page loading errors, SyntaxErrors, NameErrors, AttributeErrors, etc` present in the chapters of all the books to a ... | 2015/09/04 | [
"https://Stackoverflow.com/questions/32406711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5283513/"
] | Try to change your buttons to:
```
{
display: "Hello There",
action: functionA
}
```
And to invoke:
```
btn[i].action();
```
I changed the name `function` to `action` because `function` is a reserved word and cannot be used as an object property name. | You can store references to the functions in your array, just lose the `"` signs around their names *(which currently makes them strings instead of function references)*, creating the array like this:
```
var btn = [{
x: 50,
y: 100,
width: 80,
height: 50,... |
32,406,711 | I'm trying to write a python script using BeautifulSoup that crawls through a webpage <http://tbc-python.fossee.in/completed-books/> and collects necessary data from it. Basically it has to fetch all the `page loading errors, SyntaxErrors, NameErrors, AttributeErrors, etc` present in the chapters of all the books to a ... | 2015/09/04 | [
"https://Stackoverflow.com/questions/32406711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5283513/"
] | Try to change your buttons to:
```
{
display: "Hello There",
action: functionA
}
```
And to invoke:
```
btn[i].action();
```
I changed the name `function` to `action` because `function` is a reserved word and cannot be used as an object property name. | Don't put the name of the function in the array, put a reference to the function itself:
```
var btn = [{
x: 50,
y: 100,
width: 80,
height: 50,
display: "Hello There",
'function': functionA
}, {
x: 150,
y: 1... |
44,412,844 | I have been trying to use CloudFormation to deploy to API Gateway, however, I constantly run into the same issue with my method resources. The stack deployments keep failing with 'Invalid Resource identifier specified'.
Here is my method resource from my CloudFormation template:
```
"UsersPut": {
"Type": "AWS... | 2017/06/07 | [
"https://Stackoverflow.com/questions/44412844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067870/"
] | ResourceId must be a reference to a cloudformation resource, not a simple string.
e.g.
```
ResourceId:
Ref: UsersResource
``` | When you create an API resource(1), a default root resource(2) for the API is created for path /. In order to get the id for the MyApi resource(1) root resource(2) use:
```
"ResourceId": {
"Fn::GetAtt": [
"MyApi",
"RootResourceId"
]
}
```
(1) The stack resource
(2) The API resource |
44,412,844 | I have been trying to use CloudFormation to deploy to API Gateway, however, I constantly run into the same issue with my method resources. The stack deployments keep failing with 'Invalid Resource identifier specified'.
Here is my method resource from my CloudFormation template:
```
"UsersPut": {
"Type": "AWS... | 2017/06/07 | [
"https://Stackoverflow.com/questions/44412844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067870/"
] | I figured that actually it was the RestApiId which needed to be a reference too:
```
"RestApiId": {
"Ref": "MyApi"
},
``` | When you create an API resource(1), a default root resource(2) for the API is created for path /. In order to get the id for the MyApi resource(1) root resource(2) use:
```
"ResourceId": {
"Fn::GetAtt": [
"MyApi",
"RootResourceId"
]
}
```
(1) The stack resource
(2) The API resource |
18,150,518 | So i have a python script which generates an image, and saves over the old image which used to be the background image.
I tried to make it run using `crontab`, but couldn't get that to work, so now i just have a bash script which runs once in my `.bashrc` whdn i first log in (i have a `if [ firstRun ]` kind of thing i... | 2013/08/09 | [
"https://Stackoverflow.com/questions/18150518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432913/"
] | Well, you can change the current wallaper (in Gnome 3 compatible desktops) by running
```
import os
os.system("gsettings set org.gnome.desktop.background picture-uri file://%(path)s" % {'path':absolute_path})
os.system("gsettings set org.gnome.desktop.background picture-options wallpaper")
``` | If you're using MATE, you're using a fork of Gnome 2.x. The method I found for Gnome 2 is : `gconftool-2 --set --type string --set /desktop/gnome/background/picture_filename <absolute image path>`.
The method we tried before would have worked in Gnome Shell. |
64,963,033 | I am using below code to excute a python script every 5 minutes but when it executes next time its not excecuting at excact time as before.
example if i am executing it at exact 9:00:00 AM, next time it executes at 9:05:25 AM and next time 9:10:45 AM. as i run the python script every 5 minutes for long time its not abl... | 2020/11/23 | [
"https://Stackoverflow.com/questions/64963033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14642703/"
] | You can use the `ObservableList.contains` method to quickly check any occurrence of a similar item:
```
public void diplaysubjects() {
String item = select_subject.getSelectionModel().getSelectedItem();
ObservableList<String> courses = course_list.getItems(); // Only here to clarify the code
if (!courses.... | I suggest you to use observable list with ListView.
Do like this
```
public class Controller implements Initializable {
@FXML
private ComboBox<String> select_subject;
@FXML
private ListView<String> course_list;
private ObservableList<String> list = FXCollections.observableArrayList();
@Override
public void initial... |
64,963,033 | I am using below code to excute a python script every 5 minutes but when it executes next time its not excecuting at excact time as before.
example if i am executing it at exact 9:00:00 AM, next time it executes at 9:05:25 AM and next time 9:10:45 AM. as i run the python script every 5 minutes for long time its not abl... | 2020/11/23 | [
"https://Stackoverflow.com/questions/64963033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14642703/"
] | You can use the `ObservableList.contains` method to quickly check any occurrence of a similar item:
```
public void diplaysubjects() {
String item = select_subject.getSelectionModel().getSelectedItem();
ObservableList<String> courses = course_list.getItems(); // Only here to clarify the code
if (!courses.... | You can add an arrayList() where you add the String if it doesn't contain it and then add it to the ListView.
```java
@FXML
private ComboBox<String> select_subject;
@FXML
private ListView<String> course_list;
public void diplaysubjects() {
ArrayList<String> s = new ArrayList<>();
... |
58,040,556 | I have a Pandas DataFrame with date columns. The data is imported from a csv file. When I try to fit the regression model, I get the error `ValueError: could not convert string to float: '2019-08-30 07:51:21`.
.
How can I get rid of it?
Here is dataframe.
**source.csv**
```
event_id tsm_id rssi_ts rs... | 2019/09/21 | [
"https://Stackoverflow.com/questions/58040556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451435/"
] | The last entry in your list is missing the item property which should be the URL for the page it references.
I suspect the last one is the page itself, which is not needed in the list anyhow. | Just for the record, we found the same error message which seemed to be because the referred URL was not available to the tool (it was inside our company network but not publicly available).
Pointing to a public valid URL fixed the error message on our side. |
30,400,777 | I'm trying to install Pylzma via pip on python 2.7.9 and I'm getting the following error:
```
C:\Python27\Scripts>pip.exe install pylzma
Downloading/unpacking pylzma
Running setup.py (path:c:\users\username\appdata\local\temp\pip_build_username\pylzma\setup.py) egg_info for package pylzma
warning: no files ... | 2015/05/22 | [
"https://Stackoverflow.com/questions/30400777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4929649/"
] | The first step to do is to find where is your python.
You can do it with which or where command (which for unix where for windows). Once you have this information you will know what is actually executed as "python" command. Then you need to change it for windows (i believe) you need to change the PATH variable in such... | You need to use `python3` to use python 3.4. For example, to know version of Python use:
```
python3 -V
```
This will use python 3.4 to interpret your program or you can use the [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) to make it executable. The first line of your program should be:
```
#!/usr/bin... |
34,643,747 | **Is there a way to use and plot with opencv2 with ipython notebook?**
I am fairly new to python image analysis. I decided to go with the notebook work flow to make nice record as I process and it has been working out quite well using matplotlib/pylab to plot things.
An initial hurdle I had was how to plot things wit... | 2016/01/06 | [
"https://Stackoverflow.com/questions/34643747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5754595/"
] | This is my empty template:
```
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
%matplotlib inline
im = cv2.imread('IMG_FILENAME',0)
h,w = im.shape[:2]
print(im.shape)
plt.imshow(im,cmap='gray')
plt.show()
```
[See online sample](https://colab.research.google.com/drive/1WbOfcIwShtxaw7-Ig5Ypp... | There is also that little function that was used into the Google Deepdream Notebook:
```python
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
from cStringIO import StringIO
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
... |
34,643,747 | **Is there a way to use and plot with opencv2 with ipython notebook?**
I am fairly new to python image analysis. I decided to go with the notebook work flow to make nice record as I process and it has been working out quite well using matplotlib/pylab to plot things.
An initial hurdle I had was how to plot things wit... | 2016/01/06 | [
"https://Stackoverflow.com/questions/34643747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5754595/"
] | This is my empty template:
```
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
%matplotlib inline
im = cv2.imread('IMG_FILENAME',0)
h,w = im.shape[:2]
print(im.shape)
plt.imshow(im,cmap='gray')
plt.show()
```
[See online sample](https://colab.research.google.com/drive/1WbOfcIwShtxaw7-Ig5Ypp... | For a Jupyter notebook running on Python 3.5 I had to modify this to:
```
import io
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = io.BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
... |
34,643,747 | **Is there a way to use and plot with opencv2 with ipython notebook?**
I am fairly new to python image analysis. I decided to go with the notebook work flow to make nice record as I process and it has been working out quite well using matplotlib/pylab to plot things.
An initial hurdle I had was how to plot things wit... | 2016/01/06 | [
"https://Stackoverflow.com/questions/34643747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5754595/"
] | For a Jupyter notebook running on Python 3.5 I had to modify this to:
```
import io
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = io.BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
... | There is also that little function that was used into the Google Deepdream Notebook:
```python
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
from cStringIO import StringIO
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
... |
68,003,878 | I am new in python and would like to ask anyone of a solution related to dividing 2 rows in a data set that contains 25000 rows. It is easier to understand it by looking at my screenshot.
Thanks for a help!
[](https://i.stack.imgur.com/upP3d.png) | 2021/06/16 | [
"https://Stackoverflow.com/questions/68003878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16243841/"
] | Looks like your dataframe has a [MultiIndex](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html). Let's take the first four rows as an example. It could be problematic to let one of the row index levels have the same name (`loan_default`) as the column, so I'd change the column name to `count`:
```p... | You can try dividing with `shift` and groups.
```
import pandas as pd
df = pd.DataFrame()
df['year_of_birth'] = ['1954','1954','1955','1955', '1956', '1956']
df['loan_default'] = ['9','1','91','15','194','32']
```
Calculate the ratio:
```
df['percentage'] = df['loan_default'].div(df.groupby('year_of_birth')['lo... |
45,194,587 | This is not a duplicate of [this](https://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts-in-python), I'll explain here.
Consider `x = 1.2`. I'd like to separate it out into `1` and `0.2`. I've tried all these methods as outlined in the linked question:
```
In [370]: x = 1.2
... | 2017/07/19 | [
"https://Stackoverflow.com/questions/45194587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909087/"
] | Solution
--------
It may seem like a hack, but you could separate the string form (actually repr) and convert it back to ints and floats:
```
In [1]: x = 1.2
In [2]: s = repr(x)
In [3]: p, q = s.split('.')
In [4]: int(p)
Out[4]: 1
In [5]: float('.' + q)
Out[5]: 0.2
```
How it works
------------
The reason for ... | You could try converting 1.2 to string, splitting on the '.' and then converting the two strings ("1" and "2") back to the format you want.
Additionally padding the second portion with a '0.' will give you a nice format. |
45,194,587 | This is not a duplicate of [this](https://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts-in-python), I'll explain here.
Consider `x = 1.2`. I'd like to separate it out into `1` and `0.2`. I've tried all these methods as outlined in the linked question:
```
In [370]: x = 1.2
... | 2017/07/19 | [
"https://Stackoverflow.com/questions/45194587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909087/"
] | Solution
--------
It may seem like a hack, but you could separate the string form (actually repr) and convert it back to ints and floats:
```
In [1]: x = 1.2
In [2]: s = repr(x)
In [3]: p, q = s.split('.')
In [4]: int(p)
Out[4]: 1
In [5]: float('.' + q)
Out[5]: 0.2
```
How it works
------------
The reason for ... | So I just did the following in a python terminal and it seemed to work properly...
```
x=1.2
s=str(x).split('.')
i=int(s[0])
d=int(s[1])/10
``` |
45,194,587 | This is not a duplicate of [this](https://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts-in-python), I'll explain here.
Consider `x = 1.2`. I'd like to separate it out into `1` and `0.2`. I've tried all these methods as outlined in the linked question:
```
In [370]: x = 1.2
... | 2017/07/19 | [
"https://Stackoverflow.com/questions/45194587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909087/"
] | Solution
--------
It may seem like a hack, but you could separate the string form (actually repr) and convert it back to ints and floats:
```
In [1]: x = 1.2
In [2]: s = repr(x)
In [3]: p, q = s.split('.')
In [4]: int(p)
Out[4]: 1
In [5]: float('.' + q)
Out[5]: 0.2
```
How it works
------------
The reason for ... | Here is a solution without string manipulation (`frac_digits` is the count of decimal digits that you can guarantee the fractional part of your numbers will fit into):
```
>>> def integer_and_fraction(x, frac_digits=3):
... i = int(x)
... c = 10**frac_digits
... f = round(x*c-i*c)/c
... return (i, f)
.... |
45,194,587 | This is not a duplicate of [this](https://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts-in-python), I'll explain here.
Consider `x = 1.2`. I'd like to separate it out into `1` and `0.2`. I've tried all these methods as outlined in the linked question:
```
In [370]: x = 1.2
... | 2017/07/19 | [
"https://Stackoverflow.com/questions/45194587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909087/"
] | Here is a solution without string manipulation (`frac_digits` is the count of decimal digits that you can guarantee the fractional part of your numbers will fit into):
```
>>> def integer_and_fraction(x, frac_digits=3):
... i = int(x)
... c = 10**frac_digits
... f = round(x*c-i*c)/c
... return (i, f)
.... | You could try converting 1.2 to string, splitting on the '.' and then converting the two strings ("1" and "2") back to the format you want.
Additionally padding the second portion with a '0.' will give you a nice format. |
45,194,587 | This is not a duplicate of [this](https://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts-in-python), I'll explain here.
Consider `x = 1.2`. I'd like to separate it out into `1` and `0.2`. I've tried all these methods as outlined in the linked question:
```
In [370]: x = 1.2
... | 2017/07/19 | [
"https://Stackoverflow.com/questions/45194587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909087/"
] | Here is a solution without string manipulation (`frac_digits` is the count of decimal digits that you can guarantee the fractional part of your numbers will fit into):
```
>>> def integer_and_fraction(x, frac_digits=3):
... i = int(x)
... c = 10**frac_digits
... f = round(x*c-i*c)/c
... return (i, f)
.... | So I just did the following in a python terminal and it seemed to work properly...
```
x=1.2
s=str(x).split('.')
i=int(s[0])
d=int(s[1])/10
``` |
9,509,096 | How do you load a Django fixture so that models referenced via natural keys don't conflict with pre-existing records?
I'm trying to load such a fixture, but I'm getting IntegrityErrors from my MySQL backend, complaining about Django trying to insert duplicate records, which doesn't make any sense.
As I understand Dja... | 2012/03/01 | [
"https://Stackoverflow.com/questions/9509096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247542/"
] | Turns out the solution requires a very minor patch to Django's `loaddata` command. Since it's unlikely the Django devs would accept such a patch, I've [forked it](https://raw.githubusercontent.com/chrisspen/django-admin-steroids/master/admin_steroids/management/commands/loaddatanaturally.py) in my package of various Dj... | Actually loaddata is not supposed to work with existing data in database, it is normally used for initial load of models.
Look at this question for another way of doing it: [Import data into Django model with existing data?](https://stackoverflow.com/questions/5940294/import-data-into-django-model-with-existing-data) |
2,217,258 | I'm looking for an easy, cross platform way to join path, directory and file names into a complete path in C++. I know python has `os.path.join()` and matlab has `fullfile()`. Does Qt has something similar? `QFileInfo` doesn't seem to be able to do this. | 2010/02/07 | [
"https://Stackoverflow.com/questions/2217258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
] | [QDir](http://qt-project.org/doc/qt-5.0/qtcore/qdir.html) has `absoluteFilePath` and `relativeFilePath` to combine a path with a file name. | Offhand, I'm not sure about Qt, but Boost has a `filesystem` class that handles things like this. This has the advantage that it has been accepted as a proposal for TR2. That means it has a pretty good chance of becoming part of the C++ standard library (though probably with some minor modifications here or there). |
3,108,951 | I need to write a python script that launches a shell script and import the environment variables AFTER a script is completed.
Immagine you have a shell script "a.sh":
```
export MYVAR="test"
```
In python I would like to do something like:
```
import os
env={}
os.spawnlpe(os.P_WAIT,'sh', 'sh', 'a.sh',env)
print ... | 2010/06/24 | [
"https://Stackoverflow.com/questions/3108951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/375112/"
] | Nope, any changes made to environment variables in a subprocess stay in that subprocess. (As far as I know, that is) When the subprocess terminates, its environment is lost.
I'd suggest getting the shell script to print its environment, or at least the variables you care about, to its standard output (or standard erro... | I agree with David's post.
Perl has a [Shell::Source](http://search.cpan.org/~pjcj/Shell-Source-0.01/Source.pm) module which does this. It works by running the script you want in a subprocess appended with an `env` which produces a list of variable value pairs separated by an `=` symbol. You can parse this and "impor... |
29,548,982 | I tried: `c:/python34/scripts/pip install http://bitbucket.org/pygame/pygame`
and got this error:
```
Cannot unpack file C:\Users\Marius\AppData\Local\Temp\pip-b60d5tho-unpack\pygame
(downloaded from C:\Users\Marius\AppData\Local\Temp\pip-rqmpq4tz-build, conte
nt-type: text/html; charset=utf-8); cannot detect archiv... | 2015/04/09 | [
"https://Stackoverflow.com/questions/29548982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529330/"
] | This is the only method that works for me.
```
pip install pygame==1.9.1release --allow-external pygame --allow-unverified pygame
```
--
These are the steps that lead me to this command (I put them so people finds it easily):
```
$ pip install pygame
Collecting pygame
Could not find any downloads that satisfy th... | I realized that the compatible Pygame version was simply corrupted or broken. Therfore i had to install a previous version of python to run Pygame. Which is actually fine as most modules aren't updated to be compatible with Python 3.4 yet so it only gives me more options. |
29,548,982 | I tried: `c:/python34/scripts/pip install http://bitbucket.org/pygame/pygame`
and got this error:
```
Cannot unpack file C:\Users\Marius\AppData\Local\Temp\pip-b60d5tho-unpack\pygame
(downloaded from C:\Users\Marius\AppData\Local\Temp\pip-rqmpq4tz-build, conte
nt-type: text/html; charset=utf-8); cannot detect archiv... | 2015/04/09 | [
"https://Stackoverflow.com/questions/29548982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529330/"
] | This is the only method that works for me.
```
pip install pygame==1.9.1release --allow-external pygame --allow-unverified pygame
```
--
These are the steps that lead me to this command (I put them so people finds it easily):
```
$ pip install pygame
Collecting pygame
Could not find any downloads that satisfy th... | If you get trouble when install pygame error about missing visual studio 10+. I have the answer:
The problem is not about have or not have visual studio, because I try many version but it not work. The problem is file: between `tar.gz` and `.whl`
so, this is the solution:
1) Download file:
>
> <http://www.lfd.uci.ed... |
29,548,982 | I tried: `c:/python34/scripts/pip install http://bitbucket.org/pygame/pygame`
and got this error:
```
Cannot unpack file C:\Users\Marius\AppData\Local\Temp\pip-b60d5tho-unpack\pygame
(downloaded from C:\Users\Marius\AppData\Local\Temp\pip-rqmpq4tz-build, conte
nt-type: text/html; charset=utf-8); cannot detect archiv... | 2015/04/09 | [
"https://Stackoverflow.com/questions/29548982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529330/"
] | This is the only method that works for me.
```
pip install pygame==1.9.1release --allow-external pygame --allow-unverified pygame
```
--
These are the steps that lead me to this command (I put them so people finds it easily):
```
$ pip install pygame
Collecting pygame
Could not find any downloads that satisfy th... | I myself got this error(while using v3.10.0) and then I uninstalled the latest version and installed older version of python(v3.9.7) and it fixed the issue. Hope that works for you too. Honestly there are not many changes in the fix unless they jump from python3 to python4. so you dont need to update the python just fo... |
29,548,982 | I tried: `c:/python34/scripts/pip install http://bitbucket.org/pygame/pygame`
and got this error:
```
Cannot unpack file C:\Users\Marius\AppData\Local\Temp\pip-b60d5tho-unpack\pygame
(downloaded from C:\Users\Marius\AppData\Local\Temp\pip-rqmpq4tz-build, conte
nt-type: text/html; charset=utf-8); cannot detect archiv... | 2015/04/09 | [
"https://Stackoverflow.com/questions/29548982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529330/"
] | If you get trouble when install pygame error about missing visual studio 10+. I have the answer:
The problem is not about have or not have visual studio, because I try many version but it not work. The problem is file: between `tar.gz` and `.whl`
so, this is the solution:
1) Download file:
>
> <http://www.lfd.uci.ed... | I realized that the compatible Pygame version was simply corrupted or broken. Therfore i had to install a previous version of python to run Pygame. Which is actually fine as most modules aren't updated to be compatible with Python 3.4 yet so it only gives me more options. |
29,548,982 | I tried: `c:/python34/scripts/pip install http://bitbucket.org/pygame/pygame`
and got this error:
```
Cannot unpack file C:\Users\Marius\AppData\Local\Temp\pip-b60d5tho-unpack\pygame
(downloaded from C:\Users\Marius\AppData\Local\Temp\pip-rqmpq4tz-build, conte
nt-type: text/html; charset=utf-8); cannot detect archiv... | 2015/04/09 | [
"https://Stackoverflow.com/questions/29548982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529330/"
] | If you get trouble when install pygame error about missing visual studio 10+. I have the answer:
The problem is not about have or not have visual studio, because I try many version but it not work. The problem is file: between `tar.gz` and `.whl`
so, this is the solution:
1) Download file:
>
> <http://www.lfd.uci.ed... | I myself got this error(while using v3.10.0) and then I uninstalled the latest version and installed older version of python(v3.9.7) and it fixed the issue. Hope that works for you too. Honestly there are not many changes in the fix unless they jump from python3 to python4. so you dont need to update the python just fo... |
29,205,752 | I'm trying to produce a simple fibonacci algorithm with Cython.
I have fib.pyx:
```
def fib(int n):
cdef int i
cdef double a=0.0, b=1.0
for i in range(n):
a, b = a + b, a
return a
```
and setup.py in the same folder:
```
from distutils.core import setup
from Cython.Build import cythonize
se... | 2015/03/23 | [
"https://Stackoverflow.com/questions/29205752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4657326/"
] | Java implementation to remove all change notification registrations from the database
```
Statement stmt= conn.createStatement();
ResultSet rs = stmt.executeQuery("select regid,callback from USER_CHANGE_NOTIFICATION_REGS");
while(rs.next())
{
long regid = rs.getLong(1);
String callback = rs.getString(2);
((Orac... | You just can revoke change notification from current user and grant it again. I know, this isn't best solution, but it work. |
29,205,752 | I'm trying to produce a simple fibonacci algorithm with Cython.
I have fib.pyx:
```
def fib(int n):
cdef int i
cdef double a=0.0, b=1.0
for i in range(n):
a, b = a + b, a
return a
```
and setup.py in the same folder:
```
from distutils.core import setup
from Cython.Build import cythonize
se... | 2015/03/23 | [
"https://Stackoverflow.com/questions/29205752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4657326/"
] | Although this is a rather old question I will describe my experience with Oracle CQN just in case it helps someone. The feature works better with java where its easy not only to register but also to unregister the notification.
In .NET if the application crashes there is no way in my experience to unregister the notifi... | You just can revoke change notification from current user and grant it again. I know, this isn't best solution, but it work. |
70,161,899 | I'm trying to build drake from source on Ubuntu 20.04 by following instructions from [here](https://drake.mit.edu/from_source.html). I already checked that my system meets all the requirements, and was ale to successfully run the mandatory platform-specific setup script (and it completed saying: 'install\_prereqs: succ... | 2021/11/29 | [
"https://Stackoverflow.com/questions/70161899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598807/"
] | On another tack, you could try to temporarily work around the problem by doing (in Drake) a `bazel run //:install -- /path/to/somewhere` to install Drake, and thus skipping the CMake stuff that seems to be the problem here. | Here is some diagnostic output from my Ubuntu 20.04 system. Can you run the same, and check to see if anything looks different?
```
jwnimmer@call-cps:~$ which python
/usr/bin/python
jwnimmer@call-cps:~$ which python3
/usr/bin/python3
jwnimmer@call-cps:~$ file /usr/bin/python3
/usr/bin/python3: symbolic link to pytho... |
70,332,071 | I'm trying to get a preprocessing function to work with the Dataset map, but I get the following error (full stack trace at the bottom):
```
ValueError: Tensor-typed variable initializers must either be wrapped in an init_scope or callable (e.g., `tf.Variable(lambda : tf.truncated_normal([10, 40]))`) when building fun... | 2021/12/13 | [
"https://Stackoverflow.com/questions/70332071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213694/"
] | found the solution.
```
private var isLoading = true
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
splashScreen.setKeepVisibleCondition { isLoading }
}
private fun doApiCalls(){
...
isLoading = false
}
``` | @sujith's answer did not work for me for some reason.
I added a method in my viewModel like this:
```
fun isDataReady(): Boolean {
return isDataReady.value?:false
}
```
and used
```
splashScreen.setKeepVisibleCondition {
!viewModel.isDataReady()
}
```
This worked for me.
May be someone can explain to me ... |
70,332,071 | I'm trying to get a preprocessing function to work with the Dataset map, but I get the following error (full stack trace at the bottom):
```
ValueError: Tensor-typed variable initializers must either be wrapped in an init_scope or callable (e.g., `tf.Variable(lambda : tf.truncated_normal([10, 40]))`) when building fun... | 2021/12/13 | [
"https://Stackoverflow.com/questions/70332071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213694/"
] | found the solution.
```
private var isLoading = true
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
splashScreen.setKeepVisibleCondition { isLoading }
}
private fun doApiCalls(){
...
isLoading = false
}
``` | Expanding on @hushed\_voice's answer, *setKeepVisibleCondition()* will keep the Splash Screen on as long as it's returning true. Once it equates to false, the Splash will finish and your app will proceed forward.
Here is a short function I wrote up to handle my Splash Screen logic in my Main Activity:
```
private fun... |
73,879,190 | A is a m*n matrix
B is a n*n matrix
I want to return matrix C of size m\*n such that:
[](https://i.stack.imgur.com/Uq3SK.png)
In python it could be like below
```
for i in range(m):
for j in range(n):
C[i][j] ... | 2022/09/28 | [
"https://Stackoverflow.com/questions/73879190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12968928/"
] | I would look on much simpler construct and go from there..
lets say the max between 0 and the addition wasn't there.
so the answer would be : a(i,j)*n - sum(b(j,)
on this you could just go linearly by sum each vector and erase it from a(i,j)*n
and because you need sum each vector in b only once per j it can be done i... | For each `j`, You can sort each column `B[j][:]` and compute cumulative sums.
Then for a given `A[i][j]` you can find the sum of `B[j][k]` that are larger than `A[i][j]` in O(log n) time using binary search. If there's `x` elements of `B[j][:]` that are greater than `A[i][j]` and their sum is S, then `C[i][j] = A[i][j... |
62,667,225 | For the last 3 days, I have been trying to set up virtual Env on Vs Code for python with some luck but I have a few questions that I cant seem to find the answer to.
1. Does Vs Code have to run in WSL for me to use venv?
2. When I install venv on my device it doesn't seem to install a Scripts folder inside the vevn fo... | 2020/06/30 | [
"https://Stackoverflow.com/questions/62667225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13843817/"
] | If you have the python extension installed you should be able to select your python interpreter at the bottom.
[](https://i.stack.imgur.com/dsdfm.png)
You should then be able to select the appropriate path
[![selecting the pyt... | You don't have to create a virtual environment under WSL, it will work anywhere. But the reason you don't have a `Scripts/` directory is because (I bet) you're running VS Code with git bash and that makes Python think you're running under Unix. In that case it creates a `bin/` directory. That will also confuse VS Code ... |
62,667,225 | For the last 3 days, I have been trying to set up virtual Env on Vs Code for python with some luck but I have a few questions that I cant seem to find the answer to.
1. Does Vs Code have to run in WSL for me to use venv?
2. When I install venv on my device it doesn't seem to install a Scripts folder inside the vevn fo... | 2020/06/30 | [
"https://Stackoverflow.com/questions/62667225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13843817/"
] | Run **`Set-ExecutionPolicy Unrestricted -scope process`** before activating virtual environment.
All the best | You don't have to create a virtual environment under WSL, it will work anywhere. But the reason you don't have a `Scripts/` directory is because (I bet) you're running VS Code with git bash and that makes Python think you're running under Unix. In that case it creates a `bin/` directory. That will also confuse VS Code ... |
10,283,067 | I wanted to create a simple gui with a play and stop button to play an mp3 file in python. I created a very simple gui using Tkinter that consists of 2 buttons (stop and play).
I created a function that does the following:
```
def playsound () :
sound = pyglet.media.load('music.mp3')
sound.play()
pyglet.a... | 2012/04/23 | [
"https://Stackoverflow.com/questions/10283067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947933/"
] | You are mixing two UI libraries together - that is not intrinsically bad, but there are some problems. Notably, both of them need a main loop of their own to process their events. TKinter uses it to communicate with the desktop and user-generated events, and in this case, pyglet uses it to play your music.
Each of the... | There is a media player implementation in the pyglet documentation:
<http://www.pyglet.org/doc/programming_guide/playing_sounds_and_music.html>
The script you should look at is [media\_player.py](http://www.pyglet.org/doc/programming_guide/media_player.py)
Hopefully this will get you started |
10,283,067 | I wanted to create a simple gui with a play and stop button to play an mp3 file in python. I created a very simple gui using Tkinter that consists of 2 buttons (stop and play).
I created a function that does the following:
```
def playsound () :
sound = pyglet.media.load('music.mp3')
sound.play()
pyglet.a... | 2012/04/23 | [
"https://Stackoverflow.com/questions/10283067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947933/"
] | I would do something like:
```
import pyglet
from pyglet.gl import *
class main (pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(800, 600, fullscreen = False)
self.button_texture = pyglet.image.load('button.png')
self.button = pyglet.sprite.Sprite(self.button_texture... | There is a media player implementation in the pyglet documentation:
<http://www.pyglet.org/doc/programming_guide/playing_sounds_and_music.html>
The script you should look at is [media\_player.py](http://www.pyglet.org/doc/programming_guide/media_player.py)
Hopefully this will get you started |
10,283,067 | I wanted to create a simple gui with a play and stop button to play an mp3 file in python. I created a very simple gui using Tkinter that consists of 2 buttons (stop and play).
I created a function that does the following:
```
def playsound () :
sound = pyglet.media.load('music.mp3')
sound.play()
pyglet.a... | 2012/04/23 | [
"https://Stackoverflow.com/questions/10283067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947933/"
] | This solution is the easiest one:
```
import pyglet
foo=pyglet.media.load("/data/Me/Music/Goo Goo Dolls/[1998] Dizzy Up The Girl/11 - Iris.mp3")
foo.play()
def exiter(dt):
pyglet.app.exit()
print "Song length is: %f" % foo.duration
# foo.duration is the song length
pyglet.clock.schedule_once(exiter, foo.duration)... | There is a media player implementation in the pyglet documentation:
<http://www.pyglet.org/doc/programming_guide/playing_sounds_and_music.html>
The script you should look at is [media\_player.py](http://www.pyglet.org/doc/programming_guide/media_player.py)
Hopefully this will get you started |
10,283,067 | I wanted to create a simple gui with a play and stop button to play an mp3 file in python. I created a very simple gui using Tkinter that consists of 2 buttons (stop and play).
I created a function that does the following:
```
def playsound () :
sound = pyglet.media.load('music.mp3')
sound.play()
pyglet.a... | 2012/04/23 | [
"https://Stackoverflow.com/questions/10283067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947933/"
] | You are mixing two UI libraries together - that is not intrinsically bad, but there are some problems. Notably, both of them need a main loop of their own to process their events. TKinter uses it to communicate with the desktop and user-generated events, and in this case, pyglet uses it to play your music.
Each of the... | I would do something like:
```
import pyglet
from pyglet.gl import *
class main (pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(800, 600, fullscreen = False)
self.button_texture = pyglet.image.load('button.png')
self.button = pyglet.sprite.Sprite(self.button_texture... |
10,283,067 | I wanted to create a simple gui with a play and stop button to play an mp3 file in python. I created a very simple gui using Tkinter that consists of 2 buttons (stop and play).
I created a function that does the following:
```
def playsound () :
sound = pyglet.media.load('music.mp3')
sound.play()
pyglet.a... | 2012/04/23 | [
"https://Stackoverflow.com/questions/10283067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947933/"
] | You are mixing two UI libraries together - that is not intrinsically bad, but there are some problems. Notably, both of them need a main loop of their own to process their events. TKinter uses it to communicate with the desktop and user-generated events, and in this case, pyglet uses it to play your music.
Each of the... | This solution is the easiest one:
```
import pyglet
foo=pyglet.media.load("/data/Me/Music/Goo Goo Dolls/[1998] Dizzy Up The Girl/11 - Iris.mp3")
foo.play()
def exiter(dt):
pyglet.app.exit()
print "Song length is: %f" % foo.duration
# foo.duration is the song length
pyglet.clock.schedule_once(exiter, foo.duration)... |
26,943,578 | I'm making a simple guessing game using tkinter for my python class and was wondering if there was a way to loop it so that the player would have a maximum number of guesses before the program tells the player what the number was and changes the number, or kill the program after it tells them the answer. Heres my code ... | 2014/11/15 | [
"https://Stackoverflow.com/questions/26943578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4255017/"
] | You need to set the visibility of `$secret`
```
private $secret = "";
```
Then just remove that casting on the base64 and use `$this->secret` to access the property:
```
return base64_encode($this->secret);
```
So finally:
```
class mySimpleClass
{
// public $secret = "";
private $secret = '';
pub... | I suggest you to declare `$secret` as `public` or `private` & access it using `$this->`. Example:
```
class mySimpleClass {
public $secret = "";
public function __construct($s) {
$this -> secret = $s;
}
public function getSecret() {
return base64_encode($this->$secret);
}
}
``` |
51,309,341 | So im trying to send a saved wave file from a client to a server with socket however every attempt at doing it fails, the closest ive got is this:
```
#Server.py
requests = 0
while True:
wavfile = open(str(requests)+str(addr)+".wav", "wb")
while True:
data = clientsocket.recv(1024)
if not data:... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51309341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9995176/"
] | You could create e.g. a `utils` file, export your helpers from there, and import them when needed:
```
// utils.js
export function romanize(str) {
// ...
}
export function getDocumentType(doc) {
// ...
}
// App.js
import { romanize } from './utils';
``` | The "react way" is to structure these files in the way that makes most sense for your application. Let me give you some examples of what react applications tend to look like to help you out.
React has a declarative tree structure for the view, and other related concepts have a tendency to fall into this declarative tr... |
51,309,341 | So im trying to send a saved wave file from a client to a server with socket however every attempt at doing it fails, the closest ive got is this:
```
#Server.py
requests = 0
while True:
wavfile = open(str(requests)+str(addr)+".wav", "wb")
while True:
data = clientsocket.recv(1024)
if not data:... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51309341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9995176/"
] | There are some situations where you will need a helper functions like these and setting those up in a util or helpers folder is a great way to handle that.
However, to take full advantage of React, I'd suggest thinking about if there is a way you could make a shared component instead. For functions such as your romani... | The "react way" is to structure these files in the way that makes most sense for your application. Let me give you some examples of what react applications tend to look like to help you out.
React has a declarative tree structure for the view, and other related concepts have a tendency to fall into this declarative tr... |
51,309,341 | So im trying to send a saved wave file from a client to a server with socket however every attempt at doing it fails, the closest ive got is this:
```
#Server.py
requests = 0
while True:
wavfile = open(str(requests)+str(addr)+".wav", "wb")
while True:
data = clientsocket.recv(1024)
if not data:... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51309341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9995176/"
] | The "react way" is to structure these files in the way that makes most sense for your application. Let me give you some examples of what react applications tend to look like to help you out.
React has a declarative tree structure for the view, and other related concepts have a tendency to fall into this declarative tr... | Shared Conmponents is definetly the react way but having reusable functions in the utility/helper folder is always handy.
Here is how I would do it.
You could create a `utility` folder inside `src` folder where you could export all the reusable functions
```
--| src
----| utility
-------| formatDate.js
-------| form... |
51,309,341 | So im trying to send a saved wave file from a client to a server with socket however every attempt at doing it fails, the closest ive got is this:
```
#Server.py
requests = 0
while True:
wavfile = open(str(requests)+str(addr)+".wav", "wb")
while True:
data = clientsocket.recv(1024)
if not data:... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51309341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9995176/"
] | You could create e.g. a `utils` file, export your helpers from there, and import them when needed:
```
// utils.js
export function romanize(str) {
// ...
}
export function getDocumentType(doc) {
// ...
}
// App.js
import { romanize } from './utils';
``` | There are some situations where you will need a helper functions like these and setting those up in a util or helpers folder is a great way to handle that.
However, to take full advantage of React, I'd suggest thinking about if there is a way you could make a shared component instead. For functions such as your romani... |
51,309,341 | So im trying to send a saved wave file from a client to a server with socket however every attempt at doing it fails, the closest ive got is this:
```
#Server.py
requests = 0
while True:
wavfile = open(str(requests)+str(addr)+".wav", "wb")
while True:
data = clientsocket.recv(1024)
if not data:... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51309341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9995176/"
] | You could create e.g. a `utils` file, export your helpers from there, and import them when needed:
```
// utils.js
export function romanize(str) {
// ...
}
export function getDocumentType(doc) {
// ...
}
// App.js
import { romanize } from './utils';
``` | Shared Conmponents is definetly the react way but having reusable functions in the utility/helper folder is always handy.
Here is how I would do it.
You could create a `utility` folder inside `src` folder where you could export all the reusable functions
```
--| src
----| utility
-------| formatDate.js
-------| form... |
51,309,341 | So im trying to send a saved wave file from a client to a server with socket however every attempt at doing it fails, the closest ive got is this:
```
#Server.py
requests = 0
while True:
wavfile = open(str(requests)+str(addr)+".wav", "wb")
while True:
data = clientsocket.recv(1024)
if not data:... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51309341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9995176/"
] | There are some situations where you will need a helper functions like these and setting those up in a util or helpers folder is a great way to handle that.
However, to take full advantage of React, I'd suggest thinking about if there is a way you could make a shared component instead. For functions such as your romani... | Shared Conmponents is definetly the react way but having reusable functions in the utility/helper folder is always handy.
Here is how I would do it.
You could create a `utility` folder inside `src` folder where you could export all the reusable functions
```
--| src
----| utility
-------| formatDate.js
-------| form... |
64,708,781 | I am trying to use multiprocessing in order to run a CPU-intensive job in the background. I'd like this process to be able to use peewee ORM to write its results to the SQLite database.
In order to do so, I am trying to override the Meta.database of my model class after thread creation so that I can have a separate db... | 2020/11/06 | [
"https://Stackoverflow.com/questions/64708781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5739514/"
] | Haskell doesn't allow this because it would be ambiguous. The value constructor `Prop` is effectively a function, which may be clearer if you ask GHCi about its type:
```
> :t Const
Const :: Bool -> Prop
```
If you attempt to add one more `Const` constructor in the same module, you'd have two 'functions' called `Con... | This is somewhat horrible, but will basically let you do what you want:
```hs
{-# LANGUAGE PatternSynonyms, TypeFamilies, ViewPatterns #-}
data Prop = PropConst Bool
| PropVar Char
| PropNot Prop
| PropOr Prop Prop
| PropAnd Prop Prop
| PropImply Prop Prop
data Formu... |
46,700,236 | when I using tensorflow ,I meet with a error:
```
[W 09:27:49.213 NotebookApp] 404 GET /api/kernels/4e889506-2258-481c-b18e-d6a8e920b606/channels?session_id=0665F3F07C004BBAA7CDF6601B6E2BA1 (127.0.0.1): Kernel does not exist: 4e889506-2258-481c-b18e-d6a8e920b606
[W 09:27:49.266 NotebookApp] 404 GET /api/kernel... | 2017/10/12 | [
"https://Stackoverflow.com/questions/46700236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7786383/"
] | Run the following command in terminal:
```
nvidia-smi
```
You will get an output like this.
[](https://i.stack.imgur.com/FtqZs.png)
You will get a summary of the processes occupying the memory of your GPU. In notebooks, even if no cell is running c... | Check the cuDNN version. It should be 5.1 |
23,790,460 | I am new to Python and I installed the [`speech`](https://pypi.python.org/pypi/speech) library. But whenever I'm importing `speech` from Python shell it's giving the error
```
>>> import speech
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import speech
File "C:\Python34\lib\site-p... | 2014/05/21 | [
"https://Stackoverflow.com/questions/23790460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661976/"
] | So I have contacted the author of R2jags and he has added an addition argument to jags.parallel that lets you pass envir, which is then past onto clusterExport.
This works well except it allows clashes between the name of my data and variables in the jags.parallel function. | if you use intensively JAGS in parrallel I can suggest you to look the package `rjags` combined with the package `dclone`. I think `dclone` is realy powerfull because the syntaxe was exactly the same as `rjags`.
I have never see your problem with this package.
If you want to use `R2jags` I think you need to pass your ... |
23,790,460 | I am new to Python and I installed the [`speech`](https://pypi.python.org/pypi/speech) library. But whenever I'm importing `speech` from Python shell it's giving the error
```
>>> import speech
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import speech
File "C:\Python34\lib\site-p... | 2014/05/21 | [
"https://Stackoverflow.com/questions/23790460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661976/"
] | So I have contacted the author of R2jags and he has added an addition argument to jags.parallel that lets you pass envir, which is then past onto clusterExport.
This works well except it allows clashes between the name of my data and variables in the jags.parallel function. | Without changing the code of `R2jags`, you can still assign those data variables to the global environment in an easier way by using `list2env`.
Obviously, there is is a concern that those variable names could be overwritten in the global environment, but you probably can control for that.
Below is the same code as t... |
61,163,289 | I am pretty new to python and I am trying to swap the values of some variables in my code below:
```
def MutationPop(LocalBestInd,clmns,VNSdata):
import random
MutPop = []
for i in range(0,VNSdata[1]):
tmpMutPop = LocalBestInd
#generation of random numbers
RandomNums = []
... | 2020/04/11 | [
"https://Stackoverflow.com/questions/61163289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13271276/"
] | Based off the tutorial it looks like you've missed a crucial step.
You need to install `google-maps-react` dependency in your project.
In your console, navigate to your project root directory and run the following:
```
npm install --save google-maps-react
```
Another troubleshooting issue for those who are stuck i... | I had the same issue. I fixed it by adding `declare module 'google-map-react'`; in file `react-app-env.d.ts`
Try it out and give a feedback by the way I am using TS with React |
36,531,404 | I have a scenario, where I have to call a certain Python script multiple times in another python script.
script1:
```
import sys
path=sys.argv
print "I am a test"
print "see! I do nothing productive."
print "path:",path[1]
```
script2:
```
import subprocess
l=list()
l.append('root')
l.append('root1')
l.append('... | 2016/04/10 | [
"https://Stackoverflow.com/questions/36531404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5820814/"
] | to substitute the value of i into the string you can concatenate it:
```
cmd="python script1.py "+i
```
or format it into the string:
```
cmd="python script1.py %s"%i
```
Either way you need to use the variable i instead of the string i. | I think you are looking for this:
```
cmd="python script1.py %s" % i
``` |
36,531,404 | I have a scenario, where I have to call a certain Python script multiple times in another python script.
script1:
```
import sys
path=sys.argv
print "I am a test"
print "see! I do nothing productive."
print "path:",path[1]
```
script2:
```
import subprocess
l=list()
l.append('root')
l.append('root1')
l.append('... | 2016/04/10 | [
"https://Stackoverflow.com/questions/36531404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5820814/"
] | to substitute the value of i into the string you can concatenate it:
```
cmd="python script1.py "+i
```
or format it into the string:
```
cmd="python script1.py %s"%i
```
Either way you need to use the variable i instead of the string i. | Use `subprocess.Popen` with a lists:
```
import subprocess
paths = ['root', 'root1', 'root2']
for path in paths:
subprocess.Popen(['python', 'script1.py', path])
``` |
3,400,144 | All,
I am familiar with the ability to fake GPS information to the emulator through the use of the `geo fix long lat altitude` command when connected through the emulator.
What I'd like to do is have a simulation running on potentially a different computer produce lat, long, altitudes that should be sent over to the ... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155392/"
] | The response you're seeing is an empty response which doesn't necessarily mean there's no metric data available. A few ideas what might cause this:
* Are you using a user access token? If yes, does the user own the page? Is the 'read\_insights' extended permission granted for the user / access token? How about 'offlin... | If you want to know the number of fans a facebook page has, use something like:
```
https://graph.facebook.com/cocacola
```
The response contains a `fan_count` property. |
3,400,144 | All,
I am familiar with the ability to fake GPS information to the emulator through the use of the `geo fix long lat altitude` command when connected through the emulator.
What I'd like to do is have a simulation running on potentially a different computer produce lat, long, altitudes that should be sent over to the ... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155392/"
] | We have confirmed this bug. This is due to the end\_time having to be aligned with day delimiters in PST in order for the Insights table to return any data. To address this issue, we introduced two custom functions you can use to query the insights table:
1. end\_time\_date() : accept DATE in string form(e.g. '2010-08... | If you want to know the number of fans a facebook page has, use something like:
```
https://graph.facebook.com/cocacola
```
The response contains a `fan_count` property. |
3,400,144 | All,
I am familiar with the ability to fake GPS information to the emulator through the use of the `geo fix long lat altitude` command when connected through the emulator.
What I'd like to do is have a simulation running on potentially a different computer produce lat, long, altitudes that should be sent over to the ... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155392/"
] | The response you're seeing is an empty response which doesn't necessarily mean there's no metric data available. A few ideas what might cause this:
* Are you using a user access token? If yes, does the user own the page? Is the 'read\_insights' extended permission granted for the user / access token? How about 'offlin... | I'm not sure the date is correct. do you really want the date as an integer?
Usually SQL takes dates in db-format, so to format it you'd use:
```
Date.new(2010,9,14).to_s(:db)
(Time.now - 5.days).to_s(:db)
# or even better:
5.days.ago.to_s(:db)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.