qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
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()
``` | 11,522 |
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
``` | 11,523 |
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... | 11,533 |
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... | 11,538 |
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
``` | 11,539 |
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 ... | 11,540 |
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... | 11,541 |
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,... | 11,544 |
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 | 11,546 |
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. | 11,548 |
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... | 11,549 |
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. | 11,551 |
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... | 11,552 |
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()
... | 11,553 |
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... | 11,556 |
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. | 11,557 |
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) | 11,562 |
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). | 11,563 |
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... | 11,564 |
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. | 11,565 |
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. | 11,570 |
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... | 11,572 |
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 ... | 11,573 |
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... | 11,575 |
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 ... | 11,576 |
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 | 11,578 |
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);
}
}
``` | 11,583 |
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... | 11,584 |
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... | 11,590 |
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 | 11,591 |
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 ... | 11,592 |
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 | 11,594 |
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
``` | 11,595 |
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. | 11,597 |
44,364,458 | Currently I'm using Eclipse with Nokia/Red plugin which allows me to write robot framework test suites. Support is Python 3.6 and Selenium for it.
My project is called "Automation" and Test suites are in `.robot` files.
Test suites have test cases which are called "Keywords".
**Test Cases**
Create New Vehicle
```
C... | 2017/06/05 | [
"https://Stackoverflow.com/questions/44364458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8113230/"
] | If you need to "step into" a python defined keyword you need to use python debugger together with RED.
This can be done with any python debugger,if you like to have everything in one application, PyDev can be used with RED.
Follow below help document, if you will face any problems leave a comment here.
[RED Debug ... | If you are wanting to know which statement in the python-based keyword failed, you simply need to have it throw an appropriate error. Robot won't do this for you, however. From a reporting standpoint, a python based keyword is a black box. You will have to explicitly add logging messages, and return useful errors.
Fo... | 11,604 |
54,752,681 | I am working on a thesis regarding Jacobsthal sequences (A001045) and how they can be considered as being composed of some number of distinct sub-sequences. I have made a comment on A077947 indicating this and have included a python program. Unfortunately the program as written leaves a lot to be desired and so of cour... | 2019/02/18 | [
"https://Stackoverflow.com/questions/54752681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204443/"
] | Here's an alternative way to do it without a second for loop:
```
sequences = [ 1, 1, 2, 5, 9, 18 ]
multipliers = [ 36, 72, 144, 288, 576, 1152 ]
for x in range(100):
print(*sequences)
sequences = [ s + m*64**x for s,m in zip(sequences,multipliers) ]
```
[EDIT] Looking at the values I noticed th... | This will behave identically to your code, and is arguably prettier. You'll probably see ways to make the magic constants less arbitrary.
```
factors = [ 1, 1, 2, 5, 9, 18 ]
cofactors = [ 36*(2**n) for n in range(6) ]
for x in range(10):
print(*factors)
for i in range(6):
factors[i] = factors[i] + cof... | 11,605 |
12,884,512 | I am in my first steps in learning python so excuse my questions please. I want to run the code below (taken from: <http://docs.python.org/library/ssl.html>) :
```
import socket, ssl, pprint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# require a certificate from the server
ssl_sock = ssl.wrap_socket(s,
... | 2012/10/14 | [
"https://Stackoverflow.com/questions/12884512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1476749/"
] | Your code is referring to a certificate *file* on drive 'F:' (using the `ca_certs` parameter), which is not found during execution -- is there one?
See the relevant [documentation](http://docs.python.org/library/ssl.html#ssl.wrap_socket):
>
> The ca\_certs file contains a set of concatenated “certification
> author... | Does the certificate referenced exist on your filesystem? I think that error is in response to invalid cert from this code:
ssl\_sock = ssl.wrap\_socket(s,ca\_certs="F:/cert",cert\_reqs=ssl.CERT\_REQUIRED) | 11,608 |
68,900,182 | If I have a string which is the same as a python data type and I would like to check if another variable is that type how would I do it? Example below.
```
dtype = 'str'
x = 'hello'
bool = type(x) == dtype
```
The above obviously returns False but I'd like to check that type('hello') is a string. | 2021/08/23 | [
"https://Stackoverflow.com/questions/68900182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16737078/"
] | You can use `eval`:
```
bool = type(x) is eval(dtype)
```
but beware, `eval` will execute any python code, so if you're taking `dtype` as user input, they can execute their own code in this line. | If your code *actually* looks like the example you showed and `dtype` isn't coming from user input, then also keep in mind that `str` (as a value in Python) is a valid object which represents the string type. Consider
```
dtype = str
x = 'hello'
print(isinstance(x, dtype))
```
`str` is a value like any other and can... | 11,610 |
24,944,863 | I would like to use the Decimal() data type in python and convert it to an integer and exponent so I can send that data to a microcontroller/plc with full precision and decimal control. <https://docs.python.org/2/library/decimal.html>
I have got it to work, but it is hackish; does anyone know a better way? If not what... | 2014/07/24 | [
"https://Stackoverflow.com/questions/24944863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3862210/"
] | ```
from functools import reduce # Only in Python 3, omit this in Python 2.x
from decimal import *
d = Decimal('3.14159')
t = d.as_tuple()
theInteger = reduce(lambda rst, x: rst * 10 + x, t.digits)
theExponent = t.exponent
``` | ```
from decimal import *
d=Decimal('3.14159')
t=d.as_tuple()
digits=t.digits
theInteger=0
for x in range(len(digits)):
theInteger=theInteger+digits[x]*10**(len(digits)-x)
``` | 11,614 |
3,950,330 | Is there a way to change python2.x source code to python 3.x manually. I guess using lib2to3 this can be done but I don't know exactly how to do this ? | 2010/10/16 | [
"https://Stackoverflow.com/questions/3950330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441459/"
] | Thanks. Here is the answer I was looking for:
```
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
"""assume `files` to a be a list of all filenames you want to convert"""
r = RefactoringTool(get_fixers_from_package('lib2to3.fixes'))
r.refactor(files, write=True)
``` | Yes, porting is what you are looking here.
Porting is a non-trivial task that requires making various decisions about your code. For instance, whether or not you want to maintaing backward compatibility. There is no single, universal solution to porting. The way you port depends on your specific requirements.
The bes... | 11,620 |
6,156,358 | The example from [this post](https://stackoverflow.com/questions/6144274/string-replace-utility-conversion-from-python-to-f) has an example
```
open System.IO
let lines =
File.ReadAllLines("tclscript.do")
|> Seq.map (fun line ->
let newLine = line.Replace("{", "{{").Replace("}", "}}")
newLine )
File... | 2011/05/27 | [
"https://Stackoverflow.com/questions/6156358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | Building on Jaime's answer, since `ReadAllLines()` returns an array, just use `Array.map` instead of `Seq.map`
```
open System.IO
let lines =
File.ReadAllLines("tclscript.do")
|> Array.map (fun line ->
let newLine = line.Replace("{", "{{").Replace("}", "}}")
newLine )
File.WriteAllLines("tclscript.t... | You can use
```
File.WriteAllLines("tclscript.txt", Seq.toArray lines)
```
or alternatively just attach
```
|> Seq.toArray
```
after the Seq.map call.
(Also note that in .NET 4, there is an overload of WriteAllLines that does take a Seq) | 11,621 |
34,464,872 | I have download some mesh exporter script to learn how to write an export script in python for blender(2.6.3).
The script follows the standard register/unregister in order to register or unregister the script.
```
### REGISTER ###
def menu_func(self, context):
self.layout.operator(Export_objc.bl_idname, text="Ob... | 2015/12/25 | [
"https://Stackoverflow.com/questions/34464872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097185/"
] | Well I have found a workable way...
If you press 'F8' it will reload all plugins and remove the "dead" menu items.
That solves the multiple additions of the same addon.
So now if I want to change the addon and test it I do something like this:
1. Run script with unregister
2. Press F8
3. Run script with register
Th... | I am not 100% certain of the cause but it relates to running an addon script that adds a menu item within blender's text editor. Even blender's template scripts do the same thing.
I think the best solution is to use it like a real addon - that is save it to disk and enable/disable it in the addon preferences. You can ... | 11,624 |
48,967,621 | I will admit I'm stuck on a school project right now.
I have defined functions that will generate random numbers for me, as well as a random operator (+, -, or \*).
I have also defined a function that will display a problem using these random numbers.
I have created a program that will generate and display a random... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48967621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7856878/"
] | Just move your code that is generating the random values into your for loop:
```
for _ in range(10): #loops the program 10 times
randNum = getOp(max)
operand1 = getOp(max)
operand2 = getOp(max)
operator = getOperator()
answer = doIt(operand1, operand2, operator)
displayProblem... | You generate the problem and then show it 10 times in the loop:
```
generateProblem()
for _ in range(10):
showProblem()
```
of course you will get the same problem shown 10 times. To fix this, generate the problem *inside* the loop:
```
for _ in range(10):
generateProblem()
showProblem()
``` | 11,625 |
17,370,820 | I have come across some python code with slice notation that I am having trouble figuring out.
It looks like slice notation but uses a comma and a list:
```
list[:, [1, 2, 3]]
```
Is this syntax valid? If so what does it do?
**edit** looks like it is a 2D numpy array | 2013/06/28 | [
"https://Stackoverflow.com/questions/17370820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2502012/"
] | Assuming that the object is really a `numpy` array, this is known as [advanced indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing), and picks out the specified columns:
```
>>> import numpy as np
>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, ... | It generates a complex value and passes it to [`__*item__()`](http://docs.python.org/2/reference/datamodel.html#object.__getitem__):
```
>>> class Foo(object):
... def __getitem__(self, val):
... print val
...
>>> Foo()[:, [1, 2, 3]]
(slice(None, None, None), [1, 2, 3])
```
What it actually *performs* depends... | 11,628 |
61,996,756 | When I install npm on my project ionic with Angular. There is a failed install of node-sass/ node-gyp
error show like this :
>
> $ npm install
>
>
>
> >
> > node-sass@4.10.0 install C:\Users\d\Documents\project\app\node\_modules\node-sass
> > node scripts/install.js
> >
> >
> >
>
>
> Downloading binary from... | 2020/05/25 | [
"https://Stackoverflow.com/questions/61996756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3766841/"
] | Short answer: **Avoid global variables!**
In your `delete` function you set the value of the global variable `temp_node`.
Then you call the function `count`. In `count` you also use the global variable `temp_node`. You change it until it has the value NULL.
Then back in the `delete` function, you do:
```
temp_node... | You are probably making an extra loop in your delete function. You should check if you are deleting an node which isn't part of your linked list. | 11,629 |
1,664,587 | first time poster.
I'm turning to my first question on stack overflow because I've found little resources in trying to find an answer. I'm looking to execute Selenium python tests from a C# application. I don't want to have to compile the C# Selenium tests each time; I want to take advantage of IronPython scripting fo... | 2009/11/03 | [
"https://Stackoverflow.com/questions/1664587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201308/"
] | Looking at the [source code](http://ironpython.codeplex.com/SourceControl/ListDownloadableCommits.aspx) to the IronPython Console (ipy.exe), it looks like it eventually boils down to calling `ScriptSource.ExecuteProgram()`. You can get a `ScriptSource` from any of the various `ScriptEngine.CreateScriptSourceFrom*` meth... | Try the following:
```
unittest.main(module=__name__)
``` | 11,630 |
73,675,635 | I have 7 python dictionaries each named after the format `songn`, for example `song1`, `song2`, etc. Each dictionary includes the following information about a song: `name`, `duration`, `artist`. I created a list of songs, called `playlist full` of the form `[song1, song2, song3...,song7]`.
Here is my code:
```py
son... | 2022/09/10 | [
"https://Stackoverflow.com/questions/73675635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6267463/"
] | You could use [eval()](https://www.w3schools.com/python/ref_func_eval.asp) like:
```py
eval(playlist_full[2]).get("name")
```
which would do exactly what you want, evaluate the string as python code.
It's not great practice though. It would be better/safer to store the songs themselves in a dictionary or list that ... | You can use [`locals()`](https://docs.python.org/3/library/functions.html#locals) built-in function to do that:
```py
for i in range(1, 8):
song_i = "song"+str(i)
playlist_full.append(locals()[f'song{i}'])
``` | 11,631 |
67,180,248 | How can I get the text of a button clicked and return it to python? The button is selected using a mouse-click generated by the user in the Selenium WebDriver browser.
I'm trying to do as follows:
```
x=driver.execute_script("$(document).click(function(event){var text= $(event.target).text(); return text})")
```
bu... | 2021/04/20 | [
"https://Stackoverflow.com/questions/67180248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12296610/"
] | Once you click on the button,
You can extract the text of the button only if it's still available in the dom visible, else you can't. | ```
# Identify element
element = driver.find_element_by_id("id")
# Click element
element.click()
# Get text
print("Text is: " + element.text)
# Or
print("Text is: " + element.get_attribute("innerHTML")
``` | 11,636 |
50,639,390 | I am trying to write a music program in Python that takes some music written by the user in a text file and turns it into a midi. I'm not particularly experienced with python at this stage so I'm not sure what the reason behind this issue is. I am trying to write the source file parser for the program and part of this ... | 2018/06/01 | [
"https://Stackoverflow.com/questions/50639390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6283375/"
] | `row` contains a newline, so it's not empty. But `row.split()` doesn't find any non-whitespace characters, so it returns an empty list.
Use
```
if len(row.strip()):
```
to ignore the newline (and any other leading/trailing spaces).
Or more simply:
```
if row.strip():
```
since an empty string is falsy. | Try creating a [list comprehension](https://www.python-course.eu/python3_list_comprehension.php):
```
with open('d.txt', "r") as infile:
print([i.strip().split() for i in infile if i.strip()])
```
Output:
```
[['This', 'is'], ['A', 'test']]
``` | 11,637 |
14,633,021 | I have an AppHarbor app that I'm using as an external service which will get requested by my other servers which use Google App Engine (python). The appharbor app is basically getting pinged a lot to process some data that I send it.
Because I'll be constantly pinging the service, and time is important, is it possibl... | 2013/01/31 | [
"https://Stackoverflow.com/questions/14633021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361897/"
] | I doubt that DNS lookups will be your bottleneck, but anyway as far as I can see DNS lookups are cached by the system (for at least the TTL). | Sign up for the AppEngine Sockets Trusted Tester ([here](https://docs.google.com/a/postmaster.io/spreadsheet/viewform?formkey=dF9QR3pnQ2pNa0dqalViSTZoenVkcHc6MQ#gid=0)) and use the normal python:
```
socket.gethostbyname(...)
``` | 11,639 |
28,690,325 | I have such problem I have this piece of code on python2.7. It works approximately 60 seconds for object with slightly more than 70000 items in the object. How it works? It gets an object with paths to another objects and convert them to the ASCII strings. I think the problem why it is so slow is loops.
```
def create... | 2015/02/24 | [
"https://Stackoverflow.com/questions/28690325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4473386/"
] | ID of an element must be unique, when you use id selector it will return only the first element with the id, so all the click handlers are added to the first button.
Use classes and event delegation
```
$(document).ready(function () {
$("#image-btn").click(function () {
var $imageElement = $("<div class='... | use $(this) instead of $imageElement
```
$(document).ready(function(){
$("#image-btn").click(function(){
var $imageElement = $("<div class='image_element' id='image-element'><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='... | 11,642 |
17,438,852 | I want to pass in a string to my python script which contains escape sequences such as: `\x00` or `\t`, and spaces.
However when I pass in my string as:
```
some string\x00 more \tstring
```
python treats my string as a raw string and when I print that string from inside the script, it prints the string literally... | 2013/07/03 | [
"https://Stackoverflow.com/questions/17438852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059819/"
] | The string you receive in `sys.argv[1]` is exactly what you typed on the command line. Its backslash sequences are left intact, not interpreted.
To interpret them, follow [this answer](https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python): basically use `.decode('string_escape')`. | I don't know that you can parse entire strings without writing a custom parser but optparse supports [sending inputs in different formats](http://docs.python.org/2/library/optparse.html#standard-option-types) (hexidecimal, binary, etc).
```
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-... | 11,645 |
61,512,822 | Running in Jupyter-notebook
Python version 3.6
Pyspark version 2.4.5
Hadoop version 2.7.3
I essentially have the same issue described [Unable to write spark dataframe to a parquet file format to C drive in PySpark](https://stackoverflow.com/questions/59220832/unable-to-write-spark-dataframe-to-a-parquet-file-format... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61512822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13436683/"
] | You have to use `$sum` to sum the size of each array like this
```js
{
"$group": {
"_id": {
"vehicleid": "$vehicleid",
"date": "$date"
},
"count": { "$sum": { "$size": "$points" } }
}
}
``` | **You can follow this code**
```
$group : {
_id : {
"vehicleid":"$vehicleid",
"date":"$date"
count: { $sum: 1 }
}
}
``` | 11,648 |
33,365,055 | Hi I am using pandas to convert a column to month.
When I read my data they are objects:
```
Date object
dtype: object
```
So I am first making them to date time and then try to make them as months:
```
import pandas as pd
file = '/pathtocsv.csv'
df = pd.read_csv(file, sep = ',', encoding='utf-8-sig', us... | 2015/10/27 | [
"https://Stackoverflow.com/questions/33365055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4738736/"
] | #Convert date into the proper format so that date time operation can be easily performed
```
df_Time_Table["Date"] = pd.to_datetime(df_Time_Table["Date"])
# Cal Year
df_Time_Table['Year'] = df_Time_Table['Date'].dt.strftime('%Y')
``` | When you write
```
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')
```
It can fixed | 11,651 |
61,036,609 | As illustrated below, I am looking for an easy way to combine two or more heat-maps into one, i.e., a heat-map with multiple colormaps.
The idea is to break each cell into multiple sub-cells. I couldn't find any python library with such a visualization function already implemented. Anybody knows something (at least) c... | 2020/04/05 | [
"https://Stackoverflow.com/questions/61036609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625770/"
] | The heatmaps can be drawn column by column. White gridlines can mark the cell borders.
```py
import numpy as np
from matplotlib import pyplot as plt
a = np.random.random((5, 6))
b = np.random.random((5, 6))
vmina = a.min()
vminb = b.min()
vmaxa = a.max()
vmaxb = b.max()
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, f... | You can restructure your arrays to have empty columns between you actual data then create a masked array to plot heatmaps with transparency. Here's one method (maybe not the best) to add empty columns:
```
arr1 = np.arange(20).reshape(4, 5)
arr2 = np.arange(20, 0, -1).reshape(4, 5)
filler = np.nan * np.zeros((4, 5))
... | 11,661 |
14,459,258 | Games from Valve use following [data format](http://media.steampowered.com/apps/440/scripts/items/items_game.9aee6b38c52d8814124b8fbfc8d13e7b1faa944f.txt)
```
"name1"
{
"name2" "value2"
"name3"
{
"name4" "value4"
}
}
```
Does this format have a name or is it just self made?
Can I parse it ... | 2013/01/22 | [
"https://Stackoverflow.com/questions/14459258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670759/"
] | I'm not sure that it has a name, but it seems very straightforward: a node consists of a key and either a value or a set of values that are themselves either plain strings or sets of key-value pairs. It would be trivial to parse recursively, and maps cleanly to a structure of nested python dictionaries. | Looks like their own format, called Valve Data Format. Documentation [here](https://developer.valvesoftware.com/wiki/KeyValues), I don't know if there is a parser available in python, but here is a question about [parsing it in php](https://stackoverflow.com/questions/9301511/parsing-valve-data-format-files-in-php) | 11,662 |
50,917,003 | I'm trying to create a simple program to convert a binary number, for example `111100010` to decimal `482`. I've done the same in Python, and it works, but I can't find what I'm doing wrong in C++.
When I execute the C++ program, I get `-320505788`. What have I done wrong?
This is the Python code:
```python
def digi... | 2018/06/18 | [
"https://Stackoverflow.com/questions/50917003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5533085/"
] | The problem is that you converted this fragment of Python code
```
else:
digit = int(bit_number / exp % 10)
digit = digit * (2 ** i)
number += digit
```
into this:
```
else{
if((e % 10) == 0){
digit = 0;
}
else{
digit = bin_number / (e % 10);
}
digit = digit * pow(2, i);
... | One problem is that the 111100010 in main is not a [binary literal](https://en.cppreference.com/w/cpp/language/integer_literal) for 482 base 10 but is actually the decimal value of 111100010. If you are going to use a binary literal there is no need for any of your code, just write it out since an integer is an integer... | 11,664 |
49,677,110 | I am trying to decorate a function which is already decorated by `@click` and called from the command line.
Normal decoration to capitalise the input could look like this:
**standard\_decoration.py**
```
def capitalise_input(f):
def wrapper(*args):
args = (args[0].upper(),)
f(*args)
return wr... | 2018/04/05 | [
"https://Stackoverflow.com/questions/49677110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4288043/"
] | It appears that click passes keywords arguments. This should work. I think it needs to be the first decorator, i.e. it is called after all of the click methods are done.
```
def capitalise_input(f):
def wrapper(**kwargs):
kwargs['name'] = kwargs['name'].upper()
f(**kwargs)
return wrapper
@clic... | About click command groups - we need to take into account what the documentation says - <https://click.palletsprojects.com/en/7.x/commands/#decorating-commands>
So in the end a simple decorator like this:
```
def sample_decorator(f):
def run(*args, **kwargs):
return f(*args, param="yea", **kwargs)
ret... | 11,665 |
66,035,003 | Help! I'm trying to install cryptography on my m1. I know I can run terminal in rosetta mode, but I'm wondering if there is a way not to do that.
Output:
```
ERROR: Command errored out with exit status 1:
command: /opt/homebrew/opt/python@3.9/bin/python3.9 /opt/homebrew/lib/python3.9/site-packages/pip/_vendo... | 2021/02/03 | [
"https://Stackoverflow.com/questions/66035003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4366541/"
] | I'm using Macbook Pro M1 2020 model and faced the same issue. The issue was only with my cffi and pip versions maybe. Because these 4 steps helped me -
1. Uninstalling old cffi `pip uninstall cffi`
2. Upgrading pip `python -m pip install --upgrade pip`
3. Reinstalling cffi `pip install cffi`
4. Intalling cryptography ... | A little late to the party, but the solutions above didn't work for me. Paul got me on the right track, but my problem was that pyenv used the mac libffi for its build and cffi used the homebrew version. I read this somewhere, can't claim this unique insight.
My solution was to ensure that my python (3.8.13) was built... | 11,667 |
10,442,913 | I am working on HTML tables using python.
I want to know that how can i fetch different column values using lxml?
HTML table :
```
<table border="1">
<tr>
<td>Header_1</td>
<td>Header_2</td>
<td>Header_3</td>
<td>Header_4</td>
</tr>
<tr>
<td>row 1_cell 1</td>
<td>row 1_cell 2</td>
<td>row 1_cell 3</td>
<td>row 1_ce... | 2012/05/04 | [
"https://Stackoverflow.com/questions/10442913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778942/"
] | I do not know how do you make the choice of Header1+Header2, or Header1+Header3,... As the tables must be reasonably small, I suggest to collect all the data, and only then to extract the wanted subsets of the table. The following code show the possible solution:
```
import lxml.etree as ET
def parseTable(table_fragm... | Look into LXML as an html/xml parser that you could use. Then simply make a recursive function. | 11,677 |
18,732,803 | So I'm trying to build an insult generator that will take lists, randomize the inputs, and show the randomized code at the push of a button.
Right now, the code looks like...
```
import Tkinter
import random
section1 = ["list of stuff"]
section2 = ["list of stuff"]
section3 = ["list of stuff"]
class myapp(Tkinter.T... | 2013/09/11 | [
"https://Stackoverflow.com/questions/18732803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2658570/"
] | ```
def OnButtonClick(self):
myText = self.generator() # CALL IT!
self.labelVariable.set(myText+"(You clicked the button !)")
self.entry.focus_set()
self.entry.selection_range(0,Tkinter.END)
```
AND
```
def generator(self):....
``` | change with OnButtonClick function's second line and replace myText with generator() | 11,678 |
62,403,240 | I was doing some question in C and I was asked to provide the output of this question :
```
#include <stdio.h>
int main()
{
float a =0.7;
if(a<0.7)
{
printf("Yes");
}
else{
printf("No");
}
}
```
By just looking at the problem I thought the answer would be *NO* but after runni... | 2020/06/16 | [
"https://Stackoverflow.com/questions/62403240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9715289/"
] | ```
float a = 0.7;
if(a<0.7)
```
The first line above takes the `double` `0.7` and crams it into a `float`, which almost certainly has less precision (so you may lose information).
The second line upgrades the `float a` to a `double` (because you're comparing it with a `double 0.7`, and that's one of the things C do... | In `a<0.7` the constant `0.7` is a `double` then `a` which is a `float` is promoted
to `double` before the comparison.
Nothing guarantees that these two constants (as `float` and as `double`) are the same.
As `float` the fractional part of `0.7` is `00111111001100110011001100110011`; as `double` the fractional part... | 11,681 |
70,915,615 | I am trying to use a parent class as a blueprint for new classes.
E.g. the `FileValidator` contains all generic attributesand methods for a generic file. Then I want to create for example a `ImageValidator` inheriting everything from the FileValidator but with additional, more specific attribtues, methods. etc. In thi... | 2022/01/30 | [
"https://Stackoverflow.com/questions/70915615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11971785/"
] | Consider below approach
```
with example as (
select '670000000000100000000000000000000000000000000000000000000000000' as s
)
select s, (select sum(cast(num as int64)) from unnest(split(s,'')) num) result
from example
```
with output
[](ht... | Yet another [fun] option
```
create temp function sum_digits(expression string)
returns int64
language js as """
return eval(expression);
""";
with example as (
select '670000000000100000000000000000000000000000000000000000000000000' as s
)
select s, sum_digits(regexp_replace(replace(s, '0', ''), r'(\d)', r'+\1'))... | 11,682 |
8,219,630 | As a developer that has worked on more than one python project at once, I love the idea of Virtualenv. But, I'm currently trying to get Komodo IDE to play nice with VirtualEnv on a Windows box. I've downloaded virtualenvwrapper-win and got it working (btw, you are using Virtualenv on windows you should check it out):
... | 2011/11/21 | [
"https://Stackoverflow.com/questions/8219630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265681/"
] | I finally ended up posting the same question on the ActiveState forum. The reply was that it doesn't officially support VirtualEnv, yet. But, that you can make get it to work by adjusting the paths, etc. Here is the link to the question/reply.
<http://community.activestate.com/node/7499> | You can do this by adding the virtualenv's Python library to the project. Right-click on Project > Properties > Languages > Python > Additional Python Import Directories.
Now if someone could tell me how to add a folder like that in Mac when the virtualenv is under a hidden folder (without turning hidden folders on in... | 11,683 |
41,846,466 | I am currently experimenting with Behavioral Driven Development. I am using behave\_django with selenium. I get the following output
```
Creating test database for alias 'default'...
Feature: Open website and print title # features/first_selenium.feature:1
Scenario: Open website # features/first_sel... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41846466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7402682/"
] | I know it is a late answer but maybe somebody is going to profit from it:
you need to declare the context.browser (in a before\_all/before\_scenario/before\_feature hook definition or just test method definition) before you use it, e.g.:
```
context.browser = webdriver.Chrome()
```
Please note that the hooks must be... | In my case the browser wasn't installed. That can be a case too. Also ensure path to geckodriver is exposed if you are working with Firefox. | 11,686 |
18,005,365 | I need to start a python script with bash using nohup passing an arg that aids in defining a constant in a script I import. There are lots of questions about passing args but I haven't found a successful way using nohup.
a simplified version of my bash script:
```
#!/bin/bash
BUCKET=$1
echo $BUCKET
script='/home/p... | 2013/08/01 | [
"https://Stackoverflow.com/questions/18005365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1901847/"
] | In general, the argument vector for any program starts with the program itself, and then all of its arguments and options. Depending on the language, the program may be `sys.argv[0]`, `argv[0]`, `$0`, or something else, but it's basically always argument #0.
Each program whose job is to run another program—like `nohup... | ```
nohup python3 -u ./train.py --dataset dataset_directory/ --model model_output_directory > output.log &
```
Here Im executing train.py file with python3, Then -u is used to ignore buffering and show the logs on the go without storing, specifying my **dataset\_directory** with argument style and **model\_output\_di... | 11,687 |
18,968,607 | I'm trying to select timestamps columns from Cassandra 2.0 using cqlengine or cql(python), and i'm getting wrong results.
This is what i get from cqlsh ( or thrift ):
"2013-09-23 00:00:00-0700"
This is what i get from cqlengine and cql itself:
"\x00\x00\x01AG\x0b\xd5\xe0"
If you wanna reproduce the error, try this:
... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18968607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2808750/"
] | Unfortunately, cqlengine is not currently compatible with cassandra 2.0
There were some new types introduced with Cassandra 2.0, and we haven't had a chance to make cqlengine compatible with them. I'm also aware of a problem with blob columns.
This particular issue is caused by the cql driver returning the timestamp... | The `timestamp` datatype stores values as the number of milliseconds since the epoch, in a long. It seems that however you are printing it is interpreting it as a string. This works for me using cql-dbapi2 after creating and inserting as in the question:
```
>>> import cql
>>> con = cql.connect('localhost', keyspace='... | 11,688 |
29,320,466 | I have tried to use [emcee](http://dan.iel.fm/emcee/current/user/advanced/) library to implement Monte Carlo Markov Chain inside a class and also make multiprocessing module works but after running such a test code:
```
import numpy as np
import emcee
import scipy.optimize as op
# Choose the "true" parameters.
m_true... | 2015/03/28 | [
"https://Stackoverflow.com/questions/29320466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2811074/"
] | There are a number of SO questions that discuss what's going on:
1. <https://stackoverflow.com/a/21345273/2379433>
2. <https://stackoverflow.com/a/28887474/2379433>
3. <https://stackoverflow.com/a/21345308/2379433>
4. <https://stackoverflow.com/a/29129084/2379433>
…including this one, which seems to be your response…... | For the record, you can now create a `pathos.multiprocessing` pool, and pass it to emcee using the `pool` argument. However, be aware that the overhead of multiprocessing can actually slow things down, unless your likelihood is particularly time-consuming to compute. | 11,689 |
70,747,394 | I am trying to check if a user input as a string exists in a list called categoriesList which appends categories from a text file named categories.txt. If the user inputs a category that then exists in categoriesList my code should be able to print out "Category exists", otherwise "Category doesn't exist".
Here is the... | 2022/01/17 | [
"https://Stackoverflow.com/questions/70747394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17928821/"
] | Your `STATICFILES_FINDERS` setting tells Django that it should look for static files in the following places:
* `FileSystemFinder` tells it to look in whichever locations are listed in STATICFILES\_DIRS;
* `AppDirectoriesFinder` tells it to look in the `static` folder of each registered app in INSTALLED\_APPS.
In nor... | Try changing:
`STATICFILES_DIRS = [os.path.join(PROJECT_DIR, 'static'),]`
to
`STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]` | 11,690 |
15,128,404 | I am making a GUI in wxpython.
I want to place images next to radio buttons.
How should i do that in wxpython? | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118322/"
] | I suggest using wx.ToggleButton with bitmap labels if you are using 2.9, or one of the bitmap toggle button classes in wx.lib.buttons if you are still on 2.8. You can then implement the "radio button" functionality yourself by untoggling all other buttons in the group when one of them is toggled. Using the bitmap itsel... | I'm not sure what you mean. Are you wanting images instead of the actual radio button itself? That is not supported. If you want an image in addition to the radio button, then just use a group of horizontal box sizers or one of the grid sizers. Add the image and then the radio button. And you're done! | 11,691 |
60,976,753 | well i have this DF in python
```
folio id_incidente nombre app apm \
0 1 1 SIN DATOS SIN DATOS SIN DATOS
1 131 100085 JUAN DOMINGO GONZALEZ DELGADO
2 132 100085 FRANCISCO JAVIER VELA... | 2020/04/01 | [
"https://Stackoverflow.com/questions/60976753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11579387/"
] | Use [`Object.values`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) with [`Array.prototype.some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some):
```js
const obj = {
id: '123abc',
carrier_name: 'a',
group_id: 'a',
... | You could check with `every` and `Boolean` as callback, **if you have only strings**.
```js
const check = object => Object.values(object).every(Boolean);
console.log(check({ foo: 'bar' })); // true
console.log(check({ foo: '' })); // false
console.log(check({ foo: '', bar: 'baz' })); // false... | 11,693 |
25,449,779 | I use Google Cloud SDK under Window 7 64bit.
Google Cloud SDK and python install success. and run gcloud.
The error occurs as shown below.
```
C:\Program Files\Google\Cloud SDK>gcloud
Traceback (most recent call last):
File "C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin\..\./lib\googlecloudsdk\gcloud\gclou... | 2014/08/22 | [
"https://Stackoverflow.com/questions/25449779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485569/"
] | I had the same problem. And this helped me solve this problem
Manually removed directory: C:\Program Files\Google\Cloud SDK
Then rerun: GoogleCloudSDKInstaller.exe
And make sure that you have connection to needed DL servers (I was first behind company firewall and installer didn't download all files - and no complai... | ```
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -
sudo apt updat... | 11,696 |
18,805,720 | All I know how to do is type "python foo.py" in dos; the program runs but then exits python back to dos. Is there a way to run foo.py from within python? Or to stay in python after running? I want to do this to help debug, so that I may look at variables used in foo.py
(Thanks from a newbie) | 2013/09/14 | [
"https://Stackoverflow.com/questions/18805720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2779936/"
] | You can enter the python interpreter by just typing Python. Then if you run:
```
execfile('foo.py')
```
This will run the program and keep the interpreter open. More details [here](http://docs.python.org/2/library/functions.html#execfile). | To stay in Python afterwards you could just type 'python' on the command prompt, then run your code from inside python. That way you'll be able to manipulate the objects (lists, dictionaries, etc) as you wish. | 11,697 |
27,621,018 | how to perform
```
echo xyz | ssh [host]
```
(send xyz to host)
with python?
I have tried pexpect
```
pexpect.spawn('echo xyz | ssh [host]')
```
but it's performing
```
echo 'xyz | ssh [host]'
```
maybe other package will be better? | 2014/12/23 | [
"https://Stackoverflow.com/questions/27621018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3419895/"
] | <http://pexpect.sourceforge.net/pexpect.html#spawn>
Gives an example of running a command with a pipe :
```
shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)
```
Previous incorrect attempt deleted to make sure no-one is confused by it. | You don't need `pexpect` to simulate a simple shell pipeline. The simplest way to emulate the pipeline is the `os.system` function:
```
os.system("echo xyz | ssh [host]")
```
A more Pythonic approach is to use [the `subprocess` module](https://docs.python.org/2/library/subprocess.html):
```
p = subprocess.Popen(["s... | 11,699 |
21,946,883 | I'm writing a function to shift text by 13 spaces. The converted chars need to preserve case, and if the characters aren't letters then they should pass through unshifted. I wrote the following function:
```
def rot13(str):
result = ""
for c in str:
if 65 <= ord(c) <= 96:
result += chr((ord... | 2014/02/21 | [
"https://Stackoverflow.com/questions/21946883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036605/"
] | You are missing the "else" statement, so if the first if "fires" (`c` is an uppercase letter) then the "else" from the second if also "fires" (and concatenates the uppercase letter, as `ord(c)` is not between `97` and `122`)
```
def rot13(str):
result = ""
for c in str:
if 65 <= ord(c) <= 96:
... | This is an (rather contrived) one-liner implementation for the caesar cipher in python:
```
cipher = lambda w, s: ''.join(chr(a + (i - a + s) % 26) if (a := 65) <= (i := ord(c)) <= 90 or (a := 97) <= i <= 122 else c for c in w)
word = 'Hello, beautiful World!'
print(cipher(word, 13)) # positive shift
# Uryyb, ornhgvs... | 11,700 |
15,054,598 | So I created my project with a virtual environment and installed pip + distribute. Everything is fine so far, But when I click on the install button to install new packages it displays a beautiful : "Nothing to show".
Here is an image of it :

I hav... | 2013/02/24 | [
"https://Stackoverflow.com/questions/15054598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970581/"
] | The problem is caused by recent server-side changes in PyPI, and will be addressed in the PyCharm 2.7.1 update. Please see <http://youtrack.jetbrains.com/issue/PY-8962> to track the status of the issue. | If you are behind a proxy (e.g. in a corporate environment), then you may need to configure your proxy settings for PyCharm to show the packages.
These are in Pycharm under:
>
> File -> Settings -> Appearance & Behaviour -> System Settings -> HTTP Proxy
>
>
>
Enter your proxy settings there, e.g. a host name and... | 11,701 |
28,398,240 | I want to run my python function in console like this:
```
my_function_name
```
at any directory, I tried to follow arajek's answer in this question:
[run a python script in terminal without the python command](https://stackoverflow.com/questions/15587877/run-a-python-script-in-terminal-without-the-python-command)
... | 2015/02/08 | [
"https://Stackoverflow.com/questions/28398240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154698/"
] | Change the name of the script to no longer have the `.py` extension. | Add this shebang to the top of your file: `#!/usr/bin/env python` and remove the file extension. | 11,703 |
1,131,582 | I am using Boost with Visual Studio 2008 and I have put the path to boost directory in configuration for the project in C++/General/"Additional Include Directories" and in Linker/General/"Additional Library Directories". (as it says here: <http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#build-fro... | 2009/07/15 | [
"https://Stackoverflow.com/questions/1131582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Where is the file located, and which include path did you specify? (And how is the file `#include`'d)
There's a mismatch between some of these But it's impossible to say what's wrong when you haven't shown what you actually did.
**Edit**:
Given the paths you mentioned in comments, the problem is that they don't add ... | How do you include it? You should write something like this:
```
#include <boost/python.hpp>
```
Note that `Additional Include Directories` settings are differs in `Release` and `Debug` configurations. You should make them the same.
If boost placed to `C:\Program Files\boost\boost_1_36_0\` you should set path to `C... | 11,704 |
61,713,057 | I'm working on [google colaboratory](https://colab.research.google.com/) and i have to do some elaboration to some files based on their extensions, like:
```
!find ./ -type f -name "*.djvu" -exec file '{}' ';'
```
and i expect an output:
```
./file.djvu: DjVu multiple page document
```
but when i try to mix bash ... | 2020/05/10 | [
"https://Stackoverflow.com/questions/61713057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8069500/"
] | I found an ugly workaround passing trought a file, so first i write the array to a file in python:
```
with open('/content/file_types.txt', 'w') as f:
for ft in file_types:
f.write(ft + '\n')
```
and than i read and use it from bash in another cell:
```
%%bash
filename=/content/protected_file_types.txt
w... | This works for me
```
declare -a my_array=("pdf" "py")
for i in ${my_array[*]}; do find ./ -type f -name "*.$i" -exec file '{}' ';'; done;
``` | 11,705 |
65,362,747 | I'd like to slice a tensor (multi-dimensional array) using Rust's [ndarray](https://docs.rs/ndarray) library, but the catch is that the tensor is dynamically shaped and the slice is stored in a user provided variable.
If I knew the dimensionality up front, I expect I could simply do the following, where `idx` is the u... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65362747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7681811/"
] | You want to get the **"Bin On Hand"** fields:
You can get Location, Bin Number and On Hand from this join in your Saved Search. When done your results fields should be:
* Bin On Hand:Location
* Bin On Hand:Bin Number
* Bin On Hand:On Hand
Todd Stafford | From Admin role: List > Search > Saved Searches > New > Inventory Balance
In the results menu:
1. Item
2. Inventory Location
3. Bin
4. Quantity On Hand. | 11,706 |
67,157,938 | Trying to search no of times word appears in a file using python file handling. For example was trying to search 'believer' in the lyrics of believer song that how many times believer comes. It appears 18 times but my program is giving 12. What are the conditions I am missing.
```
def no_words_function():
f=open("be... | 2021/04/19 | [
"https://Stackoverflow.com/questions/67157938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7762964/"
] | I would suggest you adding object properties conditionally with ES6 syntax like this.
```js
const normalizeData = ({id, name = ""}) => {
const condition = !!name; // Equivalent to: name !== undefined && name !== "";
return {id, ...(condition && { name })};
}
console.log(normalizeData({id: 123, name: ""}));
consol... | You can create the object with the id first and then add a name afterwards:
```
const obj = {id: 123};
if(name) obj.name = name;
axios.post('saveUser', obj);
``` | 11,707 |
61,431,924 | here is my problem : I wrote a python bot that makes plenty of stuff, including printing colorful text for better understanding. I'm using the colorama package because it prints color even on windows command prompt.
Here is how I use colorama, which work both on unix and windows using python 3.8 :
```
from colorama im... | 2020/04/25 | [
"https://Stackoverflow.com/questions/61431924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13407332/"
] | Try:
```
pyinstaller.exe --onefile --hidden-import colorama script.py
```
This (--hidden-import colorama) should ensure that pyinstaller builds the application including colorama. | you should run `pip/pipenv install colorama` at first. | 11,708 |
14,260,714 | PyDev is reporting import errors which don't exist. The initial symptom was a fake "unresolved import" error, which was fixed by some combination of:
* Cleaning the Project
* Re-indexing the project (remove interpreter, add again)
* Restarting Eclipse
* Burning incense to the Python deities
Now the error is "unverifi... | 2013/01/10 | [
"https://Stackoverflow.com/questions/14260714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/963250/"
] | Try `ctrl+1` at the line where the error and add a comment saying that you are expecting that import. This should resolve the PyDev error, as it does static code analysis and not runtime analysis. | I added # @UndefinedVariable to the end of the line throwing the error.
This isn't much of a permanent fix, but at least it got rid of the red from my screen for the time being. If there is a better long term fix, I would be happy to hear it. | 11,709 |
38,542,675 | I'd appreciate some help with the diagnosis.
The error messages either point to the possibility that this package cannot be installed on a 64 bit machine or the wrong compiler is being selected.
**Edit:**
The [requirements](http://vmprof.readthedocs.io/en/latest/vmprof.html#requirements) for `vmprof` state that it w... | 2016/07/23 | [
"https://Stackoverflow.com/questions/38542675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2409868/"
] | This is an issue on [vmprof's github repository](http://github.com/vmprof/vmprof-python/issues/92) which is unfixed at 8/23/2016. | Finally, `vmprof` from v0.4 officially supports 64bit Windows
See the closed [GitHub Issue](https://github.com/vmprof/vmprof-python/issues/85) | 11,711 |
27,032,218 | I am using emacs-for-python provided by gabrielelanaro at this [link](https://github.com/gabrielelanaro/emacs-for-python).
Indentation doesn't seem to be working for me at all.
It doesn't happen automatically when I create a class, function or any other block of code that requires automatic indentation(if, for etc.)... | 2014/11/20 | [
"https://Stackoverflow.com/questions/27032218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2696086/"
] | Check the value of `python-indent-offset`. If it is 0, change it `M-x set-variable RET python-indent-offset RET 4 RET`.
Emacs tries to guess the offset used in a Python file when opening it. It might get confused and set that variable to 0 for some badly-formatted Python file. If this is indeed the problem, please do ... | Can you comment the lines related to auto-complete in your init.el?
```
; (add-to-list 'load-path "~/.emacs.d/auto-complete-1.3.1")
; (require 'auto-complete)
; (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
; (require 'auto-complete-config)
; (ac-config-default)
; (global-auto-complete-mode t)
``` | 11,712 |
69,895,751 | I try start my code, but process finishes on step with method cv2.namedWindow (without
any errors).
Do you have any suggestions, why it could be so?
```
import cv2
image_cv2 = cv2.imread('/home/spartak/PycharmProjects/python_base/lesson_016/python_snippets/external_data/girl.jpg')
def viewImage(image, name_of_window... | 2021/11/09 | [
"https://Stackoverflow.com/questions/69895751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14779400/"
] | I find out the problem.
I started this code in virtual environment.
Apparently, in virtual environment on UBUNTU/FEDORA, opencv have restrictions.
 | The code completes all 4 steps for me
I think there is a problem with the image path which you took
[](https://i.stack.imgur.com/zrqCV.png)
The function cv2.namedWindow creates a window that can be used as a placeholder for images and trackbars. Cre... | 11,715 |
41,487,605 | I am using DBSCAN from sklearn in python to cluster some data points. I am using a precomputed distance matrix to cluster the points.
```
import sklearn.cluster as cl
C = cl.DBSCAN(eps = 2, metric = 'precomputed', min_samples =2)
db = C.fit(Dist_Matrix)
```
Dist\_Matrix is precomputed distance matrix I am using. Ea... | 2017/01/05 | [
"https://Stackoverflow.com/questions/41487605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7342743/"
] | Clustering will *usually* not assign the same labels.
Because the label itself is *meaningless*. The only valueable information is what objects go *together*.
As for sklearn, if you use an old version, it will (unnecessarily) randomly shuffle the data. So it's not surprising you get a random permutation of the labels... | You can use a custom function to normalize the cluster labels.
```
def normalize_cluster_labels(labels):
min_value = min(labels)
if (min_value < 0):
labels = labels + abs(min(labels)) # normalize indexes
#idx = clustering.labels_ - min(clustering.labels_ )
return labels
``` | 11,717 |
37,241,819 | I have read a lot of other posts here on stackoverflow and google but I could not find a solution.
It all started when I changed the model from a CharField to a ForeignKey.
The error I recieve is:
```
Operations to perform:
Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages
Apply ... | 2016/05/15 | [
"https://Stackoverflow.com/questions/37241819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1067213/"
] | Had a similar problem i resolved it by removing the previous migration files.No technical explanation | I solved it by below:
1. First delete last migration that face problem
2. Then add like `venue_city = models.CharField(blank=True, null=True)`
3. Finally use `makemigrations` and `migrate` command | 11,718 |
21,758,560 | I've been struggling with an algorithm tied to comparisons with 3d triangle vectors. Unfortunately its very slow in places and I've gone back and forth on different methods to try and improve it. One thing I'm struggling with is speeding up a distance calculation.
I have two groups of triangles which have been broken... | 2014/02/13 | [
"https://Stackoverflow.com/questions/21758560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942439/"
] | The problem is that brute force testing of all triangles versus eachother takes quadratic time. It is better to use a datastructure which is specialized to perform such computations. Luckily, scipy contains one.
Take a look at scipy.spatial.cKDTree. The help should be self-explanatory. | I think diffverts is taking up enough memory to cause cache misses. Unfortunately while this solution is very elegant, you're probably better off computing the whole distance in one go, to avoid having to save an n\*m\*3 array of intermediate values. As ugly as it is, I would just do nested for loops. | 11,728 |
15,415,093 | For a system I am developing I need to programmatically go to a specific page. Fill out one field in the form (I know the id and name of the input element), submit it and store the results.
I have seen a few different Perl, python and java classes that do this. However I would like to do this using PHP and havent foun... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15415093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1364791/"
] | Take a look at David Walsh's simple explanation.
<http://davidwalsh.name/curl-post>
You can easily store the response (in this example, $result) in your database or logfile. | Usually PHP crawlers/scrapers use CURL - <http://php.net/manual/en/book.curl.php>.
It allows you to make a query from the server where PHP runs and get response from the website that you need to crawl. It returns response data in plain format and parsing it is up to you. You can manually check what does the form submit... | 11,729 |
50,991,402 | I'm trying to create a new tables in a new app added to my project .. `makemigrations` worked great but `migrate` is not working .. here is my models
**blog/models.py**
```
from django.db import models
# Create your models here.
from fostania_web_app.models import UserModel
class Tag(models.Model):
tag_name = m... | 2018/06/22 | [
"https://Stackoverflow.com/questions/50991402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9494140/"
] | Error message: `ValueError: invalid literal for int() with base 10: '??? ??? ?????'`
As per exception int() with base 10: `'??? ??? ?????'` doesn't qualify as int.
Check in `blog.0001_initial` migrations for `'??? ??? ?????'` and modify that value with a valid int.
You might have accidentally provided garbage default... | I had the same error.
My problem:
I had:
```
models.y
expiration_date = models.DateField(null=True, max_length=20)
```
And a validation in my:
```
forms.py
def clean_expiration_date(self):
data = self.cleaned_data['expiration_date']
if data < datetime.date.today():
return data
```
And it gave me the he... | 11,732 |
16,247,828 | Now our code have 3,000,000 id stored in set, the format is string, I try to convert it to int using list comprehension. But it cost 5 sec, how can I reduce the cost of converting string to int for these 3,000,000 id?
Here is my testing code:
```
import random
import time
a = set()
for i in xrange(3088767):
a.ad... | 2013/04/27 | [
"https://Stackoverflow.com/questions/16247828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472880/"
] | ```
ld = map(int, a)
```
should be quite faster, and also your only option not considering other python implementations | Try using [Pypy](http://pypy.org) or [Cython](http://cython.org).
These tools can made your code fly! (Pypy, specially, in my PC Pypy speed up the code 4 times..) | 11,733 |
46,164,419 | Getting a 'Label out of bound' error while running the testing script. Error is thrown in the confusion\_matrix function when the annotation values are compared with the number of classes. In my case annotation value is an image(560x560) and number\_of\_classes = 2.
```
[check_ops.assert_less(labels, num_classes_int64... | 2017/09/11 | [
"https://Stackoverflow.com/questions/46164419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8485184/"
] | In the Annotation file, the labels were 0,1,2,255. The range of label was given 3. So when 255 was detected in the annotation file above error was thrown. After I removed all 255 values the code worked without any error. | under tensorflow 1.15.2, tensorflow/models/research/deeplab is basically quite ok.
error message like:
Invalid argument: assertion failed: [`labels` out of bound] [Condition x < y did not hold element-wise:] [x (mean\_iou/confusion\_matrix/control\_dependency:0) = ]
likely due not considering background as 1 class.... | 11,734 |
45,318,255 | **Code:**
```
import numpy as np
z = np.array([[1,3,5],[2,4,6]])
print(z[0:, :2])
```
**Answer:**
```
[[1, 3] [2, 4]]
```
I am a python beginner, I was solving an interactive exercise when the above mentioned question appeared.
I am not able to understand, how z[0:, :2] works in this case? If possible, please ... | 2017/07/26 | [
"https://Stackoverflow.com/questions/45318255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4282170/"
] | You can read about Numpy slicing and indexing here:
<https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>
In this case, `0:` means "all the rows, starting from (and including) row 0 and going until the end" (you could also just use the equivalent `:`, which means "all the rows, starting from the beginning... | First you ask to get all rows (`0:` is the same as `:`):
```
[[1,3,5],
[2,4,6]]
```
Then you ask for columns 0 and 1 (`:2` is the same as `0:2` which means from 0 until 2 exclusive):
```
[[1,3],
[2,4]]
``` | 11,740 |
68,434,126 | In a Tkinter window of the Test.py file, I would like to display in a textobox what is printed in the Python console.
By clicking on button, you start a function in the Test.py file that calls the X.py and Y.py scripts (more precisely their functions). The results of the scripts are printed correctly in the Python con... | 2021/07/19 | [
"https://Stackoverflow.com/questions/68434126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16472472/"
] | For Python 3.4+, you can use `contextlib.redirect_stdout` (see [official document](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout)) to redirect `sys.stdout` to another file or file-like object temporarily.
```py
import tkinter as tk
from contextlib import redirect_stdout
from File.X impor... | Ok, so after a lot of trial and error I finally found a way to accomplish what You want (to be fair though, You were the one that was supposed to go through this phase AND show Your attempts which You failed to do, either how I don't mind much since I learned stuff too):
```py
from tkinter import Tk, Text
import subpr... | 11,745 |
48,908,156 | I am using **Django-Cookiecutter** which uses **Django-Allauth** to handle all the authentication and there is one App installed called **user** which handles everything related to users like sign-up, sign-out etc.
I am sharing the models.py file for users
```
@python_2_unicode_compatible
class User(AbstractUser):
... | 2018/02/21 | [
"https://Stackoverflow.com/questions/48908156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5881652/"
] | Unless you are offering a course to just one user, it does not make sense to have a one-to-many relationship between User and Course models. So, you need a many-to-many relationship. It is also wise to extend the user model by creating a UserProfile model and relate UserProfile to your course. You can look [here](https... | You can directly add foreign key as:
```
user = models.Foreignkey(User,related_name="zyz")
``` | 11,746 |
72,184,482 | I have a project trying to imagescrape from a website. I use a csv file with all the urls. Some urls i dont have the premission to open(or they dont exist). I get a Http error 403 in phyton from those. I just want the try the next url in the csv file and ignore the error.
```python
import urllib.request
import csv
wi... | 2022/05/10 | [
"https://Stackoverflow.com/questions/72184482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19084463/"
] | You may have an issue with the SNS access policy. There is a video of troubleshooting this issue at <https://youtu.be/RjSW75YsBMM>. | Make sure that your SNS topic has the proper Access Policy set. In my case, the default Access Policy included an `AWS:SourceOwner` condition which I needed to remove in order to allow the S3 event configuration to perform the `SNS:Publish` action against the topic. | 11,747 |
26,207,097 | I am wondering how one would create a GUI application, and interact with it from the console that started it.
As an example, I would like to create a GUI in PyQt and work with it from the console. This could be for testing settings without restarting the app, but in larger projects also for calling functions etc.
Her... | 2014/10/05 | [
"https://Stackoverflow.com/questions/26207097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356998/"
] | ops, posted wrong answer before
there is a post in Stack about that
[Execute Python code from within PyQt event loop](https://stackoverflow.com/questions/4893748/execute-python-code-from-within-pyqt-event-loop) | The easiest way is to use IPython:
```
ipython --gui=qt4
```
See `ipython --help` or the [online documentation](http://ipython.org/ipython-doc/dev/config/options/terminal.html) for more options (e.g. gtk, tk, etc). | 11,748 |
2,157,208 | In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism? | 2010/01/28 | [
"https://Stackoverflow.com/questions/2157208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261273/"
] | The GIL only requires that the interpreter completely executes a single bytecode instruction before another thread can take over. However, there is no reason to assume that an increment operation is a single instruction. For example:
```
>>> import dis
>>> dis.dis(compile("x=753","","exec"))
1 0 LOAD_CONST... | Yes, multithreading without locking almost always causes problems, with or without a GIL. | 11,750 |
56,120,774 | In the case where python executes more operations, it is slower.
The following is a very simple comparison of two separate nested loops (for finding a Pythagorean triple `(a,b,c)` which sum to 1000):
```
#Takes 9 Seconds
for a in range(1, 1000):
for b in range(a, 1000):
ab = 1000 - (a + b)
for c in range(ab... | 2019/05/13 | [
"https://Stackoverflow.com/questions/56120774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11495271/"
] | You can just count total amount of iterations in each solution and see that A takes more iterations to find the result:
```
#Takes 9 Seconds
def A():
count = 0
for a in range(1, 1000):
for b in range(a, 1000):
ab = 1000 - (a + b)
for c in range(ab, 1000):
count += 1
if(((a + b + c) == 1000) and... | You have two false premises in your confusion:
* The methods find all triples. They do not; each one finds a single triple and then aborts.
* The upper method (aka "solution A") does fewer comparisons.
I added some basic instrumentation to test your premises:
import time
```
#Takes 9 Seconds
count = 0
start = time.... | 11,751 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.