qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
48,783,650 | I have a python list l.The first few elements of the list looks like below
```
[751883787]
[751026090]
[752575831]
[751031278]
[751032392]
[751027358]
[751052118]
```
I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like
```
00751883787
00751026090
00752575831
007... | 2018/02/14 | [
"https://Stackoverflow.com/questions/48783650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9300211/"
] | you can try:
```
list=[121,123,125,145]
series='00'+pd.Series(list).astype(str)
print(series)
```
output:
```
0 00121
1 00123
2 00125
3 00145
dtype: object
``` | both the given answers are usefull ... below is the summrise one
```
import pandas as pd
mylist = [751883787,751026090,752575831,751031278]
mysers = pd.Series(mylist).astype(str).str.zfill(11)
print (mysers)
./test
0 00751883787
1 00751026090
2 00752575831
3 00751031278
dtype: object
```
another way ar... |
48,783,650 | I have a python list l.The first few elements of the list looks like below
```
[751883787]
[751026090]
[752575831]
[751031278]
[751032392]
[751027358]
[751052118]
```
I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like
```
00751883787
00751026090
00752575831
007... | 2018/02/14 | [
"https://Stackoverflow.com/questions/48783650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9300211/"
] | This is one way.
```
from itertools import chain; concat = chain.from_iterable
import pandas as pd
lst = [[751883787],
[751026090],
[752575831],
[751031278]]
pd.DataFrame({'a': pd.Series([str(i).zfill(11) for i in concat(lst)])})
a
0 00751883787
1 00751026090
2 00752575831
3 00... | both the given answers are usefull ... below is the summrise one
```
import pandas as pd
mylist = [751883787,751026090,752575831,751031278]
mysers = pd.Series(mylist).astype(str).str.zfill(11)
print (mysers)
./test
0 00751883787
1 00751026090
2 00752575831
3 00751031278
dtype: object
```
another way ar... |
48,783,650 | I have a python list l.The first few elements of the list looks like below
```
[751883787]
[751026090]
[752575831]
[751031278]
[751032392]
[751027358]
[751052118]
```
I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like
```
00751883787
00751026090
00752575831
007... | 2018/02/14 | [
"https://Stackoverflow.com/questions/48783650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9300211/"
] | First use `DataFrame` constructor with columns, then cast to `string` and last add `0` by [`Series.str.zfill`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html) if nested `list`s:
```
lst = [[751883787],
[751026090],
[752575831],
[751031278],
[751032392],
... | both the given answers are usefull ... below is the summrise one
```
import pandas as pd
mylist = [751883787,751026090,752575831,751031278]
mysers = pd.Series(mylist).astype(str).str.zfill(11)
print (mysers)
./test
0 00751883787
1 00751026090
2 00752575831
3 00751031278
dtype: object
```
another way ar... |
42,345,745 | I am using python-social-auth. But when I run makemigrations and migrate. The tables "social\_auth-\*" are not created.
My settings.py looks like this
```
INSTALLED_APPS += (
'social.apps.django_app.default',
)
AUTHENTICATION_BACKENDS += (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google... | 2017/02/20 | [
"https://Stackoverflow.com/questions/42345745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7007547/"
] | I had to migrate to social-auth-core as described in this dokument :
[Migrating from python-social-auth to split social](https://github.com/omab/python-social-auth/blob/master/MIGRATING_TO_SOCIAL.md)
Then all is working fine. But after this problems I am thinking about changing to all-auth.
Regards for any help | Strange .. when entering the admin interface I receive the exception :
```
No installed app with label 'social_django'.
```
But later in the Error Report I have :
```
INSTALLED_APPS
['django.contrib.admin',
'django.contrib.auth',
.....
'myauth.apps.MyauthConfig',
'main.apps.MainConfig',
... |
40,461,824 | I have a Adafruit Feather Huzzah ESP8266 and want to load a lua script onto it.
The script is out of [this Adafruit tutorial](https://learn.adafruit.com/manually-bridging-mqtt-mosquitto-to-adafruit-io/programming-the-esp8266) and I changed only the Wifi and MQTT connection settings.
I followed the instructions at
<h... | 2016/11/07 | [
"https://Stackoverflow.com/questions/40461824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427707/"
] | Adding a delay of 0.6 ms to the `luatool.py` solved the problem for me:
```
python ./luatool.py --delay 0.6 --port /dev/tty.SLAB_USBtoUART --src LightSensor-master/init.lua --dest init.lua --verbose
```
I found this solution because I read some advice that the python script might try to talk to the Feather faster th... | I had the same problem, I detached the cable and attached again and ran the command
```
sudo python esp8266/luatool.py --delay 0.6 --port /dev/ttyUSB0 --src init.lua --dest init.lua --restart --verbose
```
1st time it fails but next time execute the same command and it works for me. |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | Debian based images use only `python pip` to install packages with `.whl` format:
```
Downloading pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
Downloading numpy-1.14.1-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
```
WHL format was developed as a quicker and more reliable method of installing Python soft... | In this case the alpine not be the best solution change alpine for slim:
FROM python:3.8.3-alpine
========================
Change to that:
`FROM python:3.8.3-slim`
In my case it was resolved with this small change. |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | **ANSWER: AS OF 3/9/2020, FOR PYTHON 3, IT STILL DOESN'T!**
Here is a complete working Dockerfile:
```
FROM python:3.7-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
```
The build is very sensitive to... | alpine takes lot of time to install pandas and the image size is also huge. I tried the python:3.8-slim-buster version of python base image. Image build was very fast and size of image was less than half in comparison to alpine python docker image
<https://github.com/dguyhasnoname/k8s-cluster-checker/blob/master/Docke... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | `pandas` is considered a community supported package, so the answers pointing to `edge/testing` are not going to work as Alpine does not officially support pandas as a core package (it still works, it's just not supported by the core Alpine developers).
Try this Dockerfile:
```
FROM python:3.8-alpine
RUN echo "@commu... | alpine takes lot of time to install pandas and the image size is also huge. I tried the python:3.8-slim-buster version of python base image. Image build was very fast and size of image was less than half in comparison to alpine python docker image
<https://github.com/dguyhasnoname/k8s-cluster-checker/blob/master/Docke... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | Debian based images use only `python pip` to install packages with `.whl` format:
```
Downloading pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
Downloading numpy-1.14.1-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
```
WHL format was developed as a quicker and more reliable method of installing Python soft... | This worked for me:
```
FROM python:3.8-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
ENV PYTHONPATH=/usr/lib/python3.8/site-packages
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPO... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | This worked for me:
```
FROM python:3.8-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
ENV PYTHONPATH=/usr/lib/python3.8/site-packages
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPO... | The following Dockerfile worked for me to install pandas, among other dependencies as listed below.
### python:3.10-alpine Dockerfile
```
# syntax=docker/dockerfile:1
FROM python:3.10-alpine as base
RUN apk add --update --no-cache --virtual .tmp-build-deps \
gcc g++ libc-dev linux-headers postgresql-dev build-ba... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | I have solved the installation with some additional changes:
### Requirements
* Migrate from `python3.8-alpine` to `python3.10-alpine`:
```bash
docker pull python:3.10-alpine
```
>
> #### Important!
>
>
> I had to migrate because when I was installing `py3-pandas`, it installed the package as `python3.10`, not ... | alpine takes lot of time to install pandas and the image size is also huge. I tried the python:3.8-slim-buster version of python base image. Image build was very fast and size of image was less than half in comparison to alpine python docker image
<https://github.com/dguyhasnoname/k8s-cluster-checker/blob/master/Docke... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | In this case the alpine not be the best solution change alpine for slim:
FROM python:3.8.3-alpine
========================
Change to that:
`FROM python:3.8.3-slim`
In my case it was resolved with this small change. | The following Dockerfile worked for me to install pandas, among other dependencies as listed below.
### python:3.10-alpine Dockerfile
```
# syntax=docker/dockerfile:1
FROM python:3.10-alpine as base
RUN apk add --update --no-cache --virtual .tmp-build-deps \
gcc g++ libc-dev linux-headers postgresql-dev build-ba... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | Real honest advice here, switch to Debian based image and then all your problems will be gone.
Alpine for python applications doesn't work well.
Here is an example of my `dockerfile`:
```
FROM python:3.7.6-buster
RUN pip install pandas==1.0.0
RUN pip install sklearn
RUN pip install Django==3.0.2
RUN pip install cx_... | This worked for me:
```
FROM python:3.8-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
ENV PYTHONPATH=/usr/lib/python3.8/site-packages
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPO... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | **ATTENTION**
Look at the @jtlz2 answer with the **latest update**
**OUTDATED**
So, py3-pandas & py3-numpy packages moved to the testing alpine repository, so, you can download it by adding these lines in to the your Dockerfile:
```
RUN echo "http://dl-8.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositori... | This worked for me:
```
FROM python:3.8-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
ENV PYTHONPATH=/usr/lib/python3.8/site-packages
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPO... |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | **ANSWER: AS OF 3/9/2020, FOR PYTHON 3, IT STILL DOESN'T!**
Here is a complete working Dockerfile:
```
FROM python:3.7-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
```
The build is very sensitive to... | This worked for me:
```
FROM python:3.8-alpine
RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk add --update --no-cache py3-numpy py3-pandas@testing
ENV PYTHONPATH=/usr/lib/python3.8/site-packages
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPO... |
72,095,609 | With given 2D and 1D lists, I have to dot product them. But I have to calculate them without using `.dot`.
For example, I want to make these lists
```
matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, ... | 2022/05/03 | [
"https://Stackoverflow.com/questions/72095609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19021583/"
] | You could use a list comprehension with nested for loops.
```py
matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]
result_list = [sum(a*b for a,b in zip(row, vector_x)) for row in matrix_A]
print(re... | If you do not mind using numpy, this is a solution
```
import numpy as np
matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]
res = np.sum(np.array(matrix_A) * np.array(vector_x), axis=1)
print(res)
... |
41,249,099 | I am able to create a DirContext using the credentials provided. So it seems that I am connecting to the ldap server and verifying credentials but later on we do a .search on the context that we get from these credentials. Here it is failing. I have included my spring security configuration in addition to code that sho... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41249099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431499/"
] | In method searchForUser is called the method SpringSecurityLdapTemplate.searchForSingleEntryInternal where it's passed an array of objects. The first object of array relates to username@domain. The second one, is the username itself. So, when you are searching for (&(objectClass=user)(sAMAccountName={0})) in ActiveDire... | The issue was pretty straightforward once I used Apache Directory Studio to try and run the ldap queries coming out of Spring Security Active Directory defaults. They assume you have an attribute called userPrincipalName which is a combination of the sAMAccountName and the domain.
In the end I had to set the searchFi... |
49,641,899 | I am not familiar with how to export the list to the `csv` in python. Here is code for one list:
```
import csv
X = ([1,2,3],[7,8,9])
Y = ([4,5,6],[3,4,5])
for x in range(0,2,1):
csvfile = "C:/Temp/aaa.csv"
with open(csvfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
for ... | 2018/04/04 | [
"https://Stackoverflow.com/questions/49641899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6703592/"
] | To output multiple columns you can use [`zip()`](https://docs.python.org/3/library/functions.html#zip) like:
### Code:
```
import csv
x0 = [1, 2, 3]
y0 = [4, 5, 6]
x2 = [7, 8, 9]
y2 = [3, 4, 5]
csvfile = "aaa.csv"
with open(csvfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writ... | You could try:
```
with open('file.csv') as fin:
reader = csv.reader(fin)
[fout.write(r[0],r[1]) for r in reader]
```
If you need further help, leave a comment. |
49,641,899 | I am not familiar with how to export the list to the `csv` in python. Here is code for one list:
```
import csv
X = ([1,2,3],[7,8,9])
Y = ([4,5,6],[3,4,5])
for x in range(0,2,1):
csvfile = "C:/Temp/aaa.csv"
with open(csvfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
for ... | 2018/04/04 | [
"https://Stackoverflow.com/questions/49641899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6703592/"
] | To output multiple columns you can use [`zip()`](https://docs.python.org/3/library/functions.html#zip) like:
### Code:
```
import csv
x0 = [1, 2, 3]
y0 = [4, 5, 6]
x2 = [7, 8, 9]
y2 = [3, 4, 5]
csvfile = "aaa.csv"
with open(csvfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writ... | When dealing with csv files you should really just use Pandas. Put your header and data into a dataframe, and then use the .to\_csv method on that dataframe. Csv can get tricky when you have strings that contain commas, etc...
<https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html> |
52,149,479 | I am preprocessing a timeseries dataset changing its shape from 2-dimensions (datapoints, features) into a 3-dimensions (datapoints, time\_window, features).
In such perspective time windows (sometimes also called look back) indicates the number of previous time steps/datapoints that are involved as input variables to... | 2018/09/03 | [
"https://Stackoverflow.com/questions/52149479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3482860/"
] | `os.system` is deprecated. Use `subprocess` instead, which will handle the quoting nicely for you.
Since you have a pipe, you would normally have to create 2 `subprocess` objects, but here you just want to feed standard input so:
```
import subprocess
p = subprocess.Popen(["/usr/bin/cmd","-parameters"],stdin=subproce... | If you want to echo quotes, you need to escape them.
For example:
```
echo "value"
```
>
> value
>
>
>
```
echo "\"value\""
```
>
> "value"
>
>
>
So your python code should look like
```
os.system('echo {{\\"value\\": {0:0.0f}}} | /usr/bin/cmd -parameters'.format(value))
```
Note, that you should use... |
72,068,358 | Why python doesn't raise an error when I try do this, instead it print Nothing.
```
empty = []
for i in empty:
for y in i:
print(y)
```
Is that python stop iterate it the first level or it just iterates over and print **None**?
I found this when trying to create a infinite loop but it stop when list bec... | 2022/04/30 | [
"https://Stackoverflow.com/questions/72068358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18132490/"
] | There is nothing to iterate over in `empty` list. Hence, `for` loop won't run even for a single time. However, if it is required to get an error for this you can raise an exception like below:
```
empty = []
if len(empty) == 0:
raise Exception("List is empty")
for i in empty:
for y in i:
print(y)
``` | Your list variable `empty` is initialized with empty list. so, the first iteration itself will not enter, since the list is empty. |
72,068,358 | Why python doesn't raise an error when I try do this, instead it print Nothing.
```
empty = []
for i in empty:
for y in i:
print(y)
```
Is that python stop iterate it the first level or it just iterates over and print **None**?
I found this when trying to create a infinite loop but it stop when list bec... | 2022/04/30 | [
"https://Stackoverflow.com/questions/72068358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18132490/"
] | There is nothing to iterate over in `empty` list. Hence, `for` loop won't run even for a single time. However, if it is required to get an error for this you can raise an exception like below:
```
empty = []
if len(empty) == 0:
raise Exception("List is empty")
for i in empty:
for y in i:
print(y)
``` | Since the list is empty, the loop will not run at all. |
60,233,935 | I have been trying to get my first trial with templating with Ansible to work and I am stopped by this following exception. As far as I can see, I think I have maintained the indentation well and also validated the yml file. I don't know where to go from here, help pls! Below is the yml file followed by the exception I... | 2020/02/14 | [
"https://Stackoverflow.com/questions/60233935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682497/"
] | There are at minimum two things wrong with the playbook you posted:
1. `hosts:` is a `dict`, but should not be
2. `testhost:` has a `null` value
[Reading the fine manual](https://docs.ansible.com/ansible/2.9/reference_appendices/playbooks_keywords.html#term-hosts) shows that `hosts:` should be a string, or `list[str]... | This error can also happen if you wind up with the wrong structure in your playbook.
For example:
```yaml
tags: # oops
- role: foo/myrole
```
instead of
```yaml
roles:
- role: foo/myrole
``` |
19,306,963 | In a file like:
```
jaslkfdj,asldkfj,,,
slakj,aklsjf,,,
lsak,sajf,,,
```
how can you split it up so there is just a key value pair of the two words? I tried to split using commas but the only way i know how to make key/value pairs is when there is only one commma in a line.
python gives the error: "ValueError: t... | 2013/10/10 | [
"https://Stackoverflow.com/questions/19306963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844776/"
] | It seems more likely that what you tried is this:
```
>>> line = 'jaslkfdj,asldkfj,,,'
>>> key, value = line.split(',')
ValueError: too many values to unpack (expected 2)
```
There are two ways around this.
First, you can split, and then just take the first two values:
```
>>> line = 'jaslkfdj,asldkfj,,,'
>>> part... | Try slicing for the first two values:
```
"a,b,,,,,".split(",")[:2]
```
Nice summary of slice notation in [this answer](https://stackoverflow.com/a/509295/169121). |
19,306,963 | In a file like:
```
jaslkfdj,asldkfj,,,
slakj,aklsjf,,,
lsak,sajf,,,
```
how can you split it up so there is just a key value pair of the two words? I tried to split using commas but the only way i know how to make key/value pairs is when there is only one commma in a line.
python gives the error: "ValueError: t... | 2013/10/10 | [
"https://Stackoverflow.com/questions/19306963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844776/"
] | Try slicing for the first two values:
```
"a,b,,,,,".split(",")[:2]
```
Nice summary of slice notation in [this answer](https://stackoverflow.com/a/509295/169121). | ```
with open('file.csv', 'r') as wd:
newdict = dict(line.split(",")[:2] for line in wd.read().splitlines())
print newdict
```
The result is follows:
`{' jaslkfdj': 'asldkfj', ' lsak': 'sajf', ' slakj': 'aklsjf'}` |
19,306,963 | In a file like:
```
jaslkfdj,asldkfj,,,
slakj,aklsjf,,,
lsak,sajf,,,
```
how can you split it up so there is just a key value pair of the two words? I tried to split using commas but the only way i know how to make key/value pairs is when there is only one commma in a line.
python gives the error: "ValueError: t... | 2013/10/10 | [
"https://Stackoverflow.com/questions/19306963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844776/"
] | It seems more likely that what you tried is this:
```
>>> line = 'jaslkfdj,asldkfj,,,'
>>> key, value = line.split(',')
ValueError: too many values to unpack (expected 2)
```
There are two ways around this.
First, you can split, and then just take the first two values:
```
>>> line = 'jaslkfdj,asldkfj,,,'
>>> part... | ```
with open('file.csv', 'r') as wd:
newdict = dict(line.split(",")[:2] for line in wd.read().splitlines())
print newdict
```
The result is follows:
`{' jaslkfdj': 'asldkfj', ' lsak': 'sajf', ' slakj': 'aklsjf'}` |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | With this as the input:
```
$ cat file
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
Try:
```
$ sed -E ':a; s/^( *) ([^ ])/\1.\2/; ta' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f... | There are two different ways to do this in vim.
1. With a regex:
```
:%s/^\s\+/\=repeat('.', len(submatch(0)))
```
This is fairly straightforward, but a little verbose. It uses the eval register (`\=`) to generate a string of `'.'`s the same length as the number of spaces at the beginning of each line.
2. With a n... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | With this as the input:
```
$ cat file
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
Try:
```
$ sed -E ':a; s/^( *) ([^ ])/\1.\2/; ta' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f... | A little lengthy, but a fun exercise nonetheless:
```
# Function to count the number of leading spaces in a string
# Basically, this counts the number of consecutive elements that satisfy being spaces
def count_leading_spaces(s):
if not s:
return 0
else:
curr_char = s[0]
if curr_char !=... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | With this as the input:
```
$ cat file
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
Try:
```
$ sed -E ':a; s/^( *) ([^ ])/\1.\2/; ta' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f... | Since you said **`python`**:
```
#!/usr/bin/env python
import re, sys
for line in sys.stdin:
sys.stdout.write(re.sub('^ +', lambda m: len(m.group(0)) * '.', line))
```
(for each line, we replace the longest run of prefix spaces `'^ +'` with an equally long string of dots, `len(m.group(0)) * '.'`).
With the end ... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | With this as the input:
```
$ cat file
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
Try:
```
$ sed -E ':a; s/^( *) ([^ ])/\1.\2/; ta' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f... | In awk. It keeps replacing the first space with a period while the space is preceeded only by periods:
```
$ awk '{while(/^\.* / && sub(/ /,"."));}1' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f1 f2 f3
......sub21 f1 f2 f3
...sub3 f1 f2 f3
```
and here's on... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | There are two different ways to do this in vim.
1. With a regex:
```
:%s/^\s\+/\=repeat('.', len(submatch(0)))
```
This is fairly straightforward, but a little verbose. It uses the eval register (`\=`) to generate a string of `'.'`s the same length as the number of spaces at the beginning of each line.
2. With a n... | A little lengthy, but a fun exercise nonetheless:
```
# Function to count the number of leading spaces in a string
# Basically, this counts the number of consecutive elements that satisfy being spaces
def count_leading_spaces(s):
if not s:
return 0
else:
curr_char = s[0]
if curr_char !=... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | There are two different ways to do this in vim.
1. With a regex:
```
:%s/^\s\+/\=repeat('.', len(submatch(0)))
```
This is fairly straightforward, but a little verbose. It uses the eval register (`\=`) to generate a string of `'.'`s the same length as the number of spaces at the beginning of each line.
2. With a n... | Since you said **`python`**:
```
#!/usr/bin/env python
import re, sys
for line in sys.stdin:
sys.stdout.write(re.sub('^ +', lambda m: len(m.group(0)) * '.', line))
```
(for each line, we replace the longest run of prefix spaces `'^ +'` with an equally long string of dots, `len(m.group(0)) * '.'`).
With the end ... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | There are two different ways to do this in vim.
1. With a regex:
```
:%s/^\s\+/\=repeat('.', len(submatch(0)))
```
This is fairly straightforward, but a little verbose. It uses the eval register (`\=`) to generate a string of `'.'`s the same length as the number of spaces at the beginning of each line.
2. With a n... | In awk. It keeps replacing the first space with a period while the space is preceeded only by periods:
```
$ awk '{while(/^\.* / && sub(/ /,"."));}1' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f1 f2 f3
......sub21 f1 f2 f3
...sub3 f1 f2 f3
```
and here's on... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | Since you said **`python`**:
```
#!/usr/bin/env python
import re, sys
for line in sys.stdin:
sys.stdout.write(re.sub('^ +', lambda m: len(m.group(0)) * '.', line))
```
(for each line, we replace the longest run of prefix spaces `'^ +'` with an equally long string of dots, `len(m.group(0)) * '.'`).
With the end ... | A little lengthy, but a fun exercise nonetheless:
```
# Function to count the number of leading spaces in a string
# Basically, this counts the number of consecutive elements that satisfy being spaces
def count_leading_spaces(s):
if not s:
return 0
else:
curr_char = s[0]
if curr_char !=... |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | In awk. It keeps replacing the first space with a period while the space is preceeded only by periods:
```
$ awk '{while(/^\.* / && sub(/ /,"."));}1' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f1 f2 f3
......sub21 f1 f2 f3
...sub3 f1 f2 f3
```
and here's on... | A little lengthy, but a fun exercise nonetheless:
```
# Function to count the number of leading spaces in a string
# Basically, this counts the number of consecutive elements that satisfy being spaces
def count_leading_spaces(s):
if not s:
return 0
else:
curr_char = s[0]
if curr_char !=... |
73,700,589 | I have an integer array.
```
Dim a as Variant
a = Array(1,2,3,4,1,2,3,4,5)
Dim index as Integer
index = Application.Match(4,a,0) '3
```
index is 3 here. It returns the index of first occurrence of 4. But I want the last occurrence index of 4.
In python, there is rindex which returns the reverse index. I am new to v... | 2022/09/13 | [
"https://Stackoverflow.com/questions/73700589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7006773/"
] | [`XMATCH()`](https://support.microsoft.com/en-us/office/xmatch-function-d966da31-7a6b-4a13-a1c6-5a33ed6a0312) avaibalble in O365 and Excel 2021. Try-
```
Sub ReverseMatch()
Dim a As Variant
Dim index As Integer
a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
index = Application.XMatch(4, a, 0, -1) '-1 indicate search la... | Try the next way, please:
```
Sub lastOccurrenceMatch()
Dim a As Variant, index As Integer
a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
index = Application.Match(CStr(4), Split(StrReverse(Join(a, "|")), "|"), 0) '2
Debug.Print index, UBound(a) + 1 - index + 1
End Sub
```
Or a version not raising an error in ... |
73,700,589 | I have an integer array.
```
Dim a as Variant
a = Array(1,2,3,4,1,2,3,4,5)
Dim index as Integer
index = Application.Match(4,a,0) '3
```
index is 3 here. It returns the index of first occurrence of 4. But I want the last occurrence index of 4.
In python, there is rindex which returns the reverse index. I am new to v... | 2022/09/13 | [
"https://Stackoverflow.com/questions/73700589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7006773/"
] | [`XMATCH()`](https://support.microsoft.com/en-us/office/xmatch-function-d966da31-7a6b-4a13-a1c6-5a33ed6a0312) avaibalble in O365 and Excel 2021. Try-
```
Sub ReverseMatch()
Dim a As Variant
Dim index As Integer
a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
index = Application.XMatch(4, a, 0, -1) '-1 indicate search la... | **Alternative via `FilterXML()`**
Just in order to complete the valid solutions above, I demonstrate another approach via `FilterXML()` (available since vers. 2013+):
This method doesn't require to reverse the base array; instead it filters & counts all elements before the last finding (i.e. all elements that have an... |
73,700,589 | I have an integer array.
```
Dim a as Variant
a = Array(1,2,3,4,1,2,3,4,5)
Dim index as Integer
index = Application.Match(4,a,0) '3
```
index is 3 here. It returns the index of first occurrence of 4. But I want the last occurrence index of 4.
In python, there is rindex which returns the reverse index. I am new to v... | 2022/09/13 | [
"https://Stackoverflow.com/questions/73700589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7006773/"
] | Try the next way, please:
```
Sub lastOccurrenceMatch()
Dim a As Variant, index As Integer
a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
index = Application.Match(CStr(4), Split(StrReverse(Join(a, "|")), "|"), 0) '2
Debug.Print index, UBound(a) + 1 - index + 1
End Sub
```
Or a version not raising an error in ... | **Alternative via `FilterXML()`**
Just in order to complete the valid solutions above, I demonstrate another approach via `FilterXML()` (available since vers. 2013+):
This method doesn't require to reverse the base array; instead it filters & counts all elements before the last finding (i.e. all elements that have an... |
30,236,277 | I am an enthusiastic learner of opencv and write down a code for video streaming with opencv I want to learn the use of cv2.createTrackbar() to add some interactive functionality. Though, I tried this function but its not working for me :
For streaming and resizing the frame i use this code
```
import cv2
import sys... | 2015/05/14 | [
"https://Stackoverflow.com/questions/30236277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4706745/"
] | Your code will surely fail. There are too many issues indicating you haven't read the document. Even the 1st `new_size` one will **fail for sure**.
`cap = cv2.VideoCapture(sys.argv[1])` this is wrong. Because it requires `int` instead of `str`. You have to do `cap = cv2.VideoCapture(int(sys.argv[1]))`
another obviou... | Sorry, i am familiar with c++, here is the C++ code, hope it helps.
The code mentioned below adds a contrast adjustment to the live video stream from the camera using createTrackbar function
```
#include "opencv2\highgui.hpp"
#include "opencv2\core.hpp"
#include <iostream>
using namespace cv;
using namespace std;
in... |
46,248,019 | I am using plotly in a Jupyter notebook (python v3.6) and trying to get the example code for mapbox to work (see: <https://plot.ly/python/scattermapbox/>).
When I execute the cell, I don't get any error, but I see no output either, just a blank output cell. When I mouse over the output cell area, I can see there's a f... | 2017/09/15 | [
"https://Stackoverflow.com/questions/46248019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404267/"
] | D'oh! Was using the wrong mapbox token. I should have used the public token, but instead used a private one. The only error was a js one in the console.
Thanks user1561393!
```
jupyter labextension install plotlywidget
``` | What is your `mapbox_token`? My guess is you haven't signed up for Mapbox to get an API token (which allows you to download their excellent tile maps for mapbox-gl). The map's not going to show without this token. |
29,974,933 | I am using python multiprocessing Process. Why can't I start or restart a process after it exits and I do a join. The process is gone, but in the instantiated class \_popen is not set to None after the process dies and I do a join. If I try and start again it tells me I can't start a process twice. | 2015/04/30 | [
"https://Stackoverflow.com/questions/29974933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686334/"
] | From the Python multiprocessing documentation.
>
> start()
>
>
> Start the process’s activity.
>
>
> This must be called at most once per process object. It arranges for the object’s run() method to be invoked in a separate process.
>
>
>
A Process object can be run only once. If you need to re-run the same r... | From your question we can just guess, what you're talking about. Are you using `subprocess`? How do you start your process? By invoking `call()` or `Popen()`?
In case I guessed right:
Just keep your `args` list from your `subprocess` call and restart your process by calling that command again. The instance of your su... |
36,996,629 | I am doing `pip install setuptools --upgrade` but getting error below
```
Installing collected packages: setuptools
Found existing installation: setuptools 1.1.6
Uninstalling setuptools-1.1.6:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecomm... | 2016/05/03 | [
"https://Stackoverflow.com/questions/36996629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450312/"
] | Try to upgrade manually:
```
pip uninstall setuptools
pip install setuptools
```
If it doesn't work, try:
`pip install --upgrade setuptools --user python`
As you can see, the operation didn't get appropriate privilege:
`[Errno 1] Operation not permitted: '/tmp/pip-rV15My-uninstall/System/Library/Frameworks/Python... | I ran into a similar problem but with a different error, and different resolution. (My search for a solution led me here, so I'm posting my details here in case it helps.)
TL;DR: if upgrading `setuptools` in a Python virtual environment appears to work, but reports `OSError: [Errno 2] No such file or directory`, try d... |
12,683,745 | Normally, one shuts down Apache Tomcat by running its `shutdown.sh` script (or batch file). In some cases, such as when Tomcat's web container is hosting a web app that does some crazy things with multi-threading, running `shutdown.sh` gracefully shuts down *some* parts of Tomcat (as I can see more available memory ret... | 2012/10/02 | [
"https://Stackoverflow.com/questions/12683745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | you need to replace `grepResults = subprocess.call([grepCmd], shell=true)` with `grepResults = subprocess.check_output([grepCmd], shell=true)` if you want to save the results of the command in grepResults. Then you can use split to convert that to an array and the second element of the array will be the pid: `pid = int... | You can add "c" to ps so that only the command and not the arguments are printed. This would stop grab from matching its self.
I'm not sure if tomcat shows up as a java application though, so this may not work.
PS: Got this from googling: "grep includes self" and the first hit had that solution.
EDIT: My bad! OK som... |
12,683,745 | Normally, one shuts down Apache Tomcat by running its `shutdown.sh` script (or batch file). In some cases, such as when Tomcat's web container is hosting a web app that does some crazy things with multi-threading, running `shutdown.sh` gracefully shuts down *some* parts of Tomcat (as I can see more available memory ret... | 2012/10/02 | [
"https://Stackoverflow.com/questions/12683745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | You can add "c" to ps so that only the command and not the arguments are printed. This would stop grab from matching its self.
I'm not sure if tomcat shows up as a java application though, so this may not work.
PS: Got this from googling: "grep includes self" and the first hit had that solution.
EDIT: My bad! OK som... | Creating child processes to run `ps` and string match the output with `grep` is not necessary. Python has great string handling 'baked in' and Linux exposes all the needed info in /proc. The procfs mount is where the command line utilities get this info. Might as well go directly to the source.
```
import os
SIGTERM ... |
12,683,745 | Normally, one shuts down Apache Tomcat by running its `shutdown.sh` script (or batch file). In some cases, such as when Tomcat's web container is hosting a web app that does some crazy things with multi-threading, running `shutdown.sh` gracefully shuts down *some* parts of Tomcat (as I can see more available memory ret... | 2012/10/02 | [
"https://Stackoverflow.com/questions/12683745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | you need to replace `grepResults = subprocess.call([grepCmd], shell=true)` with `grepResults = subprocess.check_output([grepCmd], shell=true)` if you want to save the results of the command in grepResults. Then you can use split to convert that to an array and the second element of the array will be the pid: `pid = int... | Creating child processes to run `ps` and string match the output with `grep` is not necessary. Python has great string handling 'baked in' and Linux exposes all the needed info in /proc. The procfs mount is where the command line utilities get this info. Might as well go directly to the source.
```
import os
SIGTERM ... |
22,869,920 | I am trying to insert raw JSON strings into a sqlite database using the sqlite3 module in python.
When I do the following:
```
rows = [["a", "<json value>"]....["n", "<json_value>"]]
cursor.executemany("""INSERT OR IGNORE INTO FEATURES(UID, JSON) VALUES(?, ?)""", rows)
```
I get the following error:
>
> sqlite3.P... | 2014/04/04 | [
"https://Stackoverflow.com/questions/22869920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087908/"
] | Your input is interpreted as a list of characters (that's where the '48 supplied' is coming from - 48 is the length of the `<json value>` string).
You will be able to pass your input in as a string if you wrap it in square brackets like so
```
["<json value>"]
```
The whole line would then look like
```
rows = [["... | It's kind of a long shot... but perhaps you could quote the JSON values to ensure the parsing works as desired:
```
cursor.executemany("""INSERT OR IGNORE INTO FEATURES(UID, JSON) VALUES(?, '?')""", rows)
```
EDIT: Alternatively... this might force the json into a sting in the insertion?
```
rows = [ uid, '"{}"'.fo... |
22,869,920 | I am trying to insert raw JSON strings into a sqlite database using the sqlite3 module in python.
When I do the following:
```
rows = [["a", "<json value>"]....["n", "<json_value>"]]
cursor.executemany("""INSERT OR IGNORE INTO FEATURES(UID, JSON) VALUES(?, ?)""", rows)
```
I get the following error:
>
> sqlite3.P... | 2014/04/04 | [
"https://Stackoverflow.com/questions/22869920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087908/"
] | Your input is interpreted as a list of characters (that's where the '48 supplied' is coming from - 48 is the length of the `<json value>` string).
You will be able to pass your input in as a string if you wrap it in square brackets like so
```
["<json value>"]
```
The whole line would then look like
```
rows = [["... | Second argument passed to [`executemany()`](https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.executemany) has to be list of touples, not list of lists:
```
[tuple(l) for l in rows]
```
From [`sqlite3`](https://docs.python.org/2/library/sqlite3.html) module documentation:
>
> Put `?` as a placeholder w... |
34,227,066 | Using python I can easily increase the current process's niceness:
```
>>> import os
>>> import psutil
>>> # Use os to increase by 3
>>> os.nice(3)
3
>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10
```
However, decreasing a process's niceness does no... | 2015/12/11 | [
"https://Stackoverflow.com/questions/34227066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448640/"
] | Linux, by default, doesn't allow unprivileged users to decrease the nice value (i.e. increase the priority) of their processes, so that one user doesn't create a high-priority process to starve out other users. Python is simply forwarding the error the OS gives you as an exception.
The root user can increase the prior... | This is not a restriction by Python or the `os.nice` interface. It is described in `man 2 nice` that only the superuser may decrease the niceness of a process:
>
> nice() adds inc to the nice value for the calling process. (A higher
> nice value means a low priority.) Only the superuser may specify a
> negative inc... |
34,227,066 | Using python I can easily increase the current process's niceness:
```
>>> import os
>>> import psutil
>>> # Use os to increase by 3
>>> os.nice(3)
3
>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10
```
However, decreasing a process's niceness does no... | 2015/12/11 | [
"https://Stackoverflow.com/questions/34227066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448640/"
] | Linux, by default, doesn't allow unprivileged users to decrease the nice value (i.e. increase the priority) of their processes, so that one user doesn't create a high-priority process to starve out other users. Python is simply forwarding the error the OS gives you as an exception.
The root user can increase the prior... | I had the same Error `[Errno 2] Operation not permitted`.
I don't want to start my script with sudo so I came around with the following workaround:
```
def decrease_nice():
pid = os.getpid()
os.system("sudo renice -n -19 -p " + str(pid))
def normal_nice():
pid = os.getpid()
os.system("sudo renice -n ... |
34,227,066 | Using python I can easily increase the current process's niceness:
```
>>> import os
>>> import psutil
>>> # Use os to increase by 3
>>> os.nice(3)
3
>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10
```
However, decreasing a process's niceness does no... | 2015/12/11 | [
"https://Stackoverflow.com/questions/34227066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448640/"
] | Linux, by default, doesn't allow unprivileged users to decrease the nice value (i.e. increase the priority) of their processes, so that one user doesn't create a high-priority process to starve out other users. Python is simply forwarding the error the OS gives you as an exception.
The root user can increase the prior... | You can't decrease a nice value below 0 without sudo, but there is a way to "undo" the nice value applied earlier and get around the "ratchet mechanism"
The workaround is to use the threading module. In the example below, I start a function called `run` in it's own thread and it promptly sets its own nice value to 5. ... |
34,227,066 | Using python I can easily increase the current process's niceness:
```
>>> import os
>>> import psutil
>>> # Use os to increase by 3
>>> os.nice(3)
3
>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10
```
However, decreasing a process's niceness does no... | 2015/12/11 | [
"https://Stackoverflow.com/questions/34227066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448640/"
] | This is not a restriction by Python or the `os.nice` interface. It is described in `man 2 nice` that only the superuser may decrease the niceness of a process:
>
> nice() adds inc to the nice value for the calling process. (A higher
> nice value means a low priority.) Only the superuser may specify a
> negative inc... | I had the same Error `[Errno 2] Operation not permitted`.
I don't want to start my script with sudo so I came around with the following workaround:
```
def decrease_nice():
pid = os.getpid()
os.system("sudo renice -n -19 -p " + str(pid))
def normal_nice():
pid = os.getpid()
os.system("sudo renice -n ... |
34,227,066 | Using python I can easily increase the current process's niceness:
```
>>> import os
>>> import psutil
>>> # Use os to increase by 3
>>> os.nice(3)
3
>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10
```
However, decreasing a process's niceness does no... | 2015/12/11 | [
"https://Stackoverflow.com/questions/34227066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448640/"
] | This is not a restriction by Python or the `os.nice` interface. It is described in `man 2 nice` that only the superuser may decrease the niceness of a process:
>
> nice() adds inc to the nice value for the calling process. (A higher
> nice value means a low priority.) Only the superuser may specify a
> negative inc... | You can't decrease a nice value below 0 without sudo, but there is a way to "undo" the nice value applied earlier and get around the "ratchet mechanism"
The workaround is to use the threading module. In the example below, I start a function called `run` in it's own thread and it promptly sets its own nice value to 5. ... |
41,455,463 | For a list of daily maximum temperature values from 5 to 27 degrees celsius, I want to calculate the corresponding maximum ozone concentration, from the following pandas DataFrame:
[](https://i.stack.imgur.com/iGW9y.png)
I can do this by using the fol... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41455463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7159945/"
] | It means you are using python 2.x and you have many options because default integer division results in integer numbers
option 1: import the division library
```
from __future__ import division
```
option 2: change either of the factors to float or alternatively you can change 3 to float (decimal point) by ading .0... | You could also just do:
```
print 'The diameter of {} is {}'.format("Earth",10/3)
``` |
41,455,463 | For a list of daily maximum temperature values from 5 to 27 degrees celsius, I want to calculate the corresponding maximum ozone concentration, from the following pandas DataFrame:
[](https://i.stack.imgur.com/iGW9y.png)
I can do this by using the fol... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41455463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7159945/"
] | You can cast to float by doing `measure = 10/ float(3)`. If the numerator or denominator is a float, then the result will be also.
and
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this sa... | You could also just do:
```
print 'The diameter of {} is {}'.format("Earth",10/3)
``` |
13,639,464 | I would like a javascript function that mimics the python .format() function that works like
```
.format(*args, **kwargs)
```
A previous question gives a possible (but not complete) solution for '.format(\*args)
[JavaScript equivalent to printf/string.format](https://stackoverflow.com/questions/610406/javascript-eq... | 2012/11/30 | [
"https://Stackoverflow.com/questions/13639464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188963/"
] | UPDATE: If you're using ES6, template strings work very similarly to `String.format`: <https://developers.google.com/web/updates/2015/01/ES6-Template-Strings>
If not, the below works for all the cases above, with a very similar syntax to python's `String.format` method. Test cases below.
```js
String.prototype.format... | This should work similar to python's `format` but with an object with named keys, it could be numbers as well.
```
String.prototype.format = function( params ) {
return this.replace(
/\{(\w+)\}/g,
function( a,b ) { return params[ b ]; }
);
};
console.log( "hello {a} and {b}.".format( { a: 'foo', b: 'baz'... |
7,800,213 | I'm trying to read data from Google Fusion Tables API into Python using the *csv* library. It seems like querying the API returns CSV data, but when I try and use it with *csv.reader*, it seems to mangle the data and split it up on every character rather than just on the commas and newlines. Am I missing a step? Here's... | 2011/10/17 | [
"https://Stackoverflow.com/questions/7800213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201103/"
] | `csv.reader()` takes in a file-like object.
Change
```
reader = csv.reader(serv_resp.read())
```
to
```
reader = csv.reader(serv_resp)
```
Alternatively, you could do:
```
reader = csv.DictReader(serv_resp)
``` | It's not the CSV module that's causing the problem. Take a look at the output from `serv_resp.read()`. Try using `serv_resp.readlines()` instead. |
68,043,856 | I wrote python code to check how many characters need to be deleted from two strings for them to become anagrams of each other.
This is the problem statement "Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any chara... | 2021/06/19 | [
"https://Stackoverflow.com/questions/68043856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9262680/"
] | You can use [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) for this:
```
from collections import Counter
def makeAnagram(a, b):
return sum((Counter(a) - Counter(b) | Counter(b) - Counter(a)).values())
```
`Counter(x)` (where x is a string) returns a dictionary th... | Assuming there are only lowercase letters
The idea is to make character count arrays for both the strings and store frequency of each character. Now iterate the count arrays of both strings and difference in frequency of any character `abs(count1[str1[i]-‘a’] – count2[str2[i]-‘a’])` in both the strings is the number o... |
49,053,579 | Say I created a django project called `django_site`.
I created two sub-projects: `site1` and `polls`.
You see that I have two `index.html` in two sub-projects directories.
However, now, if I open on web browser `localhost:8000/site1` or `localhost:8000/polls`, they all point to the `index.html` of `polls`.
How can ... | 2018/03/01 | [
"https://Stackoverflow.com/questions/49053579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546678/"
] | You have to configure urls like this :
In your `django_site directory` you have an url file. You have to get urls from all your django apps :
```
from django.urls import include, path
from django.contrib import admin
from polls import views
from site1 import views
urlpatterns = [
path('polls/', include('polls.u... | I solved the problem by:
In `views.py` in `site1` or `polls`:
```
def index(request):
return render(request, 'polls/index.html', context)
```
And inside `django_site` I created a folder `templates`, then in this folder there are two folders `site1` and `polls`. In each subfolder I put `index.html` respectively. |
30,013,356 | I have a list of emails about 10.000 Long, with incomplete emails id, due to data unreliability and would like to know how can I complete them using python.
sample emails:
[email protected]
xyz@gmail.
xyz@gma
xyz@g
I've tried using `validate_email` package to filter out bad emails and have tried various re... | 2015/05/03 | [
"https://Stackoverflow.com/questions/30013356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394449/"
] | A strategy to consider is to build a "trie" data structure for the domains that you have such as `gma` and `gmail.co`. Then where a domain is a prefix of one other domain, you can consider going down the longer branch of the trie if there is a unique such branch. This will mean in your example replacing `gma` ultimatel... | ```
def email_check():
fo = open("/home/cam/Desktop/out.dat", "rw+") #output file
with open('/home/cam/Desktop/email.dat','rw') as f:
for line in f:
at_pos=line.find('@')
if line[at_pos + 1] == 'g':
line=line[:at_pos+1]+'gmail.com'
elif line[at_pos +1] == 'y':
... |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | The heart of the problem is the connection between pyspark and python, solved by redefining the environment variable.
I´ve just changed the environment variable's values `PYSPARK_DRIVER_PYTHON` from `ipython` to `jupyter` and `PYSPARK_PYTHON` from `python3` to `python`.
Now I'm using Jupyter Notebook, Python 3.7, Jav... | I had the same issue. I had set all the `environment variables` correctly but still wasn't able to resolve it
In my case,
```
import findspark
findspark.init()
```
adding this before even creating the sparkSession helped.
I was using `Visual Studio Code` on `Windows 10` and spark version was `3.2.0`. Python versio... |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | I got the same error. I solved it installing the previous version of Spark (2.3 instead of 2.4). Now it works perfectly, maybe it is an issue of the lastest version of pyspark. | There seems to be many reasons for this error to occur. I still had the same problem despite my `environmental variables` being all correctly set.
In my case adding this
```
import findspark
findspark.init()
```
solved the problem.
I'am with`jupyter notebook` on `windows10` with `spark-3.1.2, python3.6`. |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | I got the same error. I solved it installing the previous version of Spark (2.3 instead of 2.4). Now it works perfectly, maybe it is an issue of the lastest version of pyspark. | Looking at the source of the error ([worker.py#L25](https://github.com/apache/spark/blob/master/python/pyspark/worker.py#L25)), it seems that the python interpreter used to instanciate a pyspark worker doesn't have access to the `resource` module, a built-in module referred in [Python's doc](https://docs.python.org/3.7... |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | When you run the python installer, on the Customize Python section, make sure that the option Add python.exe to Path is selected. If this option is not selected, some of the PySpark utilities such as pyspark and spark-submit might not work. This worked for me! Happy Sharing :) | There seems to be many reasons for this error to occur. I still had the same problem despite my `environmental variables` being all correctly set.
In my case adding this
```
import findspark
findspark.init()
```
solved the problem.
I'am with`jupyter notebook` on `windows10` with `spark-3.1.2, python3.6`. |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | The heart of the problem is the connection between pyspark and python, solved by redefining the environment variable.
I´ve just changed the environment variable's values `PYSPARK_DRIVER_PYTHON` from `ipython` to `jupyter` and `PYSPARK_PYTHON` from `python3` to `python`.
Now I'm using Jupyter Notebook, Python 3.7, Jav... | Looking at the source of the error ([worker.py#L25](https://github.com/apache/spark/blob/master/python/pyspark/worker.py#L25)), it seems that the python interpreter used to instanciate a pyspark worker doesn't have access to the `resource` module, a built-in module referred in [Python's doc](https://docs.python.org/3.7... |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | Set Env PYSPARK\_PYTHON=python To Fix It. | Downgrading Spark back to 2.3.2 from 2.4.0 was not enough for me. I don't know why but in my case I had to create SparkContext from SparkSession like
```
sc = spark.sparkContext
```
Then the very same error disappeared. |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | I had the same issue. I had set all the `environment variables` correctly but still wasn't able to resolve it
In my case,
```
import findspark
findspark.init()
```
adding this before even creating the sparkSession helped.
I was using `Visual Studio Code` on `Windows 10` and spark version was `3.2.0`. Python versio... | Downgrading Spark back to 2.3.2 from 2.4.0 was not enough for me. I don't know why but in my case I had to create SparkContext from SparkSession like
```
sc = spark.sparkContext
```
Then the very same error disappeared. |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | The heart of the problem is the connection between pyspark and python, solved by redefining the environment variable.
I´ve just changed the environment variable's values `PYSPARK_DRIVER_PYTHON` from `ipython` to `jupyter` and `PYSPARK_PYTHON` from `python3` to `python`.
Now I'm using Jupyter Notebook, Python 3.7, Jav... | Downgrading Spark back to 2.3.2 from 2.4.0 was not enough for me. I don't know why but in my case I had to create SparkContext from SparkSession like
```
sc = spark.sparkContext
```
Then the very same error disappeared. |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | The heart of the problem is the connection between pyspark and python, solved by redefining the environment variable.
I´ve just changed the environment variable's values `PYSPARK_DRIVER_PYTHON` from `ipython` to `jupyter` and `PYSPARK_PYTHON` from `python3` to `python`.
Now I'm using Jupyter Notebook, Python 3.7, Jav... | There seems to be many reasons for this error to occur. I still had the same problem despite my `environmental variables` being all correctly set.
In my case adding this
```
import findspark
findspark.init()
```
solved the problem.
I'am with`jupyter notebook` on `windows10` with `spark-3.1.2, python3.6`. |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | I had the same issue. I had set all the `environment variables` correctly but still wasn't able to resolve it
In my case,
```
import findspark
findspark.init()
```
adding this before even creating the sparkSession helped.
I was using `Visual Studio Code` on `Windows 10` and spark version was `3.2.0`. Python versio... | When you run the python installer, on the Customize Python section, make sure that the option Add python.exe to Path is selected. If this option is not selected, some of the PySpark utilities such as pyspark and spark-submit might not work. This worked for me! Happy Sharing :) |
25,484,269 | I am not an experienced programmer, I have a problem with my code, I think it's a logical mistake of mine but I couldn't find an answer at <http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html> .
What I want is to check if the serial device is locked, and the different between conditions that "it ... | 2014/08/25 | [
"https://Stackoverflow.com/questions/25484269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3918035/"
] | Use `break` to exit a loop:
```
while True:
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
checking = ser.readline();
if checking.find(",,,,"):
print "not locked yet"
else:
print "locked and loaded"
break
```
The `True` and `False` line didn't do anything in your code; ... | You can use a variable as condition for your `while` loop instead of just `while True`. That way you can change the condition.
So instead of having this code:
```
while True:
...
if ...:
True
else:
False
```
... try this:
```
keepGoing = True
while keepGoing:
ser = serial.Serial... |
31,018,497 | I'm a newbie to python.
I was trying to display the time duration.
What I did was:
```
startTime = datetime.datetime.now().replace(microsecond=0)
... <some more codes> ...
endTime = datetime.datetime.now().replace(microsecond=0)
durationTime = endTime - startTime
print("The duration is " + str(durationTime))
```
The... | 2015/06/24 | [
"https://Stackoverflow.com/questions/31018497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528322/"
] | You can split your timedelta as follows:
```
>>> hours, remainder = divmod(durationTime.total_seconds(), 3600)
>>> minutes, seconds = divmod(remainder, 60)
>>> print '%s:%s' % (minutes, seconds)
```
This will use python's builtin divmod to convert the number of seconds in your timedelta to hours, and the remainder w... | You can do this by converting `durationTime` which is a `datetime.timedelta` object to a `datetime.time` object and then using `strftime`.
```
print datetime.time(0, 0, durationTime.seconds).strftime("%M:%S")
```
Another way would be to manipulate the string:
```
print ':'.join(str(durationTime).split(':')[1:])
``... |
42,157,406 | I'm a beginner to mongodb and python, and i'm trying to write python code to delete the documents of multiple collections older than 30 days based on date field which is of NumberLong type and also has to export the collections to CSV before deleting. I'm using below simple code to print the records as a first step by ... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42157406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7544956/"
] | I use datetime for dates in python..
This is an example:
```
import datetime
date = datetime.date(2017,2,10)
otherDate = datetime.date(1999,1,1)
date < otherDate # False
``` | You have to use [datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime) like this:
`query = {"date": {"$lt": datetime.datetime(2021, 6, 14, 0, 0, 0, 0)}}`
To use the current time you can do:
`query = {"date": {"$lt": datetime.now(timezone.utc)}}`
Source: <https://pymongo.readthedocs.i... |
42,157,406 | I'm a beginner to mongodb and python, and i'm trying to write python code to delete the documents of multiple collections older than 30 days based on date field which is of NumberLong type and also has to export the collections to CSV before deleting. I'm using below simple code to print the records as a first step by ... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42157406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7544956/"
] | I use datetime for dates in python..
This is an example:
```
import datetime
date = datetime.date(2017,2,10)
otherDate = datetime.date(1999,1,1)
date < otherDate # False
``` | Use bson.Int64() to query for timestamp in NumberLong format. It worked for me.
Customizing it for you below:
```
import bson
import pymongo
from pymongo import MongoClient
conn=MongoClient('localhost',27017)
db=conn.mydb
col=db.test
timestamp_value= <value> #calculate epoch time stamp 30 days earlier and variable sho... |
41,403,465 | My flask app is outputting 'no content' for the `for()` block and i dont know why.
I tested my query in `app.py` , here is `app.py`:
```
# mysql config
app.config['MYSQL_DATABASE_USER'] = 'user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypass'
app.config['MYSQL_DATABASE_DB'] = 'mydbname'
app.config['MYSQL_DATABASE_HO... | 2016/12/30 | [
"https://Stackoverflow.com/questions/41403465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700070/"
] | You haven't got anything in your template called `blogposts`. You need to use keyword arguments to pass the data:
```
return render_template('index.html', blogposts=blogposts)
```
Also note you should really do that query inside the function, otherwise it will only ever execute on process start and you'll always ha... | I had same problem. I solved it as change directory of terminal to the folder containing app.py and then run
```
export FLASK_APP=app.py
```
then, you should run
```
python -m flask run
``` |
35,538,814 | I have a bunch of `.java` files in a directory and I want to compile all of them to `.class` files via python code.
As you know, the `Javac` command line tool is the tool that I must use and it require the name of `.java` files to be equal with the class name. Unfortunately for my `.java` files, it isn't. I mean they... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35538814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580433/"
] | In many cases a simple regex will work.
If you want to be 100% certain I suggest using a full-blown Java parser like [javalang](https://github.com/c2nes/javalang) to parse each file, then walk the AST to pull out the class name.
Something like
```
import glob
import javalang
# look at all .java files in the working... | This regex works for me. `(?<=^public class )\b.*\b(?= extends Applet)`.
The way to use it correctly:
```
re.compile(ur'(?<=^public class )\b.*\b(?= extends Applet)', re.MULTILINE)
``` |
35,538,814 | I have a bunch of `.java` files in a directory and I want to compile all of them to `.class` files via python code.
As you know, the `Javac` command line tool is the tool that I must use and it require the name of `.java` files to be equal with the class name. Unfortunately for my `.java` files, it isn't. I mean they... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35538814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580433/"
] | In many cases a simple regex will work.
If you want to be 100% certain I suggest using a full-blown Java parser like [javalang](https://github.com/c2nes/javalang) to parse each file, then walk the AST to pull out the class name.
Something like
```
import glob
import javalang
# look at all .java files in the working... | You could come up with the following regex:
```
import re
string = your_string_here
classes = [x.strip() for x in re.findall(r'^(?:public class|package) ([^;]+?)(?=extends|;)', string, re.MULTILINE)]
# look for public class or package at the start of the line
# then anything but a semicolon
# make sure the match is i... |
42,501,900 | I just wanted to ask you all about what is fitfunc, errfunc followed by scipy.optimize.leastsq is intuitively. I am not really used to python but I would like to understand this. Here is the code that I am trying to understand.
```
def optimize_parameters2(p0,mz):
fitfunc = lambda p,p0,mz: calculate_sp2(p, p0, mz)... | 2017/02/28 | [
"https://Stackoverflow.com/questions/42501900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6646128/"
] | Inspite of `change` event trigger the modal on `click` event of `select option` like
```
$('select option').on('click',function(){
$("#modelId").modal('show');
});
``` | You can also use modal function
```
$('select option').on('click'function(){
$('modelId').modal('show');
});
``` |
42,501,900 | I just wanted to ask you all about what is fitfunc, errfunc followed by scipy.optimize.leastsq is intuitively. I am not really used to python but I would like to understand this. Here is the code that I am trying to understand.
```
def optimize_parameters2(p0,mz):
fitfunc = lambda p,p0,mz: calculate_sp2(p, p0, mz)... | 2017/02/28 | [
"https://Stackoverflow.com/questions/42501900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6646128/"
] | Inspite of `change` event trigger the modal on `click` event of `select option` like
```
$('select option').on('click',function(){
$("#modelId").modal('show');
});
``` | Create a select with a default value option.
```
<select id="slt">
<option value="default">Select Something</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
```
Every time, handle the change event for a not defaultValue option, and then reset t... |
42,501,900 | I just wanted to ask you all about what is fitfunc, errfunc followed by scipy.optimize.leastsq is intuitively. I am not really used to python but I would like to understand this. Here is the code that I am trying to understand.
```
def optimize_parameters2(p0,mz):
fitfunc = lambda p,p0,mz: calculate_sp2(p, p0, mz)... | 2017/02/28 | [
"https://Stackoverflow.com/questions/42501900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6646128/"
] | Create a select with a default value option.
```
<select id="slt">
<option value="default">Select Something</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
```
Every time, handle the change event for a not defaultValue option, and then reset t... | You can also use modal function
```
$('select option').on('click'function(){
$('modelId').modal('show');
});
``` |
58,370,832 | I wanted to include an XML file in another XML file and parse it with python. I am trying to achieve it through Xinclude. There is a file1.xml which looks like
```
<?xml version="1.0"?>
<root>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="file2.xml" parse="xml" />
</document>
<test... | 2019/10/14 | [
"https://Stackoverflow.com/questions/58370832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Not sure why you want to use XInclude, but including an XML file in another one is a basic mechanism of SGML and XML, and can be achieved without XInclude as simple as:
```
<!DOCTYPE root [
<!ENTITY externaldoc SYSTEM "file2.xml">
]>
<root>
<document>
&externaldoc;
</document>
<test>some text</test>
</root... | You need to make xml.etree to include the files referenced with xi:include.
I have added the key line to your original example:
```
from xml.etree import ElementTree, ElementInclude
tree = ElementTree.parse("file1.xml")
root = tree.getroot()
#here you make the parser actually include every referenced file
ElementInc... |
58,370,832 | I wanted to include an XML file in another XML file and parse it with python. I am trying to achieve it through Xinclude. There is a file1.xml which looks like
```
<?xml version="1.0"?>
<root>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="file2.xml" parse="xml" />
</document>
<test... | 2019/10/14 | [
"https://Stackoverflow.com/questions/58370832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Below
```
import xml.etree.ElementTree as ET
xml1 = '''<?xml version="1.0"?>
<root>
<test>some text</test>
</root>'''
xml2 = '''<para>This is a paragraph.</para>'''
root1 = ET.fromstring(xml1)
root2 = ET.fromstring(xml2)
root1.insert(0,root2)
para_value = root1.find('.//para').text
print(para_value)
```
outpu... | You need to make xml.etree to include the files referenced with xi:include.
I have added the key line to your original example:
```
from xml.etree import ElementTree, ElementInclude
tree = ElementTree.parse("file1.xml")
root = tree.getroot()
#here you make the parser actually include every referenced file
ElementInc... |
48,848,829 | I'm coming from Python so trying to figure out basic things in Js.
I have the following:
```
{
name: 'Jobs ',
path: '/plat/jobs',
meta: {
label: 'jobs',
link: 'jobs/Basic.vue'
},
```
what I want is to create this block for each element in a list using a for loop (including the brackets)
in python t... | 2018/02/18 | [
"https://Stackoverflow.com/questions/48848829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680978/"
] | Included is an example that operates on an array of objects, returning a new array of objects. An object is overloaded in JavaScript, but in this case it is synonymous in other languages to a hash, object, or dictionary (depending on application).
```js
let items = [{
name: 'foo',
path: 'foopath',
label: 'foo... | I would use the list.map function
```
items.map(i => {
return {
name: i.name,
path: i.path,
meta: {
label: i.label,
link: i.link
}
}))
```
This will return a new list of items as specified
NOTE: this can be simplified further with an implicit return
... |
45,705,876 | Say I am working with OpenGL in python.
Often times you make a call such as
```
glutDisplayFunc(display)
```
where display is a function that you have written.
What if I have a class
```
class foo:
#self.x=5
def display(self, maybe some other variables):
#run some code
print("Hooray!, X ... | 2017/08/16 | [
"https://Stackoverflow.com/questions/45705876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4327053/"
] | You can call method of another component from a different component but it will not update the value of the calling component without some tweaking like
`Event Emitters` if they have a parent child relationship or `Shared Services` or using `ngrx redux pattern`
How to Call a different component method be like
Compon... | You **`cannot`** do that, There are two possible ways you could achieve this,
1. use **[`angular service`](https://angular.io/tutorial/toh-pt4)** to pass the data between two components
2. use **[`Event Emitters`](https://angular.io/api/core/EventEmitter)** to pass the value among the components. |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | For completeness, here's another way of causing this:
```
@if(condition)
{
<input type="hidden" value="@value">
}
```
The problem is that the unclosed element makes it not obvious enough that the content is an html block (but we aren't *always* doing xhtml, right?).
In this scenario, you can use:
```
@if(condi... | I've gotten this issue with Razor. I'm not sure if it's a bug in the parser or what, but the way I've solved it is to break up the:
```
@using(Html.BeginForm()) {
<h1>Example</h1>
@foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
}
```
into:
```
@{ Html.BeginForm(); }
<h1>Ex... |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | This is basically the same answer that Mark Gravell gave, but I think this one is an easy mistake to make if you have a larger view:
Check the html tags to see where they start and end, and notice razor syntax in between, this is wrong:
```
@using (Html.BeginForm())
{
<div class="divClass">
@Html.DisplayFor(c... | I've gotten this issue with Razor. I'm not sure if it's a bug in the parser or what, but the way I've solved it is to break up the:
```
@using(Html.BeginForm()) {
<h1>Example</h1>
@foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
}
```
into:
```
@{ Html.BeginForm(); }
<h1>Ex... |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | For completeness, here's another way of causing this:
```
@if(condition)
{
<input type="hidden" value="@value">
}
```
The problem is that the unclosed element makes it not obvious enough that the content is an html block (but we aren't *always* doing xhtml, right?).
In this scenario, you can use:
```
@if(condi... | MY bad.
I've got an error in the partial view.
I've written 'class' instead of '@class' in htmlAttributes. |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | This is basically the same answer that Mark Gravell gave, but I think this one is an easy mistake to make if you have a larger view:
Check the html tags to see where they start and end, and notice razor syntax in between, this is wrong:
```
@using (Html.BeginForm())
{
<div class="divClass">
@Html.DisplayFor(c... | MY bad.
I've got an error in the partial view.
I've written 'class' instead of '@class' in htmlAttributes. |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | For completeness, here's another way of causing this:
```
@if(condition)
{
<input type="hidden" value="@value">
}
```
The problem is that the unclosed element makes it not obvious enough that the content is an html block (but we aren't *always* doing xhtml, right?).
In this scenario, you can use:
```
@if(condi... | The Razor parser of MVC4 is different from MVC3. Razor v3 is having advanced parser features and on the other hand strict parsing compare to MVC3.
--> Avoid using server blocks in views unless there is variable declaration section.
Don’t : \n
`@{if(check){body}}`
Recommended :
`@if(check){body}`
--> Avoid using @ w... |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | This is basically the same answer that Mark Gravell gave, but I think this one is an easy mistake to make if you have a larger view:
Check the html tags to see where they start and end, and notice razor syntax in between, this is wrong:
```
@using (Html.BeginForm())
{
<div class="divClass">
@Html.DisplayFor(c... | The Razor parser of MVC4 is different from MVC3. Razor v3 is having advanced parser features and on the other hand strict parsing compare to MVC3.
--> Avoid using server blocks in views unless there is variable declaration section.
Don’t : \n
`@{if(check){body}}`
Recommended :
`@if(check){body}`
--> Avoid using @ w... |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | Without for:
```
word_pilandrom = str(input("Please enter a word: "))
new_word=word_pilandrom.lower().replace(" ","")
if new_word[::1] == new_word[::-1]:
print("OK")
else:
print("NOT")
``` |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | To check sentence palindrome-ness, the algorithm seems to be:
1. Remove any non-alphabetical character
2. Compare `new_s` to `new_s[::-1]` case-insensitively.
You can do the former by doing:
```
import string
valid = set(string.ascii_letters)
result_s = ''.join([ch for ch in original_s if ch in valid])
```
Then t... | If by palindrome sentence you mean ignoring spaces, you can do that like this:
```
is_palindrome(sentence.replace(' ', ''))
``` |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | We need to check whether the reverse of a string equals the original string with two additional requirements:
* ignore case
* ignore anything except letters
The solution is:
1. Convert all letters to the same case (e.g. lower case)
2. Filter only letters
3. Check palindrome condition
```py
def is_palindrome(s):... |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | To check sentence palindrome-ness, the algorithm seems to be:
1. Remove any non-alphabetical character
2. Compare `new_s` to `new_s[::-1]` case-insensitively.
You can do the former by doing:
```
import string
valid = set(string.ascii_letters)
result_s = ''.join([ch for ch in original_s if ch in valid])
```
Then t... |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | To check sentence palindrome-ness, the algorithm seems to be:
1. Remove any non-alphabetical character
2. Compare `new_s` to `new_s[::-1]` case-insensitively.
You can do the former by doing:
```
import string
valid = set(string.ascii_letters)
result_s = ''.join([ch for ch in original_s if ch in valid])
```
Then t... | ```
str =input("Enter the word")
s =str.lower()
s1 =s.split(" ")
s2 =s1.join()
s3 =''.join(reversed(s2))
if s2 ==s3 :
print("Palindrome:")
else :
print("Not Palindrome:")
``` |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | Based on the title, sentence could be termed as palindrome in 2 ways:
1. **Order of words should be inverted**: Create list of words and check for the inverted list:
```
>>> my_sentence = 'Hello World Hello'
>>> words = my_sentence.split()
>>> words == words[::-1]
True
```
2. **Order of characters should be inverted... |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | ```
str =input("Enter the word")
s =str.lower()
s1 =s.split(" ")
s2 =s1.join()
s3 =''.join(reversed(s2))
if s2 ==s3 :
print("Palindrome:")
else :
print("Not Palindrome:")
``` |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | You could filter the string to get only the letters like this:
```
letters = ''.join(c for c in words if c in string.letters)
is_palindrome(letters)
```
You would also have to call `lower` on it:
```
def is_palindrome(s):
s = ''.join(c for c in s if c in string.letters)
s = s.lower()
return s == s[::-1]... | We need to check whether the reverse of a string equals the original string with two additional requirements:
* ignore case
* ignore anything except letters
The solution is:
1. Convert all letters to the same case (e.g. lower case)
2. Filter only letters
3. Check palindrome condition
```py
def is_palindrome(s):... |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | If by palindrome sentence you mean ignoring spaces, you can do that like this:
```
is_palindrome(sentence.replace(' ', ''))
``` |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | You could filter the string to get only the letters like this:
```
letters = ''.join(c for c in words if c in string.letters)
is_palindrome(letters)
```
You would also have to call `lower` on it:
```
def is_palindrome(s):
s = ''.join(c for c in s if c in string.letters)
s = s.lower()
return s == s[::-1]... | Without for:
```
word_pilandrom = str(input("Please enter a word: "))
new_word=word_pilandrom.lower().replace(" ","")
if new_word[::1] == new_word[::-1]:
print("OK")
else:
print("NOT")
``` |
39,834,949 | I'm aware this is normally done with twistd, but I'm wanting to use iPython to test out code 'live' on twisted code.
[How to start twisted's reactor from ipython](https://stackoverflow.com/questions/4673375/how-to-start-twisteds-reactor-from-ipython) asked basically the same thing but the first solution no longer work... | 2016/10/03 | [
"https://Stackoverflow.com/questions/39834949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4443898/"
] | Async code in general can be troublesome to run in a live interpreter. It's best just to run an async script in the background and do your iPython stuff in a separate interpreter. You can intercommunicate using files or TCP. If this went over your head, that's because it's not always simple and it might be best to avoi... | While this doesn't answer the question I thought I had, it does answer (sort of) the question I posted. Embedding ipython works in the sense that you get access to business objects with the reactor running.
```
from twisted.internet import reactor
from twisted.internet.endpoints import serverFromString
from myfactory ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.