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 |
|---|---|---|---|---|---|---|
45,300,287 | I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkin... | 2017/07/25 | [
"https://Stackoverflow.com/questions/45300287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267211/"
] | For a start webview consumes memory because it load has to load and render html data. Rather than using a webview in a recycler view, I think it would be better if you implemented it either of these two ways:
1. You handle the list of data in html and send it into the webview and remove the recycler view completely
2.... | This problem can arrive for many possible reasons
* When you scroll very fast
Recyclerview is purely based on Inflating the view minimal times and reusing the existing views. This means that while you are scrolling when a view(An item) exits your screen the same view is bought below just by changing its contents.When ... | 12,233 |
51,927,893 | So I started learning python 3 and I wanted to run a very simple code on ubuntu:
```
print type("Hello World")
^
SyntaxError: invalid syntax
```
When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 ... | 2018/08/20 | [
"https://Stackoverflow.com/questions/51927893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10140067/"
] | In Python3, `print` [was changed](https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function) from a statement to a function (with brackets):
i.e.
```
# In Python 2.x
print type("Hello World")
# In Python 3.x
print(type("Hello World"))
``` | In Python 3.x [`print()`](https://docs.python.org/3/library/functions.html#print) is a function, while in 2.x it was a statement. The correct syntax in Python 3 would be:
```
print(type("Hello World"))
``` | 12,238 |
10,352,538 | I am stuck with this problem for the past few hours.
This is how the XML looks like
```
<xmlblock>
<data1>
<username>someusername</username>
<id>12345</id>
</data1>
<data2>
<username>username</username>
<id>11111</id>
</data1>
... | 2012/04/27 | [
"https://Stackoverflow.com/questions/10352538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897906/"
] | A (probably not the best) solution
```
>>> id_to_match = 12345
>>> for event, element in cElementTree.iterparse('xmlfile.xml'):
... if 'data' in element.tag:
... for data in element:
... if data.tag == 'username':
... username = data.text
... if data.tag == 'id':
... ... | If you are ok with using [minidom](http://docs.python.org/library/xml.dom.minidom.html) the following should work
```
from xml.dom import minidom
doc = minidom.parseString('<xmlblock><data1><username>someusername</username><id>12345</id></data1><data2><username>username</username><id>11111</id></data2></xmlblock>')
us... | 12,241 |
66,910,159 | Consider the below set of lists that contain two strings each.
The pairing of two strings in a given list means the values they represent are equal. So item A is the same as item B and C, and so on.
```
l1 = [ 'A' , 'B' ]
l2 = [ 'A' , 'C' ]
l3 = [ 'B' , 'C' ]
```
What is the most efficient/pythonic way to collect... | 2021/04/01 | [
"https://Stackoverflow.com/questions/66910159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3234810/"
] | I would use a defaultdict from collections so the dictionary expands and just takes whatever you throw into it. If this is a one way correspondence I would use this code (assuming you make a list of the lists)
```
dd = collections.defaultdict(list)
for line in lists:
dd[line[0]].append(line[1])
```
for given se... | ---
Assuming you can get a list of those lists like so:
```
[[ 'A' , 'B' ], [ 'A' , 'C' ],[ 'B' , 'C' ]]
```
This should give you the relation you want:
```
d = {}
l1 = [[ 'A' , 'B' ],[ 'A' , 'C' ],[ 'B' , 'C' ]]
for sublist in l1:
if sublist[0] not in d.keys(): #check if first value is already a key in the... | 12,243 |
17,039,457 | I want to convert the first column of data from a text file into a list in python
```
data = open ('data.txt', 'r')
data.read()
```
provides
```
'12 45\n13 46\n14 47\n15 48\n16 49\n17 50\n18 51'
```
Any help, please. | 2013/06/11 | [
"https://Stackoverflow.com/questions/17039457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2473267/"
] | You can use `str.split` and a `list comprehension` here:
```
with open('data.txt') as f:
lis = [int(line.split()[0]) for line in f]
>>> lis
[12, 13, 14, 15, 16, 17, 18]
```
If the numbers to be strings:
```
>>> with open('abc') as f:
lis = [line.split()[0] for line in f]
>>> lis
['12', '13', '14', '15', '... | ```
import csv
with open ('data.txt', 'rb') as f:
print [row[0] for row in csv.reader(f, delimiter=' ')]
```
---
```
['12', '13', '14', '15', '16', '17', '18']
``` | 12,245 |
27,801,200 | How do i put this in a loop in python so that it keeps asking if player 1 has won the game, until it reaches the number of games in the match. i tried a while loop but it didn't work :(
```
Y="yes"
N="no"
PlayerOneScore=0
PlayerTwoScore=0
NoOfGamesInMatch=int(input("How many games? :- "))
while PlayerOneScore < NoOfG... | 2015/01/06 | [
"https://Stackoverflow.com/questions/27801200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424276/"
] | You can have a preRender set on the *listLabelsPage.xhtml* page you're loading
```
<f:event type="preRenderView" listener="#{yourBean.showGrowl}" />
```
and a showGrowl method having only
```
public void showGrowl() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMe... | I post an answer to my own question in order to help another people which face the same problem like I did:
```
public String addLabelInDB() {
try {
//some logic to insert in db
//below I set a flag on context which helps me to display a growl message only when the insertion was done wi... | 12,246 |
51,413,816 | Before I begin, I'd like to preface that I'm relatively new to python, and haven't had to use it much before this little project of mine. I'm trying to make a twitter bot as part of an art project, and I can't seem to get tweepy to import. I'm using macOS High Sierra and Python 3.7. I first installed tweepy by using
... | 2018/07/19 | [
"https://Stackoverflow.com/questions/51413816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10102844/"
] | Using `async` as an identifier [has been deprecated since Python 3.5, and became an error in Python 3.7](https://www.python.org/dev/peps/pep-0492/#deprecation-plans), because it's a keyword.
This Tweepy bug was [reported on 16 Mar](https://github.com/tweepy/tweepy/issues/1017), and [fixed on 12 May](https://github.com... | In Python3.7, [`async`](https://docs.python.org/3/reference/compound_stmts.html#async) became a reserved word (as can be seen in *whats new* section [here](https://docs.python.org/3/whatsnew/3.7.html)) and therefore cannot be used as argument. This is why this `Syntax Error` is raised.
That said, and following `tweet... | 12,249 |
48,143,394 | So I play a game in which I have 12 pieces of gear. Each piece of gear (for the purposes of my endeavor) has four buffs I am interested in: power, haste, critical damage, critical rating.
I have a formula in which I can enter the total power, haste, CD, and CR and generate the expected damage per second output.
Howev... | 2018/01/08 | [
"https://Stackoverflow.com/questions/48143394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5208967/"
] | Use iterator to replace for-loop:
```
keys = ['p', 'h', 'cd', 'cr']
iter_keys = itertools.product(*([keys] * 12))
for item in iter_keys:
print item
```
Output:
```
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'h', 'cr')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'p')
('p', 'p', 'p', 'p... | If you have 12 nested for loops, you probably need a recursive design like this :
```
def loops (values, num, current_list):
if num > 0:
for v in values:
loops(values, num-1, current_list+list(v))
else:
print current_list
loops (('a', 'b', 'c', 'd'), 12, [])
```
Then, you will p... | 12,250 |
12,969,897 | I have some questions about encoding in python 2.7.
1.The python code is as below,
```
#s = u"严"
s = u'\u4e25'
print 's is:', s
print 'len of s is:', len(s)
s1 = "a" + s
print 's1 is:', s1
print 'len of s1 is:', len(s1)
```
the output is:
```
s is: 严
len of s is: 1
s1 is: a严
len of s1 is: 2
```
I am confused tha... | 2012/10/19 | [
"https://Stackoverflow.com/questions/12969897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477871/"
] | >
> I am confused that why the len of s is 1, how could 4e25 be stored in 1 byte? I also notice that USC-2 is 2-bytes long and USC-4 is 4-bytes long, why unicode string s's length is 1?
>
>
>
The whole point of unicode strings is to do this. The length of a unicode string is the number of *characters* (i.e., code ... | ### Answer to Question 1:
In Python versions <3.3, length for a Unicode string `u''` is the number of UTF-16 or UTF-32 code units used (depending on build flags), not the number of bytes. `\u4e25` is one code unit, but not all characters are represented by one code unit if UTF-16 (default on Windows) is used.
```
>>>... | 12,251 |
13,623,634 | Why doesn't following code print anything:
```
#!/usr/bin/python3
class test:
def do_someting(self,value):
print(value)
return value
def fun1(self):
map(self.do_someting,range(10))
if __name__=="__main__":
t = test()
t.fun1()
```
I'm executing the above code in Python 3. I t... | 2012/11/29 | [
"https://Stackoverflow.com/questions/13623634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651941/"
] | [`map()` returns an iterator](http://docs.python.org/3/library/functions.html#map), and will not process elements until you ask it to.
Turn it into a list to force all elements to be processed:
```
list(map(self.do_someting,range(10)))
```
or use `collections.deque()` with the length set to 0 to not produce a list ... | Before Python 3, map() returned a list, not an iterator. So your example would work in Python 2.7.
list() creates a new list by iterating over its argument. ( list() is NOT JUST a type conversion from say tuple to list. So list(list((1,2))) returns [1,2]. ) So list(map(...)) is backwards compatible with Python 2.7. | 12,252 |
48,055,372 | I Converted a csv to list:
```
import csv
with open('DataAnalizada.csv', 'rb') as f:
reader = csv.reader(f)
a = list(reader)
```
I need to analyze the information on that list where it is analyzed by customer groups and dates first as AAA customer on 12/27/2017, AAA on 12/28/2017, BBB on 12/27/2017, BBB on 2... | 2018/01/02 | [
"https://Stackoverflow.com/questions/48055372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8717507/"
] | I thought this might lead you to what you want, however, not sure this will be totally helpful. Since you don't have a condition to filter data, I tried the following way to just get your desired output. Note, this is just a try to guide you towards pandas.
`pandas` would be the best way to go about this as you could... | The Pandas package has the tools you need. However I would recommend starting with [scipy](https://www.scipy.org/about.html "scipy") and [anaconda](https://www.anaconda.com/download/#linux "anaconda") since I found installing Pandas on its own to be quite difficult. | 12,255 |
52,571,930 | I have a 2D array A:
```
28 39 52
77 80 66
7 18 24
9 97 68
```
And a vector array of column indexes B:
```
1
0
2
0
```
How, in a pythonian way, using base Python or Numpy, can I select the elements from A which DO NOT correspond to the column indexes in B?
I should get this 2D array wh... | 2018/09/29 | [
"https://Stackoverflow.com/questions/52571930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10434696/"
] | You can make use of broadcasting and a row-wise mask to select elements not contained in your array for each row:
***Setup***
```
B = np.array([1, 0, 2, 0])
cols = np.arange(A.shape[1])
```
---
Now use broadcasting to create a mask, and index your array.
```
mask = B[:, None] != cols
A[mask].reshape(-1, 2)
```
... | A spin off of my answer to your other question,
[Replace 2D array elements with zeros, using a column index vector](https://stackoverflow.com/questions/52573733/replace-2d-array-elements-with-zeros-using-a-column-index-vector)
We can make a boolean `mask` with the same indexing used before:
```
In [124]: mask = np.... | 12,257 |
55,808,362 | I have just started working with python 3.7 and I am trying to create a series e.g from 0 to 23 and repeat it. Using
```
rep1 = pd.Series(range(24))
```
I figured out how to make the first 24 values and I wanted to "copy-paste" it many times so that the final series is the original 5 times, one after the other. The ... | 2019/04/23 | [
"https://Stackoverflow.com/questions/55808362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167002/"
] | you can try this:
```
pd.concat([rep1]*5)
```
This will repeat your series 5 times. | You could use a list to generate directly your Series.
```
rep = pd.Series(list(range(24))*5)
``` | 12,258 |
6,474,923 | I'm getting errors building an App store and Adhoc distributions of my project. I'm using the latest version of the three20 which I integrated into my Xcode 4 project using the given python script.
The release and debug version of the project build just fine without any build errors.
Here's the summary of the errors:... | 2011/06/25 | [
"https://Stackoverflow.com/questions/6474923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/539115/"
] | I have figured out whats going on here. The python script the header search paths for three20 to:
```
$(BUILT_PRODUCTS_DIR)/../three20
$(BUILT_PRODUCTS_DIR)/../../three20
../../libs/external/three20/Build/Products/three20
```
These paths work fine for Debug and Release builds as the macros expand to paths without an... | It might have happened because you added these 2 new targets AFTER you use the python script to add three20 project.
You will need to run the python script again to add three20 to your new targets:
```
python three20/src/scripts/ttmodule.py -p ProjectName/ProjectName.xcodeproj -c NEW_TARGET_NAME Three20
``` | 12,263 |
35,562,234 | I have a python script that displays the Date, hour and IP Address for an attack in a log file. My issue is that i need to be able to count how many attacks occur per hour per day but when i implement a count it just counts the total not what i want.
**The log file looks like this:**
```
Feb 3 08:50:39 j4-be02 sshd[... | 2016/02/22 | [
"https://Stackoverflow.com/questions/35562234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671509/"
] | The python function [`groupby()`](https://docs.python.org/2/library/itertools.html#itertools.groupby) will group your items according to any criteria you specify.
This code will print the number of attacks per hour, per day:
```
from itertools import groupby
with open('auth.log') as myAuthlog:
for key, group in ... | ```
import collections
from datetime import datetime as dt
answer = collections.defaultdict(int)
with open('path/to/logfile') as infile:
for line in infile:
stamp = line[:9]
t = dt.strptime(stamp, "%b\t%d\t%H")
answer[t] += 1
``` | 12,264 |
70,088,746 | In python I am returning numbers but I only want the last 10 numbers
Ex: 221234567890 should return 1234567890
In excel it looks like: if(len(cell) > 10, right (cell,10),.. but don't know how to do this in python | 2021/11/23 | [
"https://Stackoverflow.com/questions/70088746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17492723/"
] | ```py
a = 221234567890
result = a % 10000000000
```
This should work for ints and
```py
a = "221234567890"
result = a[-10:]
```
should work for strings | ```
a = '123456789abcdefg'
a[-10:]
``` | 12,265 |
70,951,954 | So im trying to make a script using Lexing and Parsing. I wanted to try and change the color of the texts when a user inputs something.
Say in python when I do:
'''print("Hello")'''
It changes the color of print, string, parens, etc. I just wanted to know how to do it
and/or the code to do it.
Say if my user types:
'... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70951954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18097622/"
] | You can do like this
```
import colorama
from colorama import Fore
print(Fore.RED + 'This text is red in color')
``` | Try using colorama, or termcolor in python:
Here is a link:
<https://www.geeksforgeeks.org/print-colors-python-terminal/> | 12,266 |
63,345,648 | I have been able to filter all the image url from a page and displayed them one after the other
```
import requests
from bs4 import BeautifulSoup
article_URL = "https://medium.com/bhavaniravi/build-your-1st-python-web-app-with-flask-b039d11f101c"
response = requests.get(article_URL)
soup = bs4.BeautifulSoup(response.... | 2020/08/10 | [
"https://Stackoverflow.com/questions/63345648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8053783/"
] | There is no native javascript api that allows you to find event listeners that were added using `eventTarget.addEventListener`.
You can still get events added using the `onclick` attribute whether the attribute was set using javascript or inline through html - in this case u are not getting the event listener, but you... | There is no way, to do so directly with JavaScript.
However, you can use this approach and add an attribute while binding events to the elements.
```js
document.getElementById('test2').addEventListener('keypress', function() {
this.setAttribute("event", "yes");
console.log("foo");
}
)
document.querySelecto... | 12,267 |
67,137,419 | I have started to use AWS SAM for python. When testing my functions locally I run:
```
sam build --use-container
sam local start-api
You can now browse to the above endpoints to invoke your functions. You do **not** need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/au... | 2021/04/17 | [
"https://Stackoverflow.com/questions/67137419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6281479/"
] | I believe your goal as follows.
* You want to reduce the process cost of the following script.
```
resultsSheet.hideColumns(11);
resultsSheet.hideColumns(18);
resultsSheet.hideColumns(19);
resultsSheet.showColumns(26);
resultsSheet.showColumns(27);
resultsSheet.showColumns(28);
resultsSheet.showColumns(... | To do this faster, you can hide and show rows in groups, with one SpreadsheetApp call required per group. For example, you can hide the seven columns listed in your code sample with this:
`hideColumns_(resultSheet, [11, 18, 19, 26, 27, 28, 29]);`
To show columns, use a similar pattern with `showColumns_()`. Here's th... | 12,268 |
6,576,829 | I'am looking for python async SMTP client to connect it with Torando IoLoop. I found only simple implmementation (<http://tornadogists.org/907491/>) but it's a blocking solution so it might bring performance issues.
Does anyone encountered non blocking SMTP client for Tornado? Some code snippet would be also very usef... | 2011/07/04 | [
"https://Stackoverflow.com/questions/6576829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747179/"
] | I wrote solution based on threads and queue. One thread per tornado process. This thread is a worker, gets email from queue and then send it via SMTP. You send emails from tornado application by adding it to queue. Simple and easy.
Here is sample code on GitHub: [link](https://github.com/marcinc81/quemail) | Just FYI - I just whipped up a ioloop based smtp client. While I can't say it's production tested, it will be in the near future.
<https://gist.github.com/1358253> | 12,269 |
51,307,411 | I'm trying to make an api for Pokemon, and I was thinking of packaging it, but no matter what I do, as soon as I try to import from this file, it comes up with this error.
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/student/anaconda3/lib/python3.6/site-packages/pokeapi/__... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51307411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4503723/"
] | I think the `if btnState == 2` statement is in the wrong block.
Also, what is `questionNumber`, when will it be incremented? How does it relate to `self.turn`?
You could try this:
```
@IBAction func btnUncoverQuestion(_ sender: RoundedButton) {
btnUncoverQuestion.setTitle(questionArray?[questionNumber].title ?? ... | Please use tag for different event.Example in 1st press you set the button.tag = 100 and 2nd press set the tag 200.
Check the tag in button action:
```
@IBAction func btnAction(_ sender: UIButton) {
switch sender.tag {
case 100:
//your action
sender.tag = 200
case 200:
//your acti... | 12,273 |
22,391,419 | what is the difference between curly brace and square bracket in python?
```
A ={1,2}
B =[1,2]
```
when I print `A` and `B` on my terminal, they made no difference. Is it real?
And sometimes, I noticed some code use `{}` and `[]` to initialize different variables.
E.g. `A=[]`, `B={}`
Is there any difference ther... | 2014/03/13 | [
"https://Stackoverflow.com/questions/22391419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2911587/"
] | Curly braces create [dictionaries](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) or [sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). Square brackets create [lists](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range).
They are called *li... | They create different types.
```
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>
``` | 12,274 |
17,904,216 | I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list an... | 2013/07/28 | [
"https://Stackoverflow.com/questions/17904216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209860/"
] | You can do:
```
>>> def sieve(L, i):
... temp = L[:i]
... for x, y in zip(L[i::2], L[i+1::2]):
... temp.append(x)
... temp.append(y/2)
... return temp
...
>>> sieve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
Note that `itself * (2 - 1 ) / 2` is equival... | ```
map(lambda x : x * (2 - 1) / 2 if x % 2 == 0 else x, list)
```
This should do what you want it to.
**Edit:**
Alternately in style, you could use list comprehensions for this as follows:
```
i = 2
list[:i] + [x * (i - 1) / i if x % i == 0 else x for x in list[i:]]
``` | 12,277 |
50,567,475 | I am upgrading my django application from `Django 1.5` to `Django 1.7`. While upgrading I am getting `django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet` error. I tried with some solution I got by searching. But nothing is worked for me. I think it because of one of my model. Please help me to fix thi... | 2018/05/28 | [
"https://Stackoverflow.com/questions/50567475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5939865/"
] | From the traceback I see the following:
```
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuite/apps/admin/models/__init__.py", line 14, in <module>
from occupational_standard import *
File "/home/venkat/sample-applications/wfmis-django-upgrade/wfmis-upgrade/django-pursuit... | Stop the venv before upgrading django.
Stop the server before upgrading.
Update to 1.7 style wsgi handler.
Also, use pip to manage & upgrade packages, your script is bound to break the packages otherwise. | 12,285 |
11,055,165 | From a file, i have taken a line, split the line into 5 columns using `split()`. But i have to write those columns as tab separated values in an output file.
Lets say that i have `l[1], l[2], l[3], l[4], l[5]`...a total of 5 entries. How can i achieve this using python? And also, i am not able to write `l[1], l[2], l... | 2012/06/15 | [
"https://Stackoverflow.com/questions/11055165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411416/"
] | The `write()` method takes a string as its first argument (not a variable number of strings). Try this:
```
outf.write(l[1] + l[2] + l[3] + l[4] + l[5])
```
or better yet:
```
outf.write('\t'.join(l) + '\n')
``` | ```
outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))
```
will write the data to the file tab separated. Note that write doesn't automatically append a `\n`, so if you need it you'll have to supply it yourself.
Also, it's better to open the file using `with`:
```
with open('output', 'w') as outf:
... | 12,286 |
56,899,892 | I am following along with this pycon video on python packaging.
I have a directory:
* `mypackage/`
+ `__init__.py`
+ `mypackage.py`
* `readme.md`
* `setup.py`
The contents of `mypackage.py`:
```
class MyPackage(): ... | 2019/07/05 | [
"https://Stackoverflow.com/questions/56899892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118666/"
] | First, you usually can find the root cause on **last** `Caused by` statement for debugging.
Therefore, according to the error log you posted, `Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set` should be key!
Although Hibernate is database a... | In my case:
1. I have created **separate new project** with the **same code** and in the **same work-space**.
2. Started the application.
3. This time tomcat started successfully in the first instance itself. | 12,289 |
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | `youredittext.requestFocus()` call it from activity
```
oncreate();
```
and use the above code there | ```
>>you can write your code like
if (TextUtils.isEmpty(username)) {
editTextUserName.setError("Please enter username");
editTextUserName.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Enter a password");
... | 12,296 |
34,169,770 | I am trying to select sensors by placing a box around their geographic coordinates:
```
In [1]: lat_min, lat_max = lats(data)
lon_min, lon_max = lons(data)
print(np.around(np.array([lat_min, lat_max, lon_min, lon_max]), 5))
Out[1]: [ 32.87248 33.10181 -94.37297 -94.21224]
In [2]: select_sens = sens[... | 2015/12/09 | [
"https://Stackoverflow.com/questions/34169770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765319/"
] | I'm not familiar with NumPy nor Pandas, but the error is saying that one of the objects in the comparison `if len(self) != len(other)` does not have a `__len__` method and therefore has no length.
Try doing `print(sens_data)` to see if you get a similar error. | I found a similar issue and think the problem may be related to the Python version you are using.
I wrote my code in Spyder
**Python 3.6.1 |Anaconda 4.4.0 (64-bit)**
but then passed it to someone using Spyder but
**Python 3.5.2 |Anaconda 4.2.0 (64-bit)**
I had one numpy.float64 object (as far as i understand, simila... | 12,306 |
26,593,344 | I'm writing a pandas Dataframe to a Postgres database:
```
from sqlalchemy import create_engine, MetaData
engine = create_engine(r'postgresql://user:password@localhost:5432/db')
meta = MetaData(engine, schema='data_quality')
meta.reflect(engine, schema='data_quality')
pdsql = pd.io.sql.PandasSQLAlchemy(engine, meta=me... | 2014/10/27 | [
"https://Stackoverflow.com/questions/26593344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3591836/"
] | I suppose you are using pandas 0.15. `PandasSQLAlchemy` was not yet really public, and was renamed in pandas 0.15 to `SQLDatabase`. So if you replace that in your code, it should work (so `pdsql = pd.io.sql.SQLDatabase(engine, meta=meta)`).
However, starting from pandas 0.15, there is also schema support in the `read_... | I have encountered this error recently and it was solved my removing the .pyc files located in the same directory as .py files. These files (.pyc) holds the previous version information and time, date. | 12,307 |
67,220,607 | I'm trying to save a loop output into a text file with python. However, when I try to do so only the first line of the result gets printed on the file.
This is the line I want to print the result of:
```
with open('myfile.txt','w') as f_output:
f_output.write(
for k, v in mydic.items():
... | 2021/04/22 | [
"https://Stackoverflow.com/questions/67220607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12763792/"
] | Write in append mode with `a`:
```py
mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}
with open('myfile.txt','a') as f_output:
for k, v in mydic.items():
# Also need `\n` for newlines:
f_output.write(f"{k:11}{v[0]}{v[1]:12}\n")
```
Output:
```
1 22 23
2 33 ... | Change the argument from 'w' (write) to 'a' (append).
```py
mydic = {'1': [22, 23], '2': [33, 24], '3': [44, 25]}
with open('myfile.txt','a') as f_output:
for k, v in mydic.items():
res=f"{k:11}{v[0]}{v[1]:12}"
f_output.write(f"{res}\n")
print(res)
``` | 12,308 |
45,317,767 | ```
def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
return res
print generate_n_chars(raw_input("Enter the integer value : "),raw_input("Enter the character : "))
```
I am beginner in python and I don't know why this loop going to infinity. Plea... | 2017/07/26 | [
"https://Stackoverflow.com/questions/45317767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7504540/"
] | I personally have another mental model which doesn't deal directly with identity and memory and whatnot.
`prvalue` comes from "pure rvalue" while `xvalue` comes from "expiring value" and is this information I use in my mental model:
**Pure rvalue** refers to an object that is a temporary in the "pure sense": an expre... | When calling a `func(T&& t)` the caller is saying "there's a t here" and also "I don't care what you do to it". C++ does not specify the nature of "here".
On a platform where reference parameters are implemented as addresses, this means there must be an object present somewhere. On that platform identity == address. H... | 12,309 |
25,618,016 | I have the following script which just isnt working for me :(. I essentially want to create 10 threads to port scan a range of 100 ports. It should seem simple but I dont know where I am going wrong. Im new to python and have been looking at how to get this working for the past two weeks and I know give up. When execut... | 2014/09/02 | [
"https://Stackoverflow.com/questions/25618016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3999393/"
] | You have an extra space after resource, have you tried removing that?
```
'resource ': {
``` | It looks like you're doing extra encoding of the inserted rows. They should be sent as raw json, rather than encoding the whole row as a string. That is, something like this:
```
'rows': [
{
'insertId': 123456,
'json': {'id': 123,'name':'test1'}
}
]
```
(note the difference from what you have above is ju... | 12,310 |
70,943,395 | I did the following in google colab notebook and get an error. Any idea?
```
%pip install pyenchant
import enchant
```
and get the following error:
ImportError Traceback (most recent call last)
in ()
----> 1 import enchant
1 frames
/usr/local/lib/python3.7/dist-packages/enchant/\_enchant.py in ()
159 """
160 )
--... | 2022/02/01 | [
"https://Stackoverflow.com/questions/70943395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18092070/"
] | After lots of research, I found the solution [here](https://github.com/googlecolab/colabtools/issues/441).
Run this code on goggle colab before `import enchant`
```
!apt update
!apt install enchant --fix-missing
!apt install -qq enchant
!pip install pyenchant
``` | Yes enchant doesnt work on Google colab because of C libraries. You can use Jupyter notebook for this library and it will work just fine. | 12,311 |
43,094,861 | I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the... | 2017/03/29 | [
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] | Look into [re](https://docs.python.org/2/library/re.html#re.findall)
```
import re
input = "'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'"
matches = re.findall('(\d+)', input)
# matches = ['17899792270101010000000000', '17899792270102010000000000', '1789979227010301000000... | if it's already "format" at the input :
```
>>> BC1 = input("BC1: ")
BC1: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'
>>> a=int(BC1[0])
>>> b=int(BC1[1])
>>> c=int(BC1[2])
>>> a
17899792270101010000000000
>>> b
17899792270102010000000000
>>> c
17899792270103010000000000
``... | 12,312 |
38,550,322 | Hello everyone!
I'm new to python networking programming.
My development environments are as below.
* Windows 7
* Python 3.4
I am studying with "Python Network Programming Cookbook". In this book, there's an example of **ThreadingMixIn** socket server application.
This book's code is written in Python 2.7. So I've... | 2016/07/24 | [
"https://Stackoverflow.com/questions/38550322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192555/"
] | Your program exits because your server thread is a daemon:
```
# Exit the server thread when the main thread exits
server_thread.daemon = True
```
You can either remove that line or add `server_thread.join()` at the bottom of the code to prevent the main thread from exiting early. | You will have to run on an infinite loop and on each loop wait for some data to come from client. This way the connection will be kept alive.
Same infinite loop for the server to accept more clients.
However, you will have to somehow detect when a client closes the connection with the server because in most times the... | 12,315 |
53,312,339 | I need to install COCOAPI for Python 3.5 on my linux machine but when I do "make" it automatically installs it for 2.7. Is there an option to choose for a python version while using "make" ?
**EDIT 1 :**
Going to PythonAPI folder and installing it via python3 setup.py install gives the following error.
```
sudo py... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53312339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715275/"
] | Clone the repo using `git clone https://github.com/cocodataset/cocoapi.git` then enter the dir where it is located and type `python3 setup.py install` which should install using python3.
If the above doesn't work, try `pip3 install cython` followed by `pip3 install pycocotools` (you can add the `--user` flag to all of... | You can make sure the default `python` resolves in the one you are interested in, for example by symbolically linking `python` to `python2` wherever it is defined (possibly `/usr/bin`) | 12,316 |
70,909,920 | I'm trying to write a code that will search for specific data from multiple report files, and write them into columns in a single csv.
The report file lines i'm looking for aren't always on the same line, so i'm looking for the data associated on the lines below:
Estimate file: pog\_example.bef
Estimate ID: o1\_p1
... | 2022/01/29 | [
"https://Stackoverflow.com/questions/70909920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17361896/"
] | Liquid is not going to work on JSON like this. If you want to iterate through an array of JSON objects, use Javascript. | As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array. | 12,317 |
28,228,238 | Hello guys I am really new to python and I am trying to sort the /etc/passwd file using PYTHON 3.4 based on the following criteria:
Input (regular /etc/passwd file on linux system:
```
raj:x:501:512::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
jwww:x:504:504::/htdocs/h... | 2015/01/30 | [
"https://Stackoverflow.com/questions/28228238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214003/"
] | You can open the file, throw it into a list and then throw all the users into some kinda hash table
```
with open("/etc/passwd") as f:
lines = f.readlines()
group_dict = {}
for line in lines:
split_line = line.split(":")
user = split_line[0]
gid = split_line[3]
# If the group id is not in the dict... | This should loop through your `/etc/passwd` and sort users by group. You don't have to do anything fancy to solve this problem.
```
with open('/etc/passwd', 'r') as f:
res = {}
for line in f:
parts = line.split(':')
try:
name, gid = parts[0], int(parts[3])
except IndexErro... | 12,319 |
26,643,705 | So, I have tried this problem for what it seems like a hundred times this week alone.
It's filling in the blank for the following program...
You entered jackson and ville.
When these are combined, it makes jacksonville.
Taking every other letter gives us jcsnil.
The blanks I have filled are fine, but the rest of th... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26643705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196499/"
] | Assuming that each word is on it's own line, you should be reading the file more like...
```
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
```
Remember, if you open a resour... | Set a two counters and a variable that holds the current longest word found before you start reading in with your while loop. To find the average have one counter be incremented by one each time the line is read and have the second counter add up the total number of characters in each word (obviously the total number o... | 12,320 |
61,160,595 | I'm trying to write a function that takes in a list and returns true if it contains the numbers 0,0,7 in that order. When I run this code:
```
def prob11(abc):
if 7 and 0 and 0 not in abc:
return False
x = abc.index(0)
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
retur... | 2020/04/11 | [
"https://Stackoverflow.com/questions/61160595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13201582/"
] | Your screenshot is showing data in Realtime Database, but your code is querying Firestore. They are completely different databases with different APIs. You can't use the Firestore SDK to query Realtime Database. If you want to work with Realtime Database, use the documentation [here](https://firebase.google.com/docs/da... | There is `author` between `posts` and `username` field in your data structure.
Your code means that right under some specific post there is `username` field.
So such code will work because `date` right undes post:
```
db.collection("posts").whereField("date", isEqualTo: "some-bla-bla-date")
```
In your case you hav... | 12,322 |
34,271,807 | I am trying to write a python script with several text files inside a subdirectory, e.g.
```
python script.py --inputdir ~/subdirectory
```
which will execute each file inside this subdirectory. How can one use argparse to do this? Should you write a function to access and open each file?
```
import argparse
parse... | 2015/12/14 | [
"https://Stackoverflow.com/questions/34271807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596596/"
] | I think your a mixing up the return value of setInterval.
setInterval returns an handle to the function scheduled, so you can call clearInterval().
From Mdn:
<https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval>
```
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);... | [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) returns a reference to the interval you have just created, so that later you can stop the interval.
```
var myRef = setInterval(...);
clearInterval(myRef);
```
Every time `moveBall()` is called and you run this
```
startTime ... | 12,324 |
7,513,133 | From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
``` | 2011/09/22 | [
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] | From Python, run bash with `os.system`, `os.popen` or `subprocess` and pass the appropriate command-line arguments.
```
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
``` | Bash should accept a command from args when using the -c flag:
```
C:\cygwin\bin\bash.exe -c "somecommand"
```
Combine that with C++'s [`exec`](http://linux.about.com/library/cmd/blcmdl3_execvp.htm) or python's `os.system` to run the command. | 12,325 |
67,915,835 | I and my colleague is working on a django (python) project and pushing our code on same branch(lets say branch1), as a beginner i know how to push the code on a particular branch but have no idea how pull and merge can be done. what should i do if i want full project including his codes and my codes together without ov... | 2021/06/10 | [
"https://Stackoverflow.com/questions/67915835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13963543/"
] | For node.js subprocesses there is the [cluster module](https://nodejs.org/api/cluster.html) and I strongly recommend using this. For general subprocesses (e.g. bash scripts as you mentioned) you have to use `child_process` (-> execa). Communication between processes may then be accomplished via grpc. Your approach is f... | I decided to go full with `pm2` for the time being, as they have an excellent [programmatic API](https://pm2.keymetrics.io/docs/usage/pm2-api/) - also (which I only just learned about) you can specify [different interpreters](https://pm2.keymetrics.io/docs/usage/process-management/#start-any-process-type) to run your s... | 12,328 |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | `int &foo();` declares a function called `foo()` with return type `int&`. If you call this function without providing a body then you are likely to get an undefined reference error.
In your second attempt you provided a function `int foo()`. This has a different return type to the function declared by `int& foo();`. S... | In that context the & means a reference - so foo returns a reference to an int, rather than an int.
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory wh... | 12,329 |
39,637,164 | How can i used the rt function, as i understand leading & trailing underscores `__and__()` is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,
```
class A(object):
def __rt... | 2016/09/22 | [
"https://Stackoverflow.com/questions/39637164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277603/"
] | Python doesn't translate one name into another. Specific operations will *under the covers* call a `__special_method__` if it has been defined. For example, the `__and__` method is called by Python to hook into the `&` operator, because the Python interpreter *explicitly looks for that method* and documented how it sho... | Because there are builtin methods that you can overriden and then you can use them, ex `__len__` -> `len()`, `__str__` -> `str()` and etc.
Here is the [list of these functions](https://docs.python.org/3/reference/datamodel.html#basic-customization)
>
> The following methods can be defined to customize the meaning of... | 12,339 |
65,571,031 | I am trying to install a package on a python project but having some issues with python-Levenshtein library. I'm using a virtual environment on PyCharm which is running with Python3.8 and installed all libraries in requirements.txt with pip. However I am not able to install this library.
What I've tried so far:
1. tr... | 2021/01/04 | [
"https://Stackoverflow.com/questions/65571031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5331231/"
] | That index could be used if you wrote the query like this:
```
select rh."EventHistory"
from "RemittanceHistory" rh join "ClaimPaymentHistory" ph
on ph."EventHistory" @> jsonb_build_array(jsonb_build_object('rk',rh."RemittanceRefKey"))
where ph."ClaimRefKey" = 5;
```
However, this unlikely to have good performan... | I wound up refactoring the table structure. Instead of a join through `RemittanceRefKey` I added a JSONB column to `RemittanceHistory` called `ClaimRefKeys`. This is simply an array of integer values and now I can lookup the desired rows with:
```
select "EventHistory" from "RemittanceHistory" where "ClaimRefKeys" @> ... | 12,340 |
57,593,041 | ```
>>> x = 1
>>> def f():
... print x
...
>>> f()
1
>>> x = 1
>>> def f():
... x = 3
... print x
...
>>> f()
3
>>> x
1
>>> x = 1
>>> def f():
... print x
... x = 5
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local va... | 2019/08/21 | [
"https://Stackoverflow.com/questions/57593041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335601/"
] | >
> In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
>
>
>
[Source.](https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-lo... | The behaviour is already what you want. The presence of `x =` inside the function body makes `x` a local variable which entirely shadows the outer variable. You're merely trying to print it before you assign any value to it, which is causing an error. This would cause an error under any other circumstance too; you can'... | 12,341 |
56,184,013 | Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically? | 2019/05/17 | [
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] | According to [this](https://github.com/tensorflow/tensorflow/issues/31377) thread, it is not. | You can force the computation to take place on a GPU:
```
import tensorflow as tf
with tf.device('/gpu:0'):
for i in range(10):
t = np.random.randint(len(x_test) )
...
```
Hope this helps. | 12,342 |
58,126,489 | I follow the tutorial from Traversy Media on Youtube videos. When I put the command
>
> python manage.py migrate
>
>
>
Then I got such an error like this:
```
C:\Users\Acer\Project\djangoproject>python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
Fi... | 2019/09/27 | [
"https://Stackoverflow.com/questions/58126489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11803617/"
] | There are several dedicated packages for this. For example have a look at the `combine`, `subdocs` or `docmute` packages (A list with even more suggestions can be fond at <https://www.ctan.org/recommendations/docmute>).
Here a short example with the `docmute` package
```
\documentclass{book}
\usepackage{lipsum}
\us... | A Latex document cannot have multiple `\documentclass`. One solution would be to split the header/content of your latex document in overleaf:
* Create a `master.tex` with the documentclass and put all your content (text between `\begin{document}` and `\end{document}` in a second `content.tex`. In the master, just `\in... | 12,345 |
43,736,163 | I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Trac... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] | I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:
```
print (reviews_new.columns.tolist())
```
---
I think there can be 2 problems (obviously):
**1.whitespaces in columns names (maybe in data also)**
Solutions are [`strip`](http://panda... | ```
import pandas as pd
df=pd.read_csv("file.txt", skipinitialspace=True)
df.head()
df['review']
``` | 12,346 |
28,952,282 | I'm using REPL with sublime text 3 (latest version as of today) and I'm coding in python 3.4. As far as I understand the documentation on REPL if do: tools>sublimeREPL>python>python-RUN current file
then I should run the code I have typed in using REPL. However when I do this I get an error pop up saying:
FileNotFo... | 2015/03/09 | [
"https://Stackoverflow.com/questions/28952282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4651552/"
] | I also had this problem. This is most probably due to the default location of python. If you are running portable python,
```
{
...
"default_extend_env": {"PATH": "{PATH}:\\Programming\\Python\\Portable Python 2.7.6.1\\App\\"}
...
}
```
Otherwise,
```
{
"default_extend_env": {"PATH":"C:\\python27\\"},
}
```
wou... | I had the same problem, when I installed REPL for the first time. Now, that could sound crazy, but the way to solve the problem (at least, the trick worked for me!) is to restart once Sublime Text 3.
**Update**: As pointed out by Mark in the comments, apparently you could have to restart Sublime more than once to solv... | 12,349 |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
``` | Replace `,` with `+` because `,` leaves a space by default, for example:
```
print('Material cost of the project: $' + tot_mat)
print('Labor cost of the project: $' + tot_lab)
print('Total cost of the project: $' + project)
```
You can also use `f-strings` as so:
```
print(f'Material cost of the project: ${tot_ma... | 12,350 |
25,150,502 | Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because... | 2014/08/06 | [
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] | You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) function, like this
```
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
```
The `enumerate` function gives the current index of the item and the actual item itself. In this case, the second value i... | If you only need the index to do something special on the first iteration, you could also use `.popitem()`
```
key, val = mydict.popitem()
...
for key, val in mydict.items()
...
```
this will remove the first `key, val` pair from `mydict` (but perhaps that's not an issue for you?) | 12,356 |
47,799,275 | I need to be able to login into a remote server, switch user and then, do whatever it is required.
I played with ansible and found the "become" tool, so I tried it, after all... it allows dzdo.
My playbook became something like this:
```
- name: Create empty file
file: path=touchedFile.txt state=touch
become:... | 2017/12/13 | [
"https://Stackoverflow.com/questions/47799275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803228/"
] | I have finally found a work-around for my problem, and I'm sharing this answer in case someone finds it useful.
Ansible become module is great, but for my company it is not working. As I explained in the question, it is adding a "**-u root**" at the end of the sudo, which makes the whole command to fail.
I was able t... | This playbook works for me in ansible 2.4 for your limited test case, I'm not sure how well it would work against larger / more complex tasks or modules. It basically just works around your site's dzdo/sudo limitations.
```
---
- hosts: 127.0.0.1
become: yes
become_method: dzdo
become_flags: "su - root -c"
ga... | 12,359 |
12,113,498 | I'm trying to take the dot product of two lil\_matrix sparse matrices that are approx. 100,000 x 50,000 and 50,000 x 100,000 respectively.
```
from scipy import sparse
a = sparse.lil_matrix((100000, 50000))
b = sparse.lil_matrix((50000, 100000))
c = a.dot(b)
```
and getting this error:
```
File "/usr/lib64/python... | 2012/08/24 | [
"https://Stackoverflow.com/questions/12113498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623172/"
] | This is a bad error message, but the "problem" quite simply is that your resulting matrix would be too big (has too many nonzero elements, not its dimension).
Scipy uses `int32` to store `indptr` and `indices` for the sparse formats. This means that your sparsematrix cannot have more then (approximatly) 2^31 nonzero e... | Just to add to @seberg's answer.
There are two issues related to this on github.com/scipy/scipy.
[Issue #1833](https://github.com/scipy/scipy/issues/1833#ref-issue-13651914) (marked closed April 2013) and [Issue #442](https://github.com/scipy/scipy/pull/442) with some pull requests that haven't been merged (Nov 2013 ... | 12,360 |
32,369,147 | I want to get the url of the link of tag. I have attached the class of the element to type selenium.webdriver.remote.webelement.WebElement in python:
```
elem = driver.find_elements_by_class_name("_5cq3")
```
and the html is:
```
<div class="_5cq3" data-ft="{"tn":"E"}">
<a class="_4-eo" hre... | 2015/09/03 | [
"https://Stackoverflow.com/questions/32369147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159284/"
] | Why not do it directly?
```
url = driver.find_element_by_class_name("_4-eo").get_attribute("href")
```
And if you need the div element first you can do it this way:
```
divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")
```
or anothe... | You can use xpath for same
If you want to take href of "a" tag, 2nd line according to your HTML code then use
```
url = driver.find_element_by_xpath("//div[@class='_5cq3']/a[@class='_4-eo']").get_attribute("href")
```
If you want to take href of "img" tag, 4nd line according to your HTML code then use
```
url = dr... | 12,361 |
23,034,781 | I am using scrapy 0.20 with python 2.7
According to [scrapy architecture](http://doc.scrapy.org/en/latest/topics/architecture.html), the spider sends requests to the engine. Then, after the whole crawling process, the item goes through the item pipeline.
So, the item pipeline has nothing to do when the spider opens o... | 2014/04/12 | [
"https://Stackoverflow.com/questions/23034781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] | I had similar problem and then figured it out.
It is possible that all of your left-hand side values (V5) are the same. The error is thrown as a saying that no decision can be made as it is too easy.
My source: <http://kleinfelter.com/learning-r-painful-r-learnings> | After removing all 'NA', the problem has gone. Also, the first column has to be index column. | 12,363 |
10,145,201 | We moved our SQL Server 2005 database to a new physical server, and since then it has been terminating any connection that persist for 30 seconds.
We are experiencing this in Oracle SQL developer and when connecting from python using pyodbc
Everything worked perfectly before, and now python returns this error after 30... | 2012/04/13 | [
"https://Stackoverflow.com/questions/10145201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931235/"
] | First of all what you need is profile the sql server to see if any activity is happening. Look for slow running queries, CPU and memory bottlenecks.
Also you can include the timeout in the querystring like this:
"Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;Connection Timeout=30";
and... | Maybe check your remote query timeout? It should default to 600, but maybe it's set to 30? [Info here](http://msdn.microsoft.com/en-us/library/ms189040%28v=sql.90%29.aspx) | 12,364 |
18,921,141 | I keep getting an error that there's no such module.
The project name is gmblnew, and I have two subfolders- `core` and `gmblnew` - the app I'm working on is core.
My **urls.py** file is
```
from django.conf.urls import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.a... | 2013/09/20 | [
"https://Stackoverflow.com/questions/18921141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293222/"
] | Your problem is here:
```
url(r'^league/', include('core.views.league')),
```
By using `include` you are specifying a module, which does not exist.
[`include` is used to include other url confs](https://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs), and not to target view methods
What y... | `include` takes a path to a url file, not a view. Just write this instead:
```
url(r'^league/', 'core.views.league'),
``` | 12,365 |
8,575,713 | I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from ... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] | I'm guessing you are going to mock the function `returnBar`, you'd like to use [`patch` decorator](http://www.voidspace.org.uk/python/mock/patch.html):
```
from mock import patch
from foo import printFoo
@patch('foo.returnBar')
def test_printFoo(mockBar):
mockBar.return_value = 'Foo'
printFoo()
test_printFo... | Just import the `bar` module before the `foo` module and mock it:
```
from mock import Mock
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
from foo import printFoo
printFoo()
```
When you are importing the `returnBar` in `foo.py`, you are binding the value of the module to a variable called `retu... | 12,366 |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get insta... | Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
``` | 12,369 |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
``` | You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.t... | 12,379 |
55,697,976 | I have this input `<input type="file" id="file" name="file" accept="image/*" multiple>` this allow the user select several images and I need to pass all of them to my `FormData` so I do this:
```
var formdata = new FormData();
var files = $('#file')[0].files[0];
formdata.append('file',files);
```
But that only take ... | 2019/04/15 | [
"https://Stackoverflow.com/questions/55697976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5727540/"
] | There are many problems:
1. You can't redeclare the same variable if you want to keep its previous values
2. You need to change the index so that it's not saving to the same spot
3. $("#file") - shouldn't be an array, it's an object so i'm surprised it's not throwing an error
Let's say your code is legit. You could d... | This was my solution
```
var formdata = new FormData();
var files=[];
var count = document.getElementById('file').files.length;
for (i = 0; i < cont; i++) {
files[i] = document.getElementById('file').files[i];
formdata.append('file',files[i]);
}
```
Using `JQuery` for length only brings me 1 element and give... | 12,386 |
6,965,431 | I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` ... | 2011/08/06 | [
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | These APIS work only for GAE server since the queues can be created only via queue.yaml and infact API does not expose any API for inserting queue and tasks or project. | The pull queues page has a [whole section](http://code.google.com/appengine/docs/python/taskqueue/overview-pull.html#Pulling_Tasks_from_Outside_App_Engine) about client libraries and sample code. | 12,387 |
18,401,385 | I'm using Eclipse (on the PyDev perspective), and I just installed (using pip) the python 'requests' module.
Eclipse is giving me an error warning on the 'import requests' line, saying that it is an unresolved import, but I've run it it imports just fine. (But the error message won't go away).
Its really bugging me... | 2013/08/23 | [
"https://Stackoverflow.com/questions/18401385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258464/"
] | Sometimes, PyDev is a little buggy... When it happens, I usually right-click on the folder containing the file in the PyDev Package Explorer, then "PyDev->remove error markers". And then re-run code analysis.
If it still doesn't work, try removing and adding again the directory to your `requests` module to the PyDev P... | You should manually configure properties of you PyDev project.
Right click on your project name, select **PyDev - PYTHONPATH**, then in External Libraries tab press **Add source folder** and choose the root directory of your library. | 12,390 |
71,792,025 | My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't ... | 2022/04/08 | [
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] | It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement... | The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is ... | 12,391 |
51,539,051 | I'm actually trying to send pictures(.jpg) saved on a directory of my computer to a FTP server with a python script and ftplib .
The path where are the images is : "D:/directory\_image".
I use python 2.7 and the command .storbinary from ftplib to send .jpg.
Despite my search, I get an error message that I can't resolve... | 2018/07/26 | [
"https://Stackoverflow.com/questions/51539051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10138893/"
] | [`@Transactional` can't work on private method](https://stackoverflow.com/questions/4396284/does-spring-transactional-attribute-work-on-a-private-method) because it's applied using an aspect (using dynamic proxies)
Basically you want the `retrieveAndSaveInformationFromBac()` to be a single unit of work, ie. a transact... | Since you are using `Hibernate` , you can handle this by a property:
```
<property name="hibernate.connection.autocommit">false</property>
```
Then you can commit with the transaction, like
```
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//do stuff and then
tx.commi... | 12,396 |
40,499,481 | I configured a new debug environment in Visual Studio Code under OS X.
```
{
"name": "Kivy",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "/Applications/Kivy3.app/Contents/Frameworks/python/3.5.0/bin",
"program": "${file}",
"debugOptions": [
"WaitOnAbno... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40499481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1321025/"
] | @Albert Gao,
The path you have specified above doesn't contain the name of the python file. You need to provide the path to the file, include the file name. I believe you need to change it as follows:
`"pythonPath": "/Applications/Kivy3.app/Contents/Frameworks/python/3.5.0/bin/python",`
If that doesn't work, then ... | If you are getting the spawn error above while using **OpenOCD** for the Raspberry Pi Pico, make sure that your "**cortex-debug.openocdPath**" in "*settings.json*" is set to "*<Path\_to\_openocd\_executable>***/openocd**" for example:
`"cortex-debug.openocdPath": "/home/vbhunt/pico/openocd/src/openocd", "cortex-debug.... | 12,397 |
24,043,499 | Could any please help me convert this to python? I don't how to translate the conditional operators from C++ into python?
```
Math.easeInExpo = function (t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
``` | 2014/06/04 | [
"https://Stackoverflow.com/questions/24043499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461304/"
] | ```
def easeInExpo( t, b, c, d ):
return b if t == 0 else c * pow( 2, 10 * (t/d - 1) ) + b
``` | Use `if` / `else`:
```
return b if t == 0 else c * pow(2, 10 * (t/d - 1)) +b
``` | 12,398 |
3,987,732 | I have following python code:
```
def scrapeSite(urlToCheck):
html = urllib2.urlopen(urlToCheck).read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
tdtags = soup.findAll('td', { "class" : "c" })
for t in tdtags:
print t.encode('latin1')
```
This will return me f... | 2010/10/21 | [
"https://Stackoverflow.com/questions/3987732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123172/"
] | In this case, you can use `t.contents[1].contents[0]` to get FOO and BAR.
The thing is that contents returns a list with all elements (Tags and NavigableStrings), if you print contents, you can see it's something like
`[u'\n', <a href="more.asp">FOO</a>, u'\n']`
So, to get to the actual tag you need to access `cont... | For your specific example, pyparsing's makeHTMLTags can be useful, since they are tolerant of many HTML variabilities in HTML tags, but provide a handy structure to the results:
```
html = """
<td class="c">
<a href="more.asp">FOO</a>
</td>
<td class="c">
<a href="alotmore.asp">BAR</a>
</td>
<td class="d">
<a h... | 12,400 |
68,269,165 | I have a problem. I've created model called "Flower", everything works fine, i can create new "Flowers", i can get data from them etc. The problem is when I want to use column "owner\_id" in SQL query I got an error that this column don't exist, despite I can use it to get data from objects (for example flower1.owner\_... | 2021/07/06 | [
"https://Stackoverflow.com/questions/68269165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16390472/"
] | Since `owner_id` is declared as a `ForeignKey`, it will be available in the actual SQL database as `owner_id_id`. The additional prefix `_id` is automatically appended by Django for that relational field. When using Django ORM, you would just access it via `owner_id` then Django will automatically handle things for you... | The problem is in field "owner\_id" of Flower model. When you define a Foreign Key in model, is not necessary to add "\_id" at the end since Django add it automatically
in this case, should be enough replace
```
owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
```
with
```
owner = models.For... | 12,401 |
54,085,972 | I am trying to run a playbook locally but I want all the vars in the role's task/main.yml file to refer to a group\_var in a specific inventory file.
Unfortunately the playbook is unable to access to the group\_vars directory as if fail to recognize the vars specified in the role.
The command ran is the following:
`... | 2019/01/08 | [
"https://Stackoverflow.com/questions/54085972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3130919/"
] | So, theoretically adding localhost in the inventory would have been a good solution, but in my specific case (and in general for large deployments) was not an option.
I also added `--extra-vars "myvar.json"` but did not work either.
Turns out (evil detail...) that the right way to add a var file via command line is: ... | As per the error, your ansible is not able to read the group\_vars, Can you please make sure that your group\_vars have the same folder called localhost.
Example Playbook
host is localhost
`- hosts: localhost
become: true
roles:
- { role: common, tags: [ 'common' ] }
- { role: docker, tags: [ 'docker' ] }`
So in... | 12,402 |
61,976,842 | So i look into text recognition of licensplates. Im using google cloude service for this.
it returns me a list of possible stuff. But also text on the image not containing the license plates get recognized. So i thought i could just tell python to take from the list the one text that matches the pattern of the licens... | 2020/05/23 | [
"https://Stackoverflow.com/questions/61976842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10685847/"
] | You could use a regex for this:
```
^[A-Z]{1,3}\s[A-Z]{1,2}\s\d{1,4}$
```
An explanation:
```
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
[A-Z]{1,2} ... | Here's a way:
```
import re
string='frg3453453HHH AB 1234e456 2sf 3245 yKDEH A 4 554YFDN'
print(re.findall('[A-Z]{1,3}\s[A-Z]{1,2}\s\d{1,4}',string))
```
Output:
```
['HHH AB 1234', 'DEH A 4']
``` | 12,403 |
34,677,230 | Given a list below:
```
snplist = [[1786, 0.0126525], [2463, 0.0126525], [2907, 0.0126525], [3068, 0.0126525], [3086, 0.0126525], [3398, 0.0126525], [5468,0.012654], [5531,0.0127005], [5564,0.0127005], [5580,0.0127005]]
```
I want to do a pairwise comparison of the second element in each sublist of the list, i.e. co... | 2016/01/08 | [
"https://Stackoverflow.com/questions/34677230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945881/"
] | You can `zip` the `snplist` with the same list excluding the first element, and do the comparison, like this
```
for l1, l2 in zip(snplist, snplist[1:]):
if l1[1] == l2[1]:
print l1[0], l2[0], l1[1]
```
Since you are comparing floating point numbers, I would recommend using [`math.isclose`](https://docs.py... | I suggest that you use `izip` for this to create a generator of item-neighbor pairs. Leaving the problem of comparing floating points aside, the code would look like this:
```
>>> from itertools import izip
>>> lst = [[1,2], [3,4], [5,4], [7,8], [9,10], [11, 10]]
>>> for item, next in izip(lst, lst[1:]):
... if it... | 12,404 |
73,675,665 | I know there are three thread mapping model in operating system.
1. One to One
2. Many to One
3. Many to Many
In this question I assume we use **One to One model**.
Let's say, right now I restart my computer, and there are **10** kernel-level threads already running.
After a while, I decide to run a python program ... | 2022/09/10 | [
"https://Stackoverflow.com/questions/73675665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16030398/"
] | Kernel threads are like a specialized task responsible for doing a specific operation (not meant to last long). They are not threads waiting for incoming request from user-land threads. Moreover, a system call does not systematically create a kernel thread (see [this post](https://stackoverflow.com/questions/17683067/u... | To answer this question directly. You have mixed kernel threads and threading. They are not completely different concepts, but a little different at the OS level. Also, kernel threads may last indefinitely in many cases.
There are at least three types of data,
1. `thread_info` - specific schedulable entity; always ex... | 12,405 |
65,175,268 | The formula below is a special case of the Wasserstein distance/optimal transport when the source and target distributions, `x` and `y` (also called marginal distributions) are 1D, that is, are vectors.
[](https://i.stack.imgur.com/aKURS.jpg)
where *... | 2020/12/07 | [
"https://Stackoverflow.com/questions/65175268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11637005/"
] | Note that when *n* gets large we have that a sorted set of *n* samples approaches the inverse CDF sampled at 1/n, 2/n, ..., n/n. E.g.:
```py
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.plot(norm.ppf(np.linspace(0, 1, 1000)), label="invcdf")
plt.plot(np.sort(np.random.normal(size... | I guess I am a bit late but, but this is what I would do for an exact solution (using only numpy):
```
import numpy as np
from numpy.random import randn
n = 100
m = 80
p = 2
x = np.sort(randn(n))
y = np.sort(randn(m))
a = np.ones(n)/n
b = np.ones(m)/m
# cdfs
ca = np.cumsum(a)
cb = np.cumsum(b)
# points on which we ne... | 12,406 |
31,357,459 | I try to understand the non-greedy regex in python, but I don't understand why the following examples have this results:
```
print(re.search('a??b','aaab').group())
ab
print(re.search('a*?b','aaab').group())
aaab
```
I thought it would be 'b' for the first and 'ab' for the second.
Can anyone explain that? | 2015/07/11 | [
"https://Stackoverflow.com/questions/31357459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5105884/"
] | This happens because the matches you are asking match *afterwards*. If you try to follow how the matching for `a??b` happens from left to right you'll see something like this:
* Try 0 `a` plus `b` vs `aaab`: no match (`b != a`)
* Try 1 `a` plus `b` vs `aaab` : no match (`ab != aa`)
* Try 0 `a` plus `b` vs `aab`: no ma... | Its because of that `??` is [*lazy*](http://www.rexegg.com/regex-quantifiers.html#lazy_solution) while `?` is greedy.and a lazy quantifier will match zero or one (its left token), zero if that still allows the overall pattern to match.for example all the following will returns an empty string :
```
>>> print(re.search... | 12,407 |
40,762,671 | I want to run a process on a remote machine and I want it to get terminated when my host program exits.
I have a small test script which looks like this:
```
import time
while True:
print('hello')
time.sleep(1)
```
and I start this process on a remote machine via a script like this one:
import paramiko
``... | 2016/11/23 | [
"https://Stackoverflow.com/questions/40762671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668622/"
] | When the SSH connection is closed it'll not kill the running command on remote host.
The easiest solution is:
```
ssh.exec_command('python /home/me/loop.py', get_pty=True)
# ... do something ...
ssh.close()
```
Then when the SSH connection is closed, the pty (on remote host) will also be closed and the kernel (on r... | Try [`closer`](https://haarcuba.github.io/closer/) - a library I've written specifically for this sort of thing. Doesn't use Paramiko, but perhaps it will work for you anyway. | 12,409 |
44,354,394 | how do I get a canvas to actually have a size?
```
root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)
root.after(1, draw)
mainloop()
```
just creates a window with a 1px canvas in the top left corner
edit: I omitted draw, because it didn’t throw anything, thus didn’t seem ... | 2017/06/04 | [
"https://Stackoverflow.com/questions/44354394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690599/"
] | Your canvas is not staying minimized. If you were to give the canvas a distinct background color you would see that it immediately fills the whole window, and stays that way.
You are getting `1` for the window width and height because you aren't giving tkinter enough time to draw it before asking for the size. `winfo... | I was able to get your canvas to show up and work fine. It looks like your `init` function was the problem. You don't need to define a time to wait when calling your init() function just call it directly and the program will do the rest.
Also I have looked over the tkinter documentation for canvas and I do not see any... | 12,410 |
34,035,270 | My task is to remove all instances of one particular element ('6' in this example) and move those to the end of the list. The requirement is to traverse a list making in-line changes (creating no supplemental lists).
Input example: [6,4,6,2,3,6,9,6,1,6,5]
Output example: [4,2,3,9,1,5,6,6,6,6,6]
So far, I have been a... | 2015/12/02 | [
"https://Stackoverflow.com/questions/34035270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5476661/"
] | Iterating the list reverse way, [pop](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) the element if it's 6, then [append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) it.
```
xs = [6,4,6,2,3,6,9,6,1,6,5]
for i in range(len(xs)-1, -1, -1): # 10 to 0
if xs[i] ==... | Why not try something like this?
Basically, the approach is to first count the number of values.
If 0, then returns (since Python produces a ValueError if the list.index method is called for an element not in the list).
We can then set the first acceptable index for the value to be the length of the list minus the nu... | 12,411 |
2,769,516 | I'm trying to learn OpenGL ES quickly (I know, I know, but these are the pressures that have been thrusted upon me) and I have been read around a fair bit, which lots of success at rendering basic models, some basic lighting and 'some' texturing success too.
But this is CONSTANTLY the point at which all OpenGL ES tuto... | 2010/05/04 | [
"https://Stackoverflow.com/questions/2769516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26310/"
] | 1. something many people are surprised with when starting OpenGL development is that there's no such thing as a "OpenGL file format" for models, let alone animated ones. (DirectX for example comes with a .x file format supported right away). This is because OpenGL acts somewhat at a lower level. Of course, as tm1rbrt m... | 1. Write or use a model loading library. Or use an existing graphics library; this will have routines to load models/textures already.
2. Animating models is done with bones in the 3d model editor. Graphics library will take care of moving the vertices etc for you.
3. No, artists create art and programmers create engin... | 12,421 |
71,868,469 | I'm trying to save an object using cbv's im new to using it, and I'm trying to save an object using create view but is getting this error:
"NOT NULL constraint failed: forum\_question.user\_id"
I would appreciate beginner friendly explanation on how to fix this and maybe tips as well, thank you!
models.py:
```
clas... | 2022/04/14 | [
"https://Stackoverflow.com/questions/71868469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17130619/"
] | A forum question instance must have a non null user field, but you are not specifying the user related to the object you're creating. In the case you dont want to add the user, update your model's user field to be:
```
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
... | I'm not sure if this is still useful, however, I ran into the same error. You can fix the error by deleting your migration files and the database.
The error is due to the sending of NULL data(no data) to an already existing field in the database, usually after that field have been modified or deleted. | 12,424 |
58,711,540 | What is the equivalent of C++ STL set<> in python 3?
If there is not an implementation what should I use in python to:
1) Store a list of numbers
2) Find a not less than element in that list? like lower\_bound<> of stl`s set | 2019/11/05 | [
"https://Stackoverflow.com/questions/58711540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6138473/"
] | The content scripts run in an "isolated world" which is a different context. By default devtools works in the page context so you need to [switch the context selector](https://developers.google.com/web/tools/chrome-devtools/console/reference#context) in devtools console toolbar to your extension:
![enter image descrip... | You can access your extension's console by right click on the extension popup and then selecting "Inspect". | 12,425 |
7,943,751 | What is the Python 3 equivalent of `python -m SimpleHTTPServer`? | 2011/10/30 | [
"https://Stackoverflow.com/questions/7943751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845948/"
] | Using 2to3 utility.
```
$ cat try.py
import SimpleHTTPServer
$ 2to3 try.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored try.py
--- t... | In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:
```
$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...
```
As an alias:
```
$ al... | 12,426 |
7,976,733 | I am relaying the output of my script to a local port in my system viz -
$python script.py | nc 127.0.0.1 8033
Let's assume that my computer has ip 10.0.0.3
Now, Is it possible that some other computer (say IP 10.0.0.4) can listen to this port via nc or anything else. Please suggest. | 2011/11/02 | [
"https://Stackoverflow.com/questions/7976733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270216/"
] | Not directly. The program listening on the port must be on the local machine (meaning 10.0.0.3 in your example). You could arrange for a program on the local machine to listen and send the information to another machine, but the socket connection can only be established on the host. | I use Perl to do exactly this - you could use python, of course.
In Perl, I use the `IO::Socket::INET` library.
I instantiate a new instance of `INET` with the `IP`, `port` and `Protocol`, and a time out for the `comms`. I then use the `recv` method to read data from that socket.
It's not as simple as nc; I wish NC... | 12,436 |
21,535,061 | Is it possible to create a python program, that can interact with Google's Translate?
I'm thinking of a way that firstly opens a .txt file, then reads the first line, then interacts with google translate and translates the word from a spesific language to a spesific language, then logs it into a different txt file.
M... | 2014/02/03 | [
"https://Stackoverflow.com/questions/21535061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2802035/"
] | Oh, the mind-bending horror of weak memory ordering...
The first snippet is your basic atomic read-modify-write - if someone else touches whatever address `x1` points to, the store-exclusive will fail and it will try again until it succeeds. So far so good. However, this only applies to the address (or more rightly re... | I would guess that this is simply a way of reproducing existing architecture-independent semantics for this operation.
With the `ldaxr`/`stlxr` pair, the above sequence will assure correct ordering if the AtomicAdd32 is used as a synchronization mechanism (mutex/semaphore) - regardless of whether the resulting higher-... | 12,437 |
66,357,772 | django+gunicorn+nginx gives 404 while serving static files
I am trying to deploy a Django project using nginx + gunicorn + postgresql. All the configuration is done, my admin panel project static file will serve , but other static files; it returns a 404 error.(iam use run python manage.py collectstatic)
```
my error... | 2021/02/24 | [
"https://Stackoverflow.com/questions/66357772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14751614/"
] | Try
In ---- nginx.conf:
```
location /static/ {
autoindex off;
alias /home/ubuntu/blogpy/static/; #add full path of static file directry
}
``` | To get /blogpy/home/static/ files been copied into /blogpy/static/ by collectstatic command, you need to specify STATICFILES\_DIRS setting
<https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_DIRS>
```
STATICFILES_DIRS = [
BASE_DIR / 'home' / 'static',
]
``` | 12,439 |
59,802,608 | I have this code and it raise an error in python 3 and such a comparison can work on python 2
how can I change it?
```
import tensorflow as tf
def train_set():
class MyCallBacks(tf.keras.callbacks.Callback):
def on_epoch_end(self,epoch,logs={}):
if(logs.get('acc')>0.95):
print(... | 2020/01/18 | [
"https://Stackoverflow.com/questions/59802608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11214617/"
] | Tensorflow 2.0
==============
```
DESIRED_ACCURACY = 0.979
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epochs, logs={}) :
if(logs.get('acc') is not None and logs.get('acc') >= DESIRED_ACCURACY) :
print('\nReached 99.9% accuracy so cancelling training!')
se... | I had the same problem and instead of using 'acc', I changed it to 'accuracy' everywhere. So it seems that maybe it is better to try changing 'acc' to 'accuracy'. | 12,441 |
32,991,119 | I am writing C extensions for python. I am just experimenting for the time being and I have written a hello world extension that looks like this :
```
#include <Python2.7/Python.h>
static PyObject* helloworld(PyObject* self)
{
return Py_BuildValue("s", "Hello, Python extensions!!");
}
static char helloworld_doc... | 2015/10/07 | [
"https://Stackoverflow.com/questions/32991119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5414031/"
] | You can simply compile the extension without installing (usually something like `python setup.py build`). Then you have to make sure the interpreter can find the compiled module (for example by copying it next to a script that imports it, or setting `PYTHONPATH`). | You can create your "own interpreter" by not extending python, but embedding it into your application. In that way, your objects will be always available for the users who are running your program. This is a pretty common thing to do in certain cases, for example look at the Blender project where all the `bpy`, `bmesh`... | 12,451 |
31,962,569 | I am working on MQTT and using python paho-mqtt <https://pypi.python.org/pypi/paho-mqtt>
I am unable to understand how can I publish msg to a specific client or list of clients?
I'll appreciate your help. | 2015/08/12 | [
"https://Stackoverflow.com/questions/31962569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073780/"
] | This isn't directly possible with strict MQTT, although some brokers may offer that functionality, or you can construct your application so that the topic design works to do what you need. | Although I do agree that in some cases it would be useful to send a message to a particular client (or list of clients) that's simply not how the publish/subscribe messaging paradigm works. [Read more on the publish-subscribe pattern on Wikipedia.](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) If all... | 12,452 |
61,581,612 | i am in the process of converting some cython code to python, and it went well until i came to the bitwise operations. Here is a snippet of the code:
```
in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
in_buf_word >>= bits
```
If i run this it will spit out this error:
```
TypeError: unsupported operand type(s) for ... | 2020/05/03 | [
"https://Stackoverflow.com/questions/61581612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13462790/"
] | ```
import bitstring
in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
in_buf_word = bitstring.BitArray(in_buf_word ) >> bits
```
If you dont have it. Go to your terminal
```
pip3 install bitstring --> python 3
pip install bitstring --> python 2
```
To covert it back into bytes use the tobytes() method:
```
print(... | Shifting to the right by 8 bits just means cutting off the rightmost byte.
Since you already have a `bytes` object, this can be done more easily:
```
in_buf_word = in_buf_word[:-1]
``` | 12,453 |
10,331,413 | I am working on the exel parsing using python.
till now I have worked with english language but when I encounter the regional languages, I am getting the error.
example :
```
IR05 měsíční (monthly)
```
It gives me the error as
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\u011b' in position... | 2012/04/26 | [
"https://Stackoverflow.com/questions/10331413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778942/"
] | ```
>>> "IR05 měsíční (monthly)".decode('utf8')
u'IR05 m\u011bs\xed\u010dn\xed (monthly)'
```
which is a unicode version of your original string (which was encoded in utf8).
Now you can compare it to your other string (from the file), which you decode (from utf8 or latin2 or a different format) and you can compare t... | the error may be caused by str(j),
try this:
```
for j in val:
print 'j is - ', j
j.replace("'", "")
``` | 12,455 |
16,269,396 | I know I've seen clean examples on the proper way to do this, and could even swear it was in one of the standard python libraries. I can't seem to find it now. Could you please point me in the right direction.
Iterator for a list of lists that only returns arbitrary values from the sub-list. The idea is to have this i... | 2013/04/29 | [
"https://Stackoverflow.com/questions/16269396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2097818/"
] | Perhaps you were thinking of `itemgetter`?
```
>>> from operator import itemgetter
>>> map(itemgetter(2), alist)
[3, 6, 9]
```
But that doesn't leave the elements in sublists
```
only_some_values = [[x[2]] for x in alist]
```
Gives your desired output | Here is what I had in mind:
```
from operator import itemgetter
alist = [ [1,2,3,4,5],
[2,4,6,8,10],
[3,6,9,12,15] ]
[list(x) for x in zip(map(itemgetter(2),alist),
map(itemgetter(0),alist)) ]
[[3,1], [6,2], [9,3]]
```
The idea is that you keep the left sid... | 12,456 |
48,252,967 | I'm currently doing a system that scrap data from foursquare. Right now i have scrap the review from the website using python and beautiful soup and have a json file like below
```
{"review": "From sunset too variety food u cant liked it.."}{"review": "Byk motor laju2"}{"review": "Good place to chill"}{"review": "If y... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48252967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9216577/"
] | It depends on your usages. Basically, MongoDB is suitable for JSON document so, you will be able to insert your Python object "directly". If you want/need to use MySQL, you will probably need to perform some transformations before inserting. Check this post for more information: [Inserting JSON into MySQL using Python]... | You can convert your json into a string (json.dumps()) and store in a character field.
Or, Django has support for JSONField when using Postgres ([docs](https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#jsonfield)), this has some additional features like querying inside the json | 12,457 |
44,060,080 | The subject of the study was taken from [Text processing and detection from a specific dictionary in python](https://stackoverflow.com/questions/43988958/text-processing-and-detection-from-a-specific-dictionary-in-python/43989724#43989724) topic. Perhaps i misunderstood the OP's problem but i have tried to improve the ... | 2017/05/19 | [
"https://Stackoverflow.com/questions/44060080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8016168/"
] | If I understood correctly, you want to find the number of times a "keyword" appears in a text. You can use the "re" module for this.
```
import re
dict_1={"Liquid Biopsy":"Blood for analysis","cfDNA":"Blood for analysis", "asfdafaf":"dunno"}
list_1=[u'Liquid', u'biopsy',u'based', u'on', u'circulating', u'cell-free', ... | Recently i have learned a new method about counting how many times does a dictionary key repeat in a plain text without importing "re" module. Perhaps it's suitable to put another method in this topic.
```
dict_1={"Liquid Biopsy":"Blood for analysis","cfDNA":"Blood for analysis"}
list_1=[u'Liquid', u'biopsy', u'liquid... | 12,458 |
54,830,602 | Preface
=======
I understand that `dict`s/`set`s should be created/updated with hashable objects only due to their implementation, so when this kind of code fails
```
>>> {{}} # empty dict of empty dict
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
```
... | 2019/02/22 | [
"https://Stackoverflow.com/questions/54830602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5997596/"
] | I have found a solution and want to share it here so it helps someone else looking to do the same thing. The user running the docker command (without sudo) needs to have the docker group. So I tried adding the service account as a user and gave it the docker group and that's it. `docker login` to gcr worked and so did ... | As stated in this [article](https://docs.docker.com/install/linux/linux-postinstall/), the steps you taken are the correct way to do it. Adding users to the "docker" group will allow the users to run docker commands as non root. If you create a new service account and would like to have that service account run docker ... | 12,459 |
32,834,419 | I received this message:
```
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-23-60bbe78150c2> in <module>()
17 men_only_stats=data[0::4]!="male"
18
---> 19 women_onboard = data[women_onl... | 2015/09/29 | [
"https://Stackoverflow.com/questions/32834419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5386822/"
] | You need to use `getChildFragmentManager()` instead of `getFragmentManager()` for placing and managing Fragments inside of a Fragment.
So
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = inflater.inflate(R.layou... | Try calling `getChildFragmentManager()` instead of `getFragmentManager()` and see if that helps. | 12,460 |
72,590,538 | I have 2 models 1) patientprofile and 2) medInfo. In the first model patientprofile, I am trying to get patients informations like (name and other personal information) and 2nd model I want to add patients Medical information data.. when I am trying check is there a existing medical information for the patient then sho... | 2022/06/12 | [
"https://Stackoverflow.com/questions/72590538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15837741/"
] | You have to make sure to understand the difference between string literals [1] and references to exported attribute(s) from the resources [2]. The way you are currently trying to get the output means it will output `aws_subnet.main.availability_zone[*]` as a string literal. To make sure you get the values you just need... | If your goal is to display all the Availability Zones in a region, you don't necessary need to iterate over your subnets you have created. You simply display the names from the `data.aws_availability_zones`:
```hcl
data "aws_availability_zones" "available" {
state = "available"
}
output "list_of_az" {
value = dat... | 12,461 |
32,833,575 | I a new to python and am stuck on this one exercise. I am supposed to enter a sentence and find the longest word. If there are two or more words that have the same longest length, then it is to return the first word. This is what I have so far:
```
def find_longest_word(word_list):
longest_word = ''
for wo... | 2015/09/28 | [
"https://Stackoverflow.com/questions/32833575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5386649/"
] | Use `max` python built-in function, using as `key` parameter the `len` function. It would iterate over `word_list` applying `len` function and then returning the longest one.
```
def find_longest_word(word_list):
longest_word = max(word_list, key=len)
return longest_word
``` | You shouldn't print out the length of each word. Instead, compare the length of the current `word` and the length of `longest_word`. If `word` is longer, you update `longest_word` to `word`. When you have been through all words, the longest world will be stored in `longest_word`.
Then you can print or return it.
```
... | 12,462 |
14,369,739 | I'm used to using dicts to represent graphs in python, but I'm running into some serious performance issues with large graphs and complex calculations, so I think I should cross over to using adjacency matrixes to bypass the overhead of hash tables. My question is, if I have a graph of the form g: {node: {vertex: weigh... | 2013/01/16 | [
"https://Stackoverflow.com/questions/14369739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427661/"
] | Probably not the most efficient, but a simple way to convert your format to an adjacency matrix on a list-basis could look like this:
```
g = {1:{2:.5, 3:.2}, 2:{4:.7}, 4:{5:.6, 3:.3}}
hubs = g.items() # list of nodes and outgoing vertices
size=max(map(lambda hub: max(hub[0], max(hub[1].keys())), hubs))+1 # matrix dim... | Well to implement in a adjacency list, you can create two classes, one for storing the information about the vertex's.
```
# Vertex, which will represent each vertex in the graph.Each Vertex uses a dictionary
# to keep track of the vertices to which it is connected, and the weight of each edge.
class Vertex:
# Initi... | 12,465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.