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 |
|---|---|---|---|---|---|---|
63,354,202 | i am beginer of the python programming. i am creating simple employee salary calculation using python.
**tax = salary \* 10 / 100** this line said wrong error displayed Unindent does not match outer indentation level
this is the full code
```
salary = 60000
if(salary > 50000):
tax = float(salary * 10 / 100)
e... | 2020/08/11 | [
"https://Stackoverflow.com/questions/63354202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12932093/"
] | The error message is self explanatory.
You can't indent your elif and else, they should be at the same level as the if condition.
```
salary = 60000
if(salary > 50000):
tax = salary * 10 / 100
elif(salary > 35000):
tax = salary * 5 / 100
else :
tax = 0
netsal = salary - tax
print(tax)
print(netsa... | You just need to fix your indentation, I would suggest using an IDE
```py
salary = 60000
if(salary > 50000):
tax = salary * 10 / 100
elif(salary > 35000):
tax = salary * 5 / 100
else:
tax = 0
print(tax)
>>> 6000.0
``` | 10,982 |
59,467,023 | ```
C:\Users\gabri\OneDrive\Desktop>pip3 install pyaudio
Collecting pyaudio
Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
Running setup.py install for pyaudio ... error
ERROR:... | 2019/12/24 | [
"https://Stackoverflow.com/questions/59467023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12590302/"
] | Currently, there are wheels compatible with the official distributions of **Python 2.7, 3.4, 3.5, and 3.6.**
Apparently, there is no version of that library for Python 3.7, so I'd try downgrading the Python version.
Download the wheel on this site: <https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio>.
Choose:
* Py... | You need to install Microsoft Visual C++ 14.0
This should work <https://visualstudio.microsoft.com/visual-cpp-build-tools/> | 10,983 |
18,041,050 | I've got a py2.7 project which I want to test under py3.2. For this purpose, I want to use virtualenv. I wanted to create an environment that would run 3.2 version internally:
```
virtualenv 3.2 -p /usr/bin/python3.2
```
but it failed. My default python version is `2.7` (ubuntu default settings). Here is `virtualenv... | 2013/08/04 | [
"https://Stackoverflow.com/questions/18041050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769384/"
] | To create a Python 3.2 virtual environment you should use the virtualenv you installed for Python 3.2. In your case that would be:
```
/usr/bin/virtualenv-3.2
``` | You'll have to use a Python 3 version of `virtualenv`; the version you are using is installing Python 2 tools into a Python 3 virtual environment and these are not compatible. | 10,990 |
68,762,785 | I have the following dataframes.
```
Name | Data
A foo
A bar
B foo
B bar
C foo
C bar
C cat
Name | foo | bar | cat
A 1 2 3
B 4 5 6
C 7 8 9
```
I need to lookup the values present in the 2n... | 2021/08/12 | [
"https://Stackoverflow.com/questions/68762785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16652846/"
] | You can use `.melt` + `.merge`:
```py
x = df1.merge(df2.melt("Name", var_name="Data"), on=["Name", "Data"])
print(x)
```
Prints:
```none
Name Data value
0 A foo 1
1 A bar 2
2 B foo 4
3 B bar 5
4 C foo 7
5 C bar 8
6 C cat 9
``` | You can melt your second dataframe and then merge it with your first:
```
import pandas as pd
df1 = pd.DataFrame({
'Name': ['A', 'A', 'B', 'B', 'C', 'C', 'C'],
'Data': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'cat'],
})
df2 = pd.DataFrame({
'Name': ['A', 'B', 'C'],
'foo': [1, 4, 7],
'bar': [2... | 10,993 |
56,878,362 | I'm trying to create a role wrapper which will allow me to restrict certain pages and content for different users. I already have methods implemented for checking this, but the wrapper/decorator for implementing this fails and sometimes doesn't, and I have no idea of what the cause could be.
I've searched around looki... | 2019/07/03 | [
"https://Stackoverflow.com/questions/56878362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6912830/"
] | So to solve the problem that has been plaguing me for the last couple of hours, I've looked into how the `flask_login` module actually works, and after a bit of investigating, I found out that they use an import from `functools` called `wraps`.
I imported that, copied how `flask_login` implemented it essentially, and ... | At first glance it looks like a conflict with your `run` function in the `require_role` decorator ([docs](http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/)):
```
def require_role(roles=["User"]):
def wrap(func):
def wrapped_func(*args, **kwargs):
...
``` | 10,994 |
38,882,845 | Anaconda for python 3.5 and python 2.7 seems to install just as a drop in folder inside my home folder on Ubuntu. Is there an installed version of Anaconda for Ubuntu 16? I'm not sure how to ask this but do I need python 3.5 that comes by default if I am also using Anaconda 3.5?
It seems like the best solution is doc... | 2016/08/10 | [
"https://Stackoverflow.com/questions/38882845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784304/"
] | My solution for Python 3.5 and Anaconda on Ubuntu 16.04 LTS (with the bonus of OpenCV 3) was to install Anaconda, then deprecate to 3.5. You have to be sure to update anaconda afterwards - that's the bit that got me at first. The commands I gave were:
```
bash Anaconda3-4.3.1-Linux-x86_64.sh
conda install python=3.5
c... | Use anaconda version `Anaconda3-4.2.0-Linux-x86_64.sh` from the anaconda installer archive.This comes with `python 3.5`. This worked for me. | 10,995 |
35,528,078 | I have a Python code like this,
```
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word+first+pyg
new_word[1:]
print original
else:
print 'empty'
```
The output of variable "new\_word" should b... | 2016/02/20 | [
"https://Stackoverflow.com/questions/35528078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802617/"
] | You will need your own implementation of `ToString` in your `Employee` class. You just need to override it and put your code of `PrintEmployee` in the new method.
Just to make it clear what I mean I give you a sample on how the override should look like:
```
public override string ToString()
{
return string.Forma... | Here's a simple solution
```
private void PrintRegistry()
{
foreach(Employee employee in Accounts)
{
Console.WriteLine("\nID:{0}\nFull Name: {1} {2}\nSocial Security Number: {3}\nWage: {4}\n", employee.ID, employee.FirstName, employee.LastName, employee.SocialNumber, employee.HourWage);
}
}
```
O... | 10,996 |
16,946,684 | Minimal working example that shows this error:
```
from os import listdir, getcwd
from os.path import isfile, join, realpath, dirname
import csv
def gd(mypath, myfile):
# Obtain the number of columns in the data file
with open(myfile) as f:
reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
... | 2013/06/05 | [
"https://Stackoverflow.com/questions/16946684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391441/"
] | The `u` just indicates that it is a unicode string and is not relevant to the problem.
The file isn't found because you aren't adding the `mypath` in front of the filename - try `with open(join(mypath, myfile)) as f:` | Your problem is that `myfile` is just a filename, not the result of `join(mypath,myfile)`. | 10,997 |
57,523,861 | I'm attempting to install pymc on MacOS 10.14.5 Mojave. However, there seems to be a problem with the gfortran module. The error message is minimally helpful.
I have attempted all the possible ways to install pymc as suggested here: <https://pymc-devs.github.io/pymc/INSTALL.html>
I first came across a problem with no... | 2019/08/16 | [
"https://Stackoverflow.com/questions/57523861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11935431/"
] | I'm not familiar with mongoose, so I will take for granted that `"user_count": user_count++` works.
For the rest, there are two things that won't work:
* the `$` operator in `"users.$.id": req.user.id,` is known as the positional operator, and that's not what you want, it's used to update a specific element in an ar... | ```
db.collection.findOneAndUpdate({_id: id}, {$set: {"user_count": user_count++},$addToSet: {"users": {"id": req.user.id,"action": true}}}, {returnOriginal:false}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
``` | 10,998 |
25,113,767 | I am programming in python which involves me implementing a shell in Python in Linux. I am trying to run standard unix commands by using os.execvp(). I need to keep asking the user for commands so I have used an infinite while loop. However, the infinite while loop doesn't work. I have tried searching online but they'r... | 2014/08/04 | [
"https://Stackoverflow.com/questions/25113767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3903472/"
] | Your code does not work because it uses [`os.execvp`](https://docs.python.org/3/library/os.html#os.execvp). `os.execvp` **replaces the current process image completely with the executing program**, your running process **becomes** the `ls`.
To execute a **subprocess** use the aptly named [`subprocess`](https://docs.py... | If you want it to run like a shell you are looking for os.fork() . Call this before you call os.execvp() and it will create a child process. os.fork() returns the process id. If it is 0 then you are in the child process and can call os.execvp(), otherwise continue with the code. This will keep the while loop running. Y... | 10,999 |
14,303,300 | >
> **Possible Duplicate:**
>
> [Python \_\_str\_\_ and lists](https://stackoverflow.com/questions/727761/python-str-and-lists)
>
>
>
What is the cause when python prints the address of an object instead of the object itself?
for example the output for a print instruction is this:
```
[< ro.domain.entities.P... | 2013/01/13 | [
"https://Stackoverflow.com/questions/14303300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796659/"
] | You are looking at the `repr()` representation of a custom class, which by default include the `id()` (== memory address in CPython).
This is the default used when printing a list, any contents are included using the representation:
```
>>> class CustomObject(object):
... def __str__(self):
... return "I ... | Python calls for every list item the **repr**() output of each list item.
See [Python \_\_str\_\_ and lists](https://stackoverflow.com/questions/727761/python-str-and-lists) | 11,000 |
3,306,518 | I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `py... | 2010/07/22 | [
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] | Here is a script alternative to `/usr/bin/env`, that permits passing of arguments on the hash-bang line, based on `/bin/bash` and with the restriction that spaces are disallowed in the executable path. I call it "envns" (env No Spaces):
```
#!/bin/bash
ARGS=( $1 ) # separate $1 into multiple space-delimited argument... | Building off of Larry Cai's answer, `env` allows you to set a variable directly in the command line. That means that `-u` can be replaced by the equivalent `PYTHONUNBUFFERED` setting before `python`:
```
#!/usr/bin/env PYTHONUNBUFFERED="YESSSSS" python
```
Works on RHEL 6.5. I am pretty sure that feature of `env` is... | 11,001 |
41,020,233 | How to get user-defined class attributes from class instance? I tried this:
```
class A:
FOO = 'foo'
BAR = 'bar'
a = A()
print(a.__dict__) # {}
print(vars(a)) # {}
```
I use python 3.5.
Is there a way to get them?
I know that `dir(a)` returns a list with names of attributes, but I need only used defined,... | 2016/12/07 | [
"https://Stackoverflow.com/questions/41020233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7262895/"
] | You've defined those variables within the class namespace which haven't propagated into instances. You can use the `__class__` attribute of the instance to access the class object, and then use the `__dict__` method to get the namespace's contents:
```
>>> {k: v for k, v in a.__class__.__dict__.items() if not k.starts... | Try this:
```
In [5]: [x for x in dir(a) if not x.startswith('__')]
Out[5]: ['BAR', 'FOO']
``` | 11,011 |
58,499,136 | I have a python script which I want to execute when someone clicks on a button in an HTML/PHP web page in the browser. How can this be achieved and what is the best way of doing it? | 2019/10/22 | [
"https://Stackoverflow.com/questions/58499136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8110933/"
] | You need to use flask server for this requirement as browser can not access local file.
By using flask, You need to write Ajax call in `.js`.
Sample Ajax call.
```
$(document).ready(function () {
$('#<ButtonID>').click(function (event) {
$.ajax({
url: '/<Flask URL>',
type: 'POST',
success: fu... | With `exec`,
```
$command = "python script_path";
exec($command,$output,$return_var);
if ($return_var) {
$error = error_get_last();
var_dump($error)
}
``` | 11,012 |
62,857,693 | How do I install spacy on ARM processor? I get an error
```
ERROR: Command errored out with exit status 1:
command: /root/miniforge3/bin/python3.7 /root/miniforge3/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-ahxo0t0p/overlay --no-warn-script-location --no-binary ... | 2020/07/12 | [
"https://Stackoverflow.com/questions/62857693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | >
> You cannot use "hot reload" features with flutter app because the process of deployment/running never finishes
>
>
>
Actually, you can! Just connect to the device with `adb connect <IP>` instead of going through the socket. See my full blog post here:
<https://dnmc.in/2021/01/25/setting-up-flutter-natively-wi... | If you are like me you had a lot of issues getting adb to work. You need to make sure that windows host and the linux image both have the same version of adb. Following this guide <https://www.androidexplained.com/install-adb-fastboot/#update> helped me update adb on windows. | 11,013 |
66,524,661 | Here I check the installed version of pip
`py -m pip --version`
```
pip 21.0.1 from C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\pip (python 3.9)
```
Now I try to run a pip command
`pip install pip --target $HOME\\.pyenv`
```
pip: The term 'pip' is not recognized as a name of a cmdlet, fun... | 2021/03/08 | [
"https://Stackoverflow.com/questions/66524661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/865220/"
] | Add the scripts folder to PATH
`C:\Users\hp\AppData\Local\Programs\Python\Python39\Scripts`
or
`C:\Python39\Scripts`
(depending on how you have installed python locate and add python/scripts folder) | Just use on the terminal:
```
py -m pip install
```
followed by the library you want to install. It tends to work. | 11,014 |
19,494,511 | ```
Error: Error: if n == 0 or n>4:
UnboundLocalError: local variable 'n' referenced before assignment.
```
Tried isdigit method, but seems not working. what is the issue ?
```
#!usr/bin/python
import sys
class Person:
def __init__(self, firstname=None, lastname=None, age=None, gender=None):
self.fnam... | 2013/10/21 | [
"https://Stackoverflow.com/questions/19494511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897545/"
] | Okay, you are doing a few things wrong.
First of all, `raw_input` will always give you a string.
So you need to convert it into an integer anyway. But also, you are using the variable `n` in parts of your code that it might not exist at yet.
You need to change this part:
```
print "Not a valid input"
if n1.... | Your're testing for n == something condition before setting the value of n. Simply initialize it to zero or whatever else default value.
```
def display(self):
found = False
n = 0
``` | 11,015 |
41,061,824 | I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distributi... | 2016/12/09 | [
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] | You can't `pip install csv` because the csv module is included in the Python installation.
You can directly use :
```
import csv
```
in your program
Thanks | The problem is that you have another file in your directory called `csv.py`. And in this file you do not have a `reader` function.
Change its name to `my_csv.py` | 11,018 |
47,900,257 | I have the Python Extensions for Windows installed. Within the PythonWin IDE I can get autocomplete on Automation objects (specifically, objects created with `win32com.client.Dispatch`):
[](https://i.stack.imgur.com/uxxkh.png)
How can I get the sa... | 2017/12/20 | [
"https://Stackoverflow.com/questions/47900257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111794/"
] | I don't think that the example you show with `PythonWin` is easily reproducible in VS Code. The quick start guide of `win32com` itself (cited below) says, its only possible with a COM browser or the documentation of the product (Word in this case). The latter one is unlikely, so `PythonWin` is probably using a COM brow... | I think your problem is related to defining `Python interpreter`.
Choose proper Python interpreter by executing `python interpreter` command in `VS Code` command palette by pressing **`f1`** or **`ctrl+shift+p`** key. | 11,025 |
12,756,885 | I've looked at all the other questions like this and they all seem to be a slight variation of this one in which I can't extract an answer for my problem.
```
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
```
So I installed it with homeb... | 2012/10/06 | [
"https://Stackoverflow.com/questions/12756885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1217616/"
] | Third-party add-ons ("distributions") to Python, like `numpy`, are installed to a particular instance of Python. On OS X 10.8 (Mountain Lion), the Apple-supplied Python 2.7 comes with a version of `numpy` pre-installed. You can access that python with:
```
/usr/bin/python2.7
```
I'm not sure what you mean by "downlo... | If Your Numpy not install during python 2.7 installation so you can download numpy and install easly from this link [install link](http://www.iram.fr/IRAMFR/GILDAS/doc/html/gildas-python-html/node38.html) | 11,027 |
29,786,474 | I execute `launchctl start com.xxx.xxx.plist`
I can find `AutoMakeLog.err` and the content :
```
Traceback (most recent call last):
File "/Users/xxxx/Downloads/Kevin/auto.py", line 67, in <module>
output = open(file_name, 'w')
IOError: [Errno 13] Permission denied: '2015-04-22-09:15:40.log'
```
plist content :
```... | 2015/04/22 | [
"https://Stackoverflow.com/questions/29786474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327056/"
] | `int[]` is an `integer array` type.
`int` is an `integer` type.
You can't convert an array to a number. | You have multiple problems in the code. declare int as integer, initialise Questions and You have to convert String to integer before assigning it to question.
```
int i = 0;
int [] question = new int [100];
question[i++] = Integer.parseInt(line[0]);
``` | 11,028 |
49,776,619 | I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
... | 2018/04/11 | [
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] | i'd forget the port number to enter the port, this is the URL connection string:
```
`SQLALCHEMY_DATABASE_URI = 'mysql://dt_admin:dt2016@localhost:3308/dreamteam_db'
```
it work now, thanks | For me I got this error once I was trying to fix this issue
```
raise TypeError("option values must be strings")
TypeError: option values must be strings
```
so I tried to stringify the url like so
```py
config.set_main_option(
"sqlalchemy.url", f'{os.environ.get("DATABASE_URL")}')
```
After that I got new e... | 11,030 |
50,126,064 | I've been learning about about C++ in college and one thing that interests me is the ability to create a shared header file so that all the cpp files can access the objects within. I was wondering if there is some way to do the same thing in python with variables and constants? I only know how to import and use the fun... | 2018/05/02 | [
"https://Stackoverflow.com/questions/50126064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944978/"
] | First, if you've ever used `sys.argv` or `os.sep`, you've already used another module's variables and constants.
Because the way you share variables and constants is exactly the same way you share functions and classes.
In fact, functions, classes, variables, constants—they're all just module-global variables as far ... | If you are just looking to make function definitions, then this post may answer your question:
[Python: How to import other Python files](https://stackoverflow.com/questions/2349991/python-how-to-import-other-python-files)
Then you can define a function as per here:
<https://www.tutorialspoint.com/python/python_func... | 11,040 |
5,971,635 | My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] | Try using the `os` module.
```
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
```
See the [Python docs](http://docs.python.org/library/os.html#os.environ) on `os.environ`. Also, for spaw... | Use `os.environ[str(DEBUSSY)]` for both reading and writing (<http://docs.python.org/library/os.html#os.environ>).
As for reading, you have to parse the number from the string yourself of course. | 11,041 |
3,148,352 | Need Help Creating GAE Datastore Loader Class for uploading data using appcfg.py?
Any other way to simplified this process?
is there any detailed example better than [here](http://code.google.com/appengine/docs/python/tools/uploadingdata.html)
When try using bulkloader.yaml:
```
Uploading data records.
[INFO ] Log... | 2010/06/30 | [
"https://Stackoverflow.com/questions/3148352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288541/"
] | I've created config.yaml with bulkloader config, and also written simple helper function to process None-references. I don't know why it's not done in original helper.
The helper (file `helpers.py` is very simple, just place it to the same directory where you placed `config.yaml`):
```
from google.appengine.api impor... | It looks like you have reference properties with None values, such values are handled incorrectly by bulkloader's helpers. | 11,047 |
68,490,787 | Any time I make a change in the view, and HTML, or CSS, I have to stop and re-run
```
python manage.py runserver
```
for my changes to be dispayed. This is very annoying because it wastes a lot of my time trying to find the terminal and run it again. Is there a workaround for this? | 2021/07/22 | [
"https://Stackoverflow.com/questions/68490787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14296523/"
] | `python manage.py runserver` should normally perform hot reload on your Django application, except you've updated the config in the settings.py file. Check if `DEBUG = True` in settings.py | My advice is to use Vscode for Django developing because it gives you autosave feature so you don't have to stop and rerun the server the only thing you have to do is reload the web page. I hope it might be helpful | 11,048 |
11,590,082 | I am using python and sqlite3 to handle a website. I need all timezones to be in localtime, and I need daylight savings to be accounted for. The ideal method to do this would be to use sqlite to set a global datetime('now') to be +10 hours.
If I can work out how to change sqlite's 'now' with a command, then I was goin... | 2012/07/21 | [
"https://Stackoverflow.com/questions/11590082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503619/"
] | I'm not 100% on what you're asking, but to keep this simple I would say store your dates in UTC, and present them as local time if need be:
```
sqlite> select datetime('now', 'utc');
2012-07-21 09:58:21
sqlite> select datetime('now', 'localtime');
2012-07-21 13:58:33
```
See SQLite's [date and time functions documen... | you can try this code, I am in Taiwan , so I add 8 hours:
`DateTime('now','+8 hours')` | 11,049 |
9,597,122 | I have established a basic hadoop master slave cluster setup and able to run mapreduce programs (including python) on the cluster.
Now I am trying to run a python code which accesses a C binary and so I am using the subprocess module. I am able to use the hadoop streaming for a normal python code but when I include t... | 2012/03/07 | [
"https://Stackoverflow.com/questions/9597122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1253987/"
] | Used simple id and hash token like Amazon for now... | Your site can absolutely be an OAuth server (to clients) and an OAuth consumer (of other APIs) at the same time, the same way that a hairdresser can also be the customer of another hairdresser. | 11,050 |
72,720,385 | I created a model like this.
```
class BloodDiscard(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
b... | 2022/06/22 | [
"https://Stackoverflow.com/questions/72720385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15809668/"
] | You can use the `matplotlib`'s `Dateformatter`. Updated code and plot below. I did notice that the `Date` column you posted had dates on 2nd and 17th. I changed those to show everything on the 2nd. Otherwise, there would be too many entries. Hope this helps...
```
df = pd.DataFrame({"Date":["2015-02-02 10:19:00","2015... | You would want to convert your ['Date'] column to only include time information, im not sure if you want the data to be ordered by date or not but that should just show time information on the X-axis:
```
df['Date'].dt.time
``` | 11,051 |
5,043,188 | i have a trouble with run django project on production server with Apache and mod\_wsgi. This Error happened when i'm start apache and go to site first time or go from other:
>
> ImportError at /
>
> Exception Value: cannot import name MyName
>
> Exception Location /var/www/projectname/appname/somemodule.py
>... | 2011/02/18 | [
"https://Stackoverflow.com/questions/5043188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337077/"
] | ```
php -i | more
```
should work on both Linux and Unix. On Linux, though, `more` is simply an alias for the equivalent `less` | On Linux you could do from the shell
```
php -r "phpinfo();" | less
``` | 11,052 |
33,124,269 | I have been following a Caffe example [here](http://nbviewer.ipython.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb) to plot the Convolution kernels from my ConvNet. I have attached an image below of my kernels, however it looks nothing like the kernels in the example. I have followed the example ex... | 2015/10/14 | [
"https://Stackoverflow.com/questions/33124269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5321075/"
] | Twilio developer evangelist here.
You absolutely can do app to app calls using the iOS SDK. Let me explain.
Your Twilio Client capability token is created with a TwiML Application, which supplies the URL that Twilio will hit when a call is created to find out what to do with it. Normally, you would pass a phone numbe... | Not sure it is possible with Twilio. We have used twilio for the same purpose u mentioned (Call to phone numbers) and was working fine. I think the main purpose of twilio is that. Anyways i'm not sure about it.
May be [VoIP](https://en.wikipedia.org/wiki/Voice_over_IP) will suit for your functionality. **PortSIP** is ... | 11,053 |
49,135,963 | I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] | This recursive method will scan all directories within a given directory and then print the names of the `txt` files. I kindly invite you to take it forward.
```
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.ends... | This code will look for all directories inside a directory, printing out the names of all files found there:
```
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: print filenames one level down from starting folder
#--------*---------*---------*---------*---------*---------*-----... | 11,055 |
6,131,629 | I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. D... | 2011/05/25 | [
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Those are the basic pieces of information. Anything beyond that could be viewed as SpyWare-like and privacy advocates will [justifiably] frown upon it.
The best way to obtain more information from your users is to ask them, make the fields optional, and inform your user of exactly what you will be using the informatio... | For what end?
Remember that client IP is close to meaningless now. All users coming from the same proxy or same NAT point would have the same client IP. Years go, all of AOL traffic came from just a few proxies, though now actual AOL users may be outnumbered by the proxies :).
If you want to uniquely identify a user... | 11,065 |
24,751,181 | I have a text file named headerValue.txt which contains the following data:-
```
Name Age
sam 22
Bob 21
```
I am trying to write a python script that would add a new header called 'Eligibility'.
It would read the lines from the text file and check if the age is more than 18, then it will print 'True' underne... | 2014/07/15 | [
"https://Stackoverflow.com/questions/24751181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559954/"
] | ```
fo =open("headerValue.txt", "r")
data = [l.split() for l in fo.readlines()]
headers = data[0]
headers.extend(('Eligibility', 'Adult'))
ageind = headers.index('Age')
for line in data[1:]:
if int(line[ageind]) > 18:
line.extend(('True', 'yes'))
else:
line.extend(('False', 'no'))
```
The `if`... | This module is suited for you : <https://docs.python.org/2/library/fileinput.html?highlight=fileinput#fileinput>
For a infile edition you can use:
```
#!/usr/bin/python
import fileinput
cont = 0
for line in fileinput.input("./path/to/file", inplace=True):
if not cont:
name = "Name"
age = "Age"
... | 11,075 |
67,665,789 | Hi I am a Newbie to programming. So I spent 4 days trying to learn python. I evented some new swear words too.
I was particularly interested in trying as an exercise some web-scraping to learn something new and get some exposure to see how it all works.
This is what I came up with. See code at end. It works (to a degre... | 2021/05/24 | [
"https://Stackoverflow.com/questions/67665789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16011875/"
] | In this case, to do pagination, instead of `for i in range(1, 100)` which is a hardcoded way of paging, it's better to use a `while` loop to dynamically paginate all possible pages.
"While" is an infinite loop and it will be executed until the transition to the next page is possible, in this case it will check for the... | Create the URL by putting the page number in it, then put the rest of your code into a `for` loop and you can use `len(winenames)` to count how many results you have. You should do the writing outside the `for` loop. Here's your code with those changes:
```py
import requests
import csv
from bs4 import BeautifulSoup
n... | 11,078 |
70,883,363 | I am working on a python project that depends on some other files. It all works fine while testing. However, I want the program to run on start up. The working directory for programs that run on start up seems to be `C:Windows\system32`. When installing a program, it usually asks where to install it and no matter where... | 2022/01/27 | [
"https://Stackoverflow.com/questions/70883363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12209262/"
] | >
> But now the project grade file seems different.
>
>
>
Yes, starting with the new [Bumblebee](https://android-developers.googleblog.com/2022/01/android-studio-bumblebee-202111-stable.html) update of Android Studio, the build.gradle (Project) file is changed. In order to be able to use Google Services, you have ... | I've had the same problem just add in the gradle.build project
>
> id 'com.google.gms.google-services' version '4.3.0' apply false
>
>
>
and then add in gradle.build module
>
> dependencies {
> //Regular dependecies
> implementation platform("com.google.firebase:firebase-bom:30.4.0")
> implementation "com.googl... | 11,079 |
51,039,271 | <https://github.com/ITCoders/Human-detection-and-Tracking/blob/master/main.py>
This is the code I obtained for the human detection. I'm using anaconda navigator(jupyter notebook). How can I use argument parser in this? How can I give the video path *-v* ? Can anyone please say me a solution for this? As the running of ... | 2018/06/26 | [
"https://Stackoverflow.com/questions/51039271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9993397/"
] | What you are asking seems similar to: [Passing command line arguments to argv in jupyter/ipython notebook](https://stackoverflow.com/questions/37534440/passing-command-line-arguments-to-argv-in-jupyter-ipython-notebook)
There are two different methods mentioned in the post that were helpful. That said, I would sugges... | I tried out the answers listed on "[Passing command line arguments to argv in jupyter/ipython notebook](https://stackoverflow.com/questions/37534440/passing-command-line-arguments-to-argv-in-jupyter-ipython-notebook)", and came up with a different solution.
My original code was
```
ap = argparse.ArgumentParser()
ap.a... | 11,081 |
72,879,863 | yolov5 is detecting perfect while I run detect.py but unfortunately with deepsort track.py is not tracking even not detecting with tracker. how to set parameter my tracker ?
---
yolov5:
```
>> python detect.py --source video.mp4 --weights best.pt
```
yolov5+deepsort:
```
>> python track.py --yolo-weights best.pt... | 2022/07/06 | [
"https://Stackoverflow.com/questions/72879863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14141667/"
] | DISCLAIMER: I am the creator of <https://github.com/mikel-brostrom/Yolov5_StrongSORT_OSNet>
First of all:
Does Yolov5+StrongSORT+OSNet run correctly without you custom modifications?
Secondly:
Have you checked that you are loading the same weights for Yolov5 and Yolov5+StrongSORT+OSNet?
Moreover:
Why all the cust... | I am also using the same model and was facing the same issue.
Try annotating more image and increase the image size to 1024. Also make sure to use the best weights of yolov5 in yolov5+deepsort. | 11,083 |
66,877,531 | I have the following arguments which are to be parsed using argparse
* input\_dir (string: Mandatory)
* output\_dir (string: Mandatory)
* file\_path (string: Mandatory)
* supported\_file\_extensions (comma separated string - Optional)
* ignore\_tests (boolean - Optional)
If either comma separated string and a string ... | 2021/03/30 | [
"https://Stackoverflow.com/questions/66877531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7717431/"
] | The column `type` is ambiguous because it appears in both `t1` and in your JSON\_TABLE result. You should qualify the column.
```
mysql> select distinct t.type from t1,
json_table(type, '$[*]' columns (type varchar(50) PATH '$')) as t
order by t.type;
+-------+
| type |
+-------+
| type1 |
| type2 |
|... | I am able to resolve it by writing a `CROSS JOIN`
```
SELECT distinct j.type FROM t1
CROSS JOIN
JSON_TABLE(t1.type, " $ [*]"
COLUMNS ( type VARCHAR(20) PATH '$' )
) j
``` | 11,084 |
8,456,516 | How can I go about "selecting" on multiple [`queue.Queue`](http://docs.python.org/py3k/library/queue.html)'s simultaneously?
Golang has the [desired feature](http://golang.org/doc/go_spec.html#Select_statements) with its channels:
```
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
... | 2011/12/10 | [
"https://Stackoverflow.com/questions/8456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149482/"
] | There are many different implementations of producer-consumer queues, like [queue.Queue](http://docs.python.org/py3k/library/queue.html) available. They normally differ in a lot of properties like listed on this [excellent article](http://www.1024cores.net/home/lock-free-algorithms/queues) by Dmitry Vyukov. As you can ... | If you use `queue.PriorityQueue` you can get a similar behaviour using the channel objects as priorities:
```
import threading, logging
import random, string, time
from queue import PriorityQueue, Empty
from contextlib import contextmanager
logging.basicConfig(level=logging.NOTSET,
format="%(threa... | 11,085 |
38,272,965 | It seems win32api should be able to do this given the answer [here](http://VBComponents.Remove) and [.
I would like to remove all modules from an excel workbook (.xls) using python | 2016/07/08 | [
"https://Stackoverflow.com/questions/38272965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/360826/"
] | Consider using the [VBComponents collection](https://msdn.microsoft.com/en-us/library/aa443983(v=vs.60).aspx) available in the COM interface accessible with Python's `win23com.client` module. However, inside the particular workbook you need to first grant [programmatic access to the VBA object library](https://stackove... | Actually simply reading in the file with [`xlrd`](https://pypi.python.org/pypi/xlrd), copying with [`xlutils`](https://pypi.python.org/pypi/xlutils), and spitting it out with [`xlwt`](https://pypi.python.org/pypi/xlwt) will remove the VBA (and other stuff):
```
import xlrd, xlwt
from xlutils.copy import copy as xl_cop... | 11,090 |
8,923,764 | ```
#!/bin/python
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import time
import commands
import sys
import string
import random
device = MonkeyRunner.waitForConnection(10)
device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
time.sleep(1)
device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
... | 2012/01/19 | [
"https://Stackoverflow.com/questions/8923764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706780/"
] | Not all namespaces have corresponding DLL file names used in the Add Reference dialog. System.Windows is one of these.
For example, `System.Windows.Clipboard` is resident in the PresentationCore.dll, but `System.Windows.SizeConverter` is in WindowsBase.dll. It all depends on the actual types you need to access. | System.Windows is the WPF base classes - you cant add that assembly to an ASP.NET site. You will need to change your application type to use it. | 11,091 |
55,930,785 | I am trying to understand NumPy `np.fromfunction()`.
following piece of code is extracted from this [post](https://stackoverflow.com/a/55929789/11074017).
```
dist = np.array([ 1, -1])
f = lambda x: np.linalg.norm(x, 1)
f(dist)
```
the output
```
2.0
```
is as expected.
when I put them together to use np.linalg... | 2019/05/01 | [
"https://Stackoverflow.com/questions/55930785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Look at the error:
```
In [171]: np.fromfunction(f, ds.shape)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-171-1a3ed1ade41a> in <module>
----> 1 np.fr... | As you are using a 2 dimensional array, your function needs to take 2 inputs.
The docs of `np.fromfunction()` <https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html> say "Construct an array by executing a function over each coordinate."
So it will pass the coordinates of each element of the arr... | 11,092 |
31,965,153 | I'm actually trying to program a sort of "rolegame", and actually I'm stuck in the process of creating the new Character files. I'm actually trying to make it so, if I call a character file, the system checks if it exists and, if not, it will create it. This is the code, just trying if it will create an empty file call... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31965153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5219236/"
] | This is a cordova bug - <https://issues.apache.org/jira/browse/CB-5398>.
You can change your path like this.
```
function uploadPhoto(imageURI) {
//alert(imageURI); return false;
//alert(imageURI);
if (imageURI.substring(0,21)=="content://com.android") {
photo_... | You can specify `encodingType: Camera.EncodingType.JPEG` and render image in your success callback like this- `$('#yourElement).attr('src', "data:image/jpeg;base64," + ImageData);`
```
navigator.camera.getPicture(onSuccess, onFail, {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceTyp... | 11,093 |
69,334,001 | When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve ! | 2021/09/26 | [
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] | Use `tf.keras.optimizers.Adam(learning_rate)` instead of `keras.optimizers.Adam(learning_rate)` | I think you are using Keras directly. Instead of giving as from keras.distribute import —> give as from tensorflow.keras.distribute import
Hope this would help you.. It is working for me. | 11,094 |
60,631,553 | I would like to parametize the columns and my dataframe in an cursor.execute function. I'm using pymssql, because I like the fact that I can name the parametized columns. Yet I still don't know how to properly tell python that I'm referring to a specific dataframe and I would like to use this columns. Here is the last ... | 2020/03/11 | [
"https://Stackoverflow.com/questions/60631553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12790189/"
] | I had the same issue. Try to add after your Proxy:
`RequestHeader set X-Forwarded-Proto https` to your `...ssl.conf` which is in sites-available folder. | I had same issue, I was trying to setup a SSL termination reverse proxy with apache. I followed this [article](https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension).
Using `0.0.0.0` instead of localhost worked for me.
```
<IfModule mod_ssl.c>
<V... | 11,104 |
1,383,863 | If you install multiple versions of python (I currently have the default 2.5, installed 3.0.1 and now installed 2.6.2), it automatically puts stuff in `/usr/local`, and it also adjusts the path to include the `/Library/Frameworks/Python/Versions/theVersion/bin`, but whats the point of that when `/usr/local` is already ... | 2009/09/05 | [
"https://Stackoverflow.com/questions/1383863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148195/"
] | There's no a priori guarantee that /usr/local/bin will stay on the PATH (especially it will not necessarily stay "in front of" /usr/bin!-), so it's perfectly reasonable for an installer to ensure the specifically needed /Library/.../bin directory does get on the PATH. Plus, it may be the case that the /Library/.../bin ... | I just noticed/encountered this issue on my Mac. I have Python 2.5.4, 2.6.2, and 3.1.1 on my machine, and was looking for a way to easily change between them at will. That is when I noticed all the symlinks for the executables, which I found in both '/usr/bin' and '/usr/local/bin'. I ripped all the non-version specific... | 11,105 |
58,113,118 | I have a python script that connect PostgresSQL.
Below is the script.
```
import psycopg2
conn = psycopg2.connect('connection string')
try:
curr = conn.cursor()
sql_strng = "SELECT * FROM tbl"
### Further operations###
except(Exception, psycopg2.Error) as error:
print("error",error)
finally:
if (conn... | 2019/09/26 | [
"https://Stackoverflow.com/questions/58113118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290715/"
] | Just use `this.types.filter(({id}) => !this.selected_types.includes(id))`:
```js
let types = [{
id: 1,
name: "Hello"
},
{
id: 2,
name: "World"
},
{
id: 3,
name: "Jon Doe"
}
]
let selected_types = [1, 2];
let resArr = types.filter(({id}) => !selected_types.includes(id));... | **You can achieve Javascript's native method filter, which finally returns a new object**
```
let types = [{
id: 1,
name: "Hello"
},
{
id: 2,
name: "World"
},
{
id: 3,
name: "Jon Doe"
}
]
let selected_types = [1, 2];
types = types.filter(obj => {
if (selected_types.indexOf(obj.id)... | 11,106 |
37,442,993 | I have a csv file I wish to load into pandas, but the formatting is giving me some problems. The file is such:
>
> Version 1
>
>
> ,Date Time,Name,Value
>
>
> ,26/Jan/2016 07:35:52,Name1,340rqi
>
>
> ,26/Jan/2016 07:00:00,Name2,1.00E+005
>
>
> ,26/Jan/2016 07:00:00,Name3,pulled\_9
>
>
>
(It's a mess of a ... | 2016/05/25 | [
"https://Stackoverflow.com/questions/37442993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6382244/"
] | >
> When is DbConnection.StateChange called?
>
>
>
You can find out by looking at the Microsoft reference source code.
The [`StateChange`](http://referencesource.microsoft.com/#System.Data/System/Data/Common/DBConnection.cs,191b2f1d559f7e8d) event is raised by the [`DbConnection.OnStateChange`](http://referenceso... | The `StateChange` event is meant for the state of the connection, not the instance of the database server. To get the state of the database server,
>
> The StateChange event occurs when the state of the event changes from
> closed to opened, or opened to closed.
>
>
>
From MSDN: <https://msdn.microsoft.com/en-u... | 11,107 |
12,850,550 | I'm reading conflicting reports about using PostgreSQL on Amazon's Elastic Beanstalk for python (Django).
Some sources say it isn't possible: (http://www.forbes.com/sites/netapp/2012/08/20/amazon-cloud-elastic-beanstalk-paas-python/). I've been through a dummy app setup, and it does seem that MySQL is the only option... | 2012/10/12 | [
"https://Stackoverflow.com/questions/12850550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133318/"
] | Postgre is now selectable from the AWS RDS configurations. Validated through Elastic Beanstalk application setup 2014-01-27. | >
> Is it possible to run a PostgreSQL database with a Django app on
> Elastic Beanstalk?
>
>
>
Yes. The dummy app setup you mention refers to the use of an Amazon Relational Database Service. At the moment PostgreSQL is not available as an Amazon RDS, but you can configure your beanstalk AMI to act as a local Po... | 11,108 |
65,238,577 | I have a simple Users resource with a put method to update all user information except user password. According to Flask-Restx docs when a model has set the strict and validation params to true, a validation error will be thrown if an unspecified param is provided in the request. However, this doesn't seem to be workin... | 2020/12/10 | [
"https://Stackoverflow.com/questions/65238577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8184470/"
] | I resolved my issue by pulling the latest version of Flask-RESTX from Github. The strict parameter for models was merged after Flask-RESTX version 0.2.0 was released on Pypi in March of 2020 (see the closed [issue](https://github.com/python-restx/flask-restx/issues/264) in Flask-RESTX repo for more context). My confusi... | It's been a while since I touched on this but from what I can tell, I don't think you are using the strict param correctly. From the documentation [here](https://flask-restx.readthedocs.io/en/latest/_modules/flask_restx/model.html), the `:param bool strict` is defined as
>
> :param bool strict: validation should rais... | 11,109 |
10,816,816 | I was doing some practice problems in [Coding Bat](http://codingbat.com/python), and came across this one..
```
Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.
lone_sum(1, 2, 3) → 6
lone_sum(3, 2, 3) → 2
lone_sum(3, 3... | 2012/05/30 | [
"https://Stackoverflow.com/questions/10816816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088536/"
] | Another possibility that works for an arbitrary number of arguments:
```
from collections import Counter
def lone_sum(*args):
return sum(x for x, c in Counter(args).items() if c == 1)
```
Note that in Python 2, you should use `iteritems` to avoid building a temporary list. | ```
def lone_sum(a, b, c):
z = (a,b,c)
x = []
for item in z:
if z.count(item)==1:
x.append(item)
return sum(x)
``` | 11,110 |
47,286,349 | i need a simple python code which makes a number menu, that doesn't take up many lines
```
print ("Pick an option")
menu =0
Menu = input("""
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:
Password = input("Please enter the password you want to check")
... | 2017/11/14 | [
"https://Stackoverflow.com/questions/47286349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8938872/"
] | You problem seems to arise from the fact that you use `flatMap` so if there is no data in the DB for a given `id` and you get an empty `Observable`, `flatMap` just produces no output for such `id`. So it looks like what you need is [defaultIfEmpty](http://reactivex.io/documentation/operators/defaultifempty.html) which ... | One way of doing this is the following:
**(1)** convert sequence of ids to `Observable` and `map` it with
```
id => (id, false)
```
... so you'll get an observable of type `Observable[(Int, Boolean)]` (lets call this new observable `first`).
**(2)** fetch data from database and `map` every fetched row to from:
``... | 11,120 |
13,047,458 | I'm trying to set speed limits on downloading/uploading files and found that twisted provides [twisted.protocols.policies.ThrottlingFactory](http://twistedmatrix.com/documents/current/api/twisted.protocols.policies.ThrottlingFactory.html) to handle this job, but I can't get it right. I set `readLimit` and `writeLimit`,... | 2012/10/24 | [
"https://Stackoverflow.com/questions/13047458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1770691/"
] | This does **not** look like **clustering** to me.
Instead, I figure you want a simple **decision tree classification**.
It should already be available in Rapidminer. | You could use the "Generate Attributes" operator.
This creates new attributes from existing ones.
It would be relatively tiresome to create all the rules but they would be something like
cluster : if (((A==0)&&(B==0)&&(C==0)),1,0) | 11,122 |
2,537,929 | I have a python logger set up, using python's logging module. I want to store the string I'm using with the logging Formatter object in a configuration file using the ConfigParser module.
The format string is stored in a dictionary of settings in a separate file that handles the reading and writing of the config file.... | 2010/03/29 | [
"https://Stackoverflow.com/questions/2537929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56815/"
] | Did you try to escape percents with `%%`? | There's `RawConfigParser` which is like `ConfigParser` without the interpolation behaviour. If you don't use the interpolation feature in any other part of the configuration file, you can simply replace `ConfigParser` with `RawConfigParser` in your code.
See the documentation of [RawConfigParser](http://docs.python.or... | 11,123 |
15,863,657 | Kinda a newbie in python, starting to lean on how python works with strings and iteration over strings.
Had worked on a chunk of so-called code 'Palindrome', would you take a look at which part exactly it is going wrong?
```
def palindrome(s):
if len(s) < 1:
return True
else:
i = 0
j = ... | 2013/04/07 | [
"https://Stackoverflow.com/questions/15863657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540033/"
] | Below you have a little less complicated solution:
```
def is_palindrome(s):
return s == s[::-1]
```
In your version you are always returning `True` for all strings with `len(s) >= 1` | I may be missing something obvious, but shouldn't this be enough?
```
def ispalindrome(s):
return s == s[::-1]
``` | 11,133 |
23,554,644 | I was able to get my flask app running as a service thanks to [Is it possible to run a Python script as a service in Windows? If possible, how?](https://stackoverflow.com/questions/32404/is-it-possible-to-run-a-python-script-as-a-service-in-windows-if-possible-how), but when it comes to stopping it i cannot. I have to ... | 2014/05/09 | [
"https://Stackoverflow.com/questions/23554644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917993/"
] | You can stop the Werkzeug web server gracefully before you stop the Win32 server. Example:
```
from flask import request
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.route('/sh... | I recommend you use <http://supervisord.org/>. Actually not work in Windows, but with Cygwin you can run supervisor as in Linux, including run as service.
For install Supervisord: <https://stackoverflow.com/a/18032347/3380763>
After install you must configure the app, here an example: <http://flaviusim.com/blog/Deplo... | 11,134 |
1,817,780 | I have created a python script which pulls data out of OLE streams in Word documents, but am having trouble converting the OLE2-formatted timestamp to something more human-readable :(
The timestamp which is pulled out is 12760233021 but I cannot for the life of me convert this to a date like 12 Mar 2007 or similar.
A... | 2009/11/30 | [
"https://Stackoverflow.com/questions/1817780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Well, Python 3.0 and 3.1 are already released, so you can check this out for yourself. The end result was that map and filter were kept as built-ins, and lambda was also kept. The only change was that reduce was moved to the functools module; you just need to do
```
from functools import reduce
```
to use it.
Futur... | In Python 3.x, Python continues to have a rich set of functional-ish tools built in: list comprehensions, generator expressions, iterators and generators, and functions like `any()` and `all()` that have short-circuit evaluation wherever possible.
Python's "Benevolent Dictator For Life" floated the idea of removing `m... | 11,136 |
55,118,630 | Is there a way to start a python script on a server from a webpage?
At work I've made a simple python script using selenium to do a routine job (open a webpage and click a few buttons).
I want to be able to start this remotely (still on company network) but due to security/permissions here at work I can't use telnet/... | 2019/03/12 | [
"https://Stackoverflow.com/questions/55118630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3379555/"
] | Strings are immutable. They cannot change. Any action you perform on them will result in a "new" string that is returned by the method you called upon it.
Read more about it: [Immutability of Strings in Java](https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java)
So in your example, if you wish ... | You can reassign `tempString` with its new value :
```
String tempString= "abc is very easy";
tempString = tempString.replace("very","not");
System.out.println("tempString is "+tempString);
```
Result is :
```
tempString is abc is not easy
```
Best | 11,137 |
29,999,482 | I try to "click" Javascript alert for reboot confirmation in DSL modem with a Python script as follows:
```
#!/usr/bin/env python
import selenium
import time
from selenium import webdriver
cap = {u'acceptSslCerts': True,
u'applicationCacheEnabled': True,
u'browserConnectionEnabled': True,
u'browserName': u'phantomjs... | 2015/05/02 | [
"https://Stackoverflow.com/questions/29999482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2022518/"
] | As PhantomJs has no support for Alert boxes .you need to use executor for this.
```
driver.execute_script("window.confirm = function(msg) { return true; }");
``` | In java, driver.switchTo().alert().accept(); will do the job.
I am not sure, why you are using "print al.accept()", probably are you trying to print text? then alert.getText() will do in java, sorry if i am wrong, because i am sure in python.
Thank You,
Murali
<http://seleniumtrainer.com/> | 11,138 |
69,694,596 | This is my code. It should send message to the channel when user join the server.
```py
@client.event
async def on_member_join(member):
print('+') #this works perfectly
ch = client.get_channel(84319995256905728)
await ch.send(f"{member.name} has joined")
```
But error was occur. This is the output:
```p... | 2021/10/24 | [
"https://Stackoverflow.com/questions/69694596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17067135/"
] | You can approximate the requirement this way:
```
from collections.abc import Iterable
def f2(sequence_type, *elements):
if isinstance(elements[0],Iterable):
return sequence_type(elements[0])
else:
return sequence_type(elements[:1])
```
which is close, but fails for `f(list, 'ab')` which ret... | The examples for `str` doesn't really fit the description of the function, but here are some implementations that pass your test cases - you want to wrap the element into a collection first for tuple/list/set before converting:
```py
def f(sequence_type, element):
return sequence_type([element] if sequence_type !=... | 11,139 |
52,879,261 | I have a spring boot application and i am trying to implement the spring security to override the default username and password generated by spring .but its not working. spring still using the default user credentials.
```
@EnableWebSecurity
@Configuration
public class WebSecurityConfigurtion extends WebSecurityConfig... | 2018/10/18 | [
"https://Stackoverflow.com/questions/52879261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10525271/"
] | This can be done using following properties on `application.properties` or `application.yaml` file.
```
spring.security.user.name
spring.security.user.password
spring.security.user.roles
```
Take a look at [this.](https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html) | Issue fixed by adding the config package where the security classes are availble into the component scanning of the main class. | 11,142 |
26,374,866 | I'm using the [Unirest library](http://unirest.io/python.html) for making async web requests with Python. I've read the documentation, but I wasn't able to find if I can use proxy with it. Maybe I'm just blind and there's a way to use it with Unirest?
Or is there some other way to specify proxy for Python? Proxies sh... | 2014/10/15 | [
"https://Stackoverflow.com/questions/26374866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2298183/"
] | I know nothing about Unirest, but, In all the scripts I wrote that requierd proxy support I used SocksiPy (<http://socksipy.sourceforge.net>) module. It support HTTP, SOCKS4 and SOCKS5 and it s really easy to use. :) | Would something like this work for you?
[1] <https://github.com/obriencj/python-promises> | 11,145 |
23,543,202 | While reviewing the system library `socket.py` implementation I came across this code
```
try:
import errno
except ImportError:
errno = None
EBADF = getattr(errno, 'EBADF', 9)
EINTR = getattr(errno, 'EINTR', 4)
```
Is this code just a relic of a bygone age, or there are platforms/implementations out there fo... | 2014/05/08 | [
"https://Stackoverflow.com/questions/23543202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1499402/"
] | The reason this might be a bit tricky is because the parent nodes have some set defaults.
Set width and height to 100% in initialization of `Reveal`:
```
Reveal.initialize({
width: "100%",
height:"100%"
});
```
Ensure that the slide (ie. `section`) uses the whole space:
```
.full {
height:100%;
wi... | Can you provide an example of the HTML that has the class `.reveal`? Add `position:absolute` to your selector rule. If you want the caption to sit flush at the bottom corner of each slide, it's best to set the position to `bottom:0px` instead of `top`.
For example:
```
<style type="text/css">
.reveal .reveal_sectio... | 11,146 |
34,624,964 | I want to extract certain information from the output of a program. But my method does not work. I write a rather simple script.
```
#!/usr/bin/env python
print "first hello world."
print "second"
```
After making the script executable, I type `./test | grep "first|second"`. I expect it to show the two sentences. B... | 2016/01/06 | [
"https://Stackoverflow.com/questions/34624964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5719744/"
] | Having researched this myself just now, it looks as though the Meteor version 1.4 release will be updated to version 3.2 of MongoDB, in which "*32-bit binaries are deprecated*"
* [Github ticket for the updating of MongoDB](https://github.com/meteor/meteor/issues/6957)
* [MongoDB declaration that 3.2 has deprecated 32-... | I guess you didn't install the right version of Mongo if you have a 32 bits version.
check out their installation guide:
<https://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/>
First download the right 64 bits version for Windows:
<https://www.mongodb.org/downloads#production>
and follow the instructi... | 11,147 |
8,070,186 | Is there a way with the boto python API to specify tags when creating an instance? I'm trying to avoid having to create an instance, fetch it and then add tags. It would be much easier to have the instance either pre-configured to have certain tags or to specify tags when I execute the following command:
```
ec2server... | 2011/11/09 | [
"https://Stackoverflow.com/questions/8070186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/301816/"
] | This answer was accurate at the time it was written but is now out of date. The AWS API's and Libraries (such as boto3) can now take a "TagSpecification" parameter that allows you to specify tags when running the "create\_instances" call.
---
Tags cannot be made until the instance has been created. Even though the fu... | This method has worked for me:
```
rsvn = image.run(
... standard options ...
)
sleep(1)
for instance in rsvn.instances:
instance.add_tag('<tag name>', <tag value>)
``` | 11,148 |
41,231,632 | I am taking a course that uses ipython notebook. When I try to download the notebook (through File -> Download as -> ipython notebook), I get a file that ends with ".ipynb.json". It doesn't open as an ipython notebook but as a .json file so something like this:
```
{
"cells": [
{
"cell_type": "markdown",
"met... | 2016/12/19 | [
"https://Stackoverflow.com/questions/41231632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6841599/"
] | Are you trying download this from Github? Especially on Google Chrome browsers, I've had issues download .ipynb files using right click > **Save link as...** I'm not sure if other browsers have this issue (Microsoft Edge, Mozilla Firefox, Safari, etc.).
This causes issues since when downloading, it doesn't completely ... | I opened it as/with nbviewer and then selected it all and saved it as a "txt" file that I then opened in Notepad++. I then resaved it as a file with the extension ipynb and opened it in my jupyter notebook ok. | 11,154 |
49,737,148 | I am trying to create a CNN model in Keras with multiple conv3d to work on cifar10 dataset. But facing the following issue:
>
> ValueError: ('The specified size contains a dimension with value <=
> 0', (-8000, 256))
>
>
>
Below is my code that I am trying to execute.
```python
from __future__ import print_funct... | 2018/04/09 | [
"https://Stackoverflow.com/questions/49737148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511239/"
] | What do you gain by putting this string in your scenario. IMO all you are doing is making the scenario harder to read!
What do you lose by putting this string in your scenario?
Well first of all you now have to have at least two things the determine the exact contents of the string, the thing in the application that ... | Try with a datatable approach. You will have to add a `DataTable` argument in the stepdefinition.
```
Then Drop-dow patient_breed contains
'Breed1'
'Breed2'
...
...
...
'Breed20']
```
For a multiline approach try the below. In this you will have to add a `String` argument to the stepdefinition.
```
Then Drop-dow pa... | 11,164 |
2,460,407 | I want to develop a anonymous chat website like <http://omgele.com>.
I know that this website is developed in python using `twisted matrix` framework. Using twisted matrix it's easy to develop such website.
But I am very comfortable in Java and have 1 year's experience with it, and dont know python.
1. What should I d... | 2010/03/17 | [
"https://Stackoverflow.com/questions/2460407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291241/"
] | *I would politely ask the people at omgele.com for a copy of their code and study it to*
1. learn Python and twisted matrix
2. decide to use it or if I decide against it, to apply what I learned from them to write my own Java site
unfortunately, the source code is not likely to be available..
Still I advise to lea... | Learning Python can be an informative, interesting, and valuable process. When you really get going, you will probably find you can develop more rapidly than in Java. Twisted is an fairly well-executed framework which lets you avoid many of the pitfalls you can run into with asynchronous IO; it has top-notch implementa... | 11,166 |
12,142,174 | I want to call a Python script from C, passing some arguments that are needed in the script.
The script I want to use is mrsync, or [multicast remote sync](http://sourceforge.net/projects/mrsync/). I got this working from command line, by calling:
```
python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/t... | 2012/08/27 | [
"https://Stackoverflow.com/questions/12142174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960585/"
] | Seems like you're looking for an answer using the python development APIs from Python.h. Here's an example for you that should work:
```
#My python script called mypy.py
import sys
if len(sys.argv) != 2:
sys.exit("Not enough args")
ca_one = str(sys.argv[1])
ca_two = str(sys.argv[2])
print "My command line args are... | You have two options.
1. Call
```
system("python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/targetdata")
```
in your C code.
2. Actually use the API that `mrsync` (hopefully) defines. This is more flexible, but much more complicated. The first step would be to work out how you would perform the above... | 11,174 |
20,412,091 | I am trying to make this 2 n body diagram to work in vpython, it seems that is working but something is wrong with my center or mass, or something, i don't really know. The 2 n body system is shifting and is not staying still.
```
from visual import*
mt= 1.99e30 #Kg
G=6.67e-11 #N*(m/kg)^2
#Binary System stars
StarA... | 2013/12/05 | [
"https://Stackoverflow.com/questions/20412091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839580/"
] | Two points I'd like to make about your problem:
1. You're using Euler's method of integration. That is the "i.velocity = i.velocity + i.acceleration\*dt" part of your code. This method is not very accurate, especially with oscillatory problems like this one. That's part of the reason you're noticing the drift in your ... | This is wrong:
```
for each in objects:
Xcm=Xcm/TotalMass
...
```
This division should only happen once. And then the averages should be removed from the objects, as in
```
Xcm=Xcm/TotalMass
...
for each in objects:
each.pos.x -= Xcm
...
``` | 11,175 |
28,550,511 | I am trying to learn how to use callbacks between C and Python by way of Cython and have been looking at [this demo](https://github.com/cython/cython/tree/master/Demos/callback). I would like a Python function applied to one std::vector/numpy.array and store the results in another. I can compile and run without errors,... | 2015/02/16 | [
"https://Stackoverflow.com/questions/28550511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2308288/"
] | Thanks, Ian. Based on your suggestion, I changed the code to return a vector instead of trying to modify it in place. This works, although is admittedly not particularly efficient
callback.hpp
```
typedef double (*Callback)( void *apply, double x );
vector<double> function( Callback callback, void *apply,
... | There is an implicit copy of the array made when you cast it to be a vector.
There isn't currently any way to have a vector take ownership of memory that has already been allocated, so the only workaround will be to copy the values manually or by exposing `std::copy` to cython. See [How to cheaply assign C-style array ... | 11,176 |
67,798,070 | I am more or less following [this example](http://4/1AY0e-g4pMh6JPfkexh5nvWf9lvug3sHK98_jxAnwhsYlrB3F20Jkp350PKY) to integrate the ray tune hyperparameter library with the huggingface transformers library using my own dataset.
Here is my script:
```
import ray
from ray import tune
from ray.tune import CLIReporter
fro... | 2021/06/02 | [
"https://Stackoverflow.com/questions/67798070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7254514/"
] | I had the same error when trying to use pickle.dump(), for me it worked to downgrade pickle5 from version 0.0.11 to 0.0.10 | Not a "real" solution but at least a workaround. For me this issue was occurring on Python 3.7. Switching to Python 3.8 solved the issue. | 11,177 |
66,559,058 | I would like to convert a string `temp.filename.txt` to `temp\.filename\.txt` using python
Tried string replace method but the output is not as expected
```
filename = "temp.filename.txt"
filename.replace(".", "\.")
output: 'temp\\.filename\\.txt'
``` | 2021/03/10 | [
"https://Stackoverflow.com/questions/66559058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3572886/"
] | `\` is a special character, which is *represented* as `\\`, this doesn't mean your string actually contains 2 `\` characters.
(as suggested by @saipy, if you *print* your string, only single `\` should show up...) | ```
filename = "temp.filename.txt"
result=filename.replace(".", "\.")
print(result)
```
[I stored a result in variable(result) its working fine check this](https://i.stack.imgur.com/klc8N.png) | 11,179 |
57,379,888 | The Source Code
---------------
I have a bit of code requiring that I call a property setter to test wether or not locking functionaliy of a class is working (some functions of the class are `async`, requiring that a padlock boolean be set during their execution). The setter has been written to raise a `RuntimeError` ... | 2019/08/06 | [
"https://Stackoverflow.com/questions/57379888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7423333/"
] | You need to actually *invoke* the setter, via an assignment. This is simple to do, as long as you use `assertRaises` as a context manager.
```
with self.assertRaises(RuntimeError):
my_object.filename = "testfile.txt"
```
---
If you couldn't do that, you would have to fall back to an explicit `try` statement (wh... | You can use the `setattr` method like so:
```
self.assertRaises(ValueError, setattr, p, "name", None)
```
In the above example, we will try to set `p.name` equal to `None` and check if there is a `ValueError` raised. | 11,180 |
13,212,300 | I don't know if this question has duplicates , but i haven't found one yet.
when using python you can create GUI fastly , but sometimes you cannot find a method to do what you want. for example i have the following problem:
let's suppose that there is a canvas called K with a rectangle with ID=1(canvas item id , not ... | 2012/11/03 | [
"https://Stackoverflow.com/questions/13212300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1569222/"
] | You can use [`Canvas.itemconfig`](https://web.archive.org/web/20201108093851id_/http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.itemconfig-method):
```
item = K.create_rectangle(x1,y1,x2,y2,options...)
K.itemconfig(item,options)
```
To move the item, you can use [`Canvas.move`](https://web.archive.org/web/20... | I searched around and found the perfect Tkinter method for resizing. canvas.coords() does the trick. just feed it your new coordinates and it's "good to go". Python 3.4
PS. don't forget the first param is the id. | 11,181 |
4,156,464 | I need to parse a series of short strings that are comprised of 3 parts: a question and 2 possible answers. The string will follow a consistent format:
This is the question "answer\_option\_1 is in quotes" "answer\_option\_2 is in quotes"
I need to identify the question part and the two possible answer choices that ... | 2010/11/11 | [
"https://Stackoverflow.com/questions/4156464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504732/"
] | ```
>>> import re
>>> s = "Who will win the game 'Michigan' 'Ohio State'"
>>> re.match(r'(.+)\s+([\'"])(.+?)\2\s+([\'"])(.+?)\4', s).groups()
('Who will win the game', "'", 'Michigan', "'", 'Ohio State')
``` | One possibility is that you can use regex.
```
import re
robj = re.compile(r'^(.*) [\"\'](.*)[\"\'].*[\"\'](.*)[\"\']')
str1 = "Who will win the game 'Michigan' 'Ohio State'"
r1 = robj.match(str1)
print r1.groups()
str2 = 'What color is the sky today? "blue" or "grey"'
r2 = robj.match(str2)
r2.groups()
```
Output:
... | 11,182 |
41,535,881 | I'm new to Conda package management and I want to get the latest version of Python to use f-strings in my code. Currently my version is (`python -V`):
```
Python 3.5.2 :: Anaconda 4.2.0 (x86_64)
```
How would I upgrade to Python 3.6? | 2017/01/08 | [
"https://Stackoverflow.com/questions/41535881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343241/"
] | I found [this page](https://support.anaconda.com/customer/en/portal/articles/2797011-updating-anaconda-to-python-3-6) with detailed instructions to upgrade Anaconda to a major newer version of Python (from Anaconda 4.0+). First,
```
conda update conda
conda remove argcomplete conda-manager
```
I also had to `conda r... | Only solution that works was create a new conda env with the name you want (you will, unfortunately, delete the old one to keep the name). Then create a new env with a new python version and re-run your `install.sh` script with the conda/pip installs (or the yaml file or whatever you use to keep your requirements):
``... | 11,186 |
42,549,482 | Here is the pseudo code:
```
class Foo (list):
def methods...
foo=Foo()
foo.readin()
rule='....'
bar=[for x in foo if x.match(rule)]
```
Here, bar is of a list, however I'd like it to be a instance of Foo, The only way I know is to create a for loop and append items one by one:
```
bar=Foo()
for item in foo:... | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4250879/"
] | You can pass in a [generator expression](https://docs.python.org/3/tutorial/classes.html#generator-expressions) to the `Foo()` call:
```
bar = Foo(x for x in foo if x.match(rule))
```
(When passing a generator expression to a call, where it is the only argument, you can drop the parentheses you normally would put ar... | It seems another answer got deleted because the original answerer deleted it. So I post the other way here for completeness. If the origin answerer restore he's answer I will delete this answer myself.
another way to do this is to use the build in filter function. the code is :
```
bar=filter( lambda x: x.match(rule)... | 11,196 |
51,011,204 | I have a 1D array X with both +/- elements. I'm isolating their signs as follows:
```
idxN, idxP = X<0, X>=0
```
Now I want to create an array whose value depends on the sign of X. I was trying to compute this but it gives the captioned syntax error.
```
y(idxN) = [math.log(1+np.exp(x)) for x in X(idxN)]
y(idxP) =... | 2018/06/24 | [
"https://Stackoverflow.com/questions/51011204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9473446/"
] | In some programming languages like Matlab, indexes are references with parentheses. In Python, indexes are represented with square brackets.
If I have a list, `mylist = [1,2,3,4]`, I reference elements like this:
```
> mylist[1]
2
```
Wen you say `y(idxN)`, Python thinks you are trying to pass `idxN` as an argume... | I got it to work like this:
```
y = np.zeros(X.shape)
idxN, idxP = X<0, X>=0
yn,yp,xn,xp = y[idxN], y[idxP],X[idxN],X[idxP]
yn = [math.log(1+np.exp(x)) for x in xn]
yp = xp+[math.log(np.exp(-x)+1) for x in xp];
```
If there is a better way, please let me know. Thanks. | 11,197 |
13,283,628 | I have created a mezzanine project and its name is mezzanine-heroku-test
I create a Procfile that has the content as follow:
**web: python manage.py run\_gunicorn -b "0.0.0.0:$PORT" -w 3**
Next, I access to the website to test and I receive the error: Internal Server Error.
So, Could you please help me deploy mezzani... | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/875781/"
] | Two possibilities:
1. There is a table within another schema ("database" in mysql terminology) which has a FK reference
2. The innodb internal data dictionary is out of sync with the mysql one.
You can see which table it was (one of them, anyway) by doing a "SHOW ENGINE INNODB STATUS" after the drop fails.
If it tur... | Instead of using default innodb storage engine you can easily configure django to use MyISAM. In the later case, it wouldn't restrict you from performing various operation because of the relationships. Both have their positive and negative points. | 11,198 |
39,961,414 | I am new to learning regex in python and I'm wondering how do I use regex in python to store the integers(positive and negative) i want into a list!
For example
This is the data in a list.
```
data =
[u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=-5,B=5)',
u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[3... | 2016/10/10 | [
"https://Stackoverflow.com/questions/39961414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6949864/"
] | When you use `$(".form-control")`, jquery select all `.form-control` element. But you need to select target element using `this` variable in event function and use [`.prev()`](https://api.jquery.com/prev/) to select previous element.
```js
$(".show").mousedown(function(){
$(this).prev().attr('type','text');
}).mou... | Just target the previous input instead of all inputs with the given class
```js
$(".form-control").on("keyup", function() {
if ($(this).val())
$(this).next(".show").show();
else
$(this).next(".show").hide();
}).trigger('keyup');
$(".show").mousedown(function() {
$(this).prev(".form-contro... | 11,199 |
69,516,584 | i am running npm install command on my project but getting error
>
> Build failed with error code: 1
>
>
>
Part of the log posted below.
```
0 verbose cli [
0 verbose cli 'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli 'C:\\Users\\vined\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
0 verb... | 2021/10/10 | [
"https://Stackoverflow.com/questions/69516584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16418162/"
] | You can create a second list that stores the valid index values.
```
import random
our = [3, 3, 0, 3, 3, 7]
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
# index: [0, 1, 3, 4]
random_index = random.choice(index)
```
**EDIT:** You can perform a sanity check for a non-zer... | You can use a while loop to check if the number equals 0 or not.
```
import random
our = [3, 6, 2, 0, 3, 0, 5]
random_number = 0
while random_number == 0:
random_index = random.randint(0, len(our)-2)
random_number = our[random_index]
print(random_number)
``` | 11,202 |
16,276,913 | at the moment I do:
```
def get_inet_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('mysite.com', 80))
return s.getsockname()[0]
```
This was based on:
[Finding local IP addresses using Python's stdlib](https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pyt... | 2013/04/29 | [
"https://Stackoverflow.com/questions/16276913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194306/"
] | The question is, do you just want to connect, or do you really want the address?
If you just want to connect, you can do
```
s = socket.create_connection(('mysite.com', 80))
```
and have the connection established.
However, if you are interested in the address, you can go one of these ways:
```
def get_ip_6(host,... | You should be using the function [socket.getaddrinfo()](http://docs.python.org/2/library/socket.html#socket.getaddrinfo)
Example code to get IPv6
```
def get_ip_6(host,port=80):
# discard the (family, socktype, proto, canonname) part of the tuple
# and make sure the ips are unique
alladdr = list(
... | 11,203 |
4,093,118 | Is there a way to increment the year on filtered objects using the update() method?
I am using:
```
python 2.6.5
django 1.2.1 final
mysql Ver 14.14 Distrib 5.1.41
```
I know it's possible to do something like this:
```
today = datetime.datetime.today()
for event in Event.objects.filter(end_date__lt=today).iterato... | 2010/11/04 | [
"https://Stackoverflow.com/questions/4093118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208347/"
] | One potential cause of *"Warning: Data truncated for column X"* exception is the use of non-whole day values for the timedelta being added to the **DateField** - it is fine in python, but fails when written to the mysql db. If you have a **DateTimeField**, it works too, since the precision of the persisted field matche... | Quick but ugly:
```
>>> a.created.timetuple()
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=2, tm_hour=2, tm_min=35, tm_se
c=14, tm_wday=3, tm_yday=307, tm_isdst=-1)
>>> time = list(a.created.timetuple())
>>> time[0] = time[0] + 1
>>> time
[2001, 11, 2, 2, 35, 14, 3, 307, -1]
>>>
``` | 11,204 |
58,537,324 | For multiple `csv` files in a folder, I hope to loop all files ends with `csv` and merge as one excel file, here I give two examples:
**first.csv**
```
date a b
0 2019.1 1.0 NaN
1 2019.2 NaN 2.0
2 2019.3 3.0 2.0
3 2019.4 3.0 NaN
```
**second.csv**
```
date c d
0 2019.1 1.0 Na... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58537324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8410477/"
] | You can use Linq to perform your shift, here is a simple method you can use
```
public int[] shiftRight(int[] array, int shift)
{
var result = new List<int>();
var toTake = array.Take(shift);
var toSkip = array.Skip(shift);
result.AddRange(toSkip);
result.AddRange(toTak... | If this is only for strings and the wraparound is necessary I would suggest to use `str.Substring(0,shift)`
and append it to `str.Substring(shift)` (don't try to reinvent the weel)
(some info about the substring method: [String.Substring](https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netfram... | 11,207 |
67,539,918 | After installing Flask, When I used
`from flask import Flask`
to check if flask is properly installed or not, it gave the following error
```
>>> from flask import Flask
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/flask/__init__.py", line 3,... | 2021/05/14 | [
"https://Stackoverflow.com/questions/67539918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12194111/"
] | Flask is now at 2.0.0, which has ratcheted forward on requirements.
If you're on a system that is still on Python3.5, your alternative is to install the most recent in the 1.x line, and put
```
Flask==1.1.4
```
in your `requirements.txt`, or
```
venv/bin/pip install Flask==1.1.4
```
to install it manually. | The error indicates that you're running Python 3.5. Variable annotations that the library is attempting to use weren't [introduced until 3.6 though](https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations).
Upgrade to at least 3.6 to solve this. 3.9 is available too, so unless you need to use... | 11,209 |
37,316,731 | I have a bash script which reads variable from environment and then passes it to the python script like this
```
#!/usr/bin/env bash
if [ -n "${my_param}" ]
then
my_param_str="--my_param ${my_param}"
fi
python -u my_script.py ${my_param_str}
```
Corresponding python script look like this
```
parser = argparse... | 2016/05/19 | [
"https://Stackoverflow.com/questions/37316731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1744914/"
] | For the limited example you can basically get the same behavior just using
```
arg = os.environ.get('my_param', '')
```
where the first argument to `get` is the variable name and the second is the default value used should the var not be in the environment. | The quotes you write around the string do not get preserved when you assign a Bash string variable:
```
$ export my_param="Some -- string"
$ echo $my_param
Some -- string
```
You need to place the quotes around the variable again when you use it to create the `my_param_str`:
```
my_param_str="--my_param \"${my_para... | 11,211 |
50,420,139 | I am using python to generate a query text which I then send to the `SQL server`. The query is created in a function that accepts a list of strings which are then inserted into the query.
The query looks like:
```
SELECT *
FROM DB
WHERE last_word in ('red', 'phone', 'robin')
```
The issue is that here I have just... | 2018/05/18 | [
"https://Stackoverflow.com/questions/50420139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367204/"
] | How many rows do you have in "DB"? Are there more "last\_word"s matching the 4000 words in the IN clause than not? If so, it would be better to use NOT IN, to exclude instead of include. Also, try to never use SELECT \* since this wildcard is very unperformant, it's better to explicitly define the columns you want to i... | Try doing something like this:
```
SELECT *
FROM DB INNER JOIN WORDS_TABLE
ON DB.WORDS = WORDS_TABLE.WORDS;
```
Instead of the `*` use whatever you want to get.
`JOIN` in this case will be faster than the `IN` as you will have to write another inner query if you are using a table. | 11,214 |
22,079,173 | I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011... | 2014/02/27 | [
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] | using pieces from both @hharnisc and @mick-t answers.
```
pip install python-ldap \
--global-option=build_ext \
--global-option="-I$(xcrun --show-sdk-path)/usr/include/sasl"
``` | I had the same problem. I'm using Macports on my Mac and I have cyrus-sasl2 installed which provides sasl.h in /opt/local/include/sasl/. You can pass options to build\_ext using pip's global-option argument. To pass the include PATH to /opt/local/include/sasl/sasl.h run pip like this:
`pip install python-ldap --global... | 11,219 |
2,249,162 | I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions? | 2010/02/12 | [
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You could do something like the following:
```
<% form_for @user, :url => { :action => "update" } do |user_form| %>
...
<% user_form.fields_for :profiles do |profiles_fields| %>
Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
<% end %>
<% end %>
```
But since you already have an as... | You can use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)' to do this; but there's a little trick in forms:
You must use the singular, and call fields\_for for each profile, like this:
```
<% form_for @user do |f| -%>
<% @user.profiles.each do ... | 11,229 |
9,394,947 | I have been having a few issues using the quadrature function in python 2.7 (part of the scipy.integrate module). The equation I am trying to integrate is simply:
```
x/(d^2) - (x^2)
```
The integration is between limits a and b. However, I need to do the integration at 40 different values of d and am not sure how t... | 2012/02/22 | [
"https://Stackoverflow.com/questions/9394947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171835/"
] | ```
In [9]: from scipy.integrate import quad
In [10]: a = 0
In [11]: b = 1
In [12]: [quad(lambda x, d: x/(d**2)-x**2, a, b, args=d) for d in range(2, 5)]
Out[12]:
[(-0.20833333333333334, 2.3717550132075781e-15),
(-0.27777777777777773, 3.0886887822595405e-15),
(-0.30208333333333337, 3.3546344203581545e-15)]
```
... | ```
from numpy import arange
from scipy.integrate import quad
beg = 0.
end = 4.
res = []
for d in arange(1., 40.):
res.append(quad(lambda x: x/(d**2.)-(x**2.), beg, end))
```
You can then access the results by
```
print res[0]
```
or even
```
print res
``` | 11,235 |
217,900 | i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful | 2008/10/20 | [
"https://Stackoverflow.com/questions/217900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
] | Read the [unit testing framework section](http://www.python.org/doc/2.5.2/lib/module-unittest.html) of the [Python Library Reference](http://www.python.org/doc/2.5.2/lib/lib.html).
A [basic example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) from the documentation:
```
import random
import unittest
cl... | Here's an [example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) and you might want to read a little more on [pythons unit testing](http://www.python.org/doc/2.5.2/lib/module-unittest.html). | 11,238 |
64,529,777 | I have developed an Azure ARM template to deploy an Ubuntu Linux machine that once provisioned a bash script will run to install a particular software. The software involves downloading some packages as well as pass an input parameter from the user in order to complete the configuration. The issue I am facing is that t... | 2020/10/25 | [
"https://Stackoverflow.com/questions/64529777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14497508/"
] | I ended up using this code
```
import * as React from "react";
import Form from "@rjsf/material-ui";
import {FormProps, ObjectFieldTemplateProps} from "@rjsf/core";
import Button from "@material-ui/core/Button/Button";
import styles from './LSForm.module.scss';
import Grid from "@material-ui/core/Grid/Grid";
inte... | I found a solution which is not my prefered one:
```
const ObjectFieldTemplate = (props: ObjectFieldTemplateProps) => {
return (
<div>
{props.title}
{props.description}
{props.properties.map(element => {
return <div className="property-wrapper">{elemen... | 11,241 |
68,835,056 | I have a python script that I compiled to an EXE, one of the purposes of it is to extract a 7z file and save it to a destination.
If I'm running it from PyCharm everything works great, this is the code:
```
def delete_old_version_rename_new(self):
winutils.delete(self.old_version)
print("Extracting... | 2021/08/18 | [
"https://Stackoverflow.com/questions/68835056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14895566/"
] | Single-file executables self-extract to a temporary folder and run from there, so any relative paths will be relative to that folder *not* the location of executable you originally ran.
My solution is a code snippet such as this:
```
if getattr(sys, 'frozen', False):
app_path = os.path.dirname(sys.executable)
els... | Eventually i just used a 7z command line i took from <https://superuser.com/questions/95902/7-zip-and-unzipping-from-command-line>
and used os.system() to initialize it.
Since my program is command line based it worked even better since its providing a status on the extraction process.
Only downside is i have to move t... | 11,242 |
49,677,269 | I'm trying to create an email template in Django which uses [Materialize.css](http://materializecss.com/). Here is the template code:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<m... | 2018/04/05 | [
"https://Stackoverflow.com/questions/49677269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995862/"
] | E-mails do not support all CSS functions, I recommend you create your own CSS with alternative functions to achieve the same result.
Here's a handy website on which you can check what CSS you can and can't use for certain e-mail clients.
<https://www.campaignmonitor.com/css/> | Just to provide you an option, look into MJML.
It can be used programmatically with Node.
It can create responsive and emails with all the common email clients via what is essentially a combination of HTML and CSS with baked in fixes for displaying through the various email clients.
<https://mjml.io/>
"MJML is a mark... | 11,243 |
19,601,797 | i will answer any questions i can
Basically I have a list of 70 words that I am looking for in over 500 files, and I need to replace them with new words and numbers.
ie... find "hello" and replace with "hello 233.4" but 70 words/numbers and 500+ files.
I found an informative post here, but I have been reading about ... | 2013/10/26 | [
"https://Stackoverflow.com/questions/19601797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2779846/"
] | The code that you posted above is probably to complex for what you need for your assignment. Perhaps something more simple like the following is easier to understand:
```
# example variables
word_mapping = [['horse', 'donkey'], ['left', 'right']]
filename = 'C:/search/this/file/searchme.txt'
# load the text from the ... | Maybe can try this...
[Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-with-python)
Put all 500 files in the same directory and process from there. | 11,244 |
48,600,481 | I'm working with the following string:
```
'"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"'
```
and I have to use `re.sub()` in python to replace only the double quotes (`"`) that are en... | 2018/02/03 | [
"https://Stackoverflow.com/questions/48600481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9167585/"
] | **Regex**: [`"(-?\d+(?:[\.,]\d+)?)"`](https://regex101.com/r/ySz6v5/3) **Substitution**: `\1`
Details:
* `()` Capturing group
* `(?:)` Non capturing group
* `\d` Matches a digit (equal to `[0-9]`)
* `+` Matches between one and unlimited times
* `?` Matches between zero and one times
* `\1` Group 1.
**Python code**:
... | Parse the string first with json, and later convert numbers to floats:
```
string = '{"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"}'
data = json.loads(string)
response = {}
for key, val... | 11,245 |
36,839,650 | I want to execute one python script in Jupyter, but I don't want to use the web browser (IPython Interactive terminal), I want to run a single command in the Linux terminal to load & run the python script, so that I can get the output from Jupyter.
I tried to run `jupyter notebook %run <my_script.py>`, but it seems j... | 2016/04/25 | [
"https://Stackoverflow.com/questions/36839650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6204018/"
] | You can use the `jupyter console -i` command to run an interactive jupyter session in your terminal. From there you can run `import <my_script.py>`. Do note that this is not the intended use case of either jupyter or the notebook environment. You should run scripts using your normal python interpreter instead. | You can run this command to run an interactive jupyter session in your terminal.
>
> jupyter notebook
>
>
> | 11,248 |
20,212,894 | I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Trac... | 2013/11/26 | [
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] | 1- Stop other applications that are using port 80.
2- run application with port 80 :
```
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
``` | You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on `uWSGI`. | 11,251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.