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 |
|---|---|---|---|---|---|---|
51,760,986 | I was going through the CPython source code I found the following piece of code from the standard library([`ast.py`](https://github.com/python/cpython/blob/master/Lib/ast.py#L60)).
```
if isinstance(node.op, UAdd):
return + operand
else:
return - operand
```
I tried the follow... | 2018/08/09 | [
"https://Stackoverflow.com/questions/51760986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6699447/"
] | plus and minus in this context are [unary operators](https://en.wikipedia.org/wiki/Unary_operation). That is, they accept **a single operand**. This is in comparison to the binary operator `*` (for example) that operates on **two operands**. Evidently `+1` is just `1`. So the unary operator `+` in your return statement... | `return + operand` is equivalent to `return operand` (if operand is a number). The only purpose I see is to insist on the fact that we do not want the opposite of `operand`. | 15,224 |
67,685,667 | I have a problem when I want to host an HTML file using python on the web server.
I go to cmd and type this in:
```
python -m http.server
```
The command works but when I open the domain name I get a list of HTML pages, which I can click and they open. How can I make it so that when I open the domain in chrome it i... | 2021/05/25 | [
"https://Stackoverflow.com/questions/67685667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14456620/"
] | You can add additional options:
```
python -m http.server --directory C:/ESD/ --bind 127.0.0.1
```
`--directory` will tell python in which folder to look for html files, here i specified the path `C:/ESD/`
`--bind` will tell python on which ip the server should run at
If you want to directly open the file instead ... | *it works but when I open it up in chrome it shows me lists of my html files and when I click on one it goes to it.*
This is expected behavior.
*how can I do it so that when I open it in chrome it immediately shows me the main.html?*
Rename `main.html` to `index.html`. As [docs](https://docs.python.org/3/library/htt... | 15,229 |
25,000,994 | I tried to install pyFFTW 0.9.2 to OSX mavericks, but I encounter the following errors:
```
/usr/bin/clang -bundle -undefined dynamic_lookup
-L//anaconda/lib -arch x86_64 -arch x86_64
build/temp.macosx-10.5-x86_64-2.7/anaconda/lib/python2.7/site-packages/pyFFTW-master/pyfftw/pyfftw.o
-L//anaconda/lib -lfftw3 -lfftw3... | 2014/07/28 | [
"https://Stackoverflow.com/questions/25000994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3885085/"
] | I had the same issue on OSX 10.9.4 Maverick.
Try this:
download FFTW 3.3.4 than open a terminal window and go in the extracted FFTW directory and run these commands:
```
$ ./configure --enable-long-double --enable-threads
$ make
$ sudo make install
$ ./configure --enable-float --enable-threads
$ make
$ sudo make insta... | I'm using MacOX 10.11.4 and Python 3.5.1 installed through `conda` and the above answer didn't work for me.
I would still get this error:
```
ld: library not found for -lfftw3l
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
-------------... | 15,230 |
32,171,138 | I need to generate all possible strings of certain length X that satisfies the following two rules:
1. Must end with '0'
2. There can't be two or more adjacent '1'
For example, when X = 4, all 'legal' strings are [0000, 0010, 0100, 1000, 1010].
I already wrote a piece of recursive code that simply append the newly f... | 2015/08/23 | [
"https://Stackoverflow.com/questions/32171138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759486/"
] | Assuming you're using python version >= 3.4, where `yield from` is available, you can `yield` instead of accumulating+returning. You don't need to pass around a container.
```
def generate(pre0, pre1, cur_len, max_len):
if (cur_len == max_len-1):
yield "".join((pre0, pre1, "0"))
return
if (pre... | If you were doing it in Python 3, you would adapt it as follows:
* Remove the `container` parameter.
* Change all occurrences of `container.append(*some\_value*)` to `yield *some\_value*`.
* Prepend `yield from` to all recursive calls.
To do it in Python 2, you do the same, except that Python 2 doesn’t support `yield... | 15,231 |
22,398,881 | I have a Django app on Heroku. I set up another app on the same Heroku account.
Now I want another instance of the first app.
I just cloned the first app and pushed into the newly created app, but it's not working.
Got this error when doing `git push heroku master`
```
Running setup.py install for distribut... | 2014/03/14 | [
"https://Stackoverflow.com/questions/22398881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2088432/"
] | This appears to be related to an issue [here](https://bitbucket.org/tarek/distribute/issue/91/install-glitch-when-using-pip-virtualenv#comment-5782834).
In other words, `distribute` has been deprecated and is being replaced with `setuptools`. Try replacing the line `distribute==0.6.27` with `setuptools>=0.7` as per th... | virtualenv is a tool to create isolated Python environments.
you will need to add the following to fix `command python setup.py egg_info failed with error code 1`, so inside your requirements.txt add this:
>
> virtualenv==12.0.7
>
>
> | 15,236 |
45,335,659 | Let's say I have the following simple situation:
```
import pandas as pd
def multiply(row):
global results
results.append(row[0] * row[1])
def main():
results = []
df = pd.DataFrame([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}])
df.apply(multiply, axis=1)
print(results)
if __name__ ... | 2017/07/26 | [
"https://Stackoverflow.com/questions/45335659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789863/"
] | You must declare results outside the functions like:
```
import pandas as pd
results = []
def multiply(row):
# the rest of your code...
```
### UPDATE
Also note that `list` in python is mutable, hence you don't need to specify it with global in the beginning of the functions. Example
```
def multiply(row):
... | You must move results outside of the function. I don't think there is any other way without moving the variable out.
One way is to pass results as a parameter to multiply method. | 15,237 |
49,495,211 | When I run **virt-manager --no-fork** on macOS 10.13 High Sierra I get the following:
```
Traceback (most recent call last):
File "/usr/local/Cellar/virt-manager/1.5.0/libexec/share/virt-manager/virt-manager", line 31, in <module>
import gi
ImportError: No module named gi
```
python version 2.7.6 on macOS
Tri... | 2018/03/26 | [
"https://Stackoverflow.com/questions/49495211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2575019/"
] | On debian 9.7 I had the same problem, I fixed:
```sh
apt install python-gobject-2-dev python-gobject-dev libvirt-glib-1.0-dev python3-libxml2 libosinfo-1.0-dev
```
 | (Arch-linux) I have anaconda installed which breaks virt-manager. But there is no need to uninstall it, just renamed anaconda folder to anything else and virt-manager works again. When need to use anaconda, undo the folder name change. Anaconda modifies PATH environment and when the folder is not present (the trick to ... | 15,238 |
4,356,329 | I have a generated file with thousands of lines like the following:
`CODE,XXX,DATE,20101201,TIME,070400,CONDITION_CODES,LTXT,PRICE,999.0000,QUANTITY,100,TSN,1510000001`
Some lines have more fields and others have fewer, but all follow the same pattern of key-value pairs and each line has a TSN field.
When doing some... | 2010/12/04 | [
"https://Stackoverflow.com/questions/4356329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78845/"
] | Not so much better as just [more efficient...](https://stackoverflow.com/questions/2631189/python-every-other-element-idiom/2631256#2631256)
[Full explanation](https://stackoverflow.com/questions/2233204/how-does-zipitersn-work-in-python) | ```
import itertools
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
record = dict(grouper(2, line.strip().split(","))
```
[source](http://docs.python.org/library/itertools.html) | 15,239 |
36,867,567 | Is there someway to import the attribute namespace of a class instance into a method?
Also, is there someway to direct output to the attribute namespace of the instance?
For example, consider this simple block of code:
```
class Name():
def __init__(self,name='Joe'):
self.name = name
def mangle_nam... | 2016/04/26 | [
"https://Stackoverflow.com/questions/36867567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2728074/"
] | @martin-lear has correctly answered the second part of your question. To address the first part, I'd offer these observations:
Firstly, there is no language feature that lets you "import" the instance's namespace into the method scope, other than performing attribute lookups on self.
You could probably abuse `exec` o... | So in your mangle\_name function, you are getting the error becuase you have not defined the name variable
```
self.name = name + '123'
```
should be
```
self.name = self.name + '123'
```
or something similiar | 15,245 |
13,489,299 | I am learning python and this is from
```
http://www.learnpython.org/page/MultipleFunctionArguments
```
They have an example code that does not work- I am wondering if it is just a typo or if it should not work at all.
```
def bar(first, second, third, **options):
if options.get("action") == "sum":
pri... | 2012/11/21 | [
"https://Stackoverflow.com/questions/13489299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612258/"
] | `return` is a keyword in python - you can't use it as a variable name. If you change it to something else (eg `ret`) it will work fine.
```
def bar(first, second, third, **options):
if options.get("action") == "sum":
print "The sum is: %d" % (first + second + third)
if options.get("ret") == "first":
... | You probably should not use "`return`" as an argument name, because it's a Python command. | 15,246 |
51,998,627 | I want to provide an id (unique) to every new row added to my sql database without explicitly asking the user. I was thinking about using `bigint` and incrementing value for every row added compared to the id of the previous row.
Example :
```
name id
xyz 1
```
now for another data to be added to this table,... | 2018/08/24 | [
"https://Stackoverflow.com/questions/51998627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How To - Fullscreen - <https://www.w3schools.com/howto/howto_js_fullscreen.asp>
This is the current "angular way" to do it.
**HTML**
```
<h2 (click)="openFullscreen()">open</h2>
<h2 (click)="closeFullscreen()">close</h2>
```
**Component**
```
import { DOCUMENT } from '@angular/common';
import { Component, Inject,... | You can try with `requestFullscreen`
I have create a demo on **[Stackblitz](https://angular-awqvmd.stackblitz.io/)**
```
fullScreen() {
let elem = document.documentElement;
let methodToBeInvoked = elem.requestFullscreen ||
elem.webkitRequestFullScreen || elem['mozRequestFullscreen']
||
elem[... | 15,247 |
11,190,353 | I am with a python script. I want to open a file to retrieve data inside. I add the right path to `sys.path`:
```
sys.path.append('F:\WORK\SIMILITUDE\ALGOCODE')
sys.path.append('F:\WORK\SIMILITUDE\ALGOCODE\DTW')
```
More precisely, the file `file.txt` I will open is in DTW folder, and I also add upper folder ALGOC... | 2012/06/25 | [
"https://Stackoverflow.com/questions/11190353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141493/"
] | `open()` checks only the current working directory and does not traverse your system path looking for the file. Only `import` works with that mechanism.
You will either need to change your working directory before you open the file, with `os.chdir(PATH)` or to include the entire path when trying to open it. | When you try to open file with `open`, for example:
```
open("ASTM-170512.txt","r")
```
you will try to open a file in the current directory.
It does not depend on `sys.path`. The `sys.path` variable is used when you try to import modules, but not when you open files.
You need to specify the full path to file in t... | 15,257 |
55,056,805 | I have a simple `dataframe` as follows:
```
Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 ... | 2019/03/08 | [
"https://Stackoverflow.com/questions/55056805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3578648/"
] | You can create the handles and labels for the legend directly from the data:
```
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
```
Complete example:
```
u = """ Condition State Value
0 A A... | So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to `plt.legend`.
```py
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_... | 15,258 |
31,570,675 | Couldn't find much information on try vs. if when you're checking more than one thing. I have a tuple of strings, and I want to grab an index and store the index that follows it. There are 2 cases.
```
mylist = ('a', 'b')
```
or
```
mylist = ('y', 'z')
```
I want to look at `a` or `y`, depending on which exists... | 2015/07/22 | [
"https://Stackoverflow.com/questions/31570675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2887891/"
] | Your first code snippet should rather be like below:
```
try:
item['index'] = mylist[mylist.index('a') + 1]
except ValueError:
try:
item['index'] = mylist[mylist.index('y') + 1]
except ValueError:
item['index'] = None
```
or have a for loop like this:
```
for element in ['a', 'y']:
t... | Performance-wise, exceptions in Python are not heavy like in other languages and you shouldn't worry about using them whenever it's appropriate.
That said, IMO the second code snippet is more concise and clean. | 15,259 |
23,178,606 | My python code has been crashing with error 'GC Object already Tracked' . Trying to figure out the best approach to debug this crashes.
OS : Linux.
* Is there a proper way to debug this issue.
There were couple of suggestions in the following article.
[Python memory debugging with GDB](https://stackoverflow.com/que... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23178606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992301/"
] | Found out the reason for this issue in my scenario (not necessarily the only reason for the GC object crash).
I used the GDB and Core dumps to debug this issue.
I have Python and C Extension Code (in shared object).
Python code registers a Callback routine with C Extension code.
In a certain workflow a thread from... | The problem is that you try to add an object to Python's cyclic garbage collector tracking twice.
Check out [this bug](http://bugs.python.org/issue6128), specifically:
* The [documentation for supporting cyclic garbage collection](https://docs.python.org/2/c-api/gcsupport.html) in Python
* [My documentation patch for... | 15,262 |
72,890,039 | I have two list of list and I want to check what element of l1 is not in l2 and add all this element in a new list ls in l2. For example,
input:
l1 = [[1,2,3],[5,6],[7,8,9,10]]
l2 = [[1,8,10],[3,9],[5,6]]
output:
l2 = [[1,8,10],[3,9],[5,6],[2,7]]
I write this code but it is seem doesn't work...
```
ls... | 2022/07/06 | [
"https://Stackoverflow.com/questions/72890039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19419689/"
] | This should work:
```
l1 = [[1,2,3],[5,6],[7,8,9,10]]
l2 = [[1,8,10],[3,9],[5,6]]
l1n = set([x for xs in l1 for x in xs])
l2n = set([x for xs in l2 for x in xs])
l2.append(list(l1n - l2n))
``` | You are checking whether the elements are in `l2`, not if they are in any of the sublists of `l2`. First, you should probably create a `set` from all the elements in all the sublists of `l2` to make that check faster. Then you can create a similar list comprehension on `l1` to get all the elements that are not in that ... | 15,264 |
32,555,508 | I have a large document with a similar structure:
```
Data800,
Data900,
Data1000,
]
}
```
How would I go about removing the last character from the 3rd to last line (in this case, where the comma is positioned next to Data1000). The output should look like this:
```
Data800,
Data900,
Data1000
]
}
```
It will alwa... | 2015/09/13 | [
"https://Stackoverflow.com/questions/32555508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3139767/"
] | A simple solution using `wc` to count lines and `sed` to do the editing:
```
sed "$(( $(wc -l <file) - 2))s/,$//" file
```
That will output the edited file on stdout; you can edit inplace with `sed -i`. | In python 2.\* :
```
with open('/path/of/file', 'w+') as f:
f.write(f.read().replace(',\n]', '\n]'))
``` | 15,267 |
4,756,205 | Some python 3 features and modules having been backported to python 2.7 what are the notable differences between python 3.1 and python 2.7? | 2011/01/21 | [
"https://Stackoverflow.com/questions/4756205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538850/"
] | I think these resources might help you:
* A [introduction to Python "3000"](http://www.python.org/doc/essays/ppt/pycon2008/Py3kAndYou.pdf) from Guido van Rossum
* [Porting your code to Python 3](http://peadrop.com/slides/mp5.pdf)
* and of course the documentation of [changes in Python 3.0](http://docs.python.org/py3k/... | If you want to use any of the python 3 function in python 2.7 then you can import **future** module at the beginning and then you can use it in your code. | 15,274 |
22,636,974 | I am trying to figure out how to properly make a discrete state Markov chain model with [`pymc`](http://pymc-devs.github.io/pymc/index.html).
As an example (view in [nbviewer](http://nbviewer.ipython.org/github/shpigi/pieces/blob/master/toyDbnExample.ipynb)), lets make a chain of length T=10 where the Markov state is ... | 2014/03/25 | [
"https://Stackoverflow.com/questions/22636974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3459899/"
] | Use this:
```
$('#window')
.data("kendoWindow")
.title("Add new category")
.content("") //this little thing does magic
.refresh({
url: _url
})
.center()
.open();
```
I would however suggest you rearrange your calls:
```
$('#window')
.data("kendoWindow")
.title("Add new category")
... | You might also want to add
```
.Events(e =>
{
e.Refresh("onRefresh");
})
<script>
function onRefresh() {
this.center();
}
<script>
```
to keep the window centered after the content is loaded as it is loaded asynchronously.
(if your content height is variable) | 15,275 |
18,983,906 | Why is time taken to access an element in a non-homogeneous list considered as constant or How is a non-homogeneous list stored in memory in case of python?
In case of a homogeneous list, knowing the type and position, the memory location can be determined but how is it done in case of a non homogeneous list so fast a... | 2013/09/24 | [
"https://Stackoverflow.com/questions/18983906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2216108/"
] | Expand your controller action with a new parameter:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model, bool newtransferee = false)
```
and check it inside the action. | You could use:
```
if (Request.Form["newtransferee"].ToLower() == "true")
```
or does it work if you write this instead of the manual html?
```
@Html.HiddenFor(model => model.NewTransferee)
``` | 15,276 |
13,116,026 | I am new to Python. I am writing a string function to check if a certain string contains certain multiple values. Is there a syntax in python to allow me to do something like this:
```
def strParse(str):
a = 't'
b = 'br'
c = 'ht'
if a in str AND b in str AND c in str:
print('Ok!')
```
(The pa... | 2012/10/29 | [
"https://Stackoverflow.com/questions/13116026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1507139/"
] | Almost correct, just make the `and` lower-case:
```
def strParse(str):
a = 't'
b = 'br'
c = 'ht'
if a in str and b in str and c in str:
print('Ok!')
```
Doesn't cause problems in this case, but you should avoid using variable-names that are also [built-in functions](http://docs.python.org/2/l... | Why don't you try typing this into the Python REPL? What you're trying to do is perfectly valid in python, except the `and` keyword is lowercase, not uppercase. | 15,279 |
67,628,700 | Please help me understand this as I am new to python:
I have a list of names...
```
names = ['John', 'William', 'Amanda']
```
I need to iterate through this list and print out the names as follows:
```
1. John
2. William
3. Amanda
```
I've managed to print the list out however I'm getting this extra space betwee... | 2021/05/20 | [
"https://Stackoverflow.com/questions/67628700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15166148/"
] | Couple of easy ways by which you can achieve this:
1. `enumerate` and `f-string`:
```
for index,item in enumerate(names,start=1):
print(f'{index}. {item}')
```
2. `enumerate` and `format function`:
```
for index,item in enumerate(names,start=1):
print('{}. {}'.format(index,item))
```
3. `enumerate` and `... | You can add a separator using the `sep` option in `print`
Like this
```
index = 1
names = ['John', 'William', 'Amanda']
for i in names:
print(index, '.' ,' ', i, sep='') #If you dont want the space between the '.' and i you may remove it
index += 1
#OUTPUT:
#1. John
#2. William
#3. Amanda
``` | 15,281 |
5,529,075 | I'm working on an academic project aimed at studying people behavior.
The project will be divided in three parts:
1. A program to read the data from some remote sources, and build a local data pool with it.
2. A program to validate this data pool, and to keep it coherent
3. A web interface to allow people to read/ma... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5529075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269931/"
] | Sounds that the main functionality needed can be found from:
[pytables](http://www.pytables.org/moin)
and
[scipy/numpy](http://www.scipy.org/) | Since you aren't an expert I recommend you to use mysql database as the backend of storing your data, it's easy to learn and you'll have a capability to query your data using SQL and write your data using python see this [MySQL Guide](http://dev.mysql.com/doc/refman/5.1/en/index.html) [Python-Mysql](http://www.kitebird... | 15,288 |
52,334,508 | When trying to implement a custom `get_success_url` method in python, Django throws a `TypeError: quote_from_bytes()`error. For example:
```
class SomeView(generic.CreateView):
#...
def get_success_url(self):
return HttpResponseRedirect(reverse('index'))
``` | 2018/09/14 | [
"https://Stackoverflow.com/questions/52334508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649917/"
] | `get_success_url` doesn't return an HttpResponseRedirect instead it should return the url you want to redirect to. So you can just return `reverse('index')`:
```
def get_success_url(self):
return reverse('index')
``` | A shortcut for HttpResponseRedirect is redirect("View\_name")
it returns an HttpResponse (HTML)
Reverse returns a url | 15,291 |
29,499,819 | Trying to make concentric squares in python with Turtle. Here's my attempt:
```
import turtle
def draw_square(t, size):
for i in range(4):
t.forward(size)
t.left(90)
wn = turtle.Screen()
dan = turtle.Turtle()
sizevar = 1
for i in range(10):
draw_square(dan,sizevar)
sizevar += 20
dan.penup()
... | 2015/04/07 | [
"https://Stackoverflow.com/questions/29499819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/721938/"
] | What you're currently doing is adding an onclick event to a link that calls a function *that adds another onclick event via jQuery*.
Remove the `onclick` property and the `open_file()` function wrapper so that jQuery adds the event as you intended. | You do not need `onclick="open_file()"` this:
```
<div id='linkstofiles'>
<a id="3.txt">3.txt</a>
//other links go here
</div>
$("#linkstofiles a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "t... | 15,292 |
7,492,454 | I have 2 large, unsorted arrays (structured set of xyz coordinates) and I'm trying to find the positions of all identical subarrays (common points consisting of 3 coordinates). Example:
```
a = array([[0, 1, 2], [3, 4, 5]])
b = array([[3, 4, 5], [6, 7, 8]])
```
Here the correct subarray would be `[3, 4, 5]`, but mor... | 2011/09/20 | [
"https://Stackoverflow.com/questions/7492454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/958582/"
] | A general solution for Python iterables (not specific to numpy or arrays) that works in linear average time (O(n+m), n is the number of subarrays and m is the number of unique subarrays):
```
a = [[0, 1, 2], [3, 4, 5]]
b = [[3, 4, 5], [6, 7, 8]]
from collections import defaultdict
indexmap = defaultdict(list)
for r... | Can you map each sub-array to its position index in a hash table? So basically, you change your data structure. After that in linear time O(n), where n is the size of the biggest hash hash table, in one loop you can O(1) query each hash table and find out if you have same sub-array present in two or more hash tables. | 15,295 |
66,170,590 | Currently I have a program that request JSONS from specific API. The creators of the API have claimed this data is in GeoJSON but QGIS cannot read it.
So I want to extend my Python Script to converting the JSON to GEOJSON in a readable format to get into QGIS and process it further there.
However, I have a few proble... | 2021/02/12 | [
"https://Stackoverflow.com/questions/66170590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11604150/"
] | In AuthenticatesUsers.php
```
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($response = $this->authenticated($request, $this->guard()->user())) {
return $response;
}
return $request->wantsJson()
... | When the auth middleware detects an unauthenticated user, it will redirect the user to the login named route. You may modify this behavior by updating the redirectTo function in your application's `app/Http/Middleware/Authenticate.php` file
<https://laravel.com/docs/8.x/authentication#redirecting-unauthenticated-users... | 15,298 |
9,002,569 | I am using python 2.7 and I would like to do some web2py stuff. I am trying to run web2py from eclipse and I am getting the following error trying to run web2py.py script:
WARNING:web2py:GUI not available because Tk library is not installed
I am running on Windows 7 (64 bit).
Any suggestions?
Thank you | 2012/01/25 | [
"https://Stackoverflow.com/questions/9002569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.
Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS i... | 1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to
```
F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2... | 15,299 |
72,539,738 | ```
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
def privacyfunc():
# Pin Definitions:
led_pin_1 = 7
led_pin_2 = 21
but_pin = 18
# blink LED 2 quickly 5 times when button pressed
def blink(channel):
x=GPIO.input(18)
print("blinked")
for i in range(1):
GPIO.o... | 2022/06/08 | [
"https://Stackoverflow.com/questions/72539738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19295287/"
] | For the function call you happened to post, the following regex seems to work:
```
(?:\w+ \w+|\w+\(\w*\))
```
This pattern matches, alternatively, a type followed by variable name, or a function name, with optional parameters. Here is a working [demo](https://regex101.com/r/IAep1Z/1). | You can use
```none
(?:\G(?!^)\s*,\s*|\()\K\w+(?:\s+\w+|\s*\([^()]*\))
```
See the [regex demo](https://regex101.com/r/OZZi09/1). *Details*:
* `(?:\G(?!^)\s*,\s*|\()` - either the end of the preceding match and then a comma enclosed with zero or more whitespaces, or a `(` char
* `\K` - omit the text matched so far
... | 15,306 |
4,574,605 | I wrote a simple python script using the SocketServer, it works well on Windows, but when I execute it on a remote Linux machine(Ubuntu), it doesn't work at all..
The script is like below:
```
#-*-coding:utf-8-*-
import SocketServer
class MyHandler(SocketServer.BaseRequestHandler):
def handle(self):
dat... | 2011/01/01 | [
"https://Stackoverflow.com/questions/4574605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325241/"
] | You are binding to 127.0.0.1:7777 but then trying to access it through the servers external IP (I'll use your placeholder - xxx.xxx.xxx.xxx). 127.0.0.1:7777 and xxx.xxx.xxx.xxx:7777 are *different ports* and can be bound by different processes IIRC.
If that doesn't fix it, check your firewall, many hosts set up firewa... | Try with telnet or nc first, telnet to your public ip with your port and see what response you get. Also, why are accessing /test from the browser? I don't see that part in the code. I hope you have taken care of that. | 15,308 |
17,548,865 | I followed this link : "<https://pypi.python.org/pypi/bottle-mysql/0.1.1>"
and "<http://bottlepy.org/docs/dev/>"
this is my py file:
```
import bottle
from bottle import route, run, template
import bottle_mysql
app = bottle.Bottle()
# # dbhost is optional, default is localhost
plugin = bottle_mysql.Plugin(dbuser='r... | 2013/07/09 | [
"https://Stackoverflow.com/questions/17548865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049591/"
] | Here is the complete behavior you wanted
Use `$(document)` instead `$('body')`
```
$(document).not('#menu, #menu-trigger').click(function(event) {
event.preventDefault();
if (menu.is(":visible"))
{
menu.slideUp(400);
}
});
```
[### Updated Fiddle](http://jsfiddle.net/yGMZt/6/)
And also use ... | You need to add `event.stopPropagation();` [demo](http://jsfiddle.net/ruddog2003/yGMZt/3/)
>
> Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
> [more](http://api.jquery.com/event.stopPropagation/)
>
>
> | 15,311 |
46,647,167 | I am working on a simple chat app in python 3.6.1 for personal use. I get this error with select.select:
```
Traceback (most recent call last):
File "C:\Users\Nathan Glover\Google Drive\MAGENTA Chat\chat_server.py", line
27, in <module>
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
... | 2017/10/09 | [
"https://Stackoverflow.com/questions/46647167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8099482/"
] | I know it's been a long time since this question was asked. But I wanted to let OP and others know about the problem here.
The problem here is that the SOCKET\_LIST must be containing a non-existing socket connection which may have been disconnected earlier. If you pass such connection to select it gives this error
``... | I happened to have this problem too, and I have solved it.
I hope this answer will help everyone.
The fileno of the closed socket will become -1.
So it is most likely because there is a closed socket in the input parameter list of slelect.
That is to say, in the select cycle, when your judgment logic is added to rlist,... | 15,318 |
63,182,541 | I am trying to send message from Raspberry Pi (Ubuntu 20) to Laptop (Virtualbox Ubuntu 20) via UDP socket. So I am using simple code from <https://wiki.python.org/moin/UdpCommunication>
Sending (from Raspberry Pi)
```
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = b"Hello, World!"
print("UDP target IP... | 2020/07/30 | [
"https://Stackoverflow.com/questions/63182541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13118262/"
] | The problem may be in the IP address because you are using the IP '127.0.0.1' (localhost) to reach an outside device. Please find out the IPs of your devices, try using ifconfig Linux command. Also, check that nothing is blocking your connection.
Consider that for socket.bind(address) you can use '0.0.0.0' and for soc... | If you are using a static IP on the RPi, you need to add a static route:
```
sudo ip route add 236.0.0.0/8 dev eth0
``` | 15,323 |
7,213,965 | I am using Windows 7, Apache 2.28 and Web Developer Server Suite for my server.
All files are stored under C:/www/vhosts
I downloaded Portable Python 2.7 from <http://www.portablepython.com/> and have installed it to
C:/www/portablepython
I'm trying to find mod\_wsgi to get it to work with 2.7 - but how can I do t... | 2011/08/27 | [
"https://Stackoverflow.com/questions/7213965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/847047/"
] | The script you have at C:/www/vhosts/localhost/testing.py is a CGI script and not a WSGI script. Follow the instructions for configuring mod\_wsgi and what a WSGI script file for hello world should look like at:
<http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide> | also, you should look into using a system install of python from python.org and pip+distribute+virtualenv to keep contained python environments for your different sites. This will give you maximum portability. | 15,325 |
28,097,471 | **Update**: Here is a more specific example
Suppose I want to compile some statistical data from a sizable set of files:
I can make a generator `(line for line in fileinput.input(files))` and some processor:
```
from collections import defaultdict
scores = defaultdict(int)
def process(line):
if 'Result' in... | 2015/01/22 | [
"https://Stackoverflow.com/questions/28097471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3467349/"
] | So you basically create a histogram. This is can easily be parallelized, because histograms can be merged without complication. One might want to say that this problem is trivially parallelizable or ["embarrassingly parallel"](http://en.wikipedia.org/wiki/Embarrassingly_parallel). That is, you do not need to worry abou... | I had to modify the original pool.py (the trouble was worker is defined as a method without any inheritance) to get what I want but it's not so bad, and probably better than writing a new pool entirely.
```
class worker(object):
def __init__(self, inqueue, outqueue, initializer=None, initargs=(), maxtasks=None,
... | 15,327 |
13,335,679 | I want to run a system command in the background using python 2.7, this is what I have:
```
import commands
path = '/fioverify.fio'
cmd= "/usr/local/bin/fio" + path + " "+ " &"
print cmd
handle = commands.getstatusoutput(cmd)
```
This fails. If I remove the ampersand `&` it works. I need to run a command (`/usr/loc... | 2012/11/11 | [
"https://Stackoverflow.com/questions/13335679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1618238/"
] | Don't use `commands`; it's deprecated and not actually useful for your purposes. Use `subprocess` instead.
```
fio = subprocess.Popen(["/usr/local/bin/fio", path])
```
runs the `fio` command in parallel with your process and binds the variable `fio` to a handle to the process. You can then call `fio.wait()` to wait ... | Use the [subprocess](http://docs.python.org/2/library/subprocess.html) module, [`subprocess.Popen`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen) allows you to run a command as a subprocess (in the background) and check its status. | 15,328 |
53,055,671 | How do you run the command line in order to read and write a csv file in python on a MacBook? | 2018/10/30 | [
"https://Stackoverflow.com/questions/53055671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10387703/"
] | The first APK you linked to isn't a valid APK. It's just a plain text file, with the following text repeated over and over:
```
HTTP/1.1 200 OK
Date: Sat, 27 Oct 2018 17:35:36 GMT
Strict-Transport-Security: max-age=31536000;includeSubDomains; preload
Last-Modified: Sat, 28 Jul 2018 11:40:03 GMT
ETag: "23b1fe5-5720db06... | That's encryption java classes feature (Like dexgaurd or Bangcle kh); and also that's protected with Native Library Encryption (NLE) + JNI Obfuscation (JNI) From Something like dexprotector (i found that in dynamic analysis tools)
and many tanks to semanticscholar for [This](https://pdfs.semanticscholar.org/2b02/44a29... | 15,331 |
61,861,185 | Let's say I have the following class.
```py
class A:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
obj_A = A(y=2) # Dynamically pass the parameters
```
My question is, how can I dynamically create an object of a certain class by passing only one (perhaps multiple but not all) parameters? A... | 2020/05/18 | [
"https://Stackoverflow.com/questions/61861185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474204/"
] | There is `asSequence()` function for iterator, but it returns sequence that can be iterated only once. The point is to use the same iterator for each iteration.
```
// I don't know how to name the function...
public fun <T> Iterable<T>.asIteratorSequence(): Sequence<T> {
val iterator = this.iterator()
return S... | I figured out we can use iterators for this:
```
fun main() {
val seq = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).asSequence().iterator()
println(seq.asSequence().take(4).toList().toString());
println(seq.asSequence().toList().toString())
}
```
This way the sequences advance the inner iterator. If the sequenc... | 15,332 |
40,946,211 | I've installed my Django app on an Ubuntu server with Apache2.4.7 and configured it to use py3.5.2 from a virtual environment.
However, from what I can see in the errors, it's starting at 3.5 and defaulting to 3.4.
Please explain why this is happening:
```
/var/www/venv/lib/python3.5/site-packages
/usr/lib/python3.4... | 2016/12/03 | [
"https://Stackoverflow.com/questions/40946211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591242/"
] | The mod\_wsgi module for Apache is compiled for a specific Python version. You cannot make it run using a different Python version by pointing it at a Python virtual environment for a different Python version. This is cleared mentioned in the mod\_wsgi documentation about use of Python virtual environments at:
* <http... | The source of the problem was Graham Dumpleton's answer.
I just want to give some more information in case it helps someone facing the same problem as me.
There's no official repo for Python 3.5.2 in Ubuntu server 14.04.
Rather than using some unsupported repo like [this one](https://launchpad.net/~fkrull/+archive/ubu... | 15,334 |
42,621,190 | I am following a tutorial on using python v3.6 to do decision tree with machine learning using scikit-learn.
Here is the code;
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mglearn
import graphviz
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import ... | 2017/03/06 | [
"https://Stackoverflow.com/questions/42621190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | `graphviz.Source(dot_graph)` returns a [`graphviz.files.Source`](http://graphviz.readthedocs.io/en/latest/api.html#source) object.
```
g = graphviz.Source(dot_graph)
```
use [`g.render()`](http://graphviz.readthedocs.io/en/latest/api.html#graphviz.Source.render) to create an image file. When I ran it on your code wi... | You can use display from IPython.display. Here is an example:
```
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
model = DecisionTreeClassifier()
model.fit(X, y)
from IPython.display import display
display(graphviz.Source(tree.export_graphviz(model)))
``` | 15,335 |
30,560,266 | I have a router configuration file. The router has thousands of "Interfaces", and I'm trying to make sure it DOES have *two* certain lines in EACH Interface configuration section. The typical router configuration file would look like this:
```
<whitespaces> Interface_1
<whitespaces> description Interface_1
<whitesp... | 2015/05/31 | [
"https://Stackoverflow.com/questions/30560266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4958929/"
] | I solved this issue using [collection.distinct](https://mongodb.github.io/node-mongodb-native/api-generated/collection.html#distinct):
```
collection.distinct("DataFields",(function(err, docs){
console.log(docs);
assert.equal(null, err);
db.close();
}))
``` | You could also do this by way of **[aggregation framework](http://docs.mongodb.org/manual/core/aggregation-introduction/)**. The suitable aggregation pipeline would consist of the [**`$group`**](http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group) operator stage which groups the document ... | 15,343 |
10,839,302 | I have a django application that requires PIL and I have been getting errors so I decided to play around with PIL on my hosting server.
PIL is installed in my virtual environment. However, when running the following I get an error, and when I run it outside the virtual environment it works.
```
Python 2.7.3 (defaul... | 2012/05/31 | [
"https://Stackoverflow.com/questions/10839302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269106/"
] | Most likely the Python you are using in your virtualenv has been built by yourself, not the system Python - is that right? If so your problem is that the header (.h) files for zlib are not installed in your system when building Python itself.
You have to have the "ziplib-devel" (or equivalent) package in Linux when bu... | You could try [Pillow](http://pypi.python.org/pypi/Pillow) which is a repackaged PIL which plays much nicer with virtualenv. | 15,344 |
46,423,582 | I'm attempting to install cvxopt using Conda (which comes with the Anaconda python distribution), and I received the error message below. Apparently my Anaconda installation is using python 3.6, whereas cvxopt wants python 3.5\*. How can I fix this and install cvxopt using Conda?
After typing conda install cvxopt at t... | 2017/09/26 | [
"https://Stackoverflow.com/questions/46423582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1854748/"
] | It would appear that `cvxopt` requires Python 3.5. Easiest solution would be to use `conda` to create a separate environment for python 3.5 and then install cvxopt (and any other desired python packages). For example...
```
conda create -n cvxopt-env python=3.5 cvxopt numpy scipy matplotlib jupyter
```
...depending ... | try
```
conda install cvxopt=1.1.8
```
its the new version and only version having support for python3.6 | 15,345 |
55,358,337 | How can we apply conditions for a Dataset in python, specially applying those and want to fetch the column name as an output?
let's say the below one is the dataframe so my question is how can we retrieve a colname(let's say "name") as an output by applying conditions on this dataframe
```
name salary ... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55358337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11260410/"
] | (edit: slightly simplified non-recursive solution)
You can do it like this, just for each iteration consider if the item should be included or excluded.
```
def f(maxK,K, N, L, S):
if L == 0 or not N or K == 0:
return S
#either element is included
included = f(maxK,maxK, N[1:], L-1, S + N[0] )
... | Extending the code for `itertools.combinations` shown at the [docs](https://docs.python.org/3/library/itertools.html#itertools.combinations), I built a version that includes an argument for the maximum index distance (`K`) between two values. It only needed an additional `and indices[i] - indices[i-1] < K` check in the... | 15,346 |
71,737,316 | So, I'm having the classic trouble install lxml.
Initially I was just pip installing, but when I tried to free up memory using `Element.clear()` I was getting the following error:
```
Python(58695,0x1001b4580) malloc: *** error for object 0x600000bc3f60: pointer being freed was not allocated
```
I thought this must... | 2022/04/04 | [
"https://Stackoverflow.com/questions/71737316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311220/"
] | One solution that works - build it from source:
```
git clone https://github.com/lxml/lxml
cd lxml
git checkout tags/lxml-4.9.1
python3 setup.py bdist_wheel
cd dist/
sudo pip3 install lxml-4.9.1-cp310-cp310-macosx_12_0_arm64.whl
```
For additional resources:
<https://lxml.de/installation.html> | It turned out that installing lxml with a simple `pip install` *was* working fine.
The reason for my malloc error was the fact that I was trying to clear the element before the end tag had been seen. Turns out this isn't possible and you need to wait for the end tag even if you already know you aren't interested in th... | 15,351 |
4,944,331 | I wonder about the best/easiest way to authenticate the user for the Google Data API in a desktop app.
I read through the [docs](http://code.google.com/intl/de/apis/contacts/docs/3.0/developers_guide_python.html) and it seems that my options are ClientLogin or OAuth.
For ClientLogin, it seems I have to implement the ... | 2011/02/09 | [
"https://Stackoverflow.com/questions/4944331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133374/"
] | You can use the file streaming ability available on the MediaPlayer class to do the above.
I have not tested the following code, but it should be something on these lines:
```
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(http://somedomain/some.pls);
mp.prepare();
mp.start();
```
But remember to do th... | You can try download pls file, parse the urls that are in there, and put them in MediaPlayer. | 15,352 |
48,013,074 | So I am trying to use cffi to access a c library quickly in pypy.
I am using my macpro with command line tools 9.1
specifically I am comparing a pure python priority queue, with heapq, with a cffi, and ctypes for a project.
I have got code from roman10's website for a C implementation of a priority queue.
I am fol... | 2017/12/28 | [
"https://Stackoverflow.com/questions/48013074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5062570/"
] | You must tell ffi.set\_source() about `heap.c`. The easiest way is
`with open('heap.c', 'r') as fid:
ffi.set_source(fid.read())`
like in [this example](http://cffi.readthedocs.io/en/latest/overview.html#purely-for-performance-api-level-out-of-line). The way it works is:
* declarations of functions, structs, enums, ... | Your ffi.cdef() does not have any function declaration, so the resulting \_heap\_i library doesn't export any function. Try to copy-paste the function declaration from the .h file. | 15,356 |
71,395,163 | I have a txt file of hundreds of thousands of words. I need to get into some format (I think dictionary is the right thing?) where I can put into my script something along the lines of;
```
for i in word_list:
word_length = len(i)
print("Length of " + i + word_length, file=open("LengthOutput.txt", "a"))
```
Currentl... | 2022/03/08 | [
"https://Stackoverflow.com/questions/71395163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15604077/"
] | A list would be the correct way to store the words. A dictionary requires a key-value pair and you don't need it in this case.
```
with open('filename.txt', 'r') as file:
x = [word.strip('\n') for word in file.readlines()]
``` | What you are trying to do is to read a file. An `import` statement is used when you want to, loosely speaking, use python code from another file.
The [docs](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) have a good introduction on reading and writing files -
To read a file, you first ... | 15,357 |
11,729,120 | I am having a problem reading specific lines. It's similar to the question answered here:
[python - Read file from and to specific lines of text](https://stackoverflow.com/questions/7559397/python-read-file-from-and-to-specific-lines-of-text)
The difference, I don't have a fixed end mark. Let me show an example:
```
-... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11729120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1443368/"
] | Take a look at [this file](https://github.com/void256/nifty-gui/blob/1.3/nifty-renderer-lwjgl/src/main/java/de/lessvoid/nifty/renderer/lwjgl/input/LwjglKeyboardInputEventCreator.java) of the source code of [NiftyGUI](https://github.com/void256/nifty-gui), which should contain this text handling code. | Just delete your shift handling line and add:
```
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && !Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))
shift=true;
```
before the beginning of the While loop. | 15,358 |
39,142,168 | I just started learning python a few days ago and I have been using Grok Learning. For the challenge I have everything working as far as i can see but when i submit it i am told "Testing yet another case that starts with a vowel. Your submission raised an exception of type IndexError. This occurred on line 8 of your su... | 2016/08/25 | [
"https://Stackoverflow.com/questions/39142168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | use the below query..
```
WITH cte_data
AS (
SELECT cost,(cost*round(rand()+rand(),2)origCost
FROM [dbo].[x])
UPDATE a
SET a.cost=a.origCost
FROM cte_data a
```
if you need different numbers for calculation use the below script
```
WITH cte_data
AS (
SELECT cost,ROW_NUMBER()OVER(ORDER BY cost)*(cost)origCost
FRO... | To get random decimal within 0..2 use `CAST (ABS(CHECKSUM(NewId())) % 200 /100. AS DECIMAL(3,2))` instead of `round(rand()+rand(),2)` | 15,359 |
72,010,560 | I am running [a model from github](https://github.com/wentaoyuan/pcn) and I already encountered several errors with pathing etc. After fixing this, I think the main error for now is tensorflow. This repo was probably done when TF 1.x, and now with the change to TF 2, I might need to migrate everything.
Mainly, I get t... | 2022/04/26 | [
"https://Stackoverflow.com/questions/72010560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7396613/"
] | **Disclaimer**: Unless no other choice, I would strongly recommend sticking to TensorFlow 1.x. Migrating code from TF 1.x to 2.x can be incredibly time consuming.
---
Registering a shape is done in c++ using `SetShapeFn` and not in python since TF 1.0. However, the private python API was kept in TF 1.x (I presume for... | according to tensorflow's release log, `RegisterShape` is deprecated, and you should use `SetShapeFn` to define the shape when registering your operator in c++ source file. | 15,362 |
29,570,085 | I am using a Makefile to provide consistent single commands for setting up a virtualenv, running tests, etc. I have configured my Jenkins instance to pull from a mercurial repo and then run "make virtualenv", which does this:
```
virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && pip in... | 2015/04/10 | [
"https://Stackoverflow.com/questions/29570085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332304/"
] | Jenkins pipelines can be made to run with virtual environments but there are multiple things to consider.
* The default shell that Jenkins uses is `/bin/sh` - this is configurable in **Manage Jenkins -> Configure System -> Shell -> Shell executable**. Setting this to `/bin/bash` will make `source` work.
* An activated... | [@hardbyte](https://stackoverflow.com/users/809692/hardbyte)'s answer
*The default shell that Jenkins uses is /bin/sh - this is configurable in Manage Jenkins -> Configure System -> Shell -> Shell executable. Setting this to /bin/bash will make source work.*
plus:
* <https://stackoverflow.com/a/70812248/1497139>
* [... | 15,363 |
55,980,027 | I need to add to a .csv file based on user input. Other portions of the code add to the file but I can't figure out how to have it add user input. I'm new to python and coding in general.
I have other portions of the code that can merge or draw the data from a .csv database and write it to the separate file, but can't... | 2019/05/04 | [
"https://Stackoverflow.com/questions/55980027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11450864/"
] | Trying to output a SimpleXMLElement using `var_dump()` isn't a good idea and as you have seen - doesn't give much.
If you just want to see the XML it has loaded, instead use...
```
echo $xml->asXML();
```
which will show you the XML has loaded OK, so then to output the field your after is just
```
$xml = simplexm... | Using the `XPath` query
```
$xml = new SimpleXMLElement($xmlData);
echo $xml->xpath('//AsyncReplyFlag')[0];
```
OR
You can use `xml_parser_create`
```
$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $values, $indexes);// $xml containing the XML
xml_parser_free($p);
echo $values[12]['value'];
```
For o... | 15,373 |
419,698 | **Overall Plan**
Get my class information to automatically optimize and select my uni class timetable
Overall Algorithm
1. Logon to the website using its
Enterprise Sign On Engine login
2. Find my current semester and its
related subjects (pre setup)
3. Navigate to the right page and get the data from each related
s... | 2009/01/07 | [
"https://Stackoverflow.com/questions/419698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45211/"
] | Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me...
Still, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance.
So, you have two constraints:
1.... | [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) was mentioned here a few times, e.g [get-list-of-xml-attribute-values-in-python](https://stackoverflow.com/questions/87317/get-list-of-xml-attribute-values-in-python).
>
> Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects l... | 15,376 |
5,997,027 | I don't know if this is an obvious bug, but while running a Python script for varying the parameters of a simulation, I realized the results with delta = 0.29 and delta = 0.58 were missing. On investigation, I noticed that the following Python code:
```
for i_delta in range(0, 101, 1):
delta = float(i_delta) / 100
... | 2011/05/13 | [
"https://Stackoverflow.com/questions/5997027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752910/"
] | Any number that can't be built from exact powers of two can't be represented exactly as a floating point number; it needs to be approximated. Sometimes the closest approximation will be less than the actual number.
Read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.... | Its very well known due to the nature of [floating point numbers](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html).
If you want to do decimal arithmetic not floating point arithmatic there are [libraries](http://docs.python.org/library/decimal.html) to do this.
E.g.,
```
>>> from decimal imp... | 15,378 |
25,288,927 | I have a dict and behind each key is a list stored.
Looks like this:
```
dict with values: {
u'New_York': [(u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 10), (u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 4), (u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 3)],
u'Jersy': [(u'Jersy... | 2014/08/13 | [
"https://Stackoverflow.com/questions/25288927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3935035/"
] | [`max()`](https://docs.python.org/2/library/functions.html#max) takes a second parameter, a callable `key` that lets you specify how to calculate the maximum. It is called for each entry in the input iterable and its return value is used to find the highest value. You need to apply this against each *value* in your dic... | Can you have a look at : <https://wiki.python.org/moin/HowTo/Sorting#Sorting_Mini-HOW_TO>
The answer may be :
```
In [2]: import datetime
In [3]: d = {
u'New_York': [(u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 10), (u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 4), (u'New_York', u'N... | 15,379 |
1,027,990 | I'm trying to build my first facebook app, and it seems that the python facebook ([pyfacebook](http://code.google.com/p/pyfacebook/)) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.
Are there any mature python frontends for facebook? If not, what's the best l... | 2009/06/22 | [
"https://Stackoverflow.com/questions/1027990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51197/"
] | The updated location of pyfacebook is [on github](http://github.com/sciyoshi/pyfacebook/tree/master). Plus, as [arstechnica](http://arstechnica.com/open-source/news/2009/04/how-to-using-the-new-facebook-stream-api-in-a-desktop-app.ars) well explains:
>
> PyFacebook is also very easy to extend
> when new Facebook API... | Try [this site](http://github.com/sciyoshi/pyfacebook/tree/master) instead.
It's pyfacebooks site on GitHub. The one you have is outdated. | 15,380 |
42,802,194 | Hi I am really new to JSON and Python, here is my dilemma, it's been bugging me for two days.
Here is the sample json that I want to parse.
```
{
"Tag1":"{
"TagX": [
{
"TagA": "A",
"TagB": 1.6,
"TagC": 1.4,
"TagD": 3.5,
"TagE": "01",
"TagF": null
},
{
"TagA": "A",
"TagB": 1.6,... | 2017/03/15 | [
"https://Stackoverflow.com/questions/42802194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7672271/"
] | In the returned JSON, the value of `Tag1` is a string, not more JSON. It does appear to be JSON encoded as a string though, so convert that to json once more:
```
jaysonData = json.load(urllib2.urlopen('URL'))
tag1JaysonData = json.load(jaysonData['Tag1'])
print tag1JaysonData["TagX"]
```
Also note that `TagX` is a ... | `TagX` is a `list` consisting of 2 dictionaries and `TagB` is a `dictionary`.
```
print jaysonData["Tag1"]["TagX"][0]["TagB"]
```
You need to remove double quotations before and after the curly braces of `Tag1`.
```
{
"Tag1":{
"TagX": [
{
"TagA": "A",
"TagB": 1.6,
"TagC": 1.4,
"TagD": 3.5,
... | 15,385 |
19,868,457 | I have renamed a css class name in a number of (python-django) templates. The css files however are wide-spread across multiple files in multiple directories. I have a python snippet to start renaming from the root dir and then recursively rename all the css files.
```
from os import walk, curdir
import subprocess
CO... | 2013/11/08 | [
"https://Stackoverflow.com/questions/19868457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/860421/"
] | You're not trying to run a single command, but a shell pipeline of multiple commands, and you're trying to do it without invoking the shell. That can't possibly work. The way you're doing this, `|` is just one of the arguments to `find`, which is why `find` is telling you that it doesn't understand that argument with t... | The problem is the pipe. To use a pipe with the subprocess module, you have to pass `shell=True`. | 15,388 |
28,125,214 | I'm very new to python and I'm trying to print the url of an open websitein Chrome. Here is what I could gather from this page and googeling a bit:
```
import win32gui, win32con
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_siz... | 2015/01/24 | [
"https://Stackoverflow.com/questions/28125214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489629/"
] | You are exactly right because at that time view will not be drawn so for that you have to use viewtreeobserver:
like this:
```
final ViewTreeObserver treeObserver = viewToMesure
.getViewTreeObserver();
treeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener(... | You can use a custom view to set the view's height to be tha same as its width by overriding onMeasure:
```
public class SquareButton extends Button {
public SquareButton (Context context) {
super(context);
}
public SquareButton (Context context, AttributeSet attrs) {
super(context, attrs... | 15,389 |
70,945,717 | I have Snowflake tasks that runs every 30 minutes. Currently, when the task fails due to underlying data issue in the stored procedure that the Task calls, there is no way to notify the users on the failure.
```
SELECT *
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY());
```
How can notifications be setup for a Snowflak... | 2022/02/01 | [
"https://Stackoverflow.com/questions/70945717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252662/"
] | I think currently a python script would the best way to address this.
You can use this SQL to query last runs, read into a data frame and filter out errors
```
select *
from table(information_schema.task_history(scheduled_time_range_start=>dateadd(minutes, -30,current_timestamp())))
``` | It is possible to create Notification Integration and send message when error occurs. As of May 2022 this feature is in preview, supported by accounts on Amazon Web Servives.
#### [Enabling Error Notifications for Tasks](https://docs.snowflake.com/en/user-guide/tasks-errors.html#enabling-error-notifications-for-tasks)... | 15,392 |
67,030,593 | **Problem**
When trying to access and purchase a specific item from store X, which releases limited quantities randomly throughout the week, trying to load the page via the browser is essentially pointless. 99 out of 100 requests time out. By the time 1 page loads, the stock is sold out.
**Question**
What would be the... | 2021/04/10 | [
"https://Stackoverflow.com/questions/67030593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15596095/"
] | You don't need to `JSON.stringify` your 'params'.
Change it into:
```js
const params = {
email: "someEmail@gmail.com",
name: "Some Name",
password: "123qwe!!"
}
``` | use this one-
axios.post('http://localhost:8080/users', params, {
headers: {
'Content-Type': 'application/json'
}
} | 15,395 |
4,135,261 | I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_h... | 2010/11/09 | [
"https://Stackoverflow.com/questions/4135261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197108/"
] | As a very late follow-up on this matter, I believe I was running into the same issue as waffleman, in a context of a confined network.
The hint about using `auth_none` on the `Transport` object turned out quite helpful, but I found myself a little puzzled as to how to implement that. Thing is, as of today at least, I ... | [paramiko's SSHClient](http://www.lag.net/paramiko/docs/paramiko.SSHClient-class.html) has [`load_system_host_keys`](http://www.lag.net/paramiko/docs/paramiko.SSHClient-class.html#load_system_host_keys) method which you could use to load user specific set of keys. As example in the docs explain, it needs to be run befo... | 15,397 |
73,353,608 | My script takes `-d`, `--delimiter` as argument:
```
parser.add_argument('-d', '--delimiter')
```
but when I pass it `--` as delimiter, it is empty
```
script.py --delimiter='--'
```
I know `--` is special in argument/parameter parsing, but I am using it in the form `--option='--'` and quoted.
Why does it not w... | 2022/08/14 | [
"https://Stackoverflow.com/questions/73353608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7287412/"
] | Existing bug report
-------------------
Patches have been suggested, but it hasn't been applied. [Argparse incorrectly handles '--' as argument to option](https://github.com/python/cpython/issues/58572)
Some simple examples:
---------------------
```
In [1]: import argparse
In [2]: p = argparse.ArgumentParser()
In [... | It calls `parse_args` which calls `parse_known_args` which calls `_parse_known_args`.
Then, on line 2078 (or something similar), it does this (inside a while loop going through the string):
```py
start_index = consume_optional(start_index)
```
which calls the `consume_optional` (which makes sense, because this is a... | 15,407 |
18,219,529 | In python, logging to syslog is fairly trivial:
```
syslog.openlog("ident")
syslog.syslog(0, "spilled beer on server")
syslog.closelog()
```
Is there an equivalently simple way in Java? After quite a bit of googling, I've been unable to find an easy to understand method that doesn't require reconfiguring rsyslogd or... | 2013/08/13 | [
"https://Stackoverflow.com/questions/18219529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643675/"
] | One way to go direct to the log without udp is with [syslog4j](http://www.syslog4j.org/). I wouldn't necessarily say it's simple, but it doesn't require reconfiguring syslog, at least. | The closest I can think of, would be using [Log4J](https://logging.apache.org/log4j/) and configuring the [SyslogAppender](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/net/SyslogAppender.html) so it writes to syslog. Sorry, that's not as easy as in Python! | 15,410 |
48,102,393 | I have 1000 files each having one million lines. Each line has the following form:
```
a number,a text
```
I want to remove all of the numbers from the beginning of every line of every file. including the ,
Example:
```
14671823,aboasdyflj -> aboasdyflj
```
What I'm doing is:
```
os.system("sed -i -- 's/^.*,//g... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48102393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120089/"
] | This is much faster:
```
cut -f2 -d ',' data.txt > tmp.txt && mv tmp.txt data.txt
```
On a file with 11 million rows it took less than one second.
To use this on several files in a directory, use:
```sh
TMP=/pathto/tmpfile
for file in dir/*; do
cut -f2 -d ',' "$file" > $TMP && mv $TMP "$file"
done
```
A thin... | I would use GNU `awk` (to leverage the `-i inplace` editing of file) with `,` as the field separator, *no expensive Regex manipulation*:
```
awk -F, -i inplace '{print $2}' file.txt
```
For example, if the filenames have a common prefix like `file`, you can use shell globbing:
```
awk -F, -i inplace '{print $2}' fi... | 15,413 |
61,380,617 | when I'm trying open a website with urllib library I'm getting the error. I'm not getting why this error occurs? currently I'm using python 3.6 version. Is this problem with version?
```
url = 'https://example.com'
html = urllib.request.urlopen(url).read().decode('utf-8')
text = get_text(html)
data = text.split()
prin... | 2020/04/23 | [
"https://Stackoverflow.com/questions/61380617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13139499/"
] | You should not have duplicate column names in the dataframe, we correct that using `make.unique`.
```
names(df) <- make.unique(names(df))
```
We can then remove empty rows and get data in long format using `pivot_longer`.
```
library(dplyr)
library(tidyr)
df %>%
filter(orig != '' | dest != '') %>%
pivot_longe... | a `data.table` solution. You might need to play around the `year`. As `melt` now in `data.table` cannot handle the `year` in your question correctly. I guess `pivot_longer` from `tidyr` can do this in one shot.
```r
library(data.table)
df <- fread('orig dest cartrip cartrip cartrip cartrip cartrip walking walki... | 15,418 |
15,118,974 | I'm trying to learn ruby, so I'm following an exercise of google dev. I'm trying to parse some links. In the case of successful redirection (considering that I know that it its possible only to get redirected once), I get redirect forbidden. I noticed that I go from a http protocol link to an https protocol link. Any c... | 2013/02/27 | [
"https://Stackoverflow.com/questions/15118974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388172/"
] | Ruby's [OpenURI](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open-uri/rdoc/OpenURI.html) will automatically handle redirects for you, as long as they're not "[meta-refresh](http://en.wikipedia.org/wiki/Meta_refresh)" that occur inside the HTML itself.
For instance, this follows a redirect automatically:
```
irb(main... | Basically the url in code.google that you're trying to open redirects to a https url. You can see that by yourself if you paste `http://code.google.com/edu/languages/google-python-class/images/puzzle/p-bija-baei.jpg` into your browser
Check the following [bug report](http://bugs.ruby-lang.org/issues/859) that explains... | 15,419 |
29,656,173 | I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th number in order to produce an ISBN. The numbers that the user inputs HAVE to be limited to one digit, and an error message should be displayed... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29656173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678142/"
] | You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b
```
print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
print ("Error. Only 1 digit... | Firstly, I'm assuming you are using 3.x. Secondly, if you are using 2.x, you can't use `len` on numbers.
This is what I would suggest:
```
print('Please enter your 10 digit number')
number = ''
for x in range(1,11):
digit = input('Please enter digit ' + str(x) + ': ')
while len(digit) != 1:
# digit ... | 15,420 |
66,533,544 | ```
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-b7eb239f86a7> in <module>
1 # Initialize path to SQLite database
2 path = 'data/classic_rock.db'
----> 3 con = sq3.Connection(path)
... | 2021/03/08 | [
"https://Stackoverflow.com/questions/66533544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14204983/"
] | It looks like from the traceback that you are attempting to use `sq3` and you either did not `import` the library or did not correctly alias the library in question. Cannot know for sure without your code though. | 'sq3' is not defined
That's why. Somewhere in your code you're expecting a variable called sql3 but it doesn't exist. | 15,424 |
36,467,658 | I installed firewalld on my centos server but as I tried to start it I got this:
```
$ sudo systemctl start firewalld
Job for firewalld.service failed. See 'systemctl status firewalld.service' and 'journalctl -xn' for details.
```
here is the systemctl status:
```
sudo systemctl status firewalld
firewalld.service -... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36467658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3383936/"
] | This worked for me:
```
systemctl stop firewalld
pkill -f firewalld
systemctl start firewalld
``` | I know that it is an old thread , But I was facing this problem and I just fixed it, Figured it will help someone in the nearby future.
I thought the problem was in my code or that I mis placed the file.
Well , sadly This file is corrupted (perhaps misplaced)
`/usr/lib/python2.7/site-packages/gi/_gi.so` or I think ... | 15,425 |
38,282,659 | I have two data points `x` and `y`:
```
x = 5 (value corresponding to 95%)
y = 17 (value corresponding to 102.5%)
```
No I would like to calculate the value for `xi` which should correspond to 100%.
```
x = 5 (value corresponding to 95%)
xi = ?? (value corresponding to 100%)
y = 17 (value corresponding to 1... | 2016/07/09 | [
"https://Stackoverflow.com/questions/38282659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306448/"
] | is that what you want?
```
In [145]: s = pd.Series([5, np.nan, 17], index=[95, 100, 102.5])
In [146]: s
Out[146]:
95.0 5.0
100.0 NaN
102.5 17.0
dtype: float64
In [147]: s.interpolate(method='index')
Out[147]:
95.0 5.0
100.0 13.0
102.5 17.0
dtype: float64
``` | We can easily plot this on a graph without Python:
[](https://i.stack.imgur.com/PW6fy.png)
This shows us what the answer should be (13).
But how do we calculate this? First, we find the gradient with this:
[](https://i.stack.imgur.com/... | 15,430 |
34,778,397 | I am currently creating a music player in python 3.3 and I have a way of opening the mp3/wav files, namely through using through 'os.startfile()', but, this way of running the files means that if I run more than one, the second cancels the first, and the third cancels the second, and so on and so forth, so I only end u... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34778397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966288/"
] | i've managed to do this Using an external module, as after ages of trying to do it without any, i gave up and used [tinytag](https://pypi.python.org/pypi/tinytag/), as it is easy to install and use. | Nothing you can do without external libraries, as far as I know. Try using [pymad](http://spacepants.org/src/pymad/).
Use it like this:
```
import mad
SongFile = mad.MadFile("something.mp3")
SongLength = SongFile.total_time()
``` | 15,432 |
22,490,833 | I have this string:
```
Email: promo@elysianrealestate.com
```
I want to get the email address:
### I tried this
```
Email:.*
```
but I got the whole string, not just the email
help please
### i am using scrapy with python | 2014/03/18 | [
"https://Stackoverflow.com/questions/22490833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] | If your string always finish with the email, you use:
```
r'Email:\s*(.*)'
```
I got the idea from [here](http://doc.scrapy.org/en/0.7/topics/selectors.html#using-selectors-with-regular-expressions) but I can't test it as I don't have a scrapy shell availabl at the moment. | This should capture your emails, it ensures that you only capture correctly formed emails:
```
Email:\s+(\b[A-Za-z0-9(._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b)
```
Here's how I tested it:
```
>>> import re
>>> txt = """
I have this string:
Email: promo@elysianrealestate.com foo bar baz
I want to get the email addr... | 15,433 |
57,854,020 | **My Problem**
I am trying to create a column in python which is the conditional smoothed moving 14 day average of another column. The condition is that I only want to include positive values from another column in the rolling average.
I am currently using the following code which works exactly how I want it to, but ... | 2019/09/09 | [
"https://Stackoverflow.com/questions/57854020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12041022/"
] | This should speed up your code:
`df['avg_gain'] = df[df['delta'] > 0]['delta'].rolling(14).mean()`
Does your current code converge to zero? If you can provide the data, then it would be easier for the folk to do some analysis. | I would suggest you add a column which is 0 if the value is < 0 and instead has the same value as the one you want to consider if it is >= 0. Then you take the running average of this new column.
```
df['new_col'] = df.apply(lambda x: x['delta'] if x['delta'] >= 0 else 0)
df['avg_gain'] = df['new_value'].rolling(14).m... | 15,436 |
44,934,948 | I try to get all lattitudes and longtitudes from this json.
Code:
```
import urllib.parse
import requests
raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid='
print()
userid = 735890904669618176
#userid = input('UserID: ')
url = raw_json + urllib.parse.urlencode({'userid=': userid}) + '&page_size=100... | 2017/07/05 | [
"https://Stackoverflow.com/questions/44934948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8258990/"
] | Your URL construction is incorrect. The URL you have built (as shown in the output of your script) is:
```
http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000
```
Where you actually want this:
```
http://live.ksmobile.net/live/getreplayvideos?userid=735890904669618176&pa... | According to your posted json, you have problem in this statement-
`print(coordinates['lat'], coordinates['lnt'])`
Here `coordinates` is a list having only one item which is dictionary. So your statement should be-
`print(coordinates[0]['lat'], coordinates[0]['lnt'])` | 15,437 |
63,301,691 | my code works perfectly in Python 3.8, but when I switch to Python 3.5 in same operating system, with same code and everything else, it starts throwing out "SyntaxError: invalid syntax".
Here is the error, and the part of the code that I think which relates to the error :
```
Traceback (most recent call last):
File... | 2020/08/07 | [
"https://Stackoverflow.com/questions/63301691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10214891/"
] | There are at least two issues here:
1. [Variable annotations](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep526) were new in Python 3.6.
2. The [`dataclasses`](https://docs.python.org/3/library/dataclasses.html?highlight=dataclass#module-dataclasses) module was new in Python 3.7.
Either use Python 3.7 or ... | One new and exciting feature coming in Python 3.7 is the data class. you're not able to use it in python 3.5.
You should use the traditional way and use constructor:
```
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterab... | 15,438 |
46,366,398 | I am using Pymodm as a mongoDB odm with python flask. I have looked through code and documentation (<https://github.com/mongodb/pymodm> and <http://pymodm.readthedocs.io/en/latest>) but could not find what I was looking for.
I am looking for an easy way to fetch data from the database without converting it to a pymodm... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46366398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | It is not obvious from the PyMODM documentation, but here's how to do it:
```
pymodm_obj.to_son().to_dict()
```
Actually, I just re-read your question, and I don't think anything is forcing you to use PyMODM everywhere in your project once you have made the decision to use it. So if you are just looking for the JSON... | Having:
```
from pymodm import MongoModel, fields
import json
class Foo(MongoModel):
name = fields.CharField(required=True)
a=Foo()
```
You can do:
```
jsonFooString=json.dumps(a.to_son().to_dict())
``` | 15,439 |
15,059,082 | This is my code. In the first def function, I made it return column\_choose, and I wanna use column\_choose's value in second def function(get\_data\_list). What can I do? I have tried many times. But IDLE always show:global name 'column\_choose' is not defined.
How to use column\_choose's value in second function?
By... | 2013/02/25 | [
"https://Stackoverflow.com/questions/15059082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011210/"
] | Using `float: left` on the elements will cause them to ignore the `nowrap` rule. Since you are already using `display: inline-block`, you don't need to float the elements to have them display side-by-side. Just remove `float: left` | Was because of the float:left;, once i removed that, fine. Spotted it after typing out question sorry. | 15,442 |
70,647,836 | Very new to python. I am trying to iterate over a list of floating points and append elements to a new list based on a condition. Everytime I populate the list I get double the output, for example a list with three floating points gives me an output of six elements in the new list.
```
tempretures = [39.3, 38.2, 38.1]... | 2022/01/10 | [
"https://Stackoverflow.com/questions/70647836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17887798/"
] | The issue is with the indentation of the line `new_list = new_list + ['N']`. Because it is under-indented, it runs for every instance.
If I can suggest an easier syntax:
```
temperatures = [39.3, 38.2, 38.1]
new_list = []
for temperature in temperatures:
if temperature < 38.3:
new_list.append('L')
el... | Hope it will solve your issue:
```
tempretures = [39.3, 38.2, 38.1]
new_list = []
for temperature in tempretures:
if temperature > 39.2:
new_list.append('H')
elif temperature>=38.3 and temperature<39.2:
new_list.append('N')
else:
new_list.append('L')
print (new_list)
```
sample o... | 15,443 |
57,010,692 | i am trying to extract specific data from requested json file
so after passing Authorization and using requests.get i got my request , i think it is called dictionary for python coders and called json for javascript coders
it containt too much information that i dont need and i would like to extract one or two only
fo... | 2019/07/12 | [
"https://Stackoverflow.com/questions/57010692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9952973/"
] | The `Aphid` library I created is perfect for this.
from command-prompt
```py
py -m pip install Aphid
```
Then its just as easy as loading your json data and searching it with aphid.
```
import json
import Aphid
resp = requests.get(yoururl)
data = json.loads(resp.text)
results = Aphid.findall(data, 'bio')
```
... | After you get your request either:
* you get a simple json file (in which case you import it to python using [json](https://docs.python.org/3/library/json.html)) **or**
* you get an html file from which you can extract the json code (using BeautifulSoup) which in turn you will parse using json library. | 15,446 |
16,956,523 | [Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files.
```
eppetj@desrfpkwpwmhdc.com u... | 2013/06/06 | [
"https://Stackoverflow.com/questions/16956523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2445114/"
] | You can simplify this a lot by using a `defaultdict`:
```
import csv
from collections import defaultdict
emails = defaultdict(list)
with open('email.tsv','r') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if row:
if '@' in row[0]:
emails[row[1].strip()].append(row[0]... | Not a Python answer, but maybe you can use this Bash solution.
```
$ while read email country
do
echo $email >> output-$country.csv
done < in.csv
```
This reads the lines from `in.csv`, splits them into two parts `email` and `country`, and appends (`>>`) the `email` to the file called `output-$country.csv`. | 15,447 |
71,117,916 | I'm looking to use the Kubernetes python client to delete a deployment, but then block and wait until all of the associated pods are deleted as well. A lot of the examples I'm finding recommend using the watch function something like follows.
```
try:
# try to delete if exists
AppsV1Api(api_client).delete_name... | 2022/02/14 | [
"https://Stackoverflow.com/questions/71117916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226081/"
] | ```css
.card {
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: center;
height: 400px;
}
.card img {
height: 400px;
max-width:50%;
}
```
```html
<div class = "container">
<div class = "card">
<img src="https://www.unfe.org/wp-content/uploads/2019/0... | You need to `flex`:
```css
.card{
display: flex;
justify-content: center;
gap: 20px;
margin-top: 20px;
}
.img{
width: 40%;
}
img{
width: 100%;
}
.text{
width: 40%;
}
.text p{
font-size: 12px;
}
```
```html
<div class="card">
<div class="img">
<img src="https://s6.uupload.ir/files/magearray-giftcar... | 15,450 |
50,259,795 | I just installed the discord.py rewrite branch, but attempting to use `import discord` or `from discord.ext import commands` simply results in a TypeError.
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/discord/__init__.py", line 20, in <modu... | 2018/05/09 | [
"https://Stackoverflow.com/questions/50259795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9766666/"
] | Your aiohttp package might be out of date.
Try
```
pip install --upgrade aiohttp
``` | I tried to install discord.py on my python 3.7 and it didn't work.
I had to install python 3.6.6 to make it work, maybe you are using python 3.7, if so you should try rolling back to python 3.6.6 | 15,451 |
66,306,167 | Can you please explain how the below python code is evaluated to be True
```
if 50 == 10 or 30:
print('True')
else:
print('False')
```
Output: True | 2021/02/21 | [
"https://Stackoverflow.com/questions/66306167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7121586/"
] | Replace internals of while- loop with simpler version
```
while leftIndex < left.count && rightIndex < right.count {
if left[leftIndex] <= right[rightIndex] {
mergedArr.append(left[leftIndex])
leftIndex += 1
} else {
mergedArr.append(right[rightIndex])
rightIndex += 1
}
}
... | Consider if the data remains on the `left` or `right` only.
```
public func mergeSort<T: Comparable>(_ array: [T]) -> [T] {
if array.count < 2 {
return array
}
let mid = array.count / 2
let left = [T](array[0..<mid])
let right = [T](array[mid..<array.count])
return merge(left, right)... | 15,452 |
13,907,949 | I'm having an issue and I have no idea why this is happening and how to fix it. I'm working on developing a Videogame with python and pygame and I'm getting this error:
```
File "/home/matt/Smoking-Games/sg-project00/project00/GameModel.py", line 15, in Update
self.imageDef=self.values[2]
TypeError: 'NoneType' o... | 2012/12/17 | [
"https://Stackoverflow.com/questions/13907949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908896/"
] | BrenBarn is correct. The error means you tried to do something like `None[5]`. In the backtrace, it says `self.imageDef=self.values[2]`, which means that your `self.values` is `None`.
You should go through all the functions that update `self.values` and make sure you account for all the corner cases. | The function `move.CompleteMove(events)` that you use within your class probably doesn't contain a `return` statement. So nothing is returned to `self.values` (==> None). Use `return` in `move.CompleteMove(events)` to return whatever you want to store in `self.values` and it should work. Hope this helps. | 15,454 |
58,500,923 | I have an array of elements [a\_1, a\_2, ... a\_n] and array ofprobabilities associated with this elements [p\_1, p\_2, ..., p\_n].
I want to choose "k" elements from [a\_1,...a\_n], k << n, according to probabilities [p\_1,p\_2,...,p\_n].
How can I code it in python? Thank you very much, I am not experienced at prog... | 2019/10/22 | [
"https://Stackoverflow.com/questions/58500923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256362/"
] | use `numpy.random.choice`
example:
```
from numpy.random import choice
sample_space = np.array([a_1, a_2, ... a_n]) # substitute the a_i's
discrete_probability_distribution = np.array([p_1, p_2, ..., p_n]) # substitute the p_i's
# picking N samples
N = 10
for _ in range(N):
print(choice(sample_space, discre... | Perhaps you want something similar to this?
```
import random
data = ['a', 'b', 'c', 'd']
probabilities = [0.5, 0.1, 0.9, 0.2]
for _ in range(10):
print([d for d,p in zip(data,probabilities) if p>random.random()])
```
The above would output something like:
```
['c']
['c']
['a', 'c']
['a', 'c']
['a', 'c']
[]
['a... | 15,457 |
15,305,634 | Today I progressed further into [this Python roguelike tutorial](http://roguebasin.roguelikedevelopment.org/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod), and got to the inventory. As of now, I can pick up items and use them. The only problem is, when accessing the inventory, it's only visible fo... | 2013/03/09 | [
"https://Stackoverflow.com/questions/15305634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138040/"
] | Your code is messy, there may be multiple issues but I think this line is your problem
```
txView.SetBackgroundResource(Resource.Color.PrimaryColor);
```
As you can see [here](http://developer.android.com/reference/android/view/View.html#setBackgroundResource%28int%29) in the documentation you should only pass a ref... | You need to tell which view to find id in. So instantiate a `view` after get the `factory`.
```
var view = factory.Inflate(Resource.Layout.DialogRegister, null);
```
Because the `titleView` would reference to null, it causes the crash,
Then, you can find the `title` using the `view` you just created. One thing to ... | 15,458 |
56,324,750 | I want to get docker host machine ip address and interface names i.e ifconfig of docker host machine. instead im getting docker container ip address on doing ifconfig in docker container.
It would be great if someone tell me to fetch ip address of docker host machine from a docker container.
i have tried doing ifconf... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56324750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361438/"
] | This is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)
Why? Because the issue is not the amount of data not fitting the index, that's the *symptom*.
Real problem
------------
Real problem is how to stop duplicate email entries.
Attempted solution
------------------
Attempted... | You can chenge the innodb\_large\_prefix in your config file to ON. That will set your index key prefixes up to 3072 bytes as the mysql [doc](https://dev.mysql.com/doc/refman/5.6/en/innodb-restrictions.html) says.
```
[mysqld]
innodb_large_prefix = 1
``` | 15,461 |
63,320,723 | Im a beginner in python and im currently working on a problem on code forces called Lecture Sleep. The question gives you 3 lines of inputs:
```
6 3
1 3 5 2 5 4
1 1 0 1 0 0
```
I'm trying to figure out how to link the second array of numbers `(1 3 5 2 5 4)` to the 3rd array of numbers `(1 1 0 1 0 0)`. So that `1 = 1... | 2020/08/08 | [
"https://Stackoverflow.com/questions/63320723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072979/"
] | It might not be the solution for you, but I tell what we do.
1. Prefix the package names, and using namespaces (eg. `company.product.tool`).
2. When we install our packages (including their in-house dependencies), we use a `requirements.txt` file including our PyPI URL. We run everything in container(s) and we install... | Your company could redirect all requests to pypi to a service you control first (perhaps just at your build servers' `hosts` file(s))
This would potentially allow you to
* prefer/override arbitrary packages with local ones
* detect such cases
* cache common/large upstream packages locally
* reject suspect/non-known v... | 15,462 |
12,468,022 | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.lo... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12468022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception
```
while True:
mydir = next_dir_name()
try:
os.makedirs(mydir)
break
except OS... | Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the `isdir` and `makedirs` calls.
However, it could also be possible that a *file* with the same name exists - in that case `os.path.exists` would return `True` but `os.path.isdir` returns false... | 15,466 |
63,783,587 | My goal is to install a package to a specific directory on my machine so I can package it up to be used with AWS Lambda.
Here is what I have tried:
`pip install snowflake-connector-python -t .`
`pip install --system --target=C:\Users\path2folder --install-option=--install-scripts=C:\Users\path2folder --upgrade sno... | 2020/09/07 | [
"https://Stackoverflow.com/questions/63783587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12655086/"
] | We encountered the same issue when running `pip install --target ./py_pkg -r requirements.txt --upgrade` with Microsoft store version of Python 3.9.
Adding `--no-user` to the end of it seems solves the issue. Maybe you can try that in your command and let us know if this solution works?
`pip install --target ./py_pkg... | We had the same issue just in a Python course: The error comes up if Python is installed as an app from the Microsoft app store. In our case it was resolved after re-installing Python by downloading and using the installation package directly from the Python website. | 15,475 |
56,578,199 | I am trying to save AWS CLI command into python variable (list). The trick is the following code returns result I want but doesn't save it into variable and return empty list.
```
import os
bashCommand = 'aws s3api list-buckets --query "Buckets[].Name"'
f = [os.system(bashCommand)]
print(f)
```
output:
```
[
"buck... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56578199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941134/"
] | If you are using Python and you wish to list buckets, then it would be better to use the AWS SDK for Python, which is `boto3`:
```
import boto3
s3 = boto3.resource('s3')
buckets = [bucket.name for bucket in s3.buckets.all()]
```
See: [S3 — Boto 3 Docs](https://boto3.amazonaws.com/v1/documentation/api/latest/referen... | I use this command to create a Python list of all buckets:
```
bucket_list = eval(subprocess.check_output('aws s3api list-buckets --query "Buckets[].Name"').translate(None, '\r\n '))
``` | 15,478 |
63,993,912 | python version 3.8.3
```
import telegram #imorted methodts
from telegram.ext import Updater, CommandHandler
import requests
from telegram import ReplyKeyboardMarkup, KeyboardButton
from telegram.ext.messagehandler import MessageHandler
import json
# below is function defined the buttons to be return
def start(bot, u... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63993912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315167/"
] | After a great effort, I have found a solution for this.
```
class LinearProgressWithTextWidget extends StatelessWidget {
final Color color;
final double progress;
LinearProgressWithTextWidget({Key key,@required this.color, @required this.progress}) : super(key: key);
@override
Widget build(BuildContext cont... | I added the loading indicator inside of a stack and wrapped the whole widget with a `LayoutBuilder`, which will give you the BoxConstraints of the current widget. You can use that to calculate the position of the percent indicator and place a widget (text) above it.
[. How to install python3-dev locally?
I am using ubuntu 16.04. | 2016/11/28 | [
"https://Stackoverflow.com/questions/40840480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5651936/"
] | You have a widget for this:
```
{{ form_errors(form) }}
``` | Accessing errors from **TWIG**
Displays all errors in template
```
{{ form_errors(form) }}
```
Access error for specific field
```
{{ form_errors(form.username) }}
```
Read More: [How to get error message of each field from form object in symfony2?](https://stackoverflow.com/a/40712685/2689199) | 15,482 |
48,965,221 | I'm having a dataset which as the following
```
customer products Sales
1 a 10
1 a 10
2 b 20
3 c 30
```
How can I reshape and to do that in python and pandas? I've tried with the pivot tools but since I have duplicated CUSTOMER ID ... | 2018/02/24 | [
"https://Stackoverflow.com/questions/48965221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9406236/"
] | You can use [`cumcount`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html) with [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) + [`unstack`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.ht... | Your question is unclear. In case of duplicate key, we usually aggregate values. Is that what you want ? Try this:
```
df.pivot_table(index='customer', columns='products', values ='Sales', aggfunc='sum')
products customer a b c
0 1 20.0 NaN NaN
1 2 NaN 20.0 NaN
2 3 ... | 15,483 |
26,409,964 | The [pickle documentation](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled) states that "when class instances are pickled, their class’s data are not pickled along with them. Only the instance data are pickled." Can anyone provide a recipe for including class variables as well as instanc... | 2014/10/16 | [
"https://Stackoverflow.com/questions/26409964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4147103/"
] | Use `dill` instead of pickle, and code exactly how you probably have done already.
```
>>> class A(object):
... y = 1
... x = 0
... def __call__(self, x):
... self.x = x
... return self.x + self.y
...
>>> b = A()
>>> b.y = 4
>>> b(2)
6
>>> b.z = 5
>>> import dill
>>> _b = dill.dumps(b)
>>> b_ = dill.loa... | You can do this easily using the standard library functions by using `__getstate__` and `__setstate__`:
```
class A(object):
y = 1
x = 0
def __getstate__(self):
ret = self.__dict__.copy()
ret['cls_x'] = A.x
ret['cls_y'] = A.y
return ret
def __setstate__(self, state):
A.x = state.pop('cls_... | 15,488 |
25,384,922 | I've installed some packages during the execution of my script as a user. Those packages were the first user packages, so python didn't add `~/.local/lib/python2.7/site-packages` to the `sys.path` before script run. I want to import those installed packages. But I cannot because they are not in `sys.path`.
How can I r... | 2014/08/19 | [
"https://Stackoverflow.com/questions/25384922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108548/"
] | As explained in [What sets up sys.path with Python, and when?](https://stackoverflow.com/questions/4271494/what-sets-up-sys-path-with-python-and-when) `sys.path` is populated with the help of builtin `site.py` module.
So you just need to reload it. You cannot it in one step because you don't have `site` in your namesp... | It might be better to add it directly to your `sys.path` with:
```
import sys
sys.path.append("/your/new/path")
```
Or, if it needs to be found first:
```
import sys
sys.path.insert(1, "/your/new/path")
``` | 15,490 |
18,621,624 | [I'm taking an intro to python class online](http://cscircles.cemc.uwaterloo.ca/8-remix/) and the site is designed to auto-enter input() data into the program that you write to resolve various python logic problems.
[Please see this page to see how the online class's tool uses input entries](http://cscircles.cemc.uwat... | 2013/09/04 | [
"https://Stackoverflow.com/questions/18621624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2609312/"
] | It sounds like you want to call `input` in a loop. Here's one way to do it:
```
lst = []
s = input()
while s != 'END':
lst.append(s)
s = input()
```
There are other options for how to set up the condition on the loop, but I think this is the most straight forward. If the calculation for when to stop looping ... | You can create a list and read each string one by one, and add it to the list:
```
width=int(input())
lis=[]
tmp=''
while tmp!='END':
tmp=input() #receives a string, in python 3.0+
lis.append(tmp)
``` | 15,491 |
65,643,645 | I'm pretty new to python and to programming in general. I'm trying to make the game Bounce. The game runs as expected but as soon as I close the window, it shows an error.
This is the code:
```
from tkinter import *
import random
import time
# Creating the window:
window = Tk()
window.title("Bounce")
window.geometry(... | 2021/01/09 | [
"https://Stackoverflow.com/questions/65643645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14915849/"
] | It is caused by close button on top-right corner of window, the only way you have to stop script. After you click close button, window destried, so no widget, like canvas, exist.
You can set a flag to identify if while loop should stop and exit in handler of window close button event.
```py
window.protocol("WM_DELETE... | I had this problem and solved it by restarting my iPython-console (Spyder) | 15,493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.