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 |
|---|---|---|---|---|---|---|
49,715,583 | I have this python code solving knapsack problem using dynamic programming.
this function returns the total cost of best subset but I want it to return the elements of best subset . can anybody help me with this?
```
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build t... | 2018/04/08 | [
"https://Stackoverflow.com/questions/49715583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238009/"
] | What you can do is instead of returning only K[n][W], return K
Then iterate K as :
```
elements=list()
dp=K
w = W
i = n
while (i> 0):
if dp[w][i] - dp[w - wt(i)][i-1] == val(i):
#the element 'i' is in the knapsack
element.append(i)
i = i-1 //only in 0-1 knapsack
w -=wt(i)
else:
i = i-1
... | You can add this code to the end of your function to work your way back through the items added:
```
res = K[n][W]
print(res)
w = W
for i in range(n, 0, -1):
if res <= 0:
break
if res == K[i - 1][w]:
continue
else:
print(wt[i - 1])
res = res - val[i - 1]
w = w - w... | 9,723 |
33,008,401 | How to define an attribute in a Python 3 enum class that is NOT an enum value?
```
class Color(Enum):
red = 0
blue = 1
violet = 2
foo = 'this is a regular attribute'
bar = 55 # this is also a regular attribute
```
But this seems to fail for me. It seems that Color tries to include foo and bar as... | 2015/10/08 | [
"https://Stackoverflow.com/questions/33008401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5421703/"
] | The point of the `Enum` type is to define enum values, so non-enum values are theoretically out of scope for this type. For constants, you should consider moving them out of the type anyway: They are likely not directly related to the enum values (but rather some logic that builds on those), and also should be a mutabl... | When building an `enum.Enum` class, **all** regular attributes become members of the enumeration. A different type of value does not make a difference.
By regular attributes I mean all objects that are not descriptors (like functions are) and excluded names (using single underscore names, see the [*Allowed members and... | 9,724 |
60,998,188 | I'm trying to write a python 3 code that prints out square matrix from user input. In addition the first row of this matrix must be filled by numbers from 1,n, the second row is the multiplication of the first row by 2, the third by 3, etc., until n-th row, which is created by the first row being multiplied by n. I was... | 2020/04/02 | [
"https://Stackoverflow.com/questions/60998188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111470/"
] | You can sore function in a List.
```
public class NeutralFactory: NPCFactory
{
private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> {
hp=> new Dwarf(hp),
hp=> new Fairy(hp),
hp=> new Elf(hp),
hp=> new Troll(hp),
hp=> new Orc... | To avoid having to write creation functions for each class, you can use `Activator.CreateInstance`:
```cs
using System;
using System.Collections.Generic;
namespace so60998181
{
public class Creature
{
public int hp;
public Creature()
{
this.hp = 100;
}
publi... | 9,725 |
60,579,544 | I have a frontend, which is hosted via Firebase. The code uses Firebase authentication and retrieves the token via `user.getIdToken()`. According to answers to similar questions that's the way to go.
The backend is written in Python, expects the token and verifies it using the firebase\_admin SDK. On my local machine,... | 2020/03/07 | [
"https://Stackoverflow.com/questions/60579544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110963/"
] | The error message makes it sound like the user of your client app is signed into a different Firebase project than your backend is working with. Taking the error message literally, the client is using "backend-appengine-project-name", but your backend is using "firebase-project-name". Make sure they are both configured... | ```
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
fin... | 9,730 |
44,669,963 | I'm only starting getting into a python from #C and I have this question that I wasn't able to find an answer to, maybe I wasn't able to form a question right
I need this to create two lists when using:**load(positives)** and **load(negatives)**, positives is a path to the file. From #C I'm used to use this kind of st... | 2017/06/21 | [
"https://Stackoverflow.com/questions/44669963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8192419/"
] | Integration with Spring and other frameworks available in Intellij IDEA Ultimate, but you're using Community Edition version which supports mainly Java Core features so there's no inspection capable of determining whether or not the field is assigned. | In recent versions of CE you can suppress these when @Autowired annotation is present, by using the light bulb (I'm using version 2022.2) | 9,731 |
33,169,619 | Having this:
```
a = 12
b = [1, 2, 3]
```
What is the most pythonic way to convert it into this?:
```
[12, 1, 12, 2, 12, 3]
``` | 2015/10/16 | [
"https://Stackoverflow.com/questions/33169619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468388/"
] | If you want to alternate between `a` and elements of `b`. You can use [`itertools.cycle`](https://docs.python.org/2/library/itertools.html#itertools.cycle) and `zip` , Example -
```
>>> a = 12
>>> b = [1, 2, 3]
>>> from itertools import cycle
>>> [i for item in zip(cycle([a]),b) for i in item]
[12, 1, 12, 2, 12, 3]
`... | You can use `itertools.repeat` to create an iterable with the length of `b` then use `zip` to put its item alongside the items of `a` and at last use `chain.from_iterable` function to concatenate the pairs:
```
>>> from itertools import repeat,chain
>>> list(chain.from_iterable(zip(repeat(a,len(b)),b)))
[12, 1, 12, 2,... | 9,732 |
52,821,996 | How to do early stopping in lstm.
I am using python tensorflow but not keras.
I would appreciate if you can provide a sample python code.
Regards | 2018/10/15 | [
"https://Stackoverflow.com/questions/52821996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9023836/"
] | You can do it Using `checkpoints`:
```
from keras.callbacks import EarlyStopping
earlyStop=EarlyStopping(monitor="val_loss",verbose=2,mode='min',patience=3)
history=model.fit(xTrain,yTrain,epochs=100,batch_size=10,validation_data=(xTest,yTest) ,verbose=2,callbacks=[earlyStop])
```
Training will stop when "val\_loss"... | You can find it with a little search
<https://github.com/mmuratarat/handson-ml/blob/master/11_deep_learning.ipynb>
```
max_checks_without_progress = 20
checks_without_progress = 0
best_loss = np.infty
....
if loss_val < best_loss:
save_path = saver.save(sess, './my_mnist_model.ckpt')
best_loss =... | 9,737 |
51,405,580 | I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error
```
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\be... | 2018/07/18 | [
"https://Stackoverflow.com/questions/51405580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7546921/"
] | The package is simply broken, as it is missing the `setup.py` file.
```
$ tar tzvf behave-parallel-1.2.4a1.tar.gz | grep setup.py
$
```
You might be able to download the source from Github or wherever and package it yourself (`python setup.py bdist_wheel`), then install that wheel (`pip install ../../dist/behave-par... | There is a newer feature for building python packages (see also [PEP 517](https://www.python.org/dev/peps/pep-0517/) and [PEP 518](https://www.python.org/dev/peps/pep-0518/)). A package can now be built without setup.py (with pyproject.toml), but older pip versions are not aware of this feature and raise the error show... | 9,738 |
2,332,773 | I am using newt/snack (a TUI graphical Widgit library for Python based on slang) to have some interactive scripts. However for some target terminals the output of those screens are not very nice. I can change the look of them by changing the `$TERM` variable to remove non printable characters, and to convert them to so... | 2010/02/25 | [
"https://Stackoverflow.com/questions/2332773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110488/"
] | short: no - it (newt and slang) simply doesn't **do** that.
long:
newt uses the function `SLsmg_draw_box` which is shown here for reference:
```
void SLsmg_draw_box (int r, int c, unsigned int dr, unsigned int dc)
{
if (Smg_Mode == SMG_MODE_NONE) return;
if (!dr || !dc) return;
This_Row = r; This_Col = ... | It might be based on your `$LANG` being set to something like `en_US.UTF-8`. Try changing it to `en_US` (assuming your base locale is `en_US`). | 9,744 |
41,454,563 | I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1))
Most ecosy... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41454563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970673/"
] | I toyed with an idea similar to how .net core web host waits for shutdown in console applications. I was reviewing it on GitHub and was able to extract the gist of how they performed the `Run`
<https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/WebHostExten... | I'm not sure it is production grade, but for a quick and dirty console app this works well:
```cs
await Task.Delay(-1); //-1 indicates infinite timeout
``` | 9,745 |
62,328,661 | I do understand that higher order functions are functions that take functions as parameters or return functions. I also know that decorators are functions that add some functionality to other functions. What are they exactly. Are they the functions that are passed in as parameters or are they the higher order functions... | 2020/06/11 | [
"https://Stackoverflow.com/questions/62328661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13675368/"
] | A higher order function is a function that takes a function as an argument OR\* returns a function.
A decorator in Python is (typically) an example of a higher-order function, but there are decorators that aren't (class decorators\*\*, and decorators that aren't functions), and there are higher-order functions that ar... | A higher-order function is a function that either takes a function as an argument or returns a function.
Decorator *syntax* is a syntactic shortcut:
```
@f
def g(...):
...
```
is just a convenient shorthand for
```
def g(...):
...
g = f(g)
```
As such, a decorator really is simply a function that takes a... | 9,755 |
59,505,322 | I am going through a Django tutorial but it's an old one. The videos were all made using Django 1.11 and Python 3.6. Problem is I have installed python3.8 in my machine. So I was trying to create virtualenv with python version 3.6. But as python 3.6 is not available in my machine, I couldn't do that. At this point I wa... | 2019/12/27 | [
"https://Stackoverflow.com/questions/59505322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11748245/"
] | It is possible to have two versions of python installed on the same machine. You might have to do some path manipulation to get things working, depending on the specifics of your setup. You can also probably just follow along with the tutorial using python 3.8 even if the tutorial it-self uses 3.6.
You can also use th... | Yes. You can have both versions installed on single machine. All u need to do is to download Python3.6 from its Official site, set your Interpreter to python3.6 and u r all set. | 9,756 |
25,502,666 | I want to execute a linux shell in python, for example:
```
import os
cmd='ps -ef | grep java | grep -v grep'
p=os.popen(cmd)
print p.read()
```
the code works well in python2.7,but it doesn't work well in python2.4 or python2.6
the problem is: when the environment is 2.4 or 2.6,for each process in linux it only re... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25502666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3978288/"
] | You're making an unwarranted assumption about the behavior of `read`. Use [subprocess.Popen](https://docs.python.org/2.7/library/subprocess.html#popen-objects) (and especially its `communicate` method) to read the whole thing. It was introduced in 2.4.
Use the string `splitlines` method as necessary if you want indivi... | `ps` usually clips its output according to the terminal width but, because you are piping the output to `grep`, `ps` can not determine the width, and so it determines that from various things such as the terminal type, environment variables, or command line options such as `--cols`.
You might find that you get differ... | 9,757 |
71,662,125 | Context
-------
The instructions on [the Linux/MacOS instructions](https://github.com/lava-nc/lava#linuxmacos) to setup your device for the Lava neuromorphic computing framework by Intel provide a few pip commands, a git clone command and some poetry instructions. I am used to be able to integrate `pip` commands in an... | 2022/03/29 | [
"https://Stackoverflow.com/questions/71662125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] | Just add the "slideUp" class in your HTML markup:
```
<div class="box slideUp">
```
NB: the `style="display: none;"` attribute on that element is then no longer needed, nor do you have to execute `$('.box').show()`.
Updated snippet:
```js
$(".openNav").click(function() {
$('.box').toggleClass("slideUp")
});
```
... | Try this code:
```js
$(".openNav").click(function() {
$('.box').slideToggle("fast");
});
```
```css
.clickbox {
width: 100px;
height: 100px;
background: #343434;
margin: 0 auto;
color: #fff;
}
.openNav {
color: #fff;
}
.box {
width: 200px;
height: 200px;
background: orange;
margin: 0 auto;
m... | 9,758 |
56,456,656 | I'm a newbie to data science with python. So, I wanted to play around with the following data "<https://www.ssa.gov/OACT/babynames/limits.html>." The main problem here is that instead of giving me one file containing the data for all years, it contains a separate file for each year. Furthermore, each separate file also... | 2019/06/05 | [
"https://Stackoverflow.com/questions/56456656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11557970/"
] | I saw people running into this issue on Windows by not realizing that in File Explorer file extensions are hidden by default, so while they wanted to create a file called "config", they actually created a file called "config.txt" and that's not found by kubectl. | I ended up deleting windows and install Ubuntu. Windows was a nightmare. | 9,763 |
53,421,991 | I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework. I am developing on a 2018 MacBook Pro. I am able to launch my web applications by launching them in the terminal using:
```
python3 manage.py runserver
```
However, I want to be able to launch my ap... | 2018/11/21 | [
"https://Stackoverflow.com/questions/53421991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644892/"
] | Use the command `virtualenv -p python3 venv` (or replace "venv" with your virtual environment name) in the terminal to create the virtual environment with python3 as the default when "python" is used in the terminal (e.g. `python manage.py ...`).
The `-p` is used to specify a specific version of python. | The issue was that I used the "python" command instead of the "python3" command when creating the virtual environment for my project. This was causing the debugger to execute the wrong command when trying run the local server. I was able to create a new virtual environment using the command ...
```
python3 -m venv env... | 9,766 |
860,140 | What is the best way to find out the user that a python process is running under?
I could do this:
```
name = os.popen('whoami').read()
```
But that has to start a whole new process.
```
os.environ["USER"]
```
works sometimes, but sometimes that environment variable isn't set. | 2009/05/13 | [
"https://Stackoverflow.com/questions/860140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83898/"
] | ```
import getpass
print(getpass.getuser())
```
See the documentation of the [getpass](https://docs.python.org/3/library/getpass.html) module.
>
> getpass.getuser()
>
>
> Return the βlogin nameβ of the user. Availability: Unix, Windows.
>
>
> This function checks the environment variables LOGNAME, USER,
> LNAME... | This should work under Unix.
```
import os
print(os.getuid()) # numeric uid
import pwd
print(pwd.getpwuid(os.getuid())) # full /etc/passwd info
``` | 9,769 |
2,664,099 | I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app re... | 2010/04/18 | [
"https://Stackoverflow.com/questions/2664099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use a two-way key encryption algorithms like RSA,
The password is stored encrypted (by a key, which is stored in the user's brain) on the filesystem, but to decode the password, the user must enter the key. | I don't think you are understanding the answers provided. You don't ever store a plain-text password anywhere, nor do you transmit it to another device.
>
> You wrote: Sorry, but the issue is storing a
> password on the file system... This
> password is needed to authenticate by
> the other web app.
>
>
>
You... | 9,770 |
49,524,189 | Comparing two lists is tough, there are numerous posts on this subject. But what if I have a list of lists? Simplified to extreme:
```
members=[['john',1964,'NY'], \
['anna',1991,'CA'], \
['bert',2001,'AL'], \
['eddy',1990,'OH']]
cash =[['john',200], \
['dirk',200], \
... | 2018/03/28 | [
"https://Stackoverflow.com/questions/49524189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8407665/"
] | You'll need a nested list comprehension. Additionally, you can get rid of punctuation using `re.sub`.
```
import re
data = ["How are you. Don't wait for me", "this is all fine"]
words = [
re.sub([^a-z\s], '', j.lower()).split() for i in data for j in nlp(i).sents
]
```
Or,
```
words = []
for i in data:
..... | There is a much simpler way for list comprehension.
You can first join the strings with a period '.' and split them again.
```
[x.split() for x in '.'.join(s).split('.')]
```
It will give the desired result.
```
[["How", "are","you"],["Don't", "wait", "for", "me"],["this","is","all","fine"]]
```
For Pandas datafr... | 9,780 |
18,423,941 | I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same ord... | 2013/08/24 | [
"https://Stackoverflow.com/questions/18423941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802136/"
] | If the input file is just as shown, and of the small size you mention, you can load the whole file in memory, make the substitutions, and then save it. IMHO, you don't need a RegEx to do this. The easiest to read code that does this is:
```
with open(filename) as f:
input= f.read()
input= str.replace('""','"')
inp... | I think you are overthinking the problem, why don't replace data?
```
l = list()
with open('foo.txt') as f:
for line in f:
l.append(line.replace('""','"').replace('"{','{').replace('}"','}'))
s = ''.join(l)
print s # or save it to file
```
It generates:
```
{"first_name":"John","last_name":"Smith","age... | 9,781 |
46,164,770 | Keywords [have to](https://mail.python.org/pipermail/python-dev/2012-March/117441.html) be strings
```
>>> def foo(**kwargs):
... pass
...
>>> foo(**{0:0})
TypeError: foo() keywords must be strings
```
But by some black magic, namespaces are able to bypass that
```
>>> from types import SimpleNamespace
>>> Sim... | 2017/09/11 | [
"https://Stackoverflow.com/questions/46164770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674039/"
] | >
> Could you implement a Python function that can receive integers in the kwargs mapping?
>
>
>
No, you can't. The Python evaluation loop handles calling functions defined in Python code differently from calling a callable object defined in C code. The Python evaluation loop code that handles keyword argument exp... | No, kwargs cannot be integers. This answer, however, is designed as a (very) short history lesson rather than technical answer (for that, please see @MartijnPierter's answer).
The check was originally added in 2010, in [issue 8419](https://bugs.python.org/issue8419) ([commit fb88636199c12f63d6c8c89f311cdafc91f30d2f](h... | 9,787 |
71,277,152 | ```
"127.0.0.1": {
"nmaprun": {
"@scanner": "nmap",
"@args": "nmap -v -sS -sV -sC -A -O -oX nmap 127.0.0.1 1-1024",
"@start": "1645467733",
"@startstr": "Mon Feb 21 23:52:13 2022",
"@version": "7.91",
"@xmloutputversion": "1.05",
... | 2022/02/26 | [
"https://Stackoverflow.com/questions/71277152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13668217/"
] | I would guess that `Contest` does not implement `IEquatable<Contest>` or otherwise override `Equals(object)`. Therefore `Assert.Equal` will only work when the objects are reference equal. If you don't want to do this, you can create your own `IEqualityComparer<Contest>` and use the overload `Assert.Equal(expectedRankin... | I'd suggest to use the [Fluent Assertions](https://fluentassertions.com/introduction) library for this kind of assert checks in unit tests. Instead of rigid equality, you are looking for *equivalency*.
Then your assert becomes:
```cs
input.Should().BeEquivalentTo(expectedRanking);
```
and this doesn't look for refe... | 9,789 |
9,921,976 | I have a list iteration in python defined like this:
```
for i in range(5):
for j in range(5):
if i != j:
print i , j
```
So for each element in my defined range [0..5] I want to get each element i, but also all other elements which are not i.
This code does exactly as I expect, but is there... | 2012/03/29 | [
"https://Stackoverflow.com/questions/9921976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220022/"
] | Use [`itertools.permutations`](http://docs.python.org/library/itertools.html#itertools.permutations):
```
import itertools as it
for i, j in it.permutations(range(5), 2):
print i, j
``` | [(x,y)for x in range(5) for y in range(5) if x!=y] | 9,790 |
48,339,383 | My python script is not running under my Crontab. But when i try to run it from the Terminal it works perfectly. I have placed this in the python script at the top:
```
#!/usr/bin/python
```
Also I tried:
```
#!/usr/bin/env python
```
I did my file executable:
```
chmod a+x vida.py
```
Added to my crontab and ... | 2018/01/19 | [
"https://Stackoverflow.com/questions/48339383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9239574/"
] | You should change you crontab line as such to get `stdout` and `stderr` saved to the file:
```
*/1 * * * * gg /usr/bin/python /home/gg/vida.py >> /home/gg/out1.txt 2>&1
```
Simply read `out1.txt` after crontab has run the line to see what's wrong
Edit after your comment:
Based on the error you've shared, I be... | syntax:
minutes hour dom mon dow user command
55 16 \* \* \* root /root/anaconda/bin/python /root/path/file\_name.py &>> /root/output/output.log | 9,791 |
65,699,603 | I want to use some function of ximgproc, so I uninstalled opencv-python and re-installed opencv-contrib-python
```
(venv) C:\Users\Administrator\PycharmProjects\eps>pip uninstall opencv-contrib-python opencv-python
Skipping opencv-contrib-python as it is not installed.
Uninstalling opencv-python-4.5.1.48:
Would remo... | 2021/01/13 | [
"https://Stackoverflow.com/questions/65699603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11702897/"
] | Can you check which packages you have intalled with `pip list`?
Even though you uninstalled opencv-python, you also need to uninstall `opencv-python-headless, opencv-contrib-python-headless` packages. As @skvark says
>
> never install both package
>
>
> | Install opencv and opencv-contrib modules separately.
Command for standard desktop environment:
```
$ pip install opencv-python opencv-contrib-python
``` | 9,792 |
13,262,575 | Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive.
The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively?
```
from multiprocessin... | 2012/11/07 | [
"https://Stackoverflow.com/questions/13262575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804903/"
] | Edit the [netbeans.conf](http://wiki.netbeans.org/FaqNetbeansConf) file (located in the /etc folder of your NetBeans installation), look for the line that starts with "netbeans\_default\_options=". Edit the fontsize parameter if present. If not, add something like "--fontsize 11" (without the quote) at the end of the l... | How about using a screen magnifier?
on Windows 7, [Sysinternals ZoomIt](https://technet.microsoft.com/en-us/sysinternals/zoomit.aspx) works fine.
Nearly every Linux desktop has one as well. | 9,793 |
74,327,541 | FAST CGI IS NOT WORKING PROPERLY IN DJANGO DEPLOYMENT ON IIS WINDOW SERVER
```
HTTP Error 500.0 - Internal Server Error
C:\Users\satish.pal\AppData\Local\Programs\Python\Python310\python.exe - The FastCGI process exited unexpectedly
Most likely causes:
β’IIS received the request; however, an internal error occurred ... | 2022/11/05 | [
"https://Stackoverflow.com/questions/74327541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17904860/"
] | As I see from your code, whenever you get an image from `imagePickerController` you store it into variable `self.image`. Then whenever you click Done you just upload this `self.image`
Make variable `self.image` can be nil then remember to unset it after uploading successfully
Code will be like this
```swift
var imag... | You are setting `self.image` if the user selects a photo.
But you are not *unsetting* `self.image` if the user *doesn't* select a photo. It needs to be set to `nil` (not to an empty `UIImage()`). | 9,803 |
59,705,956 | I'm working with `tensorflow-gpu` version `2.0.0` and **I have installed gpu driver and CUDA and cuDNN** (`CUDA version 10.1.243_426` and `cuDNN v7.6.5.32` and I'm using windows!)
When I compile my model or run:
```
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
```
It will ... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59705956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8342406/"
] | Taken from the official documentation of TensorFlow.
```
import tensorflow as tf
tf.debugging.set_log_device_placement(True)
# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
```
If ... | Have also noted that Windows Task Manager is not useful for monitoring GPU(dual) activity. Try installing TechPowerUp GPU-Z. (I am running dual NVidia cards). This monitors CPU and GPU activity, power and temperatures. | 9,804 |
23,968,716 | I am using the following code to get remote PC CPU percentage of usage witch is slow and loading the remote PC because of SSHing.
```
per=(subprocess.check_output('ssh root@192.168.32.218 nohup python psutilexe.py',stdin=None,stderr=subprocess.STDOUT,shell=True)).split(' ')
print 'CPU %=',float(per[0])
print 'MEM %=',... | 2014/05/31 | [
"https://Stackoverflow.com/questions/23968716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3693882/"
] | I would suggest taking look at Glances. It's written in python and can also be used for remote server monitoring:
<https://github.com/nicolargo/glances>
Using glances on remote server:
<http://mylinuxbook.com/glances-an-all-in-one-system-monitoring-tool/> | You don't need a custom Python script, since you can [have CPU usage directly with `top`](https://stackoverflow.com/a/9229692/240613), (or [with `sysstat`](https://stackoverflow.com/a/9229396/240613), if installed).
Have you **profiled** your app? Is it the custom script which is making it slow, or the SSHing itself? ... | 9,805 |
50,547,218 | Why does the python code below crash my website?
But the code at the very bottom does not crash the website
Here is the code that crashes the website:
```
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_l... | 2018/05/26 | [
"https://Stackoverflow.com/questions/50547218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9852457/"
] | You have a space between `url` and `patterns`. It should be all one word `urlpatterns`.
If you ever need to check the code for any of the other exercises in that book, they're all on github [here](https://github.com/ehmatthes/pcc). | I got to this point in the Crash Course, this area will break your site, temporarily. You will not have made all the files referenced in your code yet. In this case, you haven't made the urls.py file in learning\_logs. After this is made, you will not have updated your views.py nor made your index.html template. Keep g... | 9,807 |
73,793,403 | I frequently need to generate similar looking excel sheets for humans to read. Background colors and formatting should be similar. I'm looking to be able to read a template into python and have the values and cells filled in in Python.
It does not appear that xlsxwriter can read background color and formatting. It can... | 2022/09/20 | [
"https://Stackoverflow.com/questions/73793403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5775112/"
] | Fill color is fgColor per the OOXML specs "For solid cell fills (no pattern), fgColor is used".
You can get the color from about three attributes, all should provide the same hex value unless the fill is grey in which case the index/value is 0 and the grey content is determined by tint
```
for cell in ws['A']:
... | There were no openstack answers I could find about reading existing background color formatting. The answers I did find were about formatting of the cell into things like percentage or currency.
Here is a solution I've found for background cell color from the openpyxl documentation, though fill color was not explicit ... | 9,808 |
55,095,983 | I'm having some trouble with the `replace()` function in python. Here is my code :
```
string = input()
word = string.find('word')
if word >= 1:
string = string.replace('word', 'word.2')
print(string)
```
The output gives `word`. Shouldn't it be `word.2`?
I'm confused. Any help?
Edit: After playing around with ... | 2019/03/11 | [
"https://Stackoverflow.com/questions/55095983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11182783/"
] | Instead of
```
word >= 1
```
write
```
word >= 0
```
string.find() returns the first occurence of the word. If your string is 'word' and you find 'word', it'll return 0 as the word 'word' occurs at index 0 first.
In python, arrays start at 0. The first character in a string is at index 0.
Therefore, 'word' in ... | There is no need to use the find function, just do:
```
string = input()
string = string.replace('word', 'word.2')
```
But nevertheless, if i ran it in Python3, your code is correct ;-)
How does your input look like? | 9,809 |
54,093,253 | I've been trying to work with BeautifulSoup because I want to try and scrape a webpage (<https://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1>). So far I scraped some elements with success but now I wanted to scrape a movie description but I've been struggling. The description is simply situat... | 2019/01/08 | [
"https://Stackoverflow.com/questions/54093253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9441232/"
] | >
> [find\_all()](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all) method looks through a tagβs descendants and retrieves
> all descendants that match your filters.
>
>
>
You can then use the list's index to get the element you need. Index starts at 0, so 1 will give the second item.
Change the f... | Just playing around with `.next_sibling` was able to get it. There's probably a more elegant way though. At least might give you a start/some direction
```
from bs4 import BeautifulSoup
html = '''<div class="lister-item mode-advanced">
<div class="lister-item-content>
<p class="muted-text"> paragraph I d... | 9,812 |
64,754,032 | I am trying to use SageMaker script mode for training a model on image data. I have multiple scripts for data preparation, model creation, and training. This is the content of my working directory:
```
WORKDIR
|-- config
| |-- hyperparameters.json
| |-- lossweights.json
| `-- lr.json
|-- dataset.py
|-- densenet.... | 2020/11/09 | [
"https://Stackoverflow.com/questions/64754032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7697327/"
] | If you don't mind switching from TF 1.14 to TF 1.15.2+, you'll be able to bring a local code directory containing your custom modules to your SageMaker TensorFlow Estimator via the argument `source_dir`. Your entry point script shall be in that `source_dir`. Details in the SageMaker TensorFlow doc: <https://sagemaker.r... | This isn't exactly what the questioner asked but if anyone has come here wanting to know how to use custom libraries with SKLearn you can use `dependencies` as an argument like in the following:
```
import sagemaker
from sagemaker.sklearn.estimator import SKLearn
sess = sagemaker.Session()
role = sagemkaer.get_execut... | 9,814 |
62,097,219 | I am trying to connect to Google Sheets' API from a Django view. The bulk of the code I have taken from this link:
<https://developers.google.com/sheets/api/quickstart/python>
Anyway, here are the codes:
**sheets.py** (Copy pasted from the link above, function renamed)
```
from __future__ import print_function
impor... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056347/"
] | You shouldn't be using [Flow.run\_local\_server()](https://github.com/googleapis/google-auth-library-python-oauthlib/blob/v0.4.1/google_auth_oauthlib/flow.py#L408) unless you don't have the intention of deploying the code. This is because `run_local_server` launches a browser on the server to complete the flow.
This w... | The redirect URI tells Google the location you would like the authorization to be returned to. This must be set up properly in google developer console to avoid anyone hijacking your client. It must match exactly.
To to [Google developer console](https://console.developers.google.com/). Edit the client you are curren... | 9,815 |
24,204,582 | I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called Ra... | 2014/06/13 | [
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] | Both Numpy and the internal random generators have instantiatable classes.
For just `random`:
```
import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072
```
And for Numpy:
```
import numpy
random_generator = numpy.random.RandomState()
random_generator.uniform(0, 1, 10)
#... | Veedrac's answer did not address how one might generate independent streams.
The best way I could find to generate independent streams is to use a replacement for numpy's RandomState. This is provided by the [RandomGen package](https://bashtage.github.io/randomgen/index.html).
It supports [independent random streams]... | 9,818 |
38,430,491 | I'm writing a Python application that needs to fetch a Google document from Google Drive as markdown.
I'm looking for ideas for the design and existing open-source code.
As far as I know, Google doesn't provide export as markdown. I suppose this means I would have to figure out, which of the available download/export... | 2016/07/18 | [
"https://Stackoverflow.com/questions/38430491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852140/"
] | You might want to take a look at [Pandoc](http://pandoc.org/ "Pandoc") which supports conversions i.e. from docx to markdown. There are several Python wrappers for Pandoc, such as [pypandoc](https://pypi.python.org/pypi/pypandoc/ "pypandoc").
After fetching a document from Google Drive in docx format, the conversion i... | Google Drive offers a "Zipped HTML" export option.
[](https://i.stack.imgur.com/BosJ2.png)
Use the [Python module `html2text`](https://pypi.python.org/pypi/html2text) to convert the HTML into Markdown.
>
> html2text is a Python script that converts... | 9,827 |
9,753,885 | I'd like to have the matplotlib "show" command return to the command line
while displaying the plot. Most other plot packages, like R, do this.
But pylab hangs until the plot window closes. For example:
```
import pylab
x = pylab.arange( 0, 10, 0.1)
y = pylab.sin(x)
pylab.plot(x,y, 'ro-')
pylab.show() # Python hang... | 2012/03/17 | [
"https://Stackoverflow.com/questions/9753885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647331/"
] | Add `pylab.ion()` ([interactive mode](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ion)) before the `pylab.show()` call. That will make the UI run in a separate thread and the call to `show` will return immediately. | You need to run it as
```
$ ipython --pylab
```
and run your code as
```
In [8]: x = arange(0,10,.1)
In [9]: y = sin(x)
In [10]: plot(x,y,'ro-')
Out[10]: [<matplotlib.lines.Line2D at 0x2f2fd50>]
In [11]:
```
This gives you the prompt for cases where you would want to modify other parts or plot more. | 9,828 |
52,711,988 | I'm having trouble using Pipenv on my Windows 10 machine. Initially, I got a timeout error while trying to run `pipenv install <module>` and following [this answer](https://stackoverflow.com/a/52509038/5535114), I disabled Windows Defender.
That got rid of the timeout error and it then seems to successfully install th... | 2018/10/09 | [
"https://Stackoverflow.com/questions/52711988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535114/"
] | Finally solved it. This is current issue, with a [workaround](https://github.com/pypa/pipenv/issues/2924#issuecomment-427383459) for Windows:
`pipenv run python -m pip install -U pip==18.0` | I got the same problem . It looks like problem happen with pip18.1 . However, you are using pip 18.0 . By the way,
I solved by these commands . You can try it.
`pipenv run pip install pip==18.0
pipenv install`
Reference:
<https://github.com/pypa/pipenv/issues/2924> | 9,829 |
33,845,726 | For example this is my simple python code to send e-mail:
```
import smtplib
import getpass
mail = "example@example.com"
passs = getpass.getpass("pass: ")
sendto = "example1@example2.com"
title = "Subject: example\n"
body = "blabla\n"
msg = title + body
send = smtplib.SMTP("smtp.example.com",587)
send.ehlo()
send.star... | 2015/11/21 | [
"https://Stackoverflow.com/questions/33845726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848384/"
] | The simplest way is to ask for its `description`:
```
cell.priceLabel.text = productPrice.price.description;
```
(All those answers that suggest formatting with `"%@"` are using `description`, indirectly.)
But if it's a price, you probably want to format it like a price. For example, in the USA, prices in US dollar... | A UILabel expects its text value to be an NSString, so you need to create a string using the value of product.price.
```
cell.priceLabel.text = [NSString stringWithFormat:@"%@", product.price];
```
What's important is that you can't simply cast (change) the type of NSDecimalNumber, you have to convert the value in s... | 9,832 |
12,665,574 | I'm working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
```
>>> a = [1,2,3]
>>> a
[1,2,3]
```
what I'm getting, essentially:
```
>>> a = MyList([1,2,3])
>>> a
<MyList object at 0xdeadbeef>
```
I can't figure out which... | 2012/09/30 | [
"https://Stackoverflow.com/questions/12665574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212685/"
] | You should override the `__repr__` method in you class (and optionally the `__str__` method too), see this [post](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) for a discussion on the differences.
Something like this:
```
class MyList(object):
def __repr__(self):
#... | Allow me to answer my own question - I believe it's the \_\_ repr \_\_ method that I'm looking for. Please correct me if i'm wrong. Here's what I came up with:
```
def __repr__(self):
return str([i for i in iter(self)])
``` | 9,833 |
55,564,014 | I am unable to import the tensorflow 2.0 module into my code i end up getting this error
```
Traceback (most recent call last):
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Us... | 2019/04/07 | [
"https://Stackoverflow.com/questions/55564014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11258767/"
] | I think you hit [this bug](https://github.com/tensorflow/tensorflow/issues/22794).
You can downgrade tensorflow to `v1.10.0`
```
pip install tensorflow-gpu==1.10.0
```
or make sure that you have these versions for CUDA, Tensorflow and CUDNN:
* CUDA v9.0
* tensorflow-gpu v1.12.0
* CUDNN 7.4.1.5
Alternatively, yo... | tensorflow 2.0 is now officially available. You can retry. This time it should work without any errors, if CUDA and CuDNN are properly installed. | 9,838 |
63,160,976 | I am trying to split my nested list of strings into nested lists of floats. My nested list is below:
```
nested = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]
```
My desired output would be a nested list where these values remain in their sublist and are converted to floats as seen belo... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63160976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13984141/"
] | ```
result = [[float(t) for s in sublist for t in s.split(', ')] for sublist in nested]
```
which is equivalent to
```
result = []
for sublist in nested:
inner = []
for s in sublist:
for t in s.split(', '):
inner.append(float(t))
result.append(inner)
``` | OK, starting with your example:
myNestedList = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]
```
myOutputList = []
for subList in myNestedList:
tempList = []
for valueStr in sublist:
valueFloat = float( valueStr )
tempList.append( valueFloat )
myOutputList.appe... | 9,839 |
54,901,493 | i have problem with my code when i want signup error appear `Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'` , i try solotion of other questions same like [Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'](https://stackoverflow.com/questions/17873855/manager... | 2019/02/27 | [
"https://Stackoverflow.com/questions/54901493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10642829/"
] | Modify views.py
```
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
```
to
```
from .forms impo... | In your forms.py make changes as:
```
from django.contrib.auth import get_user_model
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
... | 9,841 |
14,447,202 | Heroku seems to prefer the apps deployed have a certain structure, mostly that the .git and manage.py is at root level and everything else is below that.
I have inherited a Django app I'm trying to deploy for testing purposes and I don't think I can restructure it so I was wondering if I have an alternative.
The stru... | 2013/01/21 | [
"https://Stackoverflow.com/questions/14447202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998312/"
] | Just in case someone else has this trouble, my findings are:
There is nothing to solve -- the sandbox is just really slow, sometimes it took a couple days for the profile to become active and send the IPN. In other words, sandbox isn't good to test these functions at all, just go live and refund a couple tests. Even l... | From PayPal doco:
"By default, PayPal does not activate the profile if the initial payment amount fails. To override this default behavior, set the FAILEDINITAMTACTION field to ContinueOnFailure. If the initial payment amount fails, ContinueOnFailure instructs PayPal to add the failed payment amount to the outstanding... | 9,842 |
25,317,140 | I may be going about this the wrong way but that's why I'm asking the question.
I have a source of serial data that is connected to a SOC then streams the serial data up to a socket on my server over UDP. The baud rate of the raw data is 57600, I'm trying to use Python to receive and parse the data. I tested that I'm ... | 2014/08/14 | [
"https://Stackoverflow.com/questions/25317140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993775/"
] | You can't treat a socket as a serial line. A socket can only send and receive data (data stream for TCP, packets for UDP). If you would need a facility to control the serial line on the SOC you would need to build an appropriate control protocol over the socket, i.e. either use another socket for control like FTP does ... | Build on facts
--------------
A first thing to start with is to summarise facts -- **begining from the very SystemOnChip** (SOC) all the way up ...:
1. an originator serial-bitstream parameters ::= **57600** Bd, **X**-<*dataBIT*>-s, **Y**-<*stopBIT*>, **Z**-<*parityBIT*>,
2. a mediator receiving process de-framing <*... | 9,843 |
61,831,953 | I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
``... | 2020/05/16 | [
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] | If you're not avert to using external packages, [`pandas.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame) might be a viable candidate since it looks like you'll be using a table:
```
import pandas as pd
df = pd.DataFrame(
index=pd.MultiIndex.from_pro... | Yes, you can achieve this using the following code:
```
import copy
structure = ['weather', 'season', 'lateness']
data = {'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed'], }
d_tree = dict()
n = len(structure) # length of the structure list
p... | 9,844 |
37,912,206 | Given a list:
```
l1 = [0, 211, 576, 941, 1307, 1672, 2037]
```
What is the most pythonic way of getting the index of the last element of the list. Given that Python lists are zero-indexed, is it:
```
len(l1) - 1
```
Or, is it the following which uses Python's list operations:
```
l1.index(l1[-1])
```
Both ret... | 2016/06/19 | [
"https://Stackoverflow.com/questions/37912206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3096712/"
] | Only the first is correct:
```
>>> lst = [1, 2, 3, 4, 1]
>>> len(lst) - 1
4
>>> lst.index(lst[-1])
0
```
However it depends on what do you mean by "the index of the last element".
Note that `index` must traverse the whole list in order to provide an answer:
```
In [1]: %%timeit lst = list(range(100000))
...: ls... | You should use the first. Why?
```
>>> l1 = [1,2,3,4,3]
>>> l1.index(l1[-1])
2
``` | 9,851 |
41,788,056 | I am following [this tutorial](https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python) on setting up cloud endpoints in python on googles app engine and keep on getting an import error
```
ImportError: No module named control
```
on the **Generating the OpenAPI configuration file**... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41788056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5327279/"
] | You have to indent all the statements after your while loops and a single iteration version of your program should work. Proper indentation is critical in python. Lots of sites talk about python indentation (see [here](http://www.peachpit.com/articles/article.aspx?p=1312792&seqNum=3) for example). You were also missing... | First, you have to do your indentation correctly in the while-loop.
Second, your while loop only create the lists, `xs` and `ys`. That's why you can't keep the prompt and plot running again and again. So you have to use another loop to repeat your code above. Here is an example.
```
import matplotlib.pyplot as plt
imp... | 9,854 |
1,756,721 | I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packag... | 2009/11/18 | [
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] | In case of upgrading your python on mac os 10.7 and pkg\_resources doesn't work, the simplest way to fix this is just reinstall setuptools as Ned mentioned above.
```
sudo pip install setuptools --upgrade
or sudo easy_install install setuptools --upgrade
``` | Try this only if you are ok with uninstalling python.
I uninstalled python using
```
brew uninstall python
```
then later installed using
```
brew install python
```
then it worked! | 9,855 |
42,838,366 | I think this question has been asked many times, but I can't find the answer. I am probably not using the correct words in my searches.
I am a beginner in python and I am learning to make simple games, with the pygame library. I would like to create a variable `character`, containing x and y coordinates.
I would like ... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42838366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682871/"
] | You could use a dictionary like this:
```
character = {'Name': 'Mary', 'xPos': 0, 'yPos': 0}
character['xPos'] = 10
``` | You can use dictionary.
```
character = dict()
character['x']= default_value
character['y']= default_value
```
You might want to have a look at this [Documentation](https://learnpythonthehardway.org/book/ex39.html) | 9,865 |
39,919,586 | I know this is probably really easy question, but i'm struggling to split a string in python. My regex has group separators like this:
```
myRegex = "(\W+)"
```
And I want to parse this string into words:
```
testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", te... | 2016/10/07 | [
"https://Stackoverflow.com/questions/39919586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5613356/"
] | As described in this answer, [How to split but ignore separators in quoted strings, in python?](https://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python), you can simply slice the array once it's split. It's easy to do so because you want every other member, starting wi... | You can simly do:
```
testAgain = testString.split() # built-in split with space
```
Different `regex` ways of doing this:
```
testAgain = re.split(r"\s+", testString) # split with space
testAgain = re.findall(r"\w+", testString) # find all words
testAgain = re.findall(r"\S+", testString) # find all non space ch... | 9,868 |
21,458,037 | I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate... | 2014/01/30 | [
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] | I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
`... | You can randomly switch the values :
```
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < ... | 9,869 |
72,521,192 | Given a reproducible dataframe, I want to find the number of unique values in each column not including missing (NA) values. Below code counts NA values, as a result the cardinality of `nat_country` column shows as 4 in `n_unique_values` dataframe (it is supposed to be 3). In python there exists `nunique()` function wh... | 2022/06/06 | [
"https://Stackoverflow.com/questions/72521192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10617194/"
] | You can use `dplyr::n_distinct` with `na.rm = T`:
```r
library(dplyr)
sapply(dat, n_distinct, na.rm = T)
#map_dbl(dat, n_distinct, na.rm = T)
#nat_country age
# 3 8
```
---
In base R, you can use `na.omit` as well:
```r
sapply(dat, \(x) length(unique(na.omit(x))))
#nat_country ... | We could use `map` or `map_dfr` with `n_distinct`:
```
library(dplyr)
library(purrr)
dat %>%
map_dfr(., n_distinct, na.rm = TRUE)
nat_country age
<int> <int>
1 3 8
```
```
library(dplyr)
library(purrr)
dat %>%
map(., n_distinct, na.rm = TRUE) %>%
unlist()
```
```
nat_country ... | 9,879 |
41,604,223 | I am trying to read N lines of file in python.
This is my code
```
N = 10
counter = 0
lines = []
with open(file) as f:
if counter < N:
lines.append(f:next())
else:
break
```
Assuming the file is a super large text file. Is there anyway to write this better. I understand in production cod... | 2017/01/12 | [
"https://Stackoverflow.com/questions/41604223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1939166/"
] | try using
`gem install nokogiri -v 1.7.0.1 -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/libxml2` | try:
gem update --system
then:
xcode-select --install
then:
gem install nokogiri
and finally:
install the rails gem | 9,882 |
68,368,323 | I want to run a Macro with python. I am doing:
```
import win32com.client as w3c
def ejecuntar_macro():
xlApp_mrapp = w3c.Dispatch("Excel.Application")
pw_str = str('Plantilla123')
mrapp = r'D:\Proyectos\Tablero estados\Tablero.xlsm'
xlApp_mrapp.Visible = True
xlApp_mrapp.DisplayAlerts = False
... | 2021/07/13 | [
"https://Stackoverflow.com/questions/68368323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16053579/"
] | Use `text-align: center;`
Link: <https://developer.mozilla.org/en-US/docs/Web/CSS/text-align>
```html
<div style="text-align:center; width: 150px;">
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore... | Give the property `text-align: center` to the element containing the text. | 9,883 |
60,306,244 | We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.
Lets say we have a table named `table1`
Steps:
```
1. Query database to get ddl for table1.
2. Get ddl... | 2020/02/19 | [
"https://Stackoverflow.com/questions/60306244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768610/"
] | This is not currently supported, but I am 80% sure it is in the roadmap.
An alternative would be to use the SDK to create the same pipeline using `ModuleStep` where I *believe* you can reference a Designer Module by its name to use it like a `PythonScriptStep` | The export Designer graph to notebook is in our roadmap. For now, please take a look at the ModuleStep in SDK and let us know if you have any questions.
Thanks,
Lu Zhang | Senior Program Manager | Azure Machine Learning | 9,886 |
2,859,081 | I'm trying to create a database connection in a python script to my DB2 database. When the connection is done I've to run some different SQL statements.
I googled the problem and has read the ibm\_db API (<http://code.google.com/p/ibm-db/wiki/APIs>) but just can't seem to get it right.
Here is what I got so far:
```... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2859081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188082/"
] | it should be:
```
query_str = "SELECT COUNT(*) FROM accounts"
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt)
``` | I'm sorry, of cause you need to error message. When trying to run my script it gives me this error:
```
Traceback (most recent call last):
File "test.py", line 16, in <module>
ibm_db.execute(query_stmt, "SELECT COUNT(*) FROM accounts")
Exception: Param is not a tuple
```
I'm pretty sure that it is my parameter... | 9,889 |
69,818,851 | I am running a simple React/Django app with webpack that is receiving this error on build:
```
ERROR in ./src/index.js
Module build failed (from ./node_modules/eslint-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'getFormatter')
at getFormatter (**[Relative path]**/frontend/node_modu... | 2021/11/03 | [
"https://Stackoverflow.com/questions/69818851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7359966/"
] | eslint-loader is deprecated:
<https://www.npmjs.com/package/eslint-loader>
You may use eslint-webpack-plugin instead:
<https://www.npmjs.com/package/eslint-webpack-plugin> | I found an issue <https://github.com/webpack-contrib/eslint-loader/issues/331> about this in the eslint-loader github, but I don't know if it will be useful for you.
. It would help to have a git repository to store the code that would be wrong for better testing. :) | 9,890 |
51,113,531 | I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
de... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] | I had same issue recently and the problems goes away using any advanced editor and changing line ending to unix style on sh entrypoint scripts.
In my case, not sure why, because git handle it very well depending on linux or windows host I ended up in same situation.
If you have files mounted in container and host(in w... | Do not use -d at the end.
Instead of this command
**docker-compose -f start\_tools.yaml up βd**
Use
**docker-compose -f start\_tools.yaml up** | 9,894 |
63,694,387 | The below is a selenium python code where I am trying to click Sign In by sending the login details via selenium. However, when I am using `find_element_by_id` method to locate the username and password input area the scripts throws an error
`Message: no such element: Unable to locate element: {"method":"css selector",... | 2020/09/01 | [
"https://Stackoverflow.com/questions/63694387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8599554/"
] | don't initialized the variables. use the `nillable` attribute and set it value to `true`
```
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "currencyCode", "discountValue", "setPrice" })
@XmlRootElement(name = "countryData")
public class CountryData {
@XmlElement(nillable=true)
protect... | Although the strings are empty they still contain non-null data and the end tag is generated. Remove the default values of the strings or set them as `null` (a default instance field value):
```
protected String discountValue;
protected String setPrice;
```
The tags become closed:
```
<discountValue/>
<setPrice/>
... | 9,904 |
1,736,655 | Before resorting to stackoverflow, i have spend a lot of times looking for the solutions. I have been a linux-user/developer for few years, now shifting to windows-7.
I am looking for seting-up a development environment (mainly c/c++/bash/python) on my windows machine. Solutions i tired -
* VirtuaBox latest, with ... | 2009/11/15 | [
"https://Stackoverflow.com/questions/1736655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132597/"
] | Here is what I do for Python development on Windows:
* EasyEclipse for Python (includes eclipse, subclipse, pydev)
* GNU Win32 [Native Windows ports for GNU tools](http://gnuwin32.sourceforge.net/)
* Vim and Emacs (for non-IDE editing work) | The following suggestions hold if you are not going to do complex template programming as the c++ IDE's other than visual studio SUCK, they cannot efficiently index modern C++ code (the boost library).
I would suggest using Netbeans (it has far better support for C++ than eclipse/CDT) with the following two build envi... | 9,905 |
16,648,670 | I am developing the structure of the MySQL database and I've faced a small decisional problem about its structure.
I have 2 tables:
1. All messages published on the site.
2. All comments published on the site.
Every message can have more than one comment associated to it.
What is a better way to make connection bet... | 2013/05/20 | [
"https://Stackoverflow.com/questions/16648670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/656100/"
] | The first option is the way to go. So you'll have:
comment\_id | message\_id | comment\_text | timestamp etc.
For your MySQL table you can specify to build the index over the first two columns for good performance.
10Mio Comments should work OK, but you could test this in advance with a test scenario yourself.
If... | Option one is the best approach. You'll want an index on the `message_id` column in the comments table. This allows MySQL to quickly and efficiently pull out all the comments for a particular message, even when there are hundreds of thousands of comments. | 9,915 |
71,607,064 | In openai.py the Completion.create is highlighting as alert and also not working.. the error is right down below.. whats the problem with the code
```
response = openai.Completion.create(
engine="text-davinci-002",
prompt="Generate blog topic on: Ethical hacking",
temperature=0.7,
max_tokens=256,
t... | 2022/03/24 | [
"https://Stackoverflow.com/questions/71607064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16521679/"
] | for my fellow doofuses going thru all the above suggestions and wondering why its not working:
make sure your file is NOT named `openai.py`. because then it will call itself, because python.
wasted 2 hours on this nonsense lol.
relevant link [How to fix AttributeError: partially initialized module?](https://stackove... | Try this,
engine="davinci" | 9,916 |
57,449,963 | I want to install ansible in RHEL 8 Centos.
To use yum install ansible i must enable epel release but i can't find a best source of epel release for Rhel 8.
**I tried this**
```
sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo yum install ansible
```
**The output i got ... | 2019/08/11 | [
"https://Stackoverflow.com/questions/57449963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7179457/"
] | EPEL8 is not released yet. There are some packages available, but a lot are still being worked on and the repo is not considered "generally available".
For now, you can install Ansible from the Python Package Index (PyPI):
```
yum install python3-pip
pip3 install ansible
``` | If you are using RHEL 8 then you can use the subscription manager to get Ansible with the host and config file pre-built.
Also, you will need to create an account on <https://developers.redhat.com> before you can do this:
```
subscription-manager register --auto-attach
subscription-manager repos --enable ansible-2.8... | 9,919 |
7,330,279 | I am writing a python interface to a c++ library and am wondering about the correct design of the library.
I have found out (the hard way) that all methods passed to python must be declared static. If I understand correctly, this means that all functions basically must be defined in the same .cpp file. My interface ha... | 2011/09/07 | [
"https://Stackoverflow.com/questions/7330279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446137/"
] | >
> I have found out (the hard way) that all methods passed to python must
> be declared static. If I understand correctly, this means that all
> functions basically must be defined in the same .cpp file. My
> interface has many functions, so this gets ugly very quickly.
>
>
>
Where did you find this out? It is... | Why do you say that all functions called by Python have to be
static? It's usual for that to be the case, in order to avoid
name conflicts (since any namespace, etc. will be ignored
because of the `extern "C"`), but whether the function is static
or not is of no consequence.
When interfacing a library in C++, in my e... | 9,922 |
7,542,421 | [Python Challenge #2](http://www.pythonchallenge.com/pc/def/ocr.html)
[Answer I found](http://ymcagodme.blogspot.com/2011/04/python-challenge-level-2.html)
```
FILE_PATH = 'l2-text'
f = open(FILE_PATH)
print ''.join([ t for t in f.read() if t.isalpha()])
f.close()
```
Question: Why is their a 't' before the for lo... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7542421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/963081/"
] | `[t for t in f.read() if t.isalpha()]` is a list comprehension. Basically, it takes the given iterable (`f.read()`) and forms a list by taking all the elements read by applying an optional filter (the `if` clause) and a mapping function (the part on the left of the `for`).
However, the mapping part is trivial here, th... | This is a [list comprehension](http://www.python.org/doc//current/tutorial/datastructures.html#list-comprehensions), not a `for`-loop.
>
> List comprehensions provide a concise way to create lists.
>
>
>
```
[t for t in f.read() if t.isalpha()]
```
This creates a [`list`](http://www.python.org/doc//current/tuto... | 9,923 |
57,077,432 | I was trying to add two tuples two create a new sort of nested tuple using the coerce function of python.
I'm using python version 3.7 which is showing that the function isn't defined.
It is supposed to be a built-in function in python | 2019/07/17 | [
"https://Stackoverflow.com/questions/57077432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11797954/"
] | Including `Building` will also include `MultiApartmentBuilding` entries (in fact all types deriving from `Building`).
You can use C# 7.0's pattern matching to test and cast at the same time (where `apartments` is the result of the query):
```
foreach (Apartment apartment in apartments) {
// Access common Building... | You can't access the child's class attributes. In other words, if you have a Building, you can't access its **MultiApartmentBuilding** attributes, because you don't even know if it really is a **MultiApartmentBuilding**.
What I would do in this case would be to change your **Apartment** class and use the type **MultiA... | 9,926 |
24,452,972 | Would like to extract all the lines from first file (GunZip \*.gz i.e Input.csv.gz), if the first file 4th field is falls within a range of
Second file (Slab.csv) first field (Start Range) and second field (End Range) then populate Slab wise count of rows and sum of 4th and 5th field of first file.
Input.csv.gz (GunZ... | 2014/06/27 | [
"https://Stackoverflow.com/questions/24452972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3350223/"
] | Here is one way using `awk` and `sort`:
```
awk '
BEGIN {
FS = OFS = SUBSEP = ",";
print "StartRange,EndRange,Count,Sum-4,Sum-5"
}
FNR == 1 { next }
NR == FNR {
ranges[$1,$2]++;
next
}
{
for (range in ranges) {
split(range, tmp, SUBSEP);
if ($4 >= tmp[1] && $4 <= tmp[2]) {
... | Here is another option using `perl` which takes benefits of creating multi-dimensional arrays and hashes.
```
perl -F, -lane'
BEGIN {
$x = pop;
## Create array of arrays from start and end ranges
## $range = ( [0,0] , [1,10] ... )
(undef, @range)= map { chomp; [split /,/] } <>;
@ARGV = $x;
}
## ... | 9,927 |
44,335,494 | So I downloaded Deuces, code for poker hand evaluations, and originally I think it was in Python 2, because all of the print statements had no parentheses. I fixed all of those, and everything seems to work, except this last part. Here is the code for it:
```
def get_lexographically_next_bit_sequence(self, bits):
... | 2017/06/02 | [
"https://Stackoverflow.com/questions/44335494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8062387/"
] | In accord with Arrivillaga's comment I had just modified what you had posted to this.
```
def get_lexographically_next_bit_sequence(bits):
"""
Bit hack from here:
http://www-graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation
Generator even does this in poker order rank
so no need to ... | It was the / symbol, as the gentleman said above it is supposed to be for floor division, and quick fix and it works fine. | 9,928 |
69,217,390 | I'm trying to build a website in python and flask however my CSS is not loading I don't see anything wrong with my code and I've tried the same code snippet from a few different sites.
My Link:
```html
<link rel="stylesheet" href="{{ url_for('static', filename= 'css/style.css') }}">
```
File structure as below:
[!... | 2021/09/17 | [
"https://Stackoverflow.com/questions/69217390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11386215/"
] | The problem was probably with the numpy function 'percentile' and how I passed in my argument to the find\_outliers\_tukey function. So these changes worked for me
step 1
======
1. Include two arguments; one for the name of df, another for the name of the feature.
2. Put the feature argument into the df explicitly.
3... | For Question 1, your code seems to work fine on my end, but of course I don't have your original data.
For Question 2, there are two problems. The first is that you are passing the column *names* to `find_outliers_tukey` instead of the columns themselves. Use `iteritems` to iterate over pairs of `(column name, column ... | 9,929 |
54,695,126 | I am trying to parse a webpage and print the link for items(href).
Can you help with where am i going wrong?
```
import requests
from bs4 import BeautifulSoup
link = "https://www.amazon.in/Power-
Banks/b/ref=nav_shopall_sbc_mobcomp_powerbank?ie=UTF8&node=6612025031"
def amazon(url):
sourcecode = requests.get(ur... | 2019/02/14 | [
"https://Stackoverflow.com/questions/54695126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4992020/"
] | You can though add headers. Then also when you do `find_all('a')`, you can just get it there is href:
```
import requests
from bs4 import BeautifulSoup
link = "https://www.amazon.in/Power-Banks/b/ref=nav_shopall_sbc_mobcomp_powerbank?ie=UTF8&node=6612025031"
def amazon(url):
headers = {'User-Agent': 'Mozilla/5.0... | If you tried to scrape Amazon right now with `requests` you won't get anything in return since Amazon will know that it's a script, and headers won't help it (as far as I know).
Instead, in response they will tell the following:
```
To discuss automated access to Amazon data please contact api-services-support@amazon... | 9,930 |
52,788,039 | I'm given a task to convert a **Perl script to Python**.
I'm really new to Perl and understanding it where I came across a command line option which is `-Sx`.
There is good documentation provided for these parameters in Perl. But there is no much documentation for the same in python (Didn't find much info in Python ... | 2018/10/12 | [
"https://Stackoverflow.com/questions/52788039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10496576/"
] | Questions I asked in a comment:
>
> Have you thought about if that bit of shell you were asking about is really necessary for what you're doing? Or are you just trying to blindly translate without understanding what things are doing?
>
>
>
I'm pretty sure the answers are no and yes respectively. That's not a go... | The following snippet is used to support ancient systems that predate the existence of `python`:
```
#!/bin/sh
exec perl -Sx $0 ${1+"$@"}
if 0;
```
Now, [it appears](https://stackoverflow.com/questions/52785232/what-does-exec-perl-perl-sx-0-1-mean-in-shell-script) that you are dealing with a bastardized and modif... | 9,932 |
48,466,337 | I have been working on creating a python GUI for some work. I would self-describe as a novice when it comes to by Python knowledge. I am using wxPython and wxGlade to help with the GUI development, as well.
The problem is as follows:
I have an empty TextCtrl object and a Button next to it.
The Button is meant to ... | 2018/01/26 | [
"https://Stackoverflow.com/questions/48466337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9272739/"
] | As others have already pointed out, the way to go is by using the text control's `SetValue`. But here's a small runnable example:
```
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
open_file_dlg_btn = wx.Button(self, label="Open FileDialog")
... | Try:
```
self.txtFeaturesPath.SetValue(pathname)
```
You have a few other buggy "features" in your example code, so watch out. | 9,933 |
44,060,906 | I just installed python-vlc via pip and when I try
```
import vlc
```
The follow error message shows up:
```
... ...
File "c:\Program Files\Python34\Lib\site-packages\vlc.py", line 173, in <module>
dll, plugin_path = find_lib()
File "c:\Program Files\Python34\Lib\site-packages\vlc.py", line 150, in find_lib
dl... | 2017/05/19 | [
"https://Stackoverflow.com/questions/44060906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7970976/"
] | The problem has been solved. I was using 64 bit python and 32 bit VLC. Installing a 64 bit VLC program fixed the problem. | `python-vlc` on Windows needs to load `libvlc.dll` from VLC. If it's not found in the normal `%PATH%`, it will try to use `pywin32` to look in the registry to find the VLC install path, and fall back to a hard-coded set of
directories after that. The stack trace looks like all of that failed.
Do you have VLC installe... | 9,935 |
68,036,975 | **Done**
I am just trying to run and replicate the following project: <https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/> . Basically until this point I have done everything as it is in the linked project but than I got the following issue:
**My Own Dataset - I hav... | 2021/06/18 | [
"https://Stackoverflow.com/questions/68036975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10270590/"
] | I continue to see this problem in 2022 when using LSTMs or GRUs in Sagemaker with conda\_tensorflow2\_p38 kernel. Here's my workaround:
Early in your notebook, before defining your model, set
```
tf.keras.backend.set_image_data_format("channels_last")
```
I know it looks weird to set image data format when you aren... | **Solution**
* I switched to AWS EC2 SageMaker "Python [conda env:tensorflow2\_p36] " so this is the exact pre made environment "tensorflow2\_p36"
* As I have read it in some other places it is probably library collision maybe with NumPy. | 9,940 |
30,284,611 | I have a python web app that carry's out calculations on data you send to it via POST / GET parameters.
The app works perfectly on my machine, but when deployed to openshift, it fails to access the parameters with an error no 32 : Broken pipe
I then used this [quickstart](https://github.com/openshift-quickstart/flask-... | 2015/05/17 | [
"https://Stackoverflow.com/questions/30284611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1677589/"
] | Don't use Flask's development server in production. Use a proper WSGI server that can handle concurrent requests, like [Gunicorn](http://gunicorn.org/ "Gunicorn"). For now try turning on the server's threaded mode and see if it works.
```
app.run(host="x.x.x.x", port=1234, threaded=True)
``` | You can get form data from the POST request via:
```
name = request.form.get("name")
```
Refactor:
```
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form.get("name")
result = "We received a POST request and the value for <name> ... | 9,942 |
4,542,730 | I have a app with a kind of rest api that I'm using to send emails . However it currently sends only text email so I need to know how to modify it and make it send html . Below is the code :
```
from __future__ import with_statement
#!/usr/bin/env python
#
import cgi
import os
import logging
import contextlib
from ... | 2010/12/27 | [
"https://Stackoverflow.com/questions/4542730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/331071/"
] | Have a look to the [Email message fields](http://code.google.com/intl/it/appengine/docs/python/mail/emailmessagefields.html) of the `send_mail` function.
Here is the parameter you need:
>
> **html**
>
> An HTML version of the body content, for recipients that prefer HTML email.
>
>
>
You should add the `h... | you can use the html field of EmailMessage class
```
message = mail.EmailMessage(sender=emailFrom,subject=emailSubject)
message.to = emailTo
message.body = emailBody
message.html = emailHtml
message.send()
``` | 9,943 |
73,906,061 | Be the following python pandas DataFrame:
| ID | country | money | code | money\_add | other | time |
| --- | --- | --- | --- | --- | --- | --- |
| 832932 | Other | NaN | 00000 | NaN | [N2,N2,N4] | 0 days 01:37:00 |
| 217#8# | NaN | NaN | NaN | NaN | [N1,N2,N3] | 2 days 01:01:00 |
| 1329T2 | France | 12131 | 00020 | 3... | 2022/09/30 | [
"https://Stackoverflow.com/questions/73906061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18396935/"
] | Because [`DataFrame.update`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html) not working well here is alternative - first use left join for new columns from second DataFrame by [`DataFrame.merge`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.ht... | This is another method different from Jezrael's, but you can try it out.
You can first create a condition variable for your dataframe.
```
condition = (df.code.isin(df1.cod_t) & ~df.code.isnull() & df.money.isna())
columns = ['money', 'money_add']
```
Next, use `df.loc` to do the update.
```
df.loc[condition, colu... | 9,944 |
43,006,368 | I am trying to connect to AWS Athena using python. I am trying to use pyathenajdbc to achieve this task. The issue I am having is obtaining a connection. When I run the code below, I receive an error message stating it cannot find the AthenaDriver. ( java.lang.RuntimeException: Class com.amazonaws.athena.jdbc.AthenaDri... | 2017/03/24 | [
"https://Stackoverflow.com/questions/43006368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3389780/"
] | The JDBC driver requires Java 8. I was currently running Java 7. I was able to install another version of Java on EC2 instance.
<https://tecadmin.net/install-java-8-on-centos-rhel-and-fedora/#>
I had to also set the java version in my code. With these changes, the code now runs as expected.
```
from mdpbi.rsi.confi... | Try this :
```
pyathenajdbc.ATHENA_JAR = ATHENA_JDBC_CLASSPATH
```
You won't be needing to specify the driver\_path argument in the connection method | 9,945 |
59,986,413 | I'm trying to use the new python dataclasses to create some mix-in classes (already as I write this I think it sounds like a rash idea), and I'm having some issues. Behold the example below:
```py
from dataclasses import dataclass
@dataclass
class NamedObj:
name: str
def __post_init__(self):
print("N... | 2020/01/30 | [
"https://Stackoverflow.com/questions/59986413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9112585/"
] | This:
```
def __post_init__(self):
super(NamedObj, self).__post_init__()
super(NumberedObj, self).__post_init__()
print("NamedAndNumbered __post_init__")
```
doesn't do what you think it does. `super(cls, obj)` will return a proxy to the class **after** `cls` in `type(obj).__mro__` - so, in your case, to... | The problem (most probably) isn't related to `dataclass`es. The problem is in Python's [method resolution](http://python-history.blogspot.com/2010/06/method-resolution-order.html). Calling method on `super()` invokes the first found method from parent class in the [MRO](https://www.python.org/download/releases/2.3/mro/... | 9,946 |
38,913,502 | I am trying to install a python package on my ubuntu.I am trying to install it through a setup script which i had written.The setup.py script looks like this:
```
from setuptools import setup
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'pyduino... | 2016/08/12 | [
"https://Stackoverflow.com/questions/38913502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5507861/"
] | Try install your packages with pip using this
```
pip install --install-option="--prefix=$PREFIX_PATH" package_name
```
as described here [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip)
and i... | Currently, you're using a `scripts` tag to install your python code. This will put your code in `/usr/local/bin`, which is not in `PYTHONPATH`.
According to [the documentation](https://docs.python.org/2/distutils/setupscript.html), you use `scripts` when you want to install executable scripts (stuff you want to call f... | 9,947 |
49,355,434 | How do I navigate to another webpage using the same driver with Selenium in python?
I do not want to open a new page. I want to keep on using the same driver.
I thought that the following would work:
```
driver.navigate().to("https://support.tomtom.com/app/contact/")
```
But it doesn't! Navigate seems not to be a 'W... | 2018/03/19 | [
"https://Stackoverflow.com/questions/49355434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3623123/"
] | To navigate to a webpage you just write
```
driver.get(__url__)
```
you can do this in your program multiple times | The line of code which you have tried as :
```
driver.navigate().to("https://support.tomtom.com/app/contact/")
```
It is a typical *Java* based line of code.
However as per the currect **Python API Docs** of [The WebDriver implementation](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.w... | 9,948 |
23,726,365 | I'm using tweepy and trying to run the basic script as shown by this [video](https://www.youtube.com/watch?v=pUUxmvvl2FE). I was previously receiving 401 errors (unsynchronized time zones) but am using the provided keys. I fixed that problem and now I'm getting this result:
```
Traceback (most recent call last):
... | 2014/05/18 | [
"https://Stackoverflow.com/questions/23726365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472645/"
] | Turns out the solution is simply to wait a day. Who would've thought! | I was also getting same error while using the python-twitter module in my script but it got resolved automatically when I tried after an interval. As there is limit for the number of try at a particular interval hence we get this error when we exceed that maximum try limit. | 9,949 |
33,340,442 | I am trying to post [some data via ajax](http://jsfiddle.net/g1wvryp7/) to our backend API, but the arrays within the json data get turned into weird things by jquery...for example, the backend (python) sees the jquery ajax data as a dict of two lists
```
{'subject': ['something'], 'members[]': ['joe','bob']}
```
... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33340442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1449443/"
] | That shouldnt be a problem since you only pass the reference to that list to other objects. That means you have only one big list.
But you should be aware that every object that has a reference to that list can change it | Well in Java, you only pass object "by reference"...
From the link in the comments:
>
> Letβs be a little bit more specific by what we mean here: objects are
> passed by reference β meaning that a reference/memory address is
> passed when an object is assigned to another β BUT (and this is whatβs
> important) tha... | 9,950 |
62,733,213 | I'm trying to figure out how to read a file from Azure blob storage.
Studying its documentation, I can see that the [download\_blob](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobclient?view=azure-python#download-blob-offset-none--length-none----kwargs-) method seems to be the ... | 2020/07/04 | [
"https://Stackoverflow.com/questions/62733213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1255356/"
] | **Update 0710:**
In the latest SDK [azure-storage-blob 12.3.2](https://pypi.org/project/azure-storage-blob/), we can also do the same thing by using `download_blob`.
The screenshot of the source code of `download_blob`:
[](https://i.stack.imgur.com/... | The accepted answer [here](https://stackoverflow.com/questions/33091830/how-best-to-convert-from-azure-blob-csv-format-to-pandas-dataframe-while-running) may be of use to you. The documentation can be found [here](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.baseblobservice.baseblo... | 9,951 |
23,201,351 | I know this is a basic question, but I'm new to python and can't figure out how to solve it.
I have a list like the next example:
```
entities = ["#1= IFCORGANIZATION($,'Autodesk Revit 2014 (ENU)',$,$,$)";, "#5= IFCAPPLICATION(#1,'2014','Autodesk Revit 2014 (ENU)','Revit');"]
```
My problem is how to add the infor... | 2014/04/21 | [
"https://Stackoverflow.com/questions/23201351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3556883/"
] | If you want to know if a value is in a list you can use `in`, like this:
```
>>> my_list = ["one", "two", "three"]
>>> "two" in my_list
True
>>>
```
If you need to get the position of the value in the list you must use `index`:
```
>>> my_list.index("two")
1
>>>
```
Note that the first element of the list has ... | Here you go:
```
>>> import re
>>> import ast
>>> entities = ["#1= IFCORGANIZATION('$','Autodesk Revit 2014 (ENU)','$','$','$');", "#5= IFCAPPLICATION('#1','2014','Autodesk Revit 2014 (ENU)','Revit');"]
>>> entities = [a.strip(';') for a in entities]
>>> pattern = re.compile(r'\((.*)\)')
>>> dic = {}
>>> for a in enti... | 9,952 |
69,637,510 | I try to add a local KVM maschine dynamically to ansible inventory with ansible 2.11.6.
```
ansible [core 2.11.6]
config file = /home/ansible/ansible.cfg
configured module search path = ['/home/ansible/library']
ansible python module location = /usr/local/lib/python3.9/dist-packages/ansible
ansible collection ... | 2021/10/19 | [
"https://Stackoverflow.com/questions/69637510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8478100/"
] | Next.js is a framework for React which helps developers manage Server-Side Rendering in react.
There are many benefits of server-side rendering including: caching specific pages (or caching only what is public and keeping user-specific data or auth-required data to be loaded on the frontend).
Since Next.js is doing s... | If this code is run on the server as part of [pre-rendering](https://nextjs.org/docs/basic-features/pages#pre-rendering) (either server-side rendering or static rendering), there will be no `window` (and hence no `window.btoa` for base64-encoding) since there is no browser, but instead node.js's `Buffer` can be utilize... | 9,955 |
70,290,737 | i tried to use this command in cmd to install module certifi:
```
pip install certifi
```
But it throws some warning like this:
```
WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages)
```
How can i fix it and install certifi ? (Python 3.9.6 ) | 2021/12/09 | [
"https://Stackoverflow.com/questions/70290737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17291416/"
] | there is no question in your title nor in description,
some mathematical resolution to your problem could be to put numbers to your directions, for example up=1 down=-1 left=2 right=-2
and then on keypress to change direction check:
```
if not actualPosition + newPosition:
#dont do anything since collision
else:
... | You can check if the new direction is different from the old one. If it is diffrent, you update the direction, otherwise you keep the same direction:
```
def new_dir(self, new_dir):
return new_dir if new_dir != self.direction else self.direction
def move_up(self):
self.direction = self.ne... | 9,956 |
32,277,153 | I'm using wxpython to code this simple form. A notebook with a scroll bar and few text controls is what i have used.I can see the widgets which are view-able on screen but the ones which needs to be scrolled down are not visible. In my code below i could see upto "Enter the Logs" and appropriate text control for that f... | 2015/08/28 | [
"https://Stackoverflow.com/questions/32277153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4672258/"
] | Your Java application is going to run in a Linux container, so you can use any Linux or Java method of setting the timezone.
The easy ones that come to mind...
`cf set-env <app-name> TZ 'America/Los_Angeles'
cf restage <app-name>`
or
`cf set-env <app-name> JAVA_OPTS '-Duser.timezone=Europe/Sofia'
cf restage <app-na... | To expand on @DanielMikusa. (Great Answer)
SAMPLE MANIFEST:
```
applications:
- path: .
buildpack: nodejs_buildpack
memory: 128M
instances: 1
name: sampleCronJobService
health-check-type: process
disk_quota: 1024M
env:
TZ: Etc/Greenwich
CF_STAGING_TIMEOUT: 15
CF_STARTUP_TIMEOUT: 15
T... | 9,961 |
50,238,512 | I have installed virtualenv on my system using <http://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv>
according to these [guidelines](http://blog.niandrei.com/2016/03/01/install-tensorflow-on-ubuntu-with-virtualenv/#comment-21), the initial step is:
$ sudo apt-get install python-pip python-dev python... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50238512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9332343/"
] | Have you noted that in the screen shot you're using version 2.5 in the references for the OpenXml assembly, but the exception message is referencing the newer 2.7.2? That could be your issue. It could be that you've referenced 2.5, but the "ClosedXML" is expecting 2.7.2 and when it doesn't find it tosses an error?
I w... | you have to go to nugget and update the document xml reference to the latest one which is 2.7 and the issue is fixed | 9,962 |
65,871,734 | **Update: I let-rally tried 12 suggested solutions but nothing worked at all.**
Is my question missing any details? The suggested answer doesn't solve the problem
In python I wrote:
```
print(s.cookies.get_dict())
```
where s is my session, the output is:
```
{'lubl': 'https%3A%2F%2Fopenworld.com%2Fconfirm', 'rish... | 2021/01/24 | [
"https://Stackoverflow.com/questions/65871734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What you are looking for is [`pandas.DataFrame.applymap`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html), which applies a function element-wise:
```
df.applymap(lambda x: -1 if x < low else (1 if x > high else 0))
```
The method [`pandas.DataFrame.apply`](https://pandas.py... | You are sending the lambda the full dataframe, but you need to send it a column:
```
for col in df.columns:
df[col].apply(lambda x: -1 if x < low else (1 if x > high else 0))
``` | 9,963 |
56,105,090 | I'm trying to upload a file using the built in wagtaildocs application in my Wagtail application. I've setup my Ubuntu 16.04 server was setup with the Digital Ocean tutorial methods for Nginx | Gunicorn | Postgres
Some initial clarifications:
1. In my Nginx config I've set `client_max_body_size` 10000M;
2. In my prod... | 2019/05/13 | [
"https://Stackoverflow.com/questions/56105090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11490399/"
] | I was never able to solve this problem directly, but I did come up with a hack to get around it.
I'm not a Wagtail or Django expert so I'm sure there is a proper solution to this answer, but anyway here's what I did. If you have any recommendations on improvement feel free to leave a comment.
As a note this is really... | I would suspect that the exception `psycopg2.DatabaseError SSL SYSCALL error: Operation timed out` will happen if the droplet is running out of memory.
Try to create a swap partition or extend your memory.
[Creating a swap partition](https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-16... | 9,964 |
9,301,531 | Why doesn't the following work?
```
$ alias sayHello='/bin/echo "Hello world!"'
$ sayHello
Hello world!
$ nohup sayHello
nohup: appending output to `nohup.out'
nohup: cannot run command `sayHello': No such file or directory
```
(the reason I ask this question is because I've aliased my `perl` and `pyth... | 2012/02/15 | [
"https://Stackoverflow.com/questions/9301531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884447/"
] | Because the shell doesn't pass aliases on to child processes (except when you use $() or ``).
$ alias sayHello='/bin/echo "Hello world!"'
Now an alias is known in this shell process, which is fine but only works in this one shell process.
```
$ sayHello
Hello world!
```
Since you said "sayHello" in the same shel... | If you look at the [Aliases](http://www.gnu.org/software/bash/manual/html_node/Aliases.html) section of the Bash manual, it says
>
> The first word of each simple command, if unquoted, is checked to see
> if it has an alias.
>
>
>
Unfortunately, it doesn't seem like `bash` has anything like `zsh`'s [global alias... | 9,965 |
21,822,054 | I've tried what's told in [How to force /bin/bash interpreter for oneliners](https://stackoverflow.com/questions/20906073/how-to-force-bin-bash-interpreter-for-oneliners)
By doing
```
os.system('GREPDB="my command"')
os.system('/bin/bash -c \'$GREPDB\'')
```
However no luck, unfortunately I need to run this comman... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21822054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453153/"
] | Both commands are executed in different subshells.
Setting variables in the first `system` call does not affect the second `system` call.
You need to put two command in one string (combining them with `;`).
```
>>> import os
>>> os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
123
0
```
**NOTE** You need to... | The solution below still initially invokes a shell, but it switches to bash for the command you are trying to execute:
```
os.system('/bin/bash -c "echo hello world"')
``` | 9,971 |
14,402,654 | extreme python/sql beginner here. I've looked around for some help with this but wasn't able to find exactly what I need- would really appreciate any assistance.
As the title indicates, I have a very large text file that I want to parse into a sql database preferably using python. The text file is set up as so:
```
... | 2013/01/18 | [
"https://Stackoverflow.com/questions/14402654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1756574/"
] | A few points:
1. From the description it seems like you aim at your data being denormalized in one table. This is generally not a good idea. Split your data into two tables: PARENT and CHILDREN.
PARENT should contain ID and CHILDREN should have at least two columns: PARENT\_ID and CHILD\_VALUE (or smth like it) with P... | you should look into **file handling** in python.
the `open() , .readlines()` methods and lists will help you **alot**.
for example:
```
f = open("NAMEOFTXTFILE.TXT","r") #r for read, w for write, a for append.
cell = f.readlines() # Displays the content in a list
f.seek(0) # Just takes the cursor to the first cell ... | 9,981 |
36,064,495 | currently I need to make some distance calculation. For this I am trying the following on my ipython-notebook (version 4.0.4):
```
from geopy.distance import vincenty
ig_gruendau = (50.195883, 9.115557)
delphi = (49.99908,19.84481)
print(vincenty(ig_gruendau,delphi).miles)
```
Unfortunately I receive the following... | 2016/03/17 | [
"https://Stackoverflow.com/questions/36064495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446609/"
] | You need to install the missing module in your python installation. So you have to run the command:
```
pip install geopy
```
in your terminal. If you don't have pip, you'll have to install it using:
```
easy_install pip
```
and if both command fail with `Permission denied`, then you'll have to either launch the ... | Even if you install using `pip install` command you still have to use:
```
conda install -c conda-forge geopy
```
This command is in the anaconda server so that it gets installed in the anaconda. | 9,982 |
34,013,185 | Let's say that I have this list in python
```
A = ["(a,1)", "(b,2)", "(c,3)", "(d,4)"]
```
so how can I print it out in the following format:
```
(a,1), (b,2), (c,3), (d,4)
```
using one line, better without using for loop
Thanks in advance | 2015/12/01 | [
"https://Stackoverflow.com/questions/34013185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5482492/"
] | When A is a list of str:
```
print(', '.join(A))
```
Or more general:
```
print(', '.join(map(str, A)))
``` | In your case below code will work
```
print(', '.join(A))
``` | 9,983 |
49,514,684 | I'm relatively new to using sklearn and python for data analysis and am trying to run some linear regression on a dataset that I loaded from a `.csv` file.
I have loaded my data into `train_test_split` without any issues, but when I try to fit my training data I receive an error `ValueError: Expected 2D array, got 1D ... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49514684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061892/"
] | You are only using one feature, so it tells you what to do within the error:
>
> Reshape your data either using array.reshape(-1, 1) if your data has a single feature.
>
>
>
The data always has to be 2D in scikit-learn.
(Don't forget the typo in `X = organic['Sunglight']`) | Once you load the data into `train_test_split(X, y, test_size=0.2)`, it returns Pandas Series `X_train` and `X_test` with `(192, )` and `(49, )` dimensions. As mentioned in the previous answers, sklearn expect matrices of shape `[n_samples,n_features]` as the `X_train`, `X_test` data. You can simply convert the Pandas ... | 9,985 |
72,484,522 | I am making a little math game, similar to [zeta mac](https://arithmetic.zetamac.com/game?key=a7220a92). Everything seems to be working well. Ideally I would like this console output to erase incorrect answers entered by the user, without reprinting the math problem again for them to solve. Is something like this possi... | 2022/06/03 | [
"https://Stackoverflow.com/questions/72484522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19244670/"
] | Keep the duration in a variable and decrease the duration in every loop
```
def blink_green2():
red1.on()
sleep_duration = 0.5
for i in range(5):
green2.toggle()
time.sleep(sleep_duration)
green2.toggle()
time.sleep(sleep_duration)
sleep_duration -= 0.01
``` | Gradually increasing the speed of blinking means that you need to decrease the sleep duration between the blinking. So in the for loop you need to decrease the value of i. so something like this.
```
def blink_green2():
red1.on()
for i in range(0,0.5,0.1):
green2.toggle()
time.sleep(0.5-i)
``` | 9,987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.