qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
42,903,036 | I am trying to find any way possible to get a SharePoint list in Python. I was able to connect to SharePoint and get the XML data using Rest API via this video: <https://www.youtube.com/watch?v=dvFbVPDQYyk>... but not sure how to get the list data into python. The ultimate goal will be to get the SharePoint data and import into SSMS daily.
Here is what I have so far..
```
import requests
from requests_ntlm import HttpNtlmAuth
url='URL would go here'
username='username would go here'
password='password would go here'
r=requests.get(url, auth=HttpNtlmAuth(username,password),verify=False)
```
I believe these would be the next steps. I really only need help getting the data from SharePoint in Excel/CSV format preferably and should be fine from there. But any recommendations would be helpful..
```
#PARSE XML VIA REST API
#PRINT INTO DATAFRAME AND CONVERT INTO CSV
#IMPORT INTO SQL SERVER
#EMAIL RESULTS
``` | 2017/03/20 | [
"https://Stackoverflow.com/questions/42903036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418496/"
] | I know this doesn't directly answer your question (and you probably have an answer by now) but I would give the [SharePlum](https://pypi.org/project/SharePlum/) library a try. It should hopefully [simplify](https://shareplum.readthedocs.io/en/latest/index.html) the process you have for interacting with SharePoint.
Also, I am not sure if you have a requirement to export the data into a csv but, you can [connect directly to SQL Server](https://stackoverflow.com/a/33787509/9350722) and insert your data more directly.
I would have just added this into the comments but don't have a high enough reputation yet. | I can help with most of these issues
```
import requests
import xml.etree.ElementTree as ET
import csv
from requests_ntlm import HttpNtlmAuth
response = requests.get("your_url", auth=HttpNtlmAuth('xxxx\\username','password'))
tree = ET.ElementTree(ET.fromstring(response.content))
tree.write('file_name_xml.xml')
root = tree.getroot()
#Create csv file
csv_file = open('file_name_csv.csv', 'w', newline = '', encoding='ansi')
csvwriter = csv.writer(csv_file)
col_names = ['Col_1', 'Col_2', 'Col_3', 'Col_n']
csvwriter.writerow(col_names)
field_tag = ['dado_1', 'dado_2', 'dado_3', 'dado_n']
#schema XML microsoft
ns0 = "http://www.w3.org/2005/Atom"
ns1 = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
ns2 = "http://schemas.microsoft.com/ado/2007/08/dataservices"
for member in root:
if member.tag == '{' + ns0 + '}entry':
for element in member:
if element.tag == '{' + ns0 + '}content':
data_line = []
for field in element[0]:
for count in range(0, len(field_tag)):
if field.tag == '{' + ns2 + '}' + field_tag[count]:
data_line.append(field.text)
csvwriter.writerow(data_line)
csv_file.close()
``` |
42,903,036 | I am trying to find any way possible to get a SharePoint list in Python. I was able to connect to SharePoint and get the XML data using Rest API via this video: <https://www.youtube.com/watch?v=dvFbVPDQYyk>... but not sure how to get the list data into python. The ultimate goal will be to get the SharePoint data and import into SSMS daily.
Here is what I have so far..
```
import requests
from requests_ntlm import HttpNtlmAuth
url='URL would go here'
username='username would go here'
password='password would go here'
r=requests.get(url, auth=HttpNtlmAuth(username,password),verify=False)
```
I believe these would be the next steps. I really only need help getting the data from SharePoint in Excel/CSV format preferably and should be fine from there. But any recommendations would be helpful..
```
#PARSE XML VIA REST API
#PRINT INTO DATAFRAME AND CONVERT INTO CSV
#IMPORT INTO SQL SERVER
#EMAIL RESULTS
``` | 2017/03/20 | [
"https://Stackoverflow.com/questions/42903036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418496/"
] | ```
from shareplum import Site
from requests_ntlm import HttpNtlmAuth
server_url = "https://sharepoint.xxx.com/"
site_url = server_url + "sites/org/"
auth = HttpNtlmAuth('xxx\\user', 'pwd')
site = Site(site_url, auth=auth, verify_ssl=False)
sp_list = site.List('list name in my share point')
data = sp_list.GetListItems('All Items', rowlimit=200)
``` | I can help with most of these issues
```
import requests
import xml.etree.ElementTree as ET
import csv
from requests_ntlm import HttpNtlmAuth
response = requests.get("your_url", auth=HttpNtlmAuth('xxxx\\username','password'))
tree = ET.ElementTree(ET.fromstring(response.content))
tree.write('file_name_xml.xml')
root = tree.getroot()
#Create csv file
csv_file = open('file_name_csv.csv', 'w', newline = '', encoding='ansi')
csvwriter = csv.writer(csv_file)
col_names = ['Col_1', 'Col_2', 'Col_3', 'Col_n']
csvwriter.writerow(col_names)
field_tag = ['dado_1', 'dado_2', 'dado_3', 'dado_n']
#schema XML microsoft
ns0 = "http://www.w3.org/2005/Atom"
ns1 = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
ns2 = "http://schemas.microsoft.com/ado/2007/08/dataservices"
for member in root:
if member.tag == '{' + ns0 + '}entry':
for element in member:
if element.tag == '{' + ns0 + '}content':
data_line = []
for field in element[0]:
for count in range(0, len(field_tag)):
if field.tag == '{' + ns2 + '}' + field_tag[count]:
data_line.append(field.text)
csvwriter.writerow(data_line)
csv_file.close()
``` |
42,903,036 | I am trying to find any way possible to get a SharePoint list in Python. I was able to connect to SharePoint and get the XML data using Rest API via this video: <https://www.youtube.com/watch?v=dvFbVPDQYyk>... but not sure how to get the list data into python. The ultimate goal will be to get the SharePoint data and import into SSMS daily.
Here is what I have so far..
```
import requests
from requests_ntlm import HttpNtlmAuth
url='URL would go here'
username='username would go here'
password='password would go here'
r=requests.get(url, auth=HttpNtlmAuth(username,password),verify=False)
```
I believe these would be the next steps. I really only need help getting the data from SharePoint in Excel/CSV format preferably and should be fine from there. But any recommendations would be helpful..
```
#PARSE XML VIA REST API
#PRINT INTO DATAFRAME AND CONVERT INTO CSV
#IMPORT INTO SQL SERVER
#EMAIL RESULTS
``` | 2017/03/20 | [
"https://Stackoverflow.com/questions/42903036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418496/"
] | ```
from shareplum import Site
from requests_ntlm import HttpNtlmAuth
server_url = "https://sharepoint.xxx.com/"
site_url = server_url + "sites/org/"
auth = HttpNtlmAuth('xxx\\user', 'pwd')
site = Site(site_url, auth=auth, verify_ssl=False)
sp_list = site.List('list name in my share point')
data = sp_list.GetListItems('All Items', rowlimit=200)
``` | this can be done using SharePlum and Pandas
following is the working code snippet
```
import pandas as pd # importing pandas to write SharePoint list in excel or csv
from shareplum import Site
from requests_ntlm import HttpNtlmAuth
cred = HttpNtlmAuth(#userid_here, #password_here)
site = Site('#sharePoint_url_here', auth=cred)
sp_list = site.List('#SharePoint_list name here') # this creates SharePlum object
data = sp_list.GetListItems('All Items') # this will retrieve all items from list
# this creates pandas data frame you can perform any operation you like do within
# pandas capabilities
data_df = pd.DataFrame(data[0:])
data_df.to_excel("data.xlsx")
```
please rate if this helps.
Thank you in advance! |
42,903,036 | I am trying to find any way possible to get a SharePoint list in Python. I was able to connect to SharePoint and get the XML data using Rest API via this video: <https://www.youtube.com/watch?v=dvFbVPDQYyk>... but not sure how to get the list data into python. The ultimate goal will be to get the SharePoint data and import into SSMS daily.
Here is what I have so far..
```
import requests
from requests_ntlm import HttpNtlmAuth
url='URL would go here'
username='username would go here'
password='password would go here'
r=requests.get(url, auth=HttpNtlmAuth(username,password),verify=False)
```
I believe these would be the next steps. I really only need help getting the data from SharePoint in Excel/CSV format preferably and should be fine from there. But any recommendations would be helpful..
```
#PARSE XML VIA REST API
#PRINT INTO DATAFRAME AND CONVERT INTO CSV
#IMPORT INTO SQL SERVER
#EMAIL RESULTS
``` | 2017/03/20 | [
"https://Stackoverflow.com/questions/42903036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418496/"
] | this can be done using SharePlum and Pandas
following is the working code snippet
```
import pandas as pd # importing pandas to write SharePoint list in excel or csv
from shareplum import Site
from requests_ntlm import HttpNtlmAuth
cred = HttpNtlmAuth(#userid_here, #password_here)
site = Site('#sharePoint_url_here', auth=cred)
sp_list = site.List('#SharePoint_list name here') # this creates SharePlum object
data = sp_list.GetListItems('All Items') # this will retrieve all items from list
# this creates pandas data frame you can perform any operation you like do within
# pandas capabilities
data_df = pd.DataFrame(data[0:])
data_df.to_excel("data.xlsx")
```
please rate if this helps.
Thank you in advance! | I can help with most of these issues
```
import requests
import xml.etree.ElementTree as ET
import csv
from requests_ntlm import HttpNtlmAuth
response = requests.get("your_url", auth=HttpNtlmAuth('xxxx\\username','password'))
tree = ET.ElementTree(ET.fromstring(response.content))
tree.write('file_name_xml.xml')
root = tree.getroot()
#Create csv file
csv_file = open('file_name_csv.csv', 'w', newline = '', encoding='ansi')
csvwriter = csv.writer(csv_file)
col_names = ['Col_1', 'Col_2', 'Col_3', 'Col_n']
csvwriter.writerow(col_names)
field_tag = ['dado_1', 'dado_2', 'dado_3', 'dado_n']
#schema XML microsoft
ns0 = "http://www.w3.org/2005/Atom"
ns1 = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
ns2 = "http://schemas.microsoft.com/ado/2007/08/dataservices"
for member in root:
if member.tag == '{' + ns0 + '}entry':
for element in member:
if element.tag == '{' + ns0 + '}content':
data_line = []
for field in element[0]:
for count in range(0, len(field_tag)):
if field.tag == '{' + ns2 + '}' + field_tag[count]:
data_line.append(field.text)
csvwriter.writerow(data_line)
csv_file.close()
``` |
44,789,394 | I have a spark cluster running in EMR. I also have a jupyter notebook running on a second EC2 machine. I would like to use spark on my EC2 instance through jupyter. I'm looking for references on how to configure spark to access the EMR cluster from EC2. Searching gives me only guides on how to setup spark on either EMR or EC2, but not how to access one from the other.
I saw a similar question here:
[Sending Commands from Jupyter/IPython running on EC2 to EMR cluster](https://stackoverflow.com/questions/35450586/sending-commands-from-jupyter-ipython-running-on-ec2-to-emr-cluster)
However, the setup there uses a bootstrap action to setup zeppelin, and I'm not sure how to edit my hadoop configuration on EC2. | 2017/06/27 | [
"https://Stackoverflow.com/questions/44789394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781958/"
] | Here you can do like following using the From ID.
```
<script>
function submitForm(){
document.getElementById("myFrom_id").submit();// Form submission
}
</script>
<form class="functionsquestionform2 classtest" id="myFrom_id" action="frameworkplayground.php" method="POST">
<input type="radio" name="functions_question2" value="1" /> Question
<div id="div_man" onclick="return submitForm();">click me</div>
</form>
```
Please do some research and study about basic HTML and JS on W3School.
There are many ways but this is the simple way that i prefer when you are beginner.
**Update: You can try following, it works**
```
<form class="functionsquestionform2 classtest" id="myFrom_id" action="frameworkplayground.php" method="POST">
<input type="radio" name="functions_question2" value="1" /> Question
<div id="div_man" onclick='document.getElementById("myFrom_id").submit();'>click me</div>
</form>
``` | ```
<script type='text/javascript'>
$(document).ready(function () {
$("div.submitter").click(function(){
$(this).parent().submit();
});
});
</script>
```
for this form:
```
<form class =".functionsquestionform2" class = "classtest" action="frameworkplayground.php" method="POST">
<input type="radio" name="functions_question2" value="1"> Question
</input>
<div class = "submitter">click me</div>
</form>
``` |
14,601,426 | I have an Ubuntu server which has a python script that runs a terminal command-based interface. I'm using plink to login and immediately execute the python script:
```
plink.exe -ssh -l goomuckel -pw greenpepper#7 192.168.1.201 "python server.py"
```
However, I get the following message:
```
TERM environment variable not set.
```
So I created a sh script (server.sh) on the Ubuntu machine:
```
export TERM=xterm
python server.py
```
Using the following plink command:
```
plink.exe -ssh -l goomuckel -pw greenpepper#7 192.168.1.201 "sh server.sh"
```
Now I don't receive the warning anymore, it seems that the python script is execute. But instead of showing the terminal interface I'm printing in the python script, only the following characters are printed:
```
←[H←[2J
```
The weird thing is, when logging in manually with Putty and executing the python script, everything works fine. I've tried adding the -t flag to plink and then the script executes. However I'm using colors for printing the terminal text, and the colors are printed as text rather than changing the colors of the text as observed in Putty.
Any ideas what I can do? | 2013/01/30 | [
"https://Stackoverflow.com/questions/14601426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/977063/"
] | You don't need to do this into a python script.
You could simply modify `.profile` -that is a file that system will execute on every login - with the same expression you use into python script
```
export TERM=xterm
```
(if you use bash)
```
setnv TERM xterm
```
(for c-shell and similar) | I had the same problem and setting the TERM variable before the command eliminated that *TERM environment variable not set.* error message:
```
plink.exe -ssh -l goomuckel -pw greenpepper#7 192.168.1.201 "export TERM=xterm; python server.py"
```
This is handy if you can't modify the *.profile* file... |
8,695,352 | i am creating a django app, my project name is domain\_com and the application name is gallery. The project is mapped to domain.com, so that works, now when i create the urls.py with these redirects its giving me these errors
```
(r'^domain_com/(?P<page_name>[^/]+)/edit/$', 'domain_com.gallery.views.edit_page'),
(r'^domain_com/(?P<page_name>[^/]+)/save/$', 'domain_com.gallery.views.save_page'),
(r'^domain_com/(?P<page_name>[^/]+)/$', 'domain_com.gallery.views.view_page')
```
error:
```
Using the URLconf defined in domain_com.urls, Django tried these URL patterns, in this order:
^domain_com/(?P<page_name>[^/]+)/edit/$
^domain_com/(?P<page_name>[^/]+)/save/$
^domain_com/(?P<page_name>[^/]+)/$
The current URL, edit, didn't match any of these.
```
any idea where the problem is? my intial install of django worked after create the application, so i am sure its the urls.py
this is my apache config
```
<VirtualHost *:80>
ServerName www.domain.com
ServerAlias domain.com
DocumentRoot /var/www/www.domain.com/htdocs/
ErrorLog /var/www/www.domain.com/logs/error.log
CustomLog /var/www/www.domain.com/logs/access.log combined
SetHandler mod_python
PythonHandler django.core.handlers.modpython
PythonPath sys.path+['/var/app/virtual/']
SetEnv DJANGO_SETTINGS_MODULE domain_com.settings
SetEnv PYTHON_EGG_CACHE /tmp
<Location "/gallery/">
SetHandler None
</Location>
</VirtualHost>
``` | 2012/01/01 | [
"https://Stackoverflow.com/questions/8695352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836677/"
] | after updated my answer:
try this:
```
(r'^/edit/(?P<page_name>\w+)$', 'gallery.views.edit_page'),
(r'^/save/(?P<page_name>\w+)$', 'gallery.views.save_page'),
(r'^/(?P<page_name>\w+)$', 'gallery.views.view_page')
```
While `urls.py` is root folder of your application.
Then if you visit:
<http://domain.com/edit/page1>
it should work | Set up both your main root urls to include the urls of your apps: <https://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs> |
8,695,352 | i am creating a django app, my project name is domain\_com and the application name is gallery. The project is mapped to domain.com, so that works, now when i create the urls.py with these redirects its giving me these errors
```
(r'^domain_com/(?P<page_name>[^/]+)/edit/$', 'domain_com.gallery.views.edit_page'),
(r'^domain_com/(?P<page_name>[^/]+)/save/$', 'domain_com.gallery.views.save_page'),
(r'^domain_com/(?P<page_name>[^/]+)/$', 'domain_com.gallery.views.view_page')
```
error:
```
Using the URLconf defined in domain_com.urls, Django tried these URL patterns, in this order:
^domain_com/(?P<page_name>[^/]+)/edit/$
^domain_com/(?P<page_name>[^/]+)/save/$
^domain_com/(?P<page_name>[^/]+)/$
The current URL, edit, didn't match any of these.
```
any idea where the problem is? my intial install of django worked after create the application, so i am sure its the urls.py
this is my apache config
```
<VirtualHost *:80>
ServerName www.domain.com
ServerAlias domain.com
DocumentRoot /var/www/www.domain.com/htdocs/
ErrorLog /var/www/www.domain.com/logs/error.log
CustomLog /var/www/www.domain.com/logs/access.log combined
SetHandler mod_python
PythonHandler django.core.handlers.modpython
PythonPath sys.path+['/var/app/virtual/']
SetEnv DJANGO_SETTINGS_MODULE domain_com.settings
SetEnv PYTHON_EGG_CACHE /tmp
<Location "/gallery/">
SetHandler None
</Location>
</VirtualHost>
``` | 2012/01/01 | [
"https://Stackoverflow.com/questions/8695352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836677/"
] | You have made a complicated URL of the form `http://domain.com/domain_com/page_name/edit/`. Yet you're testing with the URL `http://domain.com/edit`. Obviously, those don't match. | Set up both your main root urls to include the urls of your apps: <https://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs> |
60,943,751 | I am defining a pipeline using Jenkins Blue Ocean.
I'm trying to do a simple python pep8 coding convention, but if I go inside the shell and type the command directly, it runs fine.
But when the same command is executed in the pipeline, it is executed, but at the end
'script returned exit code 1' is displayed.
Because of this error code, it does not go to the next step.
Is there a workaround?
```
using credential github
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://github.com/YunTaeIl/jenkins_retest.git # timeout=10
Cleaning workspace
> git rev-parse --verify HEAD # timeout=10
Resetting working tree
> git reset --hard # timeout=10
> git clean -fdx # timeout=10
Fetching without tags
Fetching upstream changes from https://github.com/YunTaeIl/jenkins_retest.git
> git --version # timeout=10
using GIT_ASKPASS to set credentials GitHub Access Token
> git fetch --no-tags --progress -- https://github.com/YunTaeIl/jenkins_retest.git +refs/heads/master:refs/remotes/origin/master # timeout=10
Checking out Revision fe49ddf379732305a7a50f014ab4b25f9382c913 (master)
> git config core.sparsecheckout # timeout=10
> git checkout -f fe49ddf379732305a7a50f014ab4b25f9382c913 # timeout=10
> git branch -a -v --no-abbrev # timeout=10
> git branch -D master # timeout=10
> git checkout -b master fe49ddf379732305a7a50f014ab4b25f9382c913 # timeout=10
Commit message: "Added Jenkinsfile"
> git rev-list --no-walk bc12a035337857b29a4399f05d1d4442a2f0d04f # timeout=10
Cleaning workspace
> git rev-parse --verify HEAD # timeout=10
Resetting working tree
> git reset --hard # timeout=10
> git clean -fdx # timeout=10
+ ls
Jenkinsfile
README.md
jenkins-retest
+ python3.7 --version
Python 3.7.3
+ python3.7 -m flake8 jenkins-retest
jenkins-retest/N801_py3.py:3:1: E302 expected 2 blank lines, found 0
jenkins-retest/N801_py3.py:6:1: E302 expected 2 blank lines, found 0
jenkins-retest/N801_py3.py:9:1: E302 expected 2 blank lines, found 0
jenkins-retest/N801_py3.py:12:1: E302 expected 2 blank lines, found 0
jenkins-retest/N801_py3.py:15:1: E302 expected 2 blank lines, found 0
jenkins-retest/N801_py3.py:18:1: E302 expected 2 blank lines, found 0
jenkins-retest/N801_py3.py:24:1: E303 too many blank lines (4)
jenkins-retest/N801_py3.py:24:11: E999 SyntaxError: invalid syntax
jenkins-retest/python_testfile.py:1:1: E999 SyntaxError: invalid syntax
jenkins-retest/python_testfile.py:1:2: E228 missing whitespace around modulo operator
jenkins-retest/python_testfile.py:3:1: E402 module level import not at top of file
jenkins-retest/python_testfile.py:3:20: W291 trailing whitespace
jenkins-retest/python_testfile.py:5:1: E302 expected 2 blank lines, found 1
jenkins-retest/python_testfile.py:8:1: E305 expected 2 blank lines after class or function definition, found 0
jenkins-retest/python_testfile.py:11:33: W291 trailing whitespace
jenkins-retest/python_testfile.py:12:1: E402 module level import not at top of file
jenkins-retest/python_testfile.py:12:19: W291 trailing whitespace
jenkins-retest/python_testfile.py:14:4: E714 test for object identity should be 'is not'
jenkins-retest/python_testfile.py:17:16: W291 trailing whitespace
jenkins-retest/python_testfile.py:18:80: E501 line too long (95 > 79 characters)
script returned exit code 1
``` | 2020/03/31 | [
"https://Stackoverflow.com/questions/60943751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11992601/"
] | I'm surprised that more people are looking for this problem than I think.
Use `set +e` if you intend to ignore the error code exit 1 of code run as a shell script. | I had the same problem with a batch script calling an executable whose return status was 1 in case of success, and 0 in case of error.
This was a problem for Jenkins as for Jenkins, the success error code is 0 and any other status code means failure so stops the job with the following message: `script returned exit code 1`
My workaround: check the last error code and invert the return value of the script:
```
stages {
stage("My stage") {
steps {
bat label: 'My batch script',
script: ''' @echo off
return_1_if_success.exe // command which returns 1 in case of success, 0 otherwise
IF %ERRORLEVEL% EQU 1 (exit /B 0) ELSE (exit /B 1)'''
}
}
}
```
Explanation:
```
IF %ERRORLEVEL% EQU 1 (exit /B 0) ELSE (exit /B 1)
// if previous command returned 1 (meaning success for this command),
// then we exit with return code 0 (meaning success for Jenkins),
// otherwise we exit with return code 1 (meaning failure for Jenkins)
```
On Windows cmd, `%ERRORLEVEL%` holds that last error code encountered in a cmd.exe terminal or at a given point in a batch script.
For PowerShell, you might want to check `$?` instead of `ERRORLEVEL`, I'll let you check the equivalent of this for other shell and platform. |
9,856,163 | I have to parse a 1Gb XML file with a structure such as below and extract the text within the tags "Author" and "Content":
```
<Database>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
[...]
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
</Database>
```
So far I've tried two things: i) reading the whole file and going through it with .find(xmltag) and ii) parsing the xml file with lxml and iterparse().
The first option I've got it to work, but it is very slow. The second option I haven't managed to get it off the ground.
Here's part of what I have:
```
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
if element.tag == "BlogPost":
print element.text
else:
print 'Finished'
```
The result of that is only blank spaces, with no text in them.
I must be doing something wrong, but I can't grasp it. Also, In case it wasn't obvious enough, I am quite new to python and it is the first time I'm using lxml. Please, help! | 2012/03/24 | [
"https://Stackoverflow.com/questions/9856163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420622/"
] | ```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for child in element:
print(child.tag, child.text)
element.clear()
```
the final clear will stop you from using too much memory.
[update:] to get "everything between ... as a string" i guess you want one of:
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
print(etree.tostring(element))
element.clear()
```
or
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
print(''.join([etree.tostring(child) for child in element]))
element.clear()
```
or perhaps even:
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
print(''.join([child.text for child in element]))
element.clear()
``` | I prefer [XPath](http://www.w3schools.com/xpath/xpath_syntax.asp) for such things:
```py
In [1]: from lxml.etree import parse
In [2]: tree = parse('/tmp/database.xml')
In [3]: for post in tree.xpath('/Database/BlogPost'):
...: print 'Author:', post.xpath('Author')[0].text
...: print 'Content:', post.xpath('Content')[0].text
...:
Author: Last Name, Name
Content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.
Author: Last Name, Name
Content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.
Author: Last Name, Name
Content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.
```
I'm not sure if it's different in terms of processing big files, though. Comments about this would be appreciated.
Doing it your way,
```
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for info in element.iter():
if info.tag in ('Author', 'Content'):
print info.tag, ':', info.text
``` |
9,856,163 | I have to parse a 1Gb XML file with a structure such as below and extract the text within the tags "Author" and "Content":
```
<Database>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
[...]
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
</Database>
```
So far I've tried two things: i) reading the whole file and going through it with .find(xmltag) and ii) parsing the xml file with lxml and iterparse().
The first option I've got it to work, but it is very slow. The second option I haven't managed to get it off the ground.
Here's part of what I have:
```
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
if element.tag == "BlogPost":
print element.text
else:
print 'Finished'
```
The result of that is only blank spaces, with no text in them.
I must be doing something wrong, but I can't grasp it. Also, In case it wasn't obvious enough, I am quite new to python and it is the first time I'm using lxml. Please, help! | 2012/03/24 | [
"https://Stackoverflow.com/questions/9856163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420622/"
] | For future searchers: The top answer here suggests clearing the element on each iteration, but that still leaves you with an ever-increasing set of empty elements that will slowly build up in memory:
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for child in element:
print(child.tag, child.text)
element.clear()
```
^ This is not a scalable solution, especially as your source file gets larger and larger. The better solution is to get the *root* element, and clear *that* every time you load a complete record. This will keep memory usage pretty stable (sub-20MB I would say).
Here's a solution that doesn't require looking for a specific tag. This function will return a generator that yields all *1st child* nodes (e.g. `<BlogPost>` elements) underneath the root node (e.g. `<Database>`). It does this by recording the start of the first tag after the root node, then waiting for the corresponding end tag, yielding the entire element, and then clearing the root node.
```py
from lxml import etree
xmlfile = '/path/to/xml/file.xml'
def iterate_xml(xmlfile):
doc = etree.iterparse(xmlfile, events=('start', 'end'))
_, root = next(doc)
start_tag = None
for event, element in doc:
if event == 'start' and start_tag is None:
start_tag = element.tag
if event == 'end' and element.tag == start_tag:
yield element
start_tag = None
root.clear()
``` | I prefer [XPath](http://www.w3schools.com/xpath/xpath_syntax.asp) for such things:
```py
In [1]: from lxml.etree import parse
In [2]: tree = parse('/tmp/database.xml')
In [3]: for post in tree.xpath('/Database/BlogPost'):
...: print 'Author:', post.xpath('Author')[0].text
...: print 'Content:', post.xpath('Content')[0].text
...:
Author: Last Name, Name
Content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.
Author: Last Name, Name
Content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.
Author: Last Name, Name
Content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.
```
I'm not sure if it's different in terms of processing big files, though. Comments about this would be appreciated.
Doing it your way,
```
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for info in element.iter():
if info.tag in ('Author', 'Content'):
print info.tag, ':', info.text
``` |
9,856,163 | I have to parse a 1Gb XML file with a structure such as below and extract the text within the tags "Author" and "Content":
```
<Database>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
[...]
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictum vehicula.</Content>
</BlogPost>
</Database>
```
So far I've tried two things: i) reading the whole file and going through it with .find(xmltag) and ii) parsing the xml file with lxml and iterparse().
The first option I've got it to work, but it is very slow. The second option I haven't managed to get it off the ground.
Here's part of what I have:
```
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
if element.tag == "BlogPost":
print element.text
else:
print 'Finished'
```
The result of that is only blank spaces, with no text in them.
I must be doing something wrong, but I can't grasp it. Also, In case it wasn't obvious enough, I am quite new to python and it is the first time I'm using lxml. Please, help! | 2012/03/24 | [
"https://Stackoverflow.com/questions/9856163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420622/"
] | ```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for child in element:
print(child.tag, child.text)
element.clear()
```
the final clear will stop you from using too much memory.
[update:] to get "everything between ... as a string" i guess you want one of:
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
print(etree.tostring(element))
element.clear()
```
or
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
print(''.join([etree.tostring(child) for child in element]))
element.clear()
```
or perhaps even:
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
print(''.join([child.text for child in element]))
element.clear()
``` | For future searchers: The top answer here suggests clearing the element on each iteration, but that still leaves you with an ever-increasing set of empty elements that will slowly build up in memory:
```py
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for child in element:
print(child.tag, child.text)
element.clear()
```
^ This is not a scalable solution, especially as your source file gets larger and larger. The better solution is to get the *root* element, and clear *that* every time you load a complete record. This will keep memory usage pretty stable (sub-20MB I would say).
Here's a solution that doesn't require looking for a specific tag. This function will return a generator that yields all *1st child* nodes (e.g. `<BlogPost>` elements) underneath the root node (e.g. `<Database>`). It does this by recording the start of the first tag after the root node, then waiting for the corresponding end tag, yielding the entire element, and then clearing the root node.
```py
from lxml import etree
xmlfile = '/path/to/xml/file.xml'
def iterate_xml(xmlfile):
doc = etree.iterparse(xmlfile, events=('start', 'end'))
_, root = next(doc)
start_tag = None
for event, element in doc:
if event == 'start' and start_tag is None:
start_tag = element.tag
if event == 'end' and element.tag == start_tag:
yield element
start_tag = None
root.clear()
``` |
37,766,700 | I am trying to transform the age columns of a pandas dataframe by applying apply function. how to make below code work or is there a more pythonic way way to do this.
```
cps=(cps.assign(Age_grp_T=cps['age'].apply(lambda x:{x>=71:'Tradionalists',
71>x>=52:'Baby Boomers',
52>x>=46:'Generation X',
46>x>=16:'Millennials'}.get(x, ' ')))
``` | 2016/06/11 | [
"https://Stackoverflow.com/questions/37766700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4608730/"
] | i would use [cut()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html) function for that:
```
In [663]: labels=[' ','Millennials','Generation X','Baby Boomers','Tradionalists']
In [664]: a['category'] = pd.cut(a['age'], bins=[1, 16,46,52,71, 200],labels=labels)
In [665]: a
Out[665]:
age category
0 29 Millennials
1 65 Baby Boomers
2 68 Baby Boomers
3 18 Millennials
4 29 Millennials
5 58 Baby Boomers
6 15
7 67 Baby Boomers
8 21 Millennials
9 17 Millennials
10 19 Millennials
11 39 Millennials
12 64 Baby Boomers
13 70 Baby Boomers
14 33 Millennials
15 27 Millennials
16 54 Baby Boomers
17 60 Baby Boomers
18 23 Millennials
19 65 Baby Boomers
20 63 Baby Boomers
21 36 Millennials
22 53 Baby Boomers
23 29 Millennials
24 66 Baby Boomers
``` | I have found one more way to do this but thanks MaxU your answers works too
```
cps=(cps.assign(Age_grp_T=np.where(cps['age']>=71,"Tradionalists",
np.where(np.logical_and(71>cps['age'],cps['age']>=52),"Baby Boomers",
np.where(np.logical_and(52>cps['age'],cps['age']>=46),"Generation X",
np.where(np.logical_and(46>cps['age'],cps['age']>=16),"Millennials",-99))))
)
```
I wonder which one is more efficient? |
69,695,016 | I would like to install this library with pip: [ikpy library](https://pypi.org/project/ikpy/). However pip gives the error below:
```
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '/tmp/pip-build-oYTjdr/ikpy/setup.py'
```
What I understand from the error, pip cannot find setup.py, becuase library has setup.cfg instead. I tried to upgrade pip and got a different error.
```
$ pip install --upgrade pip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-KCnfi9/pip/setup.py", line 7
def read(rel_path: str) -> str:
^
SyntaxError: invalid syntax
```
I also tried pip3:
```
$ pip3 install ikpy
ModuleNotFoundError: No module named 'pip._vendor.pkg_resources'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
from pip import main
File "/usr/lib/python3/dist-packages/pip/__init__.py", line 13, in <module>
from pip.exceptions import InstallationError, CommandError, PipError
File "/usr/lib/python3/dist-packages/pip/exceptions.py", line 6, in <module>
from pip._vendor.six import iteritems
File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 75, in <module>
vendored("pkg_resources")
File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
__import__(modulename, globals(), locals(), level=0)
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2927, in <module>
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2913, in _call_aside
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in _initialize_master_working_set
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 956, in subscribe
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in <lambda>
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2515, in activate
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2097, in declare_namespace
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2047, in _handle_ns
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2066, in _rebuild_mod_path
AttributeError: '_NamespacePath' object has no attribute 'sort'
```
What should I do?
**Python 3.7.10, python3-pip: (8.1.1-2ubuntu0.6).**
**Note:**
I solved with these commands, now it can be installed with pip3:
```
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
pip3 install --upgrade setuptools
``` | 2021/10/24 | [
"https://Stackoverflow.com/questions/69695016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5384988/"
] | (*this message was created before the question was updated with pip3*)
It's likely that the `pip` command you use is for Python 2. Can you try with `pip3` instead? | Upgrade Your **`Pip`**
```
pip install --upgrade pip
```
then install **`ikpy`** Now it's should up and running ;-)
```
pip install ikpy
```
*Installed and Checked now on: Ubuntu 20.04, Pip 21.3, Python 3.8.10* |
69,695,016 | I would like to install this library with pip: [ikpy library](https://pypi.org/project/ikpy/). However pip gives the error below:
```
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '/tmp/pip-build-oYTjdr/ikpy/setup.py'
```
What I understand from the error, pip cannot find setup.py, becuase library has setup.cfg instead. I tried to upgrade pip and got a different error.
```
$ pip install --upgrade pip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-KCnfi9/pip/setup.py", line 7
def read(rel_path: str) -> str:
^
SyntaxError: invalid syntax
```
I also tried pip3:
```
$ pip3 install ikpy
ModuleNotFoundError: No module named 'pip._vendor.pkg_resources'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
from pip import main
File "/usr/lib/python3/dist-packages/pip/__init__.py", line 13, in <module>
from pip.exceptions import InstallationError, CommandError, PipError
File "/usr/lib/python3/dist-packages/pip/exceptions.py", line 6, in <module>
from pip._vendor.six import iteritems
File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 75, in <module>
vendored("pkg_resources")
File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
__import__(modulename, globals(), locals(), level=0)
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2927, in <module>
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2913, in _call_aside
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in _initialize_master_working_set
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 956, in subscribe
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in <lambda>
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2515, in activate
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2097, in declare_namespace
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2047, in _handle_ns
File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2066, in _rebuild_mod_path
AttributeError: '_NamespacePath' object has no attribute 'sort'
```
What should I do?
**Python 3.7.10, python3-pip: (8.1.1-2ubuntu0.6).**
**Note:**
I solved with these commands, now it can be installed with pip3:
```
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
pip3 install --upgrade setuptools
``` | 2021/10/24 | [
"https://Stackoverflow.com/questions/69695016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5384988/"
] | From ikpy library:
```
Starting with IKPy v3.1, only Python 3 is supported.
For versions before v3.1, the library can work with both versions of Python (2.7 and 3.x).
```
You can download the latest version compatible with python 2 here:
<https://github.com/Phylliade/ikpy/releases/tag/v3.0.1>
note: using python 2.7 is not recommended because support for Python version 2.7 will end on January 1, 2020 | Upgrade Your **`Pip`**
```
pip install --upgrade pip
```
then install **`ikpy`** Now it's should up and running ;-)
```
pip install ikpy
```
*Installed and Checked now on: Ubuntu 20.04, Pip 21.3, Python 3.8.10* |
68,384,553 | I have used idle before, but never set it up. my problem is actually getting a py file to work with. I don't actually know how to make one and it isn't an option when using save as on a text file. (only text file and all files(?) are put as options) I've attempted to open the py files already in the python folder but when selecting edit with idle I get prompted to pick what to open the file with and then if I click python nothing happens.
what am I missing? | 2021/07/14 | [
"https://Stackoverflow.com/questions/68384553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16450379/"
] | `shutil.make_archive` does not have a way to do what you want without copying files to another directory, which is inefficient. Instead you can use a compression library directly similar to the linked answer you provided. Note this doesn't handle name collisions!
```py
import zipfile
import os
with zipfile.ZipFile('output.zip','w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
for path,dirs,files in os.walk('dir_name'):
for file in files:
full = os.path.join(path,file)
z.write(full,file) # write the file, but with just the file's name not full path
# print the files in the zipfile
with zipfile.ZipFile('output.zip') as z:
for name in z.namelist():
print(name)
```
Given:
```none
dir_name
├───dir1
│ ├───cat1
│ │ file1.txt
│ │ file2.txt
│ │
│ └───cat2
│ file3.txt
│
└───dir2
└───cat3
file4.txt
```
Output:
```none
file1.txt
file2.txt
file3.txt
file4.txt
``` | ```py
# The root directory to search for
path = r'dir_name/'
import os
import glob
# List all *.txt files in the root directory
file_paths = [file_path
for root_path, _, _ in os.walk(path)
for file_path in glob.glob(os.path.join(root_path, '*.txt'))]
import tempfile
# Create a temporary directory to copy your files into
with tempfile.TemporaryDirectory() as tmp:
import shutil
for file_path in file_paths:
# Get the basename of the file
basename = os.path.basename(file_path)
# Copy the file to the temporary directory
shutil.copyfile(file_path, os.path.join(tmp, basename))
# Zip the temporary directory to the working directory
shutil.make_archive('output', 'zip', tmp)
```
This will create a *output.zip* file in the current working directory. The temporary directory will be deleted when the end of the context manager is reached. |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | The problem is for the 3rd element even though `id` attribute is not there `this.id` is not `undefined` it is an empty string. So for the 3rd element `test1` gets an empty string as the value but for `test2` the following `if` condition updates the value with the `id` data value.
One possible solution is to test the length of the `id` property instead of checking whether it is defined or not
```
var result1 = 'Result1:',
result2 = 'Result2:';
$('.test').each(function () {
var test = $(this),
testId1 = ($.trim(this.id || '').length ? this.id : test.data('id')),
testId2 = (this.id !== undefined ? this.id : '');
if (testId2 == '') {
testId2 = test.data('id');
}
result1 += testId1 + '.';
result2 += testId2 + '.';
});
$('#result1').html(result1);
$('#result2').html(result2);
```
Demo: [Fiddle](http://jsfiddle.net/arunpjohny/3wKdJ/) | Modify this line.
```
<div data-id="Test2" class="test">test</div> to
<div id="Test2" class="test">test</div>
```
**[JsFiddle](http://jsfiddle.net/sudhAnsu63/VxLUk/)** |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | The problem is for the 3rd element even though `id` attribute is not there `this.id` is not `undefined` it is an empty string. So for the 3rd element `test1` gets an empty string as the value but for `test2` the following `if` condition updates the value with the `id` data value.
One possible solution is to test the length of the `id` property instead of checking whether it is defined or not
```
var result1 = 'Result1:',
result2 = 'Result2:';
$('.test').each(function () {
var test = $(this),
testId1 = ($.trim(this.id || '').length ? this.id : test.data('id')),
testId2 = (this.id !== undefined ? this.id : '');
if (testId2 == '') {
testId2 = test.data('id');
}
result1 += testId1 + '.';
result2 += testId2 + '.';
});
$('#result1').html(result1);
$('#result2').html(result2);
```
Demo: [Fiddle](http://jsfiddle.net/arunpjohny/3wKdJ/) | The problem is because `typeof this.id` is a `string` even when it has no value set.
Because of this, the condition `typeof this.id !== "undefined"` is always true and hence both fields always have only `this.id` as value.
You should just try it the below way:
```
var test = $(this),
testId1 = (this.id !== "" ? this.id : test.data('id')),
testId2 = (this.id !== "" ? this.id : '');
``` |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | If an element has no id, element.id returns an empty string, not undefined.
Could fix and simplify :
```
var testId1 = this.id ? this.id : test.data('id');
``` | The problem is because `typeof this.id` is a `string` even when it has no value set.
Because of this, the condition `typeof this.id !== "undefined"` is always true and hence both fields always have only `this.id` as value.
You should just try it the below way:
```
var test = $(this),
testId1 = (this.id !== "" ? this.id : test.data('id')),
testId2 = (this.id !== "" ? this.id : '');
``` |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | Try this,
```
var result1 = 'Result1:',
result2 = 'Result2:';
$('.test').each(function () {
var test = $(this),
testId1 = (test.attr('id')!=undefined ? test.attr('id') : test.data('id')),
testId2 = (test.attr('id')!=undefined ? test.attr('id') : '');
if (testId2 == '') {
testId2 = test.data('id');
}
result1 += testId1 + '.';
result2 += testId2 + '.';
});
$('#result1').html(result1);
$('#result2').html(result2);
```
**Fiddle** <http://jsfiddle.net/WaJ5n/3/> | Your misstake is the html code, the id="Test2" needs to have the id tag not data-id="Test2"
```
<div id="Test" class="test">test</div>
<div id="Test1" class="test">test</div>
<div **id="Test2"** class="test">test</div>
<br />
<div id="result1"></div>
<div id="result2"></div>
```
This will give you the outpoot your are looking for. |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | The problem is for the 3rd element even though `id` attribute is not there `this.id` is not `undefined` it is an empty string. So for the 3rd element `test1` gets an empty string as the value but for `test2` the following `if` condition updates the value with the `id` data value.
One possible solution is to test the length of the `id` property instead of checking whether it is defined or not
```
var result1 = 'Result1:',
result2 = 'Result2:';
$('.test').each(function () {
var test = $(this),
testId1 = ($.trim(this.id || '').length ? this.id : test.data('id')),
testId2 = (this.id !== undefined ? this.id : '');
if (testId2 == '') {
testId2 = test.data('id');
}
result1 += testId1 + '.';
result2 += testId2 + '.';
});
$('#result1').html(result1);
$('#result2').html(result2);
```
Demo: [Fiddle](http://jsfiddle.net/arunpjohny/3wKdJ/) | Try this,
```
var result1 = 'Result1:',
result2 = 'Result2:';
$('.test').each(function () {
var test = $(this),
testId1 = (test.attr('id')!=undefined ? test.attr('id') : test.data('id')),
testId2 = (test.attr('id')!=undefined ? test.attr('id') : '');
if (testId2 == '') {
testId2 = test.data('id');
}
result1 += testId1 + '.';
result2 += testId2 + '.';
});
$('#result1').html(result1);
$('#result2').html(result2);
```
**Fiddle** <http://jsfiddle.net/WaJ5n/3/> |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | The problem is because `typeof this.id` is a `string` even when it has no value set.
Because of this, the condition `typeof this.id !== "undefined"` is always true and hence both fields always have only `this.id` as value.
You should just try it the below way:
```
var test = $(this),
testId1 = (this.id !== "" ? this.id : test.data('id')),
testId2 = (this.id !== "" ? this.id : '');
``` | Modify this line.
```
<div data-id="Test2" class="test">test</div> to
<div id="Test2" class="test">test</div>
```
**[JsFiddle](http://jsfiddle.net/sudhAnsu63/VxLUk/)** |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | If an element has no id, element.id returns an empty string, not undefined.
Could fix and simplify :
```
var testId1 = this.id ? this.id : test.data('id');
``` | Try this,
```
var result1 = 'Result1:',
result2 = 'Result2:';
$('.test').each(function () {
var test = $(this),
testId1 = (test.attr('id')!=undefined ? test.attr('id') : test.data('id')),
testId2 = (test.attr('id')!=undefined ? test.attr('id') : '');
if (testId2 == '') {
testId2 = test.data('id');
}
result1 += testId1 + '.';
result2 += testId2 + '.';
});
$('#result1').html(result1);
$('#result2').html(result2);
```
**Fiddle** <http://jsfiddle.net/WaJ5n/3/> |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | If an element has no id, element.id returns an empty string, not undefined.
Could fix and simplify :
```
var testId1 = this.id ? this.id : test.data('id');
``` | Your misstake is the html code, the id="Test2" needs to have the id tag not data-id="Test2"
```
<div id="Test" class="test">test</div>
<div id="Test1" class="test">test</div>
<div **id="Test2"** class="test">test</div>
<br />
<div id="result1"></div>
<div id="result2"></div>
```
This will give you the outpoot your are looking for. |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | If an element has no id, element.id returns an empty string, not undefined.
Could fix and simplify :
```
var testId1 = this.id ? this.id : test.data('id');
``` | Modify this line.
```
<div data-id="Test2" class="test">test</div> to
<div id="Test2" class="test">test</div>
```
**[JsFiddle](http://jsfiddle.net/sudhAnsu63/VxLUk/)** |
18,768,224 | I have built a backend for an iOS app with Google App Engine running python 2.7. When i create objects i want the backend to give it an ID which can be used by all clients as the one identifier to query. This method i use involves two put and basically just used since i was using db instead of ndb. Is there a better way of inserting objects and giving them an easily accessable Integer ID?
```
class Player(ndb.Model):
playerID = ndb.IntegerProperty()
username = db.StringProperty()
class createUserWithUsername(webapp2.RequestHandler):
def get(self):
username = self.request.get('username')
playerArr = Player.query(Player._properties["username"] == username).fetch(1)
if len(playerArr) > 0:
self.error(500)
else:
newPlayer = Player()
newPlayer.username = username
key = newPlayer.put()
newPlayer.playerID = key.id()
newPlayer.put()
# returning player as dict to client
``` | 2013/09/12 | [
"https://Stackoverflow.com/questions/18768224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071332/"
] | The problem is because `typeof this.id` is a `string` even when it has no value set.
Because of this, the condition `typeof this.id !== "undefined"` is always true and hence both fields always have only `this.id` as value.
You should just try it the below way:
```
var test = $(this),
testId1 = (this.id !== "" ? this.id : test.data('id')),
testId2 = (this.id !== "" ? this.id : '');
``` | Your misstake is the html code, the id="Test2" needs to have the id tag not data-id="Test2"
```
<div id="Test" class="test">test</div>
<div id="Test1" class="test">test</div>
<div **id="Test2"** class="test">test</div>
<br />
<div id="result1"></div>
<div id="result2"></div>
```
This will give you the outpoot your are looking for. |
16,428,401 | I have created an FTP client using ftplib. I am running the server on one of my Ubuntu virtual machine and client on another. I want to connect to the server using ftplib and I'm doing it in the following way:
```
host = "IP address of the server"
port = "Port number of the server"
ftpc = FTP()
ftpc.connect(host, port)
```
I'm getting the following error!
```
Traceback (most recent call last):
File "./client.py", line 54, in <module>
ftpc.connect(host, port)
File "/usr/lib/python2.7/ftplib.py", line 132, in connect
self.sock = socket.create_connection((self.host, self.port), self.timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 111] Connection refused
```
When I went through the docs of python, I could see ftplib used only with domain names as in FTP("domain name"). Can I use IP address instead of domain name? In my case I am unable to comprehend the error. It would be great if anyone can help me out.
Also if I use port 21 on my server, I'm getting socket error: Connection refused. How do I use port 21 for my FTP server?
Thank You. | 2013/05/07 | [
"https://Stackoverflow.com/questions/16428401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253736/"
] | It seems like you are trying to connect to SFTP server using ftplib which is giving you the Connection Refused error. Try using pysftp instead of ftplib and see if it works.
On the virtual machine, test by typing ftp and sftp commands on the console. You will get to know on which server the machine is running i.e ftp or sftp. | To solve the problem, I install and config vsftpd:
1. sudo apt install vsftpd (if not exist)
2. sudo vim /etc/vsftpd.conf
3. set "listen=YES" |
6,558,051 | Being a python programmer for four years now (it doesn't mean much though) and moving to Objective-C the one concept that is weird and "alien" to me is memory management. Luckily garbage collectiom exists and I only intend to develop apps for the mac OS 10.6+, so in all my projects so far I have always turned garbage collection to required. But here is my problem: when I use Instruments with the Alloc and Leaks tool I see leaked bytes poppin in the graph. ??? Very weird. What does Garbage Collection really do, when it is required. The way I see it is that you can completely forget about retain, release, etc. But is that true? Please provide examples where GC will help and where it won't (if any), so that I can understand what I am doing wrong.
Edit
----
I probably should have been more clear. The problem I want to solve is the fact that, even after GC is set up as required, Instruments still finds leaks. I also asked what GC does just so I could make sure that it does what I think, and the problem is not in my code or in GC, but elsewhere. That "elsewhere" is what I want to find out. | 2011/07/02 | [
"https://Stackoverflow.com/questions/6558051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778396/"
] | Make an array of `(i,j)` integer doublets covering all possible name-surname combinations. Shuffle the array. Then just loop through the array, and take names from it one by one.
You'll get unique full names in random order (provided that your name and surname lists don't contain duplicates).
**EDIT**
Pseudocode, per request.
First, do these setup steps:
```
indexList = emptyList
for i = 1 to length(first_names)
for j = 1 to length(last_names)
indexList.push( (i,j) )
shuffle(indexList)
```
`push` here means adding an element to the end of the list.
Now every time you need a new name, just take one index pair off `indexList`, and return the corresponding names from the name arrays:
```
function getName()
(i, j) = indexList.pop()
return concatenate(first_names[i], " ", last_names[j])
```
`pop` here means remove an element from the end of the list and return it. It is unlikely that you'd have so many names that the `indexList` should take up too much memory. | Loop over the first and last names, check if you already generated that combination. In PHP:
```
$full_names = array();
foreach ($names as $first_name) {
foreach ($surnames as $last_name) {
$candidate = $first_name . " " . $last_name;
if (!isset($full_names[$candidate])) {
$full_names[$candidate] = true;
}
}
}
print_r(array_keys($full_names));
```
Or same in Python:
```
print set([first + ' ' + last for first in names for last in surnames])
``` |
10,722,976 | I have a Python Script that generate a CSV (data parsed from a website).
Here is an exemple of the CSV file:
**File1.csv**
```
China;Beijing;Auralog Software Development (Deijing) Co. Ltd.;;;
United Kingdom;Oxford;Azad University (Ir) In Oxford Ltd;;;
Italy;Bari;Bari, The British School;;Yes;
China;Beijing;Beijing Foreign Enterprise Service Group Co Ltd;;;
China;Beijing;Beijing Ying Biao Human Resources Development Limited;;Yes;
China;Beijing;BeiwaiOnline BFSU;;;
Italy;Curno;Bergamo, Anderson House;;Yes;
```
**File2.csv**
```
China;Beijing;Auralog Software Development (Deijing) Co. Ltd.;;;
United Kingdom;Oxford;Azad University (Ir) In Oxford Ltd;;;
Italy;Bari;Bari, The British School;;Yes;
China;Beijing;Beijing Foreign Enterprise Service Group Co Ltd;;;
China;Beijing;Beijing Ying Biao Human Resources Development Limited;;Yes;
This;Is;A;New;Line;;
Italy;Curno;Bergamo, Anderson House;;Yes;
```
As you can see,
*China;Beijing;BeiwaiOnline BFSU;;;* ==> This line from File1.csv is not more present in File2.csv and *This;Is;A;New;Line;;* ==> This line from File2.csv is new (is not present in File1.csv).
I am looking for a way to compare this two CSV files (one important thing to know is that the order of the lines doesn't count ... they cant be anywhere).
What I'd like to have is a script which can tell me:
- One new line : *This;Is;A;New;Line;;*
- One removed line : *China;Beijing;BeiwaiOnline BFSU;;;*
And so on ... !
I've tried but without any success:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
f1 = file('now.csv', 'r')
f2 = file('past.csv', 'r')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
now = [row for row in c2]
past = [row for row in c1]
for row in now:
#print row
lol = past.index(row)
print lol
f1.close()
f2.close()
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
```
Any idea of the best way to proceed ? Thank you so much in advance ;)
EDIT:
```
import csv
f1 = file('now.csv', 'r')
f2 = file('past.csv', 'r')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
s1 = set(c1)
s2 = set(c2)
lol = s1 - s2
print type(lol)
print lol
```
This seems to be a good idea but :
```
Traceback (most recent call last):
File "compare.py", line 20, in <module>
s1 = set(c1)
TypeError: unhashable type: 'list'
```
**EDIT 2 (Please don't care about what is above):**
\**with your help, here is the script I'm writing :*\*
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import csv
### COMPARISON THING ###
x=0
fichiers = os.listdir('/me/CSV')
for fichier in fichiers:
if '.csv' in fichier:
print('%s -----> %s' % (x,fichier))
x=x+1
choice = raw_input("Which file do you want to compare with the new output ? ->>>")
past_file = fichiers[int(choice)]
print 'We gonna compare %s to our output' % past_file
s_now = frozenset(tuple(row) for row in csv.reader(open('/me/CSV/now.csv', 'r'), delimiter=';')) ## OUR OUTPUT
s_past = frozenset(tuple(row) for row in csv.reader(open('/me/CSV/'+past_file, 'r'), delimiter=';')) ## CHOOSEN ONE
added = [";".join(row) for row in s_now - s_past] # in "now" but not in "past"
removed = [";".join(row) for row in s_past - s_now] # in "past" but not in "now"
c = csv.writer(open("CHANGELOG.csv", "a"),delimiter=";" )
line = ['AD']
for item_added in added:
line.append(item_added)
c.writerow(['AD',item_added])
line = ['RM']
for item_removed in removed:
line.append(item_removed)
c.writerow(line)
```
Two kind of errors:
```
File "programcompare.py", line 21, in <genexpr>
s_past = frozenset(tuple(row) for row in csv.reader(open('/me/CSV/'+past_file, 'r'), delimiter=';')) ## CHOOSEN ONE
_csv.Error: line contains NULL byte
```
or
```
File "programcompare.py", line 21, in <genexpr>
s_past = frozenset(tuple(row) for row in csv.reader(open('/me/CSV/'+past_file, 'r'), delimiter=';')) ## CHOOSEN ONE
_csv.Error: newline inside string
```
It was working few minutes ago but I've changed the CSV files to test with different datas and here I am :-)
Sorry, last question ! | 2012/05/23 | [
"https://Stackoverflow.com/questions/10722976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1323870/"
] | If your data is not prohibitively large, loading them into a [set (or frozenset)](http://docs.python.org/library/stdtypes.html#set) will be an easy approach:
```
s_now = frozenset(tuple(row) for row in csv.reader(open('now.csv', 'r'), delimiter=';'))
s_past = frozenset(tuple(row) for row in csv.reader(open('past.csv', 'r'), delimiter=';'))
```
To get the list of entries that were added:
```
added = [";".join(row) for row in s_now - s_past] # in "now" but not in "past"
# Or, simply "added = list(s_now - s_past)" to keep them as tuples.
```
similarly, list of entries that were removed:
```
removed = [";".join(row) for row in s_past - s_now] # in "past" but not in "now"
```
---
To address your updated question on why you're seeing `TypeError: unhashable type: 'list'`, the csv returns each entry as a `list` when iterated. `lists` are not [hashable](http://docs.python.org/glossary.html#term-hashable) and therefore cannot be inserted into a `set`.
To address this, you'll need to convert the `list` entries into `tuple`s before adding the to the set. See previous section in my answer for an example of how this can be done.
---
To address the additional errors you're seeing, they are both due to the content of your CSV files.
**\_csv.Error: newline inside string**
It looks like you have quote characters (`"`) somewhere in data which confuses the parser. I'm not familiar enough with the CSV module to tell you exactly what has gone wrong, not without having a peek at your data anyway.
I did however manage to reproduce the error as such:
```
>>> [e for e in csv.reader(['hello;wo;"rld'], delimiter=";")]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_csv.Error: newline inside string
```
In this case, it can fixed by instructing the reader not to do any special processing with quotes (see [csv.QUOTE\_NONE](http://docs.python.org/library/csv.html#csv.QUOTE_NONE)). (Do note that this will disable the handling of quoted data whereby delimiters can appear within a quoted string without the string being split into separate entries.)
```
>>> [e for e in csv.reader(['hello;wo;"rld'], delimiter=";", quoting=csv.QUOTE_NONE)]
[['hello', 'wo', '"rld']]
```
**\_csv.Error: line contains NULL byte**
I'm guessing this might be down to the encoding of your CSV files. See the following questions:
* [Python CSV error: line contains NULL byte](https://stackoverflow.com/questions/4166070/python-csv-error-line-contains-null-byte)
* ["Line contains NULL byte" in CSV reader (Python)](https://stackoverflow.com/questions/7894856/line-contains-null-byte-in-csv-reader-python) | Read the csv files line by line into sets. Compare the sets.
```
>>> s1 = set('''China;Beijing;Auralog Software Development (Deijing) Co. Ltd.;;;
... United Kingdom;Oxford;Azad University (Ir) In Oxford Ltd;;;
... Italy;Bari;Bari, The British School;;Yes;
... China;Beijing;Beijing Foreign Enterprise Service Group Co Ltd;;;
... China;Beijing;Beijing Ying Biao Human Resources Development Limited;;Yes;
... China;Beijing;BeiwaiOnline BFSU;;;
... Italy;Curno;Bergamo, Anderson House;;Yes;'''.split('\n'))
>>> s2 = set('''China;Beijing;Auralog Software Development (Deijing) Co. Ltd.;;;
... United Kingdom;Oxford;Azad University (Ir) In Oxford Ltd;;;
... Italy;Bari;Bari, The British School;;Yes;
... China;Beijing;Beijing Foreign Enterprise Service Group Co Ltd;;;
... China;Beijing;Beijing Ying Biao Human Resources Development Limited;;Yes;
... This;Is;A;New;Line;;
... Italy;Curno;Bergamo, Anderson House;;Yes;'''.split('\n'))
>>> s1 - s2
set(['China;Beijing;BeiwaiOnline BFSU;;;'])
>>> s2 - s1
set(['This;Is;A;New;Line;;'])
``` |
71,808,755 | I am doing vehicle registration plate detection using YOLOv4 in colab. When I ran !python \convert\_annotations.py file I got following error
```
Currently in subdirectory: validation
Converting annotations for class: Vehicle registration plate
0% 0/30 [00:00<?, ?it/s]
Traceback (most recent call last):
File "convert_annotations.py", line 63, in <module>
coords = np.asarray([float(labels[1]), float(labels[2]), float(labels[3]), float(labels[4])])
ValueError: could not convert string to float: 'registration'
```
convert\_annotations.py file is as follows.
```
import os
import cv2
import numpy as np
from tqdm import tqdm
import argparse
import fileinput
# function that turns XMin, YMin, XMax, YMax coordinates to normalized yolo format
def convert(filename_str, coords):
os.chdir("..")
image = cv2.imread(filename_str + ".jpg")
coords[2] -= coords[0]
coords[3] -= coords[1]
x_diff = int(coords[2]/2)
y_diff = int(coords[3]/2)
coords[0] = coords[0]+x_diff
coords[1] = coords[1]+y_diff
coords[0] /= int(image.shape[1])
coords[1] /= int(image.shape[0])
coords[2] /= int(image.shape[1])
coords[3] /= int(image.shape[0])
os.chdir("Label")
return coords
ROOT_DIR = os.getcwd()
# create dict to map class names to numbers for yolo
classes = {}
with open("classes.txt", "r") as myFile:
for num, line in enumerate(myFile, 0):
line = line.rstrip("\n")
classes[line] = num
myFile.close()
# step into dataset directory
os.chdir(os.path.join("OID", "Dataset"))
DIRS = os.listdir(os.getcwd())
# for all train, validation and test folders
for DIR in DIRS:
if os.path.isdir(DIR):
os.chdir(DIR)
print("Currently in subdirectory:", DIR)
CLASS_DIRS = os.listdir(os.getcwd())
# for all class folders step into directory to change annotations
for CLASS_DIR in CLASS_DIRS:
if os.path.isdir(CLASS_DIR):
os.chdir(CLASS_DIR)
print("Converting annotations for class: ", CLASS_DIR)
# Step into Label folder where annotations are generated
os.chdir("Label")
for filename in tqdm(os.listdir(os.getcwd())):
filename_str = str.split(filename, ".")[0]
if filename.endswith(".txt"):
annotations = []
with open(filename) as f:
for line in f:
for class_type in classes:
line = line.replace(class_type, str(classes.get(class_type)))
labels = line.split()
coords = np.asarray([float(labels[1]), float(labels[2]), float(labels[3]), float(labels[4])])
coords = convert(filename_str, coords)
labels[1], labels[2], labels[3], labels[4] = coords[0], coords[1], coords[2], coords[3]
newline = str(labels[0]) + " " + str(labels[1]) + " " + str(labels[2]) + " " + str(labels[3]) + " " + str(labels[4])
line = line.replace(line, newline)
annotations.append(line)
f.close()
os.chdir("..")
with open(filename, "w") as outfile:
for line in annotations:
outfile.write(line)
outfile.write("\n")
outfile.close()
os.chdir("Label")
os.chdir("..")
os.chdir("..")
os.chdir("..")
```
I am doing this by seeing youtube videos so in video he didn't get error but I am getting error. What could be the problem, please help? | 2022/04/09 | [
"https://Stackoverflow.com/questions/71808755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11578411/"
] | Brian, the solution to your problem :
With your terminal, go to your directory, for example :
```
yolov4/OIDv4_ToolKit
```
To get 15 images for the training data:
```
python3 main.py downloader --classes Vehicle_registration_plate --type_csv train --limit 15
```
To get 3 images for the validation:
```
python3 main.py downloader --classes Vehicle_registration_plate --type_csv validation --limit 3
```
(If you want, you can set higher numbers, like 1500 images for the training data and 300 for the validation data)
Within the root `OIDv4_ToolKit` folder open the file `classes.txt` and edit it to have the classes you just downloaded and type exactly:
```
Vehicle registration plate
```
Finally, the command to convert all labels to YOLOv4 format:
```
python3 convert_annotations.py
```
Normally, this solution works like a charm. | remove apostrophes in 'Vehicle registration plate' and run it.
if the issue is not solved, then try running pip install -r requirements.txt before running this command |
68,967,823 | I'm using a python-based software, which utilizes long multiline-strings to run. I would like to create a loop in which I change one value to e.g. 40 other values and create 40 new strings where everything is the same except the target value.
I've achieved "what-I-want" as an output through this code:
```
for x in range(0, 40000, 40):
for line in mystring.splitlines(keepends=True):
line = line.replace("24000", str(x))
line = line.strip()
print(line)
```
and it prints all 40 of the long strings, but how can I save them to new strings and use them in the software?
I could also achieve 1 iteration but only 1, through this code:
```
for x in range(0,40000,40):
mystring = mystring.split("\n")
mystring[17] = "Constant = " + str(x)
mystring = "\n".join(mystring)
print(mystring)
```
Hope my question makes sense. I would just like 40 (in this example) new strings identical except the one value changing throughout.
Thank you | 2021/08/28 | [
"https://Stackoverflow.com/questions/68967823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16776029/"
] | You're trying to find the ID from the response object itself. The response object has all kind of data related to the HTTP request response, but most of that is irrelevant to you.
The actual data that comes in the response is within the 'data' property of the response.
So simply access that data variable, for example by destructuring it, and then use the native find function of arrays:
```
const { data } = await axios.get('http://localhost:4200/products');
return data.find((product) => product._id === id)
```
Note that you can't use the Mongoose's findById function here. That is a function related to the database, but you're not interacting with the database here, even though the HTTP request to get the products you want internally gets them from some database related to the other service. | You can achieve this with the following code:
```
const element = response.data.filter(e => e.id == <your_id>);
``` |
68,967,823 | I'm using a python-based software, which utilizes long multiline-strings to run. I would like to create a loop in which I change one value to e.g. 40 other values and create 40 new strings where everything is the same except the target value.
I've achieved "what-I-want" as an output through this code:
```
for x in range(0, 40000, 40):
for line in mystring.splitlines(keepends=True):
line = line.replace("24000", str(x))
line = line.strip()
print(line)
```
and it prints all 40 of the long strings, but how can I save them to new strings and use them in the software?
I could also achieve 1 iteration but only 1, through this code:
```
for x in range(0,40000,40):
mystring = mystring.split("\n")
mystring[17] = "Constant = " + str(x)
mystring = "\n".join(mystring)
print(mystring)
```
Hope my question makes sense. I would just like 40 (in this example) new strings identical except the one value changing throughout.
Thank you | 2021/08/28 | [
"https://Stackoverflow.com/questions/68967823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16776029/"
] | Since you are looking for a specific ID in an array (`data`) of products you need to filter out the data in your response from `/products`.
```
app.get('/add-to-cart/:id', async (req, res) => {
let id = req.params.id;
let cart = new Cart(req.body.cart ? req.body.cart : {});
const { data } = await axios.get('http://localhost:4200/products')
const productId = data.find(el => el._id === id);
response.findById(productId)
});
``` | You can achieve this with the following code:
```
const element = response.data.filter(e => e.id == <your_id>);
``` |
68,967,823 | I'm using a python-based software, which utilizes long multiline-strings to run. I would like to create a loop in which I change one value to e.g. 40 other values and create 40 new strings where everything is the same except the target value.
I've achieved "what-I-want" as an output through this code:
```
for x in range(0, 40000, 40):
for line in mystring.splitlines(keepends=True):
line = line.replace("24000", str(x))
line = line.strip()
print(line)
```
and it prints all 40 of the long strings, but how can I save them to new strings and use them in the software?
I could also achieve 1 iteration but only 1, through this code:
```
for x in range(0,40000,40):
mystring = mystring.split("\n")
mystring[17] = "Constant = " + str(x)
mystring = "\n".join(mystring)
print(mystring)
```
Hope my question makes sense. I would just like 40 (in this example) new strings identical except the one value changing throughout.
Thank you | 2021/08/28 | [
"https://Stackoverflow.com/questions/68967823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16776029/"
] | You're trying to find the ID from the response object itself. The response object has all kind of data related to the HTTP request response, but most of that is irrelevant to you.
The actual data that comes in the response is within the 'data' property of the response.
So simply access that data variable, for example by destructuring it, and then use the native find function of arrays:
```
const { data } = await axios.get('http://localhost:4200/products');
return data.find((product) => product._id === id)
```
Note that you can't use the Mongoose's findById function here. That is a function related to the database, but you're not interacting with the database here, even though the HTTP request to get the products you want internally gets them from some database related to the other service. | Since you are looking for a specific ID in an array (`data`) of products you need to filter out the data in your response from `/products`.
```
app.get('/add-to-cart/:id', async (req, res) => {
let id = req.params.id;
let cart = new Cart(req.body.cart ? req.body.cart : {});
const { data } = await axios.get('http://localhost:4200/products')
const productId = data.find(el => el._id === id);
response.findById(productId)
});
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | From the [Python documentation](http://docs.python.org/reference/expressions.html#boolean-operations):
>
> The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
>
>
>
You're getting the second value returned.
P.S. I had never seen this behavior before either, I had to look it up myself. My naive expectation was that a boolean expression would yield a boolean result. | Python works by short-circuiting its boolean and gives the result expression as the result.
A populated list evaluates to true and gives the result as the value of the second list. Look at this, when I just interchanged the position of your first and second list.
```
In [3]: [True,True,True] and [True, True, False]
Out[3]: [True, True, False]
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | From the [Python documentation](http://docs.python.org/reference/expressions.html#boolean-operations):
>
> The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
>
>
>
You're getting the second value returned.
P.S. I had never seen this behavior before either, I had to look it up myself. My naive expectation was that a boolean expression would yield a boolean result. | `[True, True, False]` is being evaluated as a boolean (because of the `and` operator), and evaluates to `True` since it is non-empty. Same with `[True, True, True]`. The result of either statement is then just whatever is after the `and` operator.
You could do something like `[ai and bi for ai, bi in zip(a, b)]` for lists `a` and `b`. |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | From the [Python documentation](http://docs.python.org/reference/expressions.html#boolean-operations):
>
> The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
>
>
>
You're getting the second value returned.
P.S. I had never seen this behavior before either, I had to look it up myself. My naive expectation was that a boolean expression would yield a boolean result. | As far as I know, you need to zip through the list. Try a list comprehension of this sort:
```
l1 = [True,True,False]
l2 = [True,True,True]
res = [ x and y for (x,y) in zip(l1, l2)]
print res
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | Others have explained what's going on. Here are some ways to get what you want:
```
>>> a = [True, True, True]
>>> b = [True, True, False]
```
Use a listcomp:
```
>>> [ai and bi for ai,bi in zip(a,b)]
[True, True, False]
```
Use the `and_` function with a `map`:
```
>>> from operator import and_
>>> map(and_, a, b)
[True, True, False]
```
Or my preferred way (although this does require `numpy`):
```
>>> from numpy import array
>>> a = array([True, True, True])
>>> b = array([True, True, False])
>>> a & b
array([ True, True, False], dtype=bool)
>>> a | b
array([ True, True, True], dtype=bool)
>>> a ^ b
array([False, False, True], dtype=bool)
``` | From the [Python documentation](http://docs.python.org/reference/expressions.html#boolean-operations):
>
> The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
>
>
>
You're getting the second value returned.
P.S. I had never seen this behavior before either, I had to look it up myself. My naive expectation was that a boolean expression would yield a boolean result. |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | As far as I know, you need to zip through the list. Try a list comprehension of this sort:
```
l1 = [True,True,False]
l2 = [True,True,True]
res = [ x and y for (x,y) in zip(l1, l2)]
print res
``` | Python works by short-circuiting its boolean and gives the result expression as the result.
A populated list evaluates to true and gives the result as the value of the second list. Look at this, when I just interchanged the position of your first and second list.
```
In [3]: [True,True,True] and [True, True, False]
Out[3]: [True, True, False]
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | Others have explained what's going on. Here are some ways to get what you want:
```
>>> a = [True, True, True]
>>> b = [True, True, False]
```
Use a listcomp:
```
>>> [ai and bi for ai,bi in zip(a,b)]
[True, True, False]
```
Use the `and_` function with a `map`:
```
>>> from operator import and_
>>> map(and_, a, b)
[True, True, False]
```
Or my preferred way (although this does require `numpy`):
```
>>> from numpy import array
>>> a = array([True, True, True])
>>> b = array([True, True, False])
>>> a & b
array([ True, True, False], dtype=bool)
>>> a | b
array([ True, True, True], dtype=bool)
>>> a ^ b
array([False, False, True], dtype=bool)
``` | [`and`](http://docs.python.org/library/stdtypes.html?highlight=short%20circuit#boolean-operations-and-or-not) returns the last element if they all are evaluated to `True`.
```
>>> 1 and 2 and 3
3
```
The same is valid for lists, which are evalueted to `True` if they are not empty (as in your case). |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | Others have explained what's going on. Here are some ways to get what you want:
```
>>> a = [True, True, True]
>>> b = [True, True, False]
```
Use a listcomp:
```
>>> [ai and bi for ai,bi in zip(a,b)]
[True, True, False]
```
Use the `and_` function with a `map`:
```
>>> from operator import and_
>>> map(and_, a, b)
[True, True, False]
```
Or my preferred way (although this does require `numpy`):
```
>>> from numpy import array
>>> a = array([True, True, True])
>>> b = array([True, True, False])
>>> a & b
array([ True, True, False], dtype=bool)
>>> a | b
array([ True, True, True], dtype=bool)
>>> a ^ b
array([False, False, True], dtype=bool)
``` | Python works by short-circuiting its boolean and gives the result expression as the result.
A populated list evaluates to true and gives the result as the value of the second list. Look at this, when I just interchanged the position of your first and second list.
```
In [3]: [True,True,True] and [True, True, False]
Out[3]: [True, True, False]
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | Others have explained what's going on. Here are some ways to get what you want:
```
>>> a = [True, True, True]
>>> b = [True, True, False]
```
Use a listcomp:
```
>>> [ai and bi for ai,bi in zip(a,b)]
[True, True, False]
```
Use the `and_` function with a `map`:
```
>>> from operator import and_
>>> map(and_, a, b)
[True, True, False]
```
Or my preferred way (although this does require `numpy`):
```
>>> from numpy import array
>>> a = array([True, True, True])
>>> b = array([True, True, False])
>>> a & b
array([ True, True, False], dtype=bool)
>>> a | b
array([ True, True, True], dtype=bool)
>>> a ^ b
array([False, False, True], dtype=bool)
``` | As far as I know, you need to zip through the list. Try a list comprehension of this sort:
```
l1 = [True,True,False]
l2 = [True,True,True]
res = [ x and y for (x,y) in zip(l1, l2)]
print res
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | Any populated list evaluates to `True`. `True and x` produces `x`, the second list. | Python works by short-circuiting its boolean and gives the result expression as the result.
A populated list evaluates to true and gives the result as the value of the second list. Look at this, when I just interchanged the position of your first and second list.
```
In [3]: [True,True,True] and [True, True, False]
Out[3]: [True, True, False]
``` |
12,898,804 | I try:
```
[True,True,False] and [True,True,True]
```
and get
[True, True True]
but
```
[True,True,True] and [True,True,False]
```
gives
```
[True,True,False]
```
Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want
```
[True,True,False] and [True,True,True]
```
to evaluate to
```
[True,True,False]
``` | 2012/10/15 | [
"https://Stackoverflow.com/questions/12898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729412/"
] | Any populated list evaluates to `True`. `True and x` produces `x`, the second list. | [`and`](http://docs.python.org/library/stdtypes.html?highlight=short%20circuit#boolean-operations-and-or-not) returns the last element if they all are evaluated to `True`.
```
>>> 1 and 2 and 3
3
```
The same is valid for lists, which are evalueted to `True` if they are not empty (as in your case). |
54,857,129 | Please enter a sentence: The quick brown fox jumps over the lazy dog.
Output: The brown jumps the dog
I've been doing some learning in strings in python, but no matter what I do, I can't seem to write a program that will remove the 2nd letter of every sentence.
```
word=(input ("enter setence"))
del word[::2]
print(word[char],
end="")
Print("\n")
```
This was my closest attempt. At least I was able to write the sentence on the command prompt but was unable to get the required output. | 2019/02/24 | [
"https://Stackoverflow.com/questions/54857129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110810/"
] | ```
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]
```
You split the original string using spaces, then you take every other word from it with the [::2] splice. | Try something like :
`" ".join(c for c in word.split(" ")[::2])` |
54,857,129 | Please enter a sentence: The quick brown fox jumps over the lazy dog.
Output: The brown jumps the dog
I've been doing some learning in strings in python, but no matter what I do, I can't seem to write a program that will remove the 2nd letter of every sentence.
```
word=(input ("enter setence"))
del word[::2]
print(word[char],
end="")
Print("\n")
```
This was my closest attempt. At least I was able to write the sentence on the command prompt but was unable to get the required output. | 2019/02/24 | [
"https://Stackoverflow.com/questions/54857129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110810/"
] | ```
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]
```
You split the original string using spaces, then you take every other word from it with the [::2] splice. | Try this:
```
sentenceInput=(input ("Please enter sentence: "))
# Function for deleting every 2nd word
def wordDelete(sentence):
# Splitting sentence into pieces by thinking they're seperated by space.
# Comma and other signs are kept.
sentenceList = sentence.split(" ")
# Checking if sentence contains more than 1 word seperated and only then remove the word
if len(sentenceList) > 1:
sentenceList.remove(sentenceList[1])
# If not raise the exception
else:
print("Entered sentence does not contain two words.")
raise Exception
# Re-joining sentence
droppedSentence = ' '.join(sentenceList)
# Returning the result
return droppedSentence
wordDelete(sentenceInput)
``` |
54,857,129 | Please enter a sentence: The quick brown fox jumps over the lazy dog.
Output: The brown jumps the dog
I've been doing some learning in strings in python, but no matter what I do, I can't seem to write a program that will remove the 2nd letter of every sentence.
```
word=(input ("enter setence"))
del word[::2]
print(word[char],
end="")
Print("\n")
```
This was my closest attempt. At least I was able to write the sentence on the command prompt but was unable to get the required output. | 2019/02/24 | [
"https://Stackoverflow.com/questions/54857129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110810/"
] | ```
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]
```
You split the original string using spaces, then you take every other word from it with the [::2] splice. | Try something like that.
`sentence = input("enter sentence: ")
words = sentence.split(' ')
print(words[::2])` |
3,264,024 | I am running in ubuntu and I can code in python, without problem. I have tried to install pygame and to do make it so, I did:
>
> sudo apt-get instal python-pygame
>
>
>
When I go into the python IDLE and write:
>
> import pygame
>
>
>
I get:
>
> Traceback (most recent call last):
>
>
> File "", line 1, in
>
>
> ImportError: No module named pygame
>
>
>
What can I do to solve this problem? I am forgetting something, or doing something wrong? | 2010/07/16 | [
"https://Stackoverflow.com/questions/3264024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388456/"
] | apt-get will install pygame for the registered and pygame-package-supported Python versions. Execute
```
ls -1 /usr/lib/python*/site-packages/pygame/__init__.pyc
```
to find out which. On my old debian system, that prints
```
/usr/lib/python2.4/site-packages/pygame/__init__.pyc
/usr/lib/python2.5/site-packages/pygame/__init__.pyc
```
That means if I'm not using either Python 2.4 or Python 2.5, pygame will not be available. The Python version your IDLE is using should be displayed at the top (you can also see it with `import sys; print(sys.version)`).
You can either manually install pygame or try to add the installed version with
```
import sys
sys.path.append('/usr/lib/python2.5/site-packages/')
import pygame
```
Depending on the complexity of the loaded module(pygame in your case), this might cause some problems later though. | If you don't like to download an unpack then install manually, you can use apt to install **setuptools** . After that you can use **easy\_install**(or **easy\_install-2.7**?) to install many python packages, including pygame, of course. |
3,264,024 | I am running in ubuntu and I can code in python, without problem. I have tried to install pygame and to do make it so, I did:
>
> sudo apt-get instal python-pygame
>
>
>
When I go into the python IDLE and write:
>
> import pygame
>
>
>
I get:
>
> Traceback (most recent call last):
>
>
> File "", line 1, in
>
>
> ImportError: No module named pygame
>
>
>
What can I do to solve this problem? I am forgetting something, or doing something wrong? | 2010/07/16 | [
"https://Stackoverflow.com/questions/3264024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388456/"
] | apt-get will install pygame for the registered and pygame-package-supported Python versions. Execute
```
ls -1 /usr/lib/python*/site-packages/pygame/__init__.pyc
```
to find out which. On my old debian system, that prints
```
/usr/lib/python2.4/site-packages/pygame/__init__.pyc
/usr/lib/python2.5/site-packages/pygame/__init__.pyc
```
That means if I'm not using either Python 2.4 or Python 2.5, pygame will not be available. The Python version your IDLE is using should be displayed at the top (you can also see it with `import sys; print(sys.version)`).
You can either manually install pygame or try to add the installed version with
```
import sys
sys.path.append('/usr/lib/python2.5/site-packages/')
import pygame
```
Depending on the complexity of the loaded module(pygame in your case), this might cause some problems later though. | I just had this same problem!
I read this and while it works to do the sys.path.append thing, I decided to try and get it to work with out.
What I did was went to the Ubuntu Software center uninstalled the python IDLE i had installed and then installed the IDLE.
This seems confusing the way I said it so to clarify you want to download the IDLE that doesn't come with its own version of python, it'll then use the python that already comes with Ubuntu!
If this doesn't make since or doesn't help fix your problem let me know! |
3,264,024 | I am running in ubuntu and I can code in python, without problem. I have tried to install pygame and to do make it so, I did:
>
> sudo apt-get instal python-pygame
>
>
>
When I go into the python IDLE and write:
>
> import pygame
>
>
>
I get:
>
> Traceback (most recent call last):
>
>
> File "", line 1, in
>
>
> ImportError: No module named pygame
>
>
>
What can I do to solve this problem? I am forgetting something, or doing something wrong? | 2010/07/16 | [
"https://Stackoverflow.com/questions/3264024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388456/"
] | apt-get will install pygame for the registered and pygame-package-supported Python versions. Execute
```
ls -1 /usr/lib/python*/site-packages/pygame/__init__.pyc
```
to find out which. On my old debian system, that prints
```
/usr/lib/python2.4/site-packages/pygame/__init__.pyc
/usr/lib/python2.5/site-packages/pygame/__init__.pyc
```
That means if I'm not using either Python 2.4 or Python 2.5, pygame will not be available. The Python version your IDLE is using should be displayed at the top (you can also see it with `import sys; print(sys.version)`).
You can either manually install pygame or try to add the installed version with
```
import sys
sys.path.append('/usr/lib/python2.5/site-packages/')
import pygame
```
Depending on the complexity of the loaded module(pygame in your case), this might cause some problems later though. | check that you are installing pygame for the right version of python. I think the pygame for python 2.7 won't work on python 3.3. I had the same problem but even after installing the right version it didn't work. So after a little googling I found that I was installing pygame meant for 32-bit but my os is 64-bit. so try to google "pygame for window 64-bit" or something like that. I hope it helps. |
3,264,024 | I am running in ubuntu and I can code in python, without problem. I have tried to install pygame and to do make it so, I did:
>
> sudo apt-get instal python-pygame
>
>
>
When I go into the python IDLE and write:
>
> import pygame
>
>
>
I get:
>
> Traceback (most recent call last):
>
>
> File "", line 1, in
>
>
> ImportError: No module named pygame
>
>
>
What can I do to solve this problem? I am forgetting something, or doing something wrong? | 2010/07/16 | [
"https://Stackoverflow.com/questions/3264024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388456/"
] | If you don't like to download an unpack then install manually, you can use apt to install **setuptools** . After that you can use **easy\_install**(or **easy\_install-2.7**?) to install many python packages, including pygame, of course. | check that you are installing pygame for the right version of python. I think the pygame for python 2.7 won't work on python 3.3. I had the same problem but even after installing the right version it didn't work. So after a little googling I found that I was installing pygame meant for 32-bit but my os is 64-bit. so try to google "pygame for window 64-bit" or something like that. I hope it helps. |
3,264,024 | I am running in ubuntu and I can code in python, without problem. I have tried to install pygame and to do make it so, I did:
>
> sudo apt-get instal python-pygame
>
>
>
When I go into the python IDLE and write:
>
> import pygame
>
>
>
I get:
>
> Traceback (most recent call last):
>
>
> File "", line 1, in
>
>
> ImportError: No module named pygame
>
>
>
What can I do to solve this problem? I am forgetting something, or doing something wrong? | 2010/07/16 | [
"https://Stackoverflow.com/questions/3264024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388456/"
] | I just had this same problem!
I read this and while it works to do the sys.path.append thing, I decided to try and get it to work with out.
What I did was went to the Ubuntu Software center uninstalled the python IDLE i had installed and then installed the IDLE.
This seems confusing the way I said it so to clarify you want to download the IDLE that doesn't come with its own version of python, it'll then use the python that already comes with Ubuntu!
If this doesn't make since or doesn't help fix your problem let me know! | check that you are installing pygame for the right version of python. I think the pygame for python 2.7 won't work on python 3.3. I had the same problem but even after installing the right version it didn't work. So after a little googling I found that I was installing pygame meant for 32-bit but my os is 64-bit. so try to google "pygame for window 64-bit" or something like that. I hope it helps. |
66,144,266 | I am looking to sort my list(class) into the order of small - large - small, for example if it were purely numeric and the list was [1,5,3,7,7,3,2] the sort would look like [1,3,7,7,5,3,2].
The basic class structure is:
```
class LaneData:
def __init__(self):
self.Name = "Random"
self.laneWeight = 5
```
So essentially the sort function would work from the LaneData.laneWeight variable.
I found this answer [here](https://stackoverflow.com/questions/10482684/python-reorder-a-sorted-list-so-the-highest-value-is-in-the-middle) which I'm not entirely sure if it will work in this instance using a class as the list variable.
My second idea is like so (pseudo code below) [[inspired by]](https://stackoverflow.com/a/752330/8763997):
```
def sortByWeight(e):
return e.getLaneWeight()
newList = [] # create a new list to store
lanes.sort(key=sortByWeight) # python default sort by our class attrib
newList = lanes[:len(lanes) // 2] # get the first half of the sorted list (low-high)
lanes.sort(key=sortByWeight, reverse=True) # reverse the sort
newList = newList + lanes[:len(lanes) // 2] # get the first half of the sorted list (high-low)
```
If possible I'd like to keep the sort small and efficient, I don't mind building a small algorithm for it if needs be.
What's your thoughts team? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8763997/"
] | Your solution works but you sort the end of the list in ascending order first and in descending order afterwards.
You could optimize it by :
* Looking for the index of the max, swap the max with the element in the middle position and finally sort separately the first half of the table (in ascending order) and the second half (in descending order).
* Instead of doing a reverse sort of the second half, you can simply reverse it (with the reverse function). This is less complex (O(n) instead of O(nlog(n)) | Discussion
==========
Given that you can just use the `key` parameter, I would just ignore it for the time being.
Your algorithm for a given sequence looks like:
```py
def middle_sort_flip_OP(seq, key=None):
result = []
length = len(seq)
seq.sort(key=key)
result = seq[:length // 2]
seq.sort(key=key, reverse=True)
result.extend(seq[:length // 2])
return result
print(middle_sort_flip_OP([1, 5, 3, 7, 3, 2, 9, 8]))
# [1, 2, 3, 3, 9, 8, 7, 5]
print(middle_sort_flip_OP([1, 5, 3, 7, 3, 2, 8]))
# [1, 2, 3, 8, 7, 5]
```
The second sorting step is completely unnecessary (but has the same computational complexity as a simple reversing for the [Timsort](https://en.wikipedia.org/wiki/Timsort) algorithm implemented in [Python](https://github.com/python/cpython/blob/master/Objects/listobject.c)), since you can simply slice the sorted sequence backward (making sure to compute the correct offset for the "middle" element):
```
def middle_sort_flip(seq, key=None):
length = len(seq)
offset = length % 2
seq.sort(key=key)
return seq[:length // 2] + seq[:length // 2 - 1 + offset:-1]
print(middle_sort_flip([1, 5, 3, 7, 3, 2, 9, 8]))
# [1, 2, 3, 3, 9, 8, 7, 5]
print(middle_sort_flip([1, 5, 3, 7, 3, 2, 8]))
# [1, 2, 3, 8, 7, 5]
```
---
Another approach which is theoretically more efficient consist in ordering the left and right side of the sequence separately. This is more efficient because each sorting step is `O(N/2 log N/2)` and, when combined gives `O(N log N/2)` (instead of `O(N + N log N)`):
```
def middle_sort_half(seq, key=None):
length = len(seq)
return \
sorted(seq[:length // 2], key=key) \
+ sorted(seq[length // 2:], key=key, reverse=True)
```
---
However, those approaches either give a largely unbalanced result where the whole right side is larger than the left side (`middle_sort_flip()`), or have a balancing which is dependent on the initial ordering of the input (`middle_sort_half()`).
A more balanced result can be obtained by extracting and recombining the odd and even subsequences. This is simple enough in Python thanks to the slicing operations and has the same asymptotic complexity as `middle_sort_flip()` but with much better balancing properties:
```
def middle_sort_mix(seq, key=None):
length = len(seq)
offset = length % 2
seq.sort(key=key)
result = [None] * length
result[:length // 2] = seq[::2]
result[length // 2 + offset:] = seq[-1 - offset::-2]
return result
print(middle_sort_mix([1, 5, 3, 7, 3, 2, 9, 8]))
# [1, 3, 5, 8, 9, 7, 3, 2]
print(middle_sort_mix([1, 5, 3, 7, 3, 2, 8]))
# [1, 3, 5, 8, 7, 3, 2]
```
---
Benchmarks
==========
Speedwise they are all very similar when the `key` parameter is not used, because the execution time is dominated by the copying around:
```
import random
nums = [10 ** i for i in range(1, 7)]
funcs = middle_sort_flip_OP, middle_sort_flip, middle_sort_half, middle_sort_mix
print(nums)
# [10, 100, 1000, 10000, 100000, 1000000]
def gen_input(num):
return list(range(num))
for num in nums:
print(f"N = {num}")
for func in funcs:
seq = gen_input(num)
random.shuffle(seq)
print(f"{func.__name__:>24s}", end=" ")
%timeit func(seq.copy())
print()
```
```
...
N = 1000000
middle_sort_flip_OP 542 ms ± 54.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_flip 510 ms ± 49 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_half 546 ms ± 4.28 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_mix 539 ms ± 63 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
---
On the other hand, when the `key` parameter is non-trivial, your approach has a much larger amount of function calls as the other two, which may result in a significant increase in execution time for `middle_sort_OP()`:
```
def gen_input(num):
return list(range(num))
def key(x):
return x ** 2
for num in nums:
print(f"N = {num}")
for func in funcs:
seq = gen_input(num)
random.shuffle(seq)
print(f"{func.__name__:>24s}", end=" ")
%timeit func(seq.copy(), key=key)
print()
```
```
...
N = 1000000
middle_sort_flip_OP 1.33 s ± 16.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_flip 1.09 s ± 23.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_half 1.1 s ± 27.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_mix 1.11 s ± 8.88 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
or, closer to your use-case:
```
class Container():
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
def gen_input(num):
return [Container(x) for x in range(num)]
def key(c):
return c.get_x()
for num in nums:
print(f"N = {num}")
for func in funcs:
seq = gen_input(num)
random.shuffle(seq)
print(f"{func.__name__:>24s}", end=" ")
%timeit func(seq.copy(), key=key)
print()
```
```
...
N = 1000000
middle_sort_flip_OP 1.27 s ± 4.44 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_flip 1.13 s ± 13.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_half 1.24 s ± 12.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
middle_sort_mix 1.16 s ± 8.07 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
which seems to be a bit less dramatic. |
71,707,011 | I'm trying to setup the Django AllAuth Twitter login. When the user authenticates with Twitter and is redirected to my website, Django AllAuth raises the Error "No access to private resources at api.twitter.com" and I'm pretty lost here. I have the following settings in my settings.py:
```
SOCIALACCOUNT_PROVIDERS = {
"twitter": {
# From https://developer.twitter.com
"APP": {
"client_id": os.environ["TWITTER_API_KEY"],
"secret": os.environ["TWITTER_API_SECRET"],
}
},
}
```
Stack Trace:
```
DEBUG Signing request <PreparedRequest [POST]> using client <Client client_key={consuner_key}, client_secret=****, resource_owner_key=None, resource_owner_secret=None, signature_method=HMAC-SHA1, signature_type=AUTH_HEADER, callback_uri=None, rsa_key=None, verifier=None, realm=None, encoding=utf-8, decoding=utf-8, nonce=None, timestamp=None>
DEBUG Including body in call to sign: False
DEBUG Collected params: [('oauth_callback', 'http://127.0.0.1:8000/accounts/twitter/login/callback/'), ('oauth_nonce', '107239631555922908281648822311'), ('oauth_timestamp', '1648822311'), ('oauth_version', '1.0'), ('oauth_signature_method', 'HMAC-SHA1'), ('oauth_consumer_key', '{consuner_key}')]
DEBUG Normalized params: oauth_callback=http%3A%2F%2F127.0.0.1%3A8000%2Faccounts%2Ftwitter%2Flogin%2Fcallback%2F&oauth_consumer_key={consuner_key}&oauth_nonce=107239631555922908281648822311&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1648822311&oauth_version=1.0
DEBUG Normalized URI: https://api.twitter.com/oauth/request_token
DEBUG Signing: signature base string: POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252F127.0.0.1%253A8000%252Faccounts%252Ftwitter%252Flogin%252Fcallback%252F%26oauth_consumer_key%3D{consuner_key}%26oauth_nonce%3D107239631555922908281648822311%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1648822311%26oauth_version%3D1.0
DEBUG Signature: {signature}
DEBUG Encoding URI, headers and body to utf-8.
DEBUG Updated url: https://api.twitter.com/oauth/request_token?oauth_callback=http%3A%2F%2F127.0.0.1%3A8000%2Faccounts%2Ftwitter%2Flogin%2Fcallback%2F
DEBUG Updated headers: {b'User-Agent': b'python-requests/2.27.1', b'Accept-Encoding': b'gzip, deflate', b'Accept': b'*/*', b'Connection': b'keep-alive', b'Content-Length': b'0', b'Authorization': b'OAuth oauth_nonce="107239631555922908281648822311", oauth_timestamp="1648822311", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="{consuner_key}", oauth_signature="{oauth_signature}"'}
DEBUG Updated body: None
DEBUG Starting new HTTPS connection (1): api.twitter.com:443
DEBUG https://api.twitter.com:443 "POST /oauth/request_token?oauth_callback=http%3A%2F%2F127.0.0.1%3A8000%2Faccounts%2Ftwitter%2Flogin%2Fcallback%2F HTTP/1.1" 200 129
[01/Apr/2022 14:11:52] "GET /accounts/twitter/login/ HTTP/1.1" 302 0
DEBUG Signing request <PreparedRequest [POST]> using client <Client client_key={consuner_key}, client_secret=****, resource_owner_key=dkDlygAAAAABa6NrAAABf-V328s, resource_owner_secret=****, signature_method=HMAC-SHA1, signature_type=AUTH_HEADER, callback_uri=None, rsa_key=None, verifier=None, realm=None, encoding=utf-8, decoding=utf-8, nonce=None, timestamp=None>
DEBUG Including body in call to sign: False
DEBUG Collected params: [('oauth_verifier', '{verifier_value}'), ('oauth_nonce', '23913555268131873461648822314'), ('oauth_timestamp', '1648822314'), ('oauth_version', '1.0'), ('oauth_signature_method', 'HMAC-SHA1'), ('oauth_consumer_key', '{consuner_key}'), ('oauth_token', 'dkDlygAAAAABa6NrAAABf-V328s')]
DEBUG Normalized params: oauth_consumer_key={consuner_key}&oauth_nonce=23913555268131873461648822314&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1648822314&oauth_token={oauth_token}&oauth_verifier={verifier_value}&oauth_version=1.0
DEBUG Normalized URI: https://api.twitter.com/oauth/access_token
DEBUG Signing: signature base string: POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Faccess_token&oauth_consumer_key%3D{consuner_key}%26oauth_nonce%3D23913555268131873461648822314%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1648822314%26oauth_token%3DdkDlygAAAAABa6NrAAABf-V328s%26oauth_verifier%3D{verifier_value}%26oauth_version%3D1.0
DEBUG Signature: 6Lpfmoe6tKAvi5x3cYg/3Jl7rzU=
DEBUG Encoding URI, headers and body to utf-8.
DEBUG Updated url: https://api.twitter.com/oauth/access_token?oauth_verifier={verifier_value}
DEBUG Updated headers: {b'User-Agent': b'python-requests/2.27.1', b'Accept-Encoding': b'gzip, deflate', b'Accept': b'*/*', b'Connection': b'keep-alive', b'Content-Length': b'0', b'Authorization': b'OAuth oauth_nonce="23913555268131873461648822314", oauth_timestamp="1648822314", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="{consuner_key}", oauth_token="{oauth_token}"'}
DEBUG Updated body: None
DEBUG Starting new HTTPS connection (1): api.twitter.com:443
DEBUG https://api.twitter.com:443 "POST /oauth/access_token?oauth_verifier={verifier_value} HTTP/1.1" 200 172
DEBUG Signing request <PreparedRequest [GET]> using client <Client client_key={consuner_key}, client_secret=****, resource_owner_key=1508849183922569220-ptdyhtd6a5IEAeSWvM9iSZEYGKMzaf, resource_owner_secret=****, signature_method=HMAC-SHA1, signature_type=AUTH_HEADER, callback_uri=None, rsa_key=None, verifier=None, realm=None, encoding=utf-8, decoding=utf-8, nonce=None, timestamp=None>
DEBUG Including body in call to sign: False
DEBUG Collected params: [('oauth_nonce', '69076491240381283361648822315'), ('oauth_timestamp', '1648822315'), ('oauth_version', '1.0'), ('oauth_signature_method', 'HMAC-SHA1'), ('oauth_consumer_key', '{consuner_key}'), ('oauth_token', '1508849183922569220-ptdyhtd6a5IEAeSWvM9iSZEYGKMzaf')]
DEBUG Normalized params: oauth_consumer_key={consuner_key}&oauth_nonce=69076491240381283361648822315&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1648822315&oauth_token=1508849183922569220-ptdyhtd6a5IEAeSWvM9iSZEYGKMzaf&oauth_version=1.0
DEBUG Normalized URI: https://api.twitter.com/1.1/account/verify_credentials.json
DEBUG Signing: signature base string: GET&https%3A%2F%2Fapi.twitter.com%2F1.1%2Faccount%2Fverify_credentials.json&oauth_consumer_key%3D{consuner_key}%26oauth_nonce%3D69076491240381283361648822315%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1648822315%26oauth_token%3D1508849183922569220-ptdyhtd6a5IEAeSWvM9iSZEYGKMzaf%26oauth_version%3D1.0
DEBUG Signature: fwWKf2KRDy3wGjJo1X6U8NHJveU=
DEBUG Encoding URI, headers and body to utf-8.
DEBUG Updated url: https://api.twitter.com/1.1/account/verify_credentials.json
DEBUG Updated headers: {b'User-Agent': b'python-requests/2.27.1', b'Accept-Encoding': b'gzip, deflate', b'Accept': b'*/*', b'Connection': b'keep-alive', b'Authorization': b'OAuth oauth_nonce="69076491240381283361648822315", oauth_timestamp="1648822315", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="{consuner_key}", oauth_token="{token}", oauth_signature="{
{signature}"'}
DEBUG Updated body: None
DEBUG Starting new HTTPS connection (1): api.twitter.com:443
DEBUG https://api.twitter.com:443 "GET /1.1/account/verify_credentials.json HTTP/1.1" 403 270
[01/Apr/2022 14:11:58] "GET /accounts/twitter/login/callback/?oauth_token={token}&oauth_verifier={verifier_value} HTTP/1.1" 200 93
DEBUG Updated body: None
DEBUG Starting new HTTPS connection (1): api.twitter.com:443
DEBUG https://api.twitter.com:443 "GET /1.1/account/verify_credentials.json HTTP/1.1" 403 270
```
My app has the following privilege rights in the developer portal:
* OAuth1 Endpoints
* OAuth2 Endpoints
* User Email
* Read Tweets and Profiles
Any ideas why this could be happening? Thanks in advance! | 2022/04/01 | [
"https://Stackoverflow.com/questions/71707011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3608004/"
] | The reason this is happening is that your developer account doesn't have access to the v1.1 API. To do so you need to apply for the 'Elevated' API access level as described here: <https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api>
I was getting the exact same error as you, and then tried it again on an older dev account I have that is grandfathered in to Elevated, and everything started working for me. (Any dev account created before Nov 2021 automatically has Elevated access.)
Update: Elevated access was approved for my account in about ten hours, so seems straightforward to get. | i am still having a different problem after going through the process of creating the headers and hashing.
i used this library that streamlines the OAuth1 and i believe the OAuth2 process, with the consumer key and secret and no need of nonce or timestamps.
they also go through some twitter API examples that helped me for another API.
posting in case this helps someone else.
<https://docs.authlib.org/en/latest/client/oauth1.html> |
28,399,335 | I have an error on a script I have wrote since few months, it worked very good with a raspberry pi, but now with an orange pi I have this:
```
>>> import paramiko
>>> transport = paramiko.Transport("192.168.2.2", 22)
>>> transport.connect(username = "orangepi", password = "my_pass")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 978, in connect
self.start_client()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 406, in start_client
raise e
paramiko.ssh_exception.SSHException: Incompatible ssh server (no acceptable macs)
```
I can connect in console with ssh without problem.
Somebody has an idea ? | 2015/02/08 | [
"https://Stackoverflow.com/questions/28399335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314648/"
] | You should check if any of those MACs algorithms are available on your SSH server (sshd\_config, key: MACs) :
* HMAC-SHA1
* HMAC-MD5
* HMAC-SHA1-96
* HMAC-MD5-96.
They are **needed** in order for Paramiko to connect to your SSH server. | On your **remote** server, edit `/etc/ssh/sshd_config` and **add a `MACs` line or append to the existing one**, with one or more of `hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96` (values are comma-separated), for example:
```
MACs hmac-sha1
```
Now **restart sshd**: `sudo systemctl restart ssh`. |
28,399,335 | I have an error on a script I have wrote since few months, it worked very good with a raspberry pi, but now with an orange pi I have this:
```
>>> import paramiko
>>> transport = paramiko.Transport("192.168.2.2", 22)
>>> transport.connect(username = "orangepi", password = "my_pass")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 978, in connect
self.start_client()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 406, in start_client
raise e
paramiko.ssh_exception.SSHException: Incompatible ssh server (no acceptable macs)
```
I can connect in console with ssh without problem.
Somebody has an idea ? | 2015/02/08 | [
"https://Stackoverflow.com/questions/28399335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314648/"
] | You should check if any of those MACs algorithms are available on your SSH server (sshd\_config, key: MACs) :
* HMAC-SHA1
* HMAC-MD5
* HMAC-SHA1-96
* HMAC-MD5-96.
They are **needed** in order for Paramiko to connect to your SSH server. | If the above solutions do not work, you need to upgrade Paramiko as found out by this [answer](https://stackoverflow.com/questions/36561792/paramiko-incompatible-ssh-server-no-acceptable-macs). |
28,399,335 | I have an error on a script I have wrote since few months, it worked very good with a raspberry pi, but now with an orange pi I have this:
```
>>> import paramiko
>>> transport = paramiko.Transport("192.168.2.2", 22)
>>> transport.connect(username = "orangepi", password = "my_pass")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 978, in connect
self.start_client()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 406, in start_client
raise e
paramiko.ssh_exception.SSHException: Incompatible ssh server (no acceptable macs)
```
I can connect in console with ssh without problem.
Somebody has an idea ? | 2015/02/08 | [
"https://Stackoverflow.com/questions/28399335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314648/"
] | On your **remote** server, edit `/etc/ssh/sshd_config` and **add a `MACs` line or append to the existing one**, with one or more of `hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96` (values are comma-separated), for example:
```
MACs hmac-sha1
```
Now **restart sshd**: `sudo systemctl restart ssh`. | If the above solutions do not work, you need to upgrade Paramiko as found out by this [answer](https://stackoverflow.com/questions/36561792/paramiko-incompatible-ssh-server-no-acceptable-macs). |
28,542,083 | I am currently working on a small project experimenting with different regions of python. I decided to make a multi-client TCP server in python, and wanted to be able to send a "packet" through the server, it be received by the other clients then parsed. However, I get an error if I try to send the packet, saying I must send either bytes or a string, is there a way to convert the object into bytes, then back or send the packet object through the server itself.
**## EDIT ##**
I have researched into UDP servers, and I do not believe that is what I am looking for, I probably provided too little information. I am creating a small trial game, for me and some friends to mess about on, I need there to be a constant connection to the server, as information is going to be constantly being sent across the network such as location,direction,speech,inventory etc. and I wanted a way to turn the entire Entity class into a byte array then send that and it be turned back into an instance of the Entity class when it was received. | 2015/02/16 | [
"https://Stackoverflow.com/questions/28542083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410007/"
] | You could use pickle to serialize/deserialize objects to strings and back. <https://docs.python.org/2/library/pickle.html> | The simplest possible approach would be to send (gzipped?) JSON'd or [msgpack](https://pypi.python.org/pypi/msgpack-python/)'d objects.
For example, using UDP, this could look something like the below code; note that you would want to reuse the socket object rather than instantiating a new one every time.
```py
import socket
import msgpack
def send_object(obj=None, ip, port):
if obj:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(msgpack.dumps(obj), (ip, port))
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | **Other Cases**
This happened on my python3.7 installation but not my main python3 after i upgrade my ubuntu to 20.04
[Solution](https://github.com/pypa/get-pip/issues/43#issuecomment-621262469):
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.7
``` | I still got error message after trying to install python3.9-distutils for python version 3.9 in pipenv.
As I noticed [here](https://github.com/pypa/pipenv/issues/3890) python3.9-distutils is in conflict with earlier versions of that package and cannot be installed on Ubuntu18.04.
I move on by using `python_version = "3.6"` with pipenv otherwise `$ pipenv install` would take the highest version of python and write it in the `Pipfile` and `Pipfile.lock`.
```
$ pipenv --rm #To remove the old environment
$ rm Pipfile* #Remove both Pipfiles
$ pipenv install --python 3.6
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | **Other Cases**
This happened on my python3.7 installation but not my main python3 after i upgrade my ubuntu to 20.04
[Solution](https://github.com/pypa/get-pip/issues/43#issuecomment-621262469):
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.7
``` | Currently, I'm using `ubuntu 18.04` and `python 3.6.9`. My problem was solved after running the following command as [mentioned here](https://github.com/giampaolo/psutil/issues/1387):
```
sudo apt-get install python3-dev
```
**More Details:** Some modules in python are needed that not installed. |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | If I have multiple versions of python3 (etc 3.8 as main and 3.9 from ppa:deadsnakes/ppa) on ubuntu 20.04 (in my case kubuntu 20.04) **and it doesn't work**
```
sudo apt install python3-distutils
```
then **it works for me**
```
sudo apt install python3.9-distutils
``` | For me the problem was solved by specifically using python3 thus making sure python3.8 was used
```sh
python --version
Python 3.7.5
python3 --version
Python 3.8.5
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | **Other Cases**
This happened on my python3.7 installation but not my main python3 after i upgrade my ubuntu to 20.04
[Solution](https://github.com/pypa/get-pip/issues/43#issuecomment-621262469):
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.7
``` | For me the problem was solved by specifically using python3 thus making sure python3.8 was used
```sh
python --version
Python 3.7.5
python3 --version
Python 3.8.5
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | For me the problem was solved by specifically using python3 thus making sure python3.8 was used
```sh
python --version
Python 3.7.5
python3 --version
Python 3.8.5
``` | I still got error message after trying to install python3.9-distutils for python version 3.9 in pipenv.
As I noticed [here](https://github.com/pypa/pipenv/issues/3890) python3.9-distutils is in conflict with earlier versions of that package and cannot be installed on Ubuntu18.04.
I move on by using `python_version = "3.6"` with pipenv otherwise `$ pipenv install` would take the highest version of python and write it in the `Pipfile` and `Pipfile.lock`.
```
$ pipenv --rm #To remove the old environment
$ rm Pipfile* #Remove both Pipfiles
$ pipenv install --python 3.6
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | Currently, I'm using `ubuntu 18.04` and `python 3.6.9`. My problem was solved after running the following command as [mentioned here](https://github.com/giampaolo/psutil/issues/1387):
```
sudo apt-get install python3-dev
```
**More Details:** Some modules in python are needed that not installed. | For me the problem was solved by specifically using python3 thus making sure python3.8 was used
```sh
python --version
Python 3.7.5
python3 --version
Python 3.8.5
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | Currently, I'm using `ubuntu 18.04` and `python 3.6.9`. My problem was solved after running the following command as [mentioned here](https://github.com/giampaolo/psutil/issues/1387):
```
sudo apt-get install python3-dev
```
**More Details:** Some modules in python are needed that not installed. | I still got error message after trying to install python3.9-distutils for python version 3.9 in pipenv.
As I noticed [here](https://github.com/pypa/pipenv/issues/3890) python3.9-distutils is in conflict with earlier versions of that package and cannot be installed on Ubuntu18.04.
I move on by using `python_version = "3.6"` with pipenv otherwise `$ pipenv install` would take the highest version of python and write it in the `Pipfile` and `Pipfile.lock`.
```
$ pipenv --rm #To remove the old environment
$ rm Pipfile* #Remove both Pipfiles
$ pipenv install --python 3.6
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | If I have multiple versions of python3 (etc 3.8 as main and 3.9 from ppa:deadsnakes/ppa) on ubuntu 20.04 (in my case kubuntu 20.04) **and it doesn't work**
```
sudo apt install python3-distutils
```
then **it works for me**
```
sudo apt install python3.9-distutils
``` | Currently, I'm using `ubuntu 18.04` and `python 3.6.9`. My problem was solved after running the following command as [mentioned here](https://github.com/giampaolo/psutil/issues/1387):
```
sudo apt-get install python3-dev
```
**More Details:** Some modules in python are needed that not installed. |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | Python base interpreter does require some additional modules. Those are not installed with e.g. Ubuntu 18.04 as default.
To solve this we need to first find the python version you're running. If you have only installed one python version on your system (and you are sure about it) you can skip this step.
```
# from your project interpreter run
# your_project_python --version
$ python3 --version
Python 3.7.8
```
You now need to install for this precise python interpreter the distutils.
So here the **solution** for this example would be:
```
sudo apt install python3.7-distutils
# sudo apt install python3-distutils # would just update default python intrpreter
```
Keep in mind, that just running python from any command line might be an other version of python then you're running in your project!
*If this hasn't helped, look for the following possibilities. This will bring you the binary which resolved from the alias in the command line.*
```
$ which python
/usr/bin/python
$ ls -lach /usr/bin/python
lrwxrwxrwx 1 root root 9 Jun 8 2018 /usr/bin/python -> python2.7
```
original source: [refer to this article](https://superuser.com/questions/1319047/cant-install-virtual-interpreter-in-pycharm-in-linux)
For this answer I've also merged, summarized, ordered and explained some of the content which has been provided by Neo, Andrei, Mostafa and Wolfgang.
***As a side note for sorcerer's apprentice:** You might be tempted to uninstall python interpreters. For proposed solution not necessary at all!! How ever, keep in mind that there is one python interpreter which your whole OS depends on. So this default one, you don't want to uninstall. If you do so, you're in a certain mess in finding your desktop taskbar and basically everything.* | I still got error message after trying to install python3.9-distutils for python version 3.9 in pipenv.
As I noticed [here](https://github.com/pypa/pipenv/issues/3890) python3.9-distutils is in conflict with earlier versions of that package and cannot be installed on Ubuntu18.04.
I move on by using `python_version = "3.6"` with pipenv otherwise `$ pipenv install` would take the highest version of python and write it in the `Pipfile` and `Pipfile.lock`.
```
$ pipenv --rm #To remove the old environment
$ rm Pipfile* #Remove both Pipfiles
$ pipenv install --python 3.6
``` |
55,749,206 | I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`.
Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises:
```
ModuleNotFoundError: No module named 'distutils.core'
```
[](https://i.stack.imgur.com/kKMZC.png)
I can't figure out what to do.
I tried to install distutils:
```
milano@milano-PC:~$ sudo apt-get install python3-distutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-distutils is already the newest version (3.7.3-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
```
But as you can see I have the newest version.
Do you know what to do? | 2019/04/18 | [
"https://Stackoverflow.com/questions/55749206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2607447/"
] | Python base interpreter does require some additional modules. Those are not installed with e.g. Ubuntu 18.04 as default.
To solve this we need to first find the python version you're running. If you have only installed one python version on your system (and you are sure about it) you can skip this step.
```
# from your project interpreter run
# your_project_python --version
$ python3 --version
Python 3.7.8
```
You now need to install for this precise python interpreter the distutils.
So here the **solution** for this example would be:
```
sudo apt install python3.7-distutils
# sudo apt install python3-distutils # would just update default python intrpreter
```
Keep in mind, that just running python from any command line might be an other version of python then you're running in your project!
*If this hasn't helped, look for the following possibilities. This will bring you the binary which resolved from the alias in the command line.*
```
$ which python
/usr/bin/python
$ ls -lach /usr/bin/python
lrwxrwxrwx 1 root root 9 Jun 8 2018 /usr/bin/python -> python2.7
```
original source: [refer to this article](https://superuser.com/questions/1319047/cant-install-virtual-interpreter-in-pycharm-in-linux)
For this answer I've also merged, summarized, ordered and explained some of the content which has been provided by Neo, Andrei, Mostafa and Wolfgang.
***As a side note for sorcerer's apprentice:** You might be tempted to uninstall python interpreters. For proposed solution not necessary at all!! How ever, keep in mind that there is one python interpreter which your whole OS depends on. So this default one, you don't want to uninstall. If you do so, you're in a certain mess in finding your desktop taskbar and basically everything.* | **Other Cases**
This happened on my python3.7 installation but not my main python3 after i upgrade my ubuntu to 20.04
[Solution](https://github.com/pypa/get-pip/issues/43#issuecomment-621262469):
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.7
``` |
23,873,821 | I'm not an experienced python coder, so be gentle.
I have a very large (100s of Gb) binary file, that requires a particular command line tool (called parseTool here) to parse it. The format of the output of parseTool is simple raw text that I am doing some basic processing of (counting values, etc.).
Before I think about running multiple instances of my code on a cluster I want to make sure I am doing things reasonably efficiently.
Here is what I am using to iterate over the output of parseTool:
```
proc = subprocess.Popen(procTool +' myFile.file ',
shell=True,
stdout=subprocess.PIPE)
for line in proc.stdout:
linep=line.split("\t")
#process each line until end of stream
```
To be clear, my main concern is efficiently iterating over the output of parseTool. Any helpful tips out there? | 2014/05/26 | [
"https://Stackoverflow.com/questions/23873821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/295182/"
] | Your code is perfectly fine and will "stream" the data efficiently, assuming that the "parseTool" also streams properly and that the text output does not have really long lines.
**If** it did have long lines (in particular, ones that scale as the input does, rather than having some upper bound) then you would want to take care to read chunks smaller than a line rather than reading a whole line and then splitting it. | You say your file is in binary.
If you use:
```
for line in proc.stdout:
...
```
Then the interpreter will read the binary data until it finds a new line character.
Since you said "binary", this seams to be a bad solution.
I would read in fixed chunks:
```
max_length=1024
while True:
chunk=proc.stdout.read(max_length)
if not chunk:
break
print chunk
``` |
13,585,857 | I'm using boto/python to launch a new EC2 instance that boots from an EBS volume. At the time I launch the instance, I'd like to override the default size of the booting EBS volume.
I found no boto methods or parameters that might fit into my launch code:
```
ec2 = boto.connect_ec2( ACCESS_KEY, SECRET_KEY, region=region )
reservation = ec2.run_instances( image_id=AMI_ID,
key_name=EC2_KEY_HANDLE,
instance_type=INSTANCE_TYPE,
security_groups = [ SECGROUP_HANDLE, ] )
```
[This web page](http://alestic.com/2010/02/ec2-resize-running-ebs-root) shows how to increase the size of a running EC2-instance's EBS volume using command-line tools, but I'd like to use boto at the time the EC2 instance is specified: | 2012/11/27 | [
"https://Stackoverflow.com/questions/13585857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856725/"
] | You have to create a block device mapping first:
```
dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType()
dev_sda1.size = 50 # size in Gigabytes
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1
```
After this you can give the block device map in your `run_instances` call:
```
reservation = ec2.run_instances( image_id=AMI_ID,
key_name=EC2_KEY_HANDLE,
instance_type=INSTANCE_TYPE,
security_groups = [ SECGROUP_HANDLE, ],
block_device_mappings = [bdm])
```
Unfortunately this is [not really well documented](https://github.com/boto/boto/issues/736), but the example [can be found in the source code](https://github.com/boto/boto/blob/develop/boto/ec2/blockdevicemapping.py#L85). | You can also use [CloudFormation](http://aws.amazon.com/cloudformation), which is used to document and automate your environment.
You can check the template for the ESB definition at: <https://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2WithEBSSample.template>
```
"Resources" : {
"Ec2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"AvailabilityZone" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "TestAz" ]},
"SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
"KeyName" : { "Ref" : "KeyName" },
"ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]},
"Volumes" : [
{ "VolumeId" : { "Ref" : "NewVolume" },
"Device" : "/dev/sdk"
}
]
}
},
...
"NewVolume" : {
"Type" : "AWS::EC2::Volume",
"Properties" : {
"Size" : "100",
"AvailabilityZone" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "TestAz" ]}
}
}
```
You can then use [Boto CloudFormation API](http://boto.cloudhackers.com/en/latest/ref/cloudformation.html) to deploy your environment. |
13,585,857 | I'm using boto/python to launch a new EC2 instance that boots from an EBS volume. At the time I launch the instance, I'd like to override the default size of the booting EBS volume.
I found no boto methods or parameters that might fit into my launch code:
```
ec2 = boto.connect_ec2( ACCESS_KEY, SECRET_KEY, region=region )
reservation = ec2.run_instances( image_id=AMI_ID,
key_name=EC2_KEY_HANDLE,
instance_type=INSTANCE_TYPE,
security_groups = [ SECGROUP_HANDLE, ] )
```
[This web page](http://alestic.com/2010/02/ec2-resize-running-ebs-root) shows how to increase the size of a running EC2-instance's EBS volume using command-line tools, but I'd like to use boto at the time the EC2 instance is specified: | 2012/11/27 | [
"https://Stackoverflow.com/questions/13585857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856725/"
] | You have to create a block device mapping first:
```
dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType()
dev_sda1.size = 50 # size in Gigabytes
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1
```
After this you can give the block device map in your `run_instances` call:
```
reservation = ec2.run_instances( image_id=AMI_ID,
key_name=EC2_KEY_HANDLE,
instance_type=INSTANCE_TYPE,
security_groups = [ SECGROUP_HANDLE, ],
block_device_mappings = [bdm])
```
Unfortunately this is [not really well documented](https://github.com/boto/boto/issues/736), but the example [can be found in the source code](https://github.com/boto/boto/blob/develop/boto/ec2/blockdevicemapping.py#L85). | Here is a version of the code using the boto3 "everything is a resource" approach. Note also how to avoid hard-coded disk names:
```
import boto3
ec2 = boto3.resource('ec2')
def ec2_one_by_key_and_value(collection: str, key: str, value: str):
handler = getattr(ec2, collection)
return list(handler.filter(Filters=[{'Name': key, 'Values': [value]}]))[0]
image = ec2_one_by_key_and_value('images', 'name', 'ubuntu/images/hvm-ssd/...')
root_disk = None
for block_device in image.block_device_mappings:
if block_device['DeviceName'] == image.root_device_name:
root_disk = block_device
assert root_disk['Ebs']
root_disk['Ebs']['VolumeSize'] = 16 # New disk
break
assert root_disk
instances = ec2.create_instances(MinCount=1, ..., ImageId=image.id,
BlockDeviceMappings=image.block_device_mappings)
``` |
13,744,473 | I'm calling a command line program in python using the `os.system(command)` call.
How can I call this command passing a different folder for execution? There is a system call for this? Or I should save the current folder, and, after execution, change restore it. | 2012/12/06 | [
"https://Stackoverflow.com/questions/13744473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329082/"
] | The [`subprocess`](https://docs.python.org/2/library/subprocess.html) module is a very good solution.
```
import subprocess
p = subprocess.Popen([command, argument1,...], cwd=working_directory)
p.wait()
```
It has also arguments for modifying environment variables, redirecting input/output to the calling program, etc. | Try to `os.chdir(path)` before invoking the command.
From [here](http://docs.python.org/2/library/os.html#os.chdir):
>
> os.chdir(path) Change the current working directory to path.
>
>
> Availability: Unix, Windows
>
>
>
**EDIT**
This will change the current working dir, you can get the current working by:
```
os.getcwd()
```
If you want to save it and restore it later, if you need to do some work in the original working dir.
**EDIT 2**
In any case you should probably move to `subprocess` ([doc](http://docs.python.org/2/library/subprocess.html#module-subprocess)) as suggested [here](http://docs.python.org/2/library/os.html#os.system). If you use `subprocess`'s `Popen` you have the choice of providing `cwd` parameter to specify the working directory for the subprocess: [read this](http://docs.python.org/2/library/subprocess.html#popen-constructor).
```
subprocess.Popen(args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0)
```
>
> ...
>
>
> If cwd is not None, the child’s current directory will be changed to
> cwd before it is executed. Note that this directory is not considered
> when searching the executable, so you can’t specify the program’s path
> relative to cwd.
>
>
> |
13,744,473 | I'm calling a command line program in python using the `os.system(command)` call.
How can I call this command passing a different folder for execution? There is a system call for this? Or I should save the current folder, and, after execution, change restore it. | 2012/12/06 | [
"https://Stackoverflow.com/questions/13744473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329082/"
] | Try to `os.chdir(path)` before invoking the command.
From [here](http://docs.python.org/2/library/os.html#os.chdir):
>
> os.chdir(path) Change the current working directory to path.
>
>
> Availability: Unix, Windows
>
>
>
**EDIT**
This will change the current working dir, you can get the current working by:
```
os.getcwd()
```
If you want to save it and restore it later, if you need to do some work in the original working dir.
**EDIT 2**
In any case you should probably move to `subprocess` ([doc](http://docs.python.org/2/library/subprocess.html#module-subprocess)) as suggested [here](http://docs.python.org/2/library/os.html#os.system). If you use `subprocess`'s `Popen` you have the choice of providing `cwd` parameter to specify the working directory for the subprocess: [read this](http://docs.python.org/2/library/subprocess.html#popen-constructor).
```
subprocess.Popen(args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0)
```
>
> ...
>
>
> If cwd is not None, the child’s current directory will be changed to
> cwd before it is executed. Note that this directory is not considered
> when searching the executable, so you can’t specify the program’s path
> relative to cwd.
>
>
> | Here, I made a little function to change the path you're working on :
```py
import os
def make_path(r_path):
ack = 1
try:
root = os.path.dirname(__file__)
rel_path = os.path.join("..", r_path)
abs_path = os.path.join(root, rel_path)
os.chdir(abs_path)
ack = 0
except Exception as details:
print('problem to get to the path '+r_path+' (0001) : ' + str(details))
return ack
```
So here, `r_path` is the relative path you want to go to. I added `".."` to the `path.join()` methode so, if you're in a folder and want to exit it before searching for your path, it does it automatically. So, if your relative directory looks like this :
```
-path_to_reach
-a_random_file.txt
-your_current_folder
-your_program.py
```
you can do those lines to go inside the `path_to_reach` and make your command, in exemple :
```py
command = ls
make_path('path_to_reach/')
os.system(command)
```
This command would not be useful, but you see the idea! |
13,744,473 | I'm calling a command line program in python using the `os.system(command)` call.
How can I call this command passing a different folder for execution? There is a system call for this? Or I should save the current folder, and, after execution, change restore it. | 2012/12/06 | [
"https://Stackoverflow.com/questions/13744473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329082/"
] | The [`subprocess`](https://docs.python.org/2/library/subprocess.html) module is a very good solution.
```
import subprocess
p = subprocess.Popen([command, argument1,...], cwd=working_directory)
p.wait()
```
It has also arguments for modifying environment variables, redirecting input/output to the calling program, etc. | Here, I made a little function to change the path you're working on :
```py
import os
def make_path(r_path):
ack = 1
try:
root = os.path.dirname(__file__)
rel_path = os.path.join("..", r_path)
abs_path = os.path.join(root, rel_path)
os.chdir(abs_path)
ack = 0
except Exception as details:
print('problem to get to the path '+r_path+' (0001) : ' + str(details))
return ack
```
So here, `r_path` is the relative path you want to go to. I added `".."` to the `path.join()` methode so, if you're in a folder and want to exit it before searching for your path, it does it automatically. So, if your relative directory looks like this :
```
-path_to_reach
-a_random_file.txt
-your_current_folder
-your_program.py
```
you can do those lines to go inside the `path_to_reach` and make your command, in exemple :
```py
command = ls
make_path('path_to_reach/')
os.system(command)
```
This command would not be useful, but you see the idea! |
45,439,492 | I would like be able to several layers together, but before specifying the input, something like the following:
```
# conv is just a layer, no application
conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv')
# this doesn't work:
bn = BatchNormalization()(conv)
```
Note that I don't want to specify the input nor its shape if it can be avoided, I want to use this as a shared layer for multiple inputs at a later point.
Is there a way to do that? The above gives the following error:
```
>>> conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv')
>>> bn = BatchNormalization()(conv)
Traceback (most recent call last):
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 419, in assert_input_compatibility
K.is_keras_tensor(x)
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 393, in is_keras_tensor
raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.convolutional.Conv2D'>`. Expected a symbolic tensor instance.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 552, in __call__
self.assert_input_compatibility(inputs)
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 425, in assert_input_compatibility
str(inputs) + '. All inputs to the layer '
ValueError: Layer batch_normalization_4 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.convolutional.Conv2D'>. Full input: [<keras.layers.convolutional.Conv2D object at 0x7f3f6e54b748>]. All inputs to the layer should be tensors.
```
Grabbing the output of the conv layer doesn't do the trick either:
```
>>> bn = BatchNormalization()(conv.output)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 941, in output
' has no inbound nodes.')
AttributeError: Layer conv has no inbound nodes.
``` | 2017/08/01 | [
"https://Stackoverflow.com/questions/45439492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/729288/"
] | Try this:
```
def create_shared_layers():
layers = [
Conv2D(64, (3,3), activation='relu', padding='same', name='conv'),
BatchNormalization()
]
def shared_layers(x):
for layer in layers:
x = layer(x)
return x
return shared_layers
```
Later, you can do something like:
```
shared_layers = create_shared_layers()
...
h1 = shared_layers(x1)
h2 = shared_layers(x2)
``` | What about using a Lambda layer.
```py
import functools
from typing import List
from tensorflow import keras
def compose_layers(layers: List[keras.layers.Layer], **kargs) -> keras.layers.Layer:
return keras.layers.Lambda(
lambda x: functools.reduce(lambda tensor, layer: layer(tensor), layers, x),
**kargs,
)
```
then you can just call the `compose_layers` method to get the composition.
```py
layers = [
Conv2D(64, (3,3), activation='relu', padding='same', name='conv'),
BatchNormalization()
]
composed_layers = compose_layers(layers, name='composed_layers')
``` |
45,439,492 | I would like be able to several layers together, but before specifying the input, something like the following:
```
# conv is just a layer, no application
conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv')
# this doesn't work:
bn = BatchNormalization()(conv)
```
Note that I don't want to specify the input nor its shape if it can be avoided, I want to use this as a shared layer for multiple inputs at a later point.
Is there a way to do that? The above gives the following error:
```
>>> conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv')
>>> bn = BatchNormalization()(conv)
Traceback (most recent call last):
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 419, in assert_input_compatibility
K.is_keras_tensor(x)
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 393, in is_keras_tensor
raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.convolutional.Conv2D'>`. Expected a symbolic tensor instance.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 552, in __call__
self.assert_input_compatibility(inputs)
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 425, in assert_input_compatibility
str(inputs) + '. All inputs to the layer '
ValueError: Layer batch_normalization_4 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.convolutional.Conv2D'>. Full input: [<keras.layers.convolutional.Conv2D object at 0x7f3f6e54b748>]. All inputs to the layer should be tensors.
```
Grabbing the output of the conv layer doesn't do the trick either:
```
>>> bn = BatchNormalization()(conv.output)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 941, in output
' has no inbound nodes.')
AttributeError: Layer conv has no inbound nodes.
``` | 2017/08/01 | [
"https://Stackoverflow.com/questions/45439492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/729288/"
] | Try this:
```
def create_shared_layers():
layers = [
Conv2D(64, (3,3), activation='relu', padding='same', name='conv'),
BatchNormalization()
]
def shared_layers(x):
for layer in layers:
x = layer(x)
return x
return shared_layers
```
Later, you can do something like:
```
shared_layers = create_shared_layers()
...
h1 = shared_layers(x1)
h2 = shared_layers(x2)
``` | You can also treat `tk.Sequential` as layer
```py
import tensorflow.keras as tk
import tensorflow as tf
_layer1 = tk.layers.Conv2D(
64, (3,3), activation='relu',
padding='same', name='conv'
)
_layer2 = tk.layers.BatchNormalization()
_composed_layer = tk.Sequential(
[_layer1, _layer2]
)
_some_input = tf.random.normal((100,20,33,2))
_out = _composed_layer(_some_input)
``` |
45,439,492 | I would like be able to several layers together, but before specifying the input, something like the following:
```
# conv is just a layer, no application
conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv')
# this doesn't work:
bn = BatchNormalization()(conv)
```
Note that I don't want to specify the input nor its shape if it can be avoided, I want to use this as a shared layer for multiple inputs at a later point.
Is there a way to do that? The above gives the following error:
```
>>> conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv')
>>> bn = BatchNormalization()(conv)
Traceback (most recent call last):
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 419, in assert_input_compatibility
K.is_keras_tensor(x)
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 393, in is_keras_tensor
raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.convolutional.Conv2D'>`. Expected a symbolic tensor instance.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 552, in __call__
self.assert_input_compatibility(inputs)
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 425, in assert_input_compatibility
str(inputs) + '. All inputs to the layer '
ValueError: Layer batch_normalization_4 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.convolutional.Conv2D'>. Full input: [<keras.layers.convolutional.Conv2D object at 0x7f3f6e54b748>]. All inputs to the layer should be tensors.
```
Grabbing the output of the conv layer doesn't do the trick either:
```
>>> bn = BatchNormalization()(conv.output)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mitchus/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/topology.py", line 941, in output
' has no inbound nodes.')
AttributeError: Layer conv has no inbound nodes.
``` | 2017/08/01 | [
"https://Stackoverflow.com/questions/45439492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/729288/"
] | What about using a Lambda layer.
```py
import functools
from typing import List
from tensorflow import keras
def compose_layers(layers: List[keras.layers.Layer], **kargs) -> keras.layers.Layer:
return keras.layers.Lambda(
lambda x: functools.reduce(lambda tensor, layer: layer(tensor), layers, x),
**kargs,
)
```
then you can just call the `compose_layers` method to get the composition.
```py
layers = [
Conv2D(64, (3,3), activation='relu', padding='same', name='conv'),
BatchNormalization()
]
composed_layers = compose_layers(layers, name='composed_layers')
``` | You can also treat `tk.Sequential` as layer
```py
import tensorflow.keras as tk
import tensorflow as tf
_layer1 = tk.layers.Conv2D(
64, (3,3), activation='relu',
padding='same', name='conv'
)
_layer2 = tk.layers.BatchNormalization()
_composed_layer = tk.Sequential(
[_layer1, _layer2]
)
_some_input = tf.random.normal((100,20,33,2))
_out = _composed_layer(_some_input)
``` |
64,320,386 | I have a model which looks like this:
```
class InputTypeMap(models.Model):
input_type = models.ForeignKey(InputType, on_delete=models.CASCADE)
training = models.ForeignKey(Training, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
gender = models.ForeignKey(Gender, on_delete=models.CASCADE)
```
When I try to create instances of this model with:
```
InputTypeMap.objects.create(input_type=input_type,
training=training,
gender=gender,
category=category)
```
I get an exception
```
Traceback (most recent call last):
File "/home/hove/sleipner/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.NotNullViolation: null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, Maintenance, Female, MareGielding, No).
```
From the error message it seems to me that a ID key for the new entry is not generated.
This code has worked as I expected for quite some time, but has "suddenly" started to fail locally - probably after a `apt get upgrade`. When I run the same code with sqlite or Postgres-10.14 things continue to work as before. It is not clear to me whether this is a bug in my code (most probable ...), Django or Postgres. I am using Django version 3.1.2
I have version 9.6 of the Postgres server | 2020/10/12 | [
"https://Stackoverflow.com/questions/64320386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422005/"
] | most probably, that is a primary\_key problem, in my case i added to my model something like:
```
person_id = models.AutoField(primary_key=True)
```
adapt my views to it, and it solved it, | [Changing primary key int type to serial](https://stackoverflow.com/questions/23578427/changing-primary-key-int-type-to-serial) solved it for me.
credit goes to [nishit chittora](https://stackoverflow.com/users/5081918/nishit-chittora). |
39,483,862 | Following examples and the numpy C-API (<http://docs.scipy.org/doc/numpy/reference/c-api.html>), I'm trying to access numpy array data in cpp, like this:
```
#include <Python.h>
#include <frameobject.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // TOGGLE OR NOT
#include "numpy/ndarraytypes.h"
#include "numpy/arrayobject.h"
...
// here I have passed "some_python_object" to the C code
// .. and "some_python_object" has member "infobuf" that is a numpy array
//
unsigned long* fInfoBuffer;
PyObject* infobuffer = PyObject_GetAttrString(some_python_object, "infobuf");
PyObject* x_array = PyArray_FROM_OT(infobuffer, NPY_UINT32);
fInfoBuffer = (unsigned long*)PyArray_DATA(x_array); // DOES NOT WORK WHEN API DEPRECATION IS TOGGLED
```
When the API deprecation is toggled, I get, when compiling:
```
error: cannot convert ‘PyObject* {aka _object*}’ to ‘PyArrayObject* {aka tagPyArrayObject*}’ for argument ‘1’ to ‘void* PyArray_DATA(PyArrayObject*)’
```
What would be the legitimate way of doing this in numpy 1.7+ ? | 2016/09/14 | [
"https://Stackoverflow.com/questions/39483862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4121210/"
] | You could try using a higher-level library that wraps numpy arrays in C++ containers with proper container semantics.
Try out `xtensor` and the `xtensor-python` bindings.
* Numpy to xtensor cheat sheet <http://xtensor.readthedocs.io/en/latest/numpy.html>
* The xtensor-python project
<http://xtensor-python.readthedocs.io/en/latest/>
There is also a cookiecutter to generate a minimal C++ extension project with all the boilerplate for testing, html documentation and setup.p...
**Example: C++ code**
```
#include <numeric> // Standard library import for std::accumulate
#include "pybind11/pybind11.h" // Pybind11 import to define Python bindings
#include "xtensor/xmath.hpp" // xtensor import for the C++ universal functions
#define FORCE_IMPORT_ARRAY // numpy C api loading
#include "xtensor-python/pyarray.hpp" // Numpy bindings
double sum_of_sines(xt::pyarray<double> &m)
{
auto sines = xt::sin(m);
// sines does not actually hold any value, which are only computed upon access
return std::accumulate(sines.begin(), sines.end(), 0.0);
}
PYBIND11_PLUGIN(xtensor_python_test)
{
xt::import_numpy();
pybind11::module m("xtensor_python_test", "Test module for xtensor python bindings");
m.def("sum_of_sines", sum_of_sines,
"Computes the sum of the sines of the values of the input array");
return m.ptr();
}
```
**Python Code:**
```
import numpy as np
import xtensor_python_test as xt
a = np.arange(15).reshape(3, 5)
s = xt.sum_of_sines(v)
s
``` | It is because `PyArray_DATA` expects a `PyArrayObject*`.
You can try to change the type of `x_array`:
```
PyArrayObject* x_array = (PyArrayObject*) PyArray_FROM_OT(infobuffer, NPY_UINT32)
``` |
59,853,922 | In python, how to generate a random number such that it is not a power of 2? The output needs to be a list of 8 random numbers. This should be done in a single statement (comprehension style) in python. | 2020/01/22 | [
"https://Stackoverflow.com/questions/59853922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778195/"
] | You can use array\_sum with array\_map like below,
```
$array1 = [1, 2, 2, 3];
$array2 = [10, 20, 30, 50];
$array_sum1 = [];
foreach ($array1 as $key => $value) {
$array_sum1[$value][] = $array2[$key];
}
$array_sum1 = array_map("array_sum", $array_sum1);
print_r($array_sum1);
$array3 = [4, 4, 4, 6];
$array4 = [10, 20, 30, 50];
$array_sum2 = [];
foreach ($array3 as $key => $value) {
$array_sum2[$value][] = $array4[$key];
}
$array_sum2 = array_map("array_sum", $array_sum2);
print_r($array_sum2);die;
```
[Demo](https://3v4l.org/5sXjt)
**Output:-**
```
Array
(
[1] => 10
[2] => 50
[3] => 50
)
Array
(
[4] => 60
[6] => 50
)
``` | It is indirect to perform two iterations of your data to group & sum.
Use the "id" values as keys in your output array. If a given "id" is encountered for the first time, then save the "val" value to the "id"; after the first encounter, add the "val" to the "id".
Code: ([Demo](https://3v4l.org/fjINV))
```
$ids = [1, 2, 2, 3];
$vals = [10, 20, 30, 50];
foreach ($ids as $index => $id) {
if (!isset($result[$id])) {
$result[$id] = $vals[$index];
} else {
$result[$id] += $vals[$index];
}
}
var_export($result);
```
Output:
```
array (
1 => 10,
2 => 50,
3 => 50,
)
```
Here are similar (near duplicate) answers:
* <https://stackoverflow.com/a/53141488/2943403>
* <https://stackoverflow.com/a/52485161/2943403>
* <https://stackoverflow.com/a/47926978/2943403>
* <https://stackoverflow.com/a/54421292/2943403> |
74,320,720 | I have some existing code that uses boto3 (python) DynamoDB Table objects to query the database:
```py
import boto3
resource = boto3.resource("dynamodb")
table = resource.table("my_table")
# Do stuff here
```
We now want to run the tests for this code using DynamoDB Local instead of connecting to DynamoDB proper, to try and get them running faster and save on resources. To do that, I gather that I need to use a client object, not a table object:
```py
import boto3
session = boto3.session.Session()
db_client = session.client(service_name="dynamodb", endpoint_url="http://localhost:8000")
# Do slightly different stuff here, 'cos clients and tables work differently
```
However, there's really rather a lot of the existing code, to the point that the cost of rewriting everything to work with clients rather than tables is likely to be prohibitive.
Is there any way to either get a table object while specifying the endpoint\_url so I can point it at DynamoDB Local on creation, or else obtain a boto3 dynamodb table object from a boto3 dynamodb client object?
PS: I know I could also mock out the boto3 calls and not access the database at all. But that's also prohibitively costly, because for all of the existing tests we'd have to work out where they touch the database and what the appropriate mock setup and use is. For a couple of tests that's perfectly fine, but it's a lot of work if you've got a lot of tests. | 2022/11/04 | [
"https://Stackoverflow.com/questions/74320720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5734324/"
] | Yes, you can use the resource-level classes such as [Table](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#table) with both the real DynamoDB service and DynamoDB Local via the [DynamoDB service resource](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#service-resource), as follows:
```
resource = boto3.resource('dynamodb', endpoint_url='http://localhost:8000')
table = resource.Table(name)
``` | The other answers correctly told you that if you liked the "resource" API, you can still use it even with DynamoDB local (by the way, shameless plug: if you're looking for self-installable version of DynamoDB, you can also consider the open-source ScyllaDB project which has a DynamoDB API).
I just wanted to add that if you do want to switch to the "client" API - which I recommend (it's easier to use) - it's still possible to get a table object from a client. Just do:
```py
table = db_client.Table(name)
``` |
11,087,032 | I have a XML file which contains values having unwanted characters like
```
\xc2d
d\xa0
\xe7
\xc3\ufffdd
\xc3\ufffdd
\xc2\xa0
\xc3\xa7
\xa0\xa0
'619d813\xa03697'
\xe9.com
```
input examples could be
```
name : John Hinners\xc2d
email: abc@gmail\xe9.com
and others ....
```
desired output should be
```
name : John Hinners
email: abc@gmail.com
and others ....
```
I come from python background where this task can be done easily as
```
def remove_non_ascii(s):
return ''.join(i for i in s if ord(i)<128)
```
Is there some similar way to perform the same task in Java? | 2012/06/18 | [
"https://Stackoverflow.com/questions/11087032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379235/"
] | In java it will not be as pretty.
You can use a regexp but if you don't have a simple definition of your characters the best is probably to do this :
```
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++) {
if (((int)s.charAt(i))<128) sb.append(s.charAt(i));
}
``` | ```
String s = "WantedCharactersunwantedCharacters";
```
If I want the remaining String to be "WantedCharacters", I simply write:
```
s = s.replaceAll("unwantedCharacters", "");
```
[EDIT]:
You could, of course, also write
```
private static String removeNonAscii(String s){
StringBuffer sb = new StringBuffer();
for(int i=0; i<s.length(); ++i){
if(s.charAt(i) < 128){
sb.append(s.charAt(i));
}
}
return sb.toString();
}
```
if that's a satisfying solution |
11,087,032 | I have a XML file which contains values having unwanted characters like
```
\xc2d
d\xa0
\xe7
\xc3\ufffdd
\xc3\ufffdd
\xc2\xa0
\xc3\xa7
\xa0\xa0
'619d813\xa03697'
\xe9.com
```
input examples could be
```
name : John Hinners\xc2d
email: abc@gmail\xe9.com
and others ....
```
desired output should be
```
name : John Hinners
email: abc@gmail.com
and others ....
```
I come from python background where this task can be done easily as
```
def remove_non_ascii(s):
return ''.join(i for i in s if ord(i)<128)
```
Is there some similar way to perform the same task in Java? | 2012/06/18 | [
"https://Stackoverflow.com/questions/11087032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379235/"
] | As I said here:
[Similar Question](https://stackoverflow.com/a/31424164/2630033)
Use regex
```
String clean = str.replaceAll("\\P{Print}", "");
```
Removes all non printable characters.
But that also includes \n (line feed), \t(tab) and \r(carriage return), and if you want to keep those characters use:
```
String clean = str.replaceAll("[^\\n\\r\\t\\p{Print}]", "");
``` | ```
String s = "WantedCharactersunwantedCharacters";
```
If I want the remaining String to be "WantedCharacters", I simply write:
```
s = s.replaceAll("unwantedCharacters", "");
```
[EDIT]:
You could, of course, also write
```
private static String removeNonAscii(String s){
StringBuffer sb = new StringBuffer();
for(int i=0; i<s.length(); ++i){
if(s.charAt(i) < 128){
sb.append(s.charAt(i));
}
}
return sb.toString();
}
```
if that's a satisfying solution |
11,087,032 | I have a XML file which contains values having unwanted characters like
```
\xc2d
d\xa0
\xe7
\xc3\ufffdd
\xc3\ufffdd
\xc2\xa0
\xc3\xa7
\xa0\xa0
'619d813\xa03697'
\xe9.com
```
input examples could be
```
name : John Hinners\xc2d
email: abc@gmail\xe9.com
and others ....
```
desired output should be
```
name : John Hinners
email: abc@gmail.com
and others ....
```
I come from python background where this task can be done easily as
```
def remove_non_ascii(s):
return ''.join(i for i in s if ord(i)<128)
```
Is there some similar way to perform the same task in Java? | 2012/06/18 | [
"https://Stackoverflow.com/questions/11087032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379235/"
] | As I said here:
[Similar Question](https://stackoverflow.com/a/31424164/2630033)
Use regex
```
String clean = str.replaceAll("\\P{Print}", "");
```
Removes all non printable characters.
But that also includes \n (line feed), \t(tab) and \r(carriage return), and if you want to keep those characters use:
```
String clean = str.replaceAll("[^\\n\\r\\t\\p{Print}]", "");
``` | In java it will not be as pretty.
You can use a regexp but if you don't have a simple definition of your characters the best is probably to do this :
```
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++) {
if (((int)s.charAt(i))<128) sb.append(s.charAt(i));
}
``` |
62,333,071 | I have been using a working Anaconda install (Python 3.7) for about a year, but suddenly I'm getting this warning when I run the interpreter:
```none
> python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated. Libraries may fail to load. To activate this environment
please see https://conda.io/activation
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I quite often use virtual environments, but never with Conda. Note that I've been able to run Python from the command line with just `python` for a long time now, and have never had to use `conda activate base`. I don't even have Conda on my path.
I've found these answers, but neither gives any clarity into why this may have started happening:
* *[CMD warning: "Python interpreter is in a conda environment, but the environment has not been activated"](https://stackoverflow.com/questions/56623269/cmd-warning-python-interpreter-is-in-a-conda-environment-but-the-environment-h)*
* *[Python is in a Conda environment, but it has not been activated in a Windows virtual environment](https://stackoverflow.com/questions/56679132/python-is-in-conda-env-but-has-not-been-activated-in-windows-virtual-env)* | 2020/06/11 | [
"https://Stackoverflow.com/questions/62333071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8605685/"
] | If you receive this warning, you need to activate your environment. To do so on Windows, use the Anaconda Prompt shortcut in your Windows start menu. If you have an existing cmd.exe session that you’d like to activate conda in run:
`call <your anaconda/miniconda install location>\Scripts\activate base.` | I have the same problem, by following this post [conda-is-not-recognized-as-internal-or-external-command](https://stackoverflow.com/questions/44515769/conda-is-not-recognized-as-internal-or-external-command), I am able to solve the problem.
The reason may be that your default Python interpreter has been switch to the the Conda python (e.g. on my Wondows 10, the path is `C:\Users\Xiang\anaconda3\python.exe`). Therefore, we need to add the Conda related path to the Environments Path, with details explained in the link. |
43,110,228 | I'm learning to use rpy2 in Jupyter notebook. I'm having troubles with the plotting. When I use this example from the rpy2 [docs](http://rpy2.readthedocs.io/en/version_2.8.x/interactive.html?highlight=ipython#ipython-magic-integration-was-rmagic) for interactive work:
```
from rpy2.interactive import process_revents
from rpy2.robjects.packages import importr
from rpy2.robjects.vectors import IntVector
process_revents.start()
graphics = importr("graphics")
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
```
Jupyter opens a new window with the plot. The window "title" reads: R Graphics: Device 2 (ACTIVE) (Not Responding). My Jupyter kernel is active. When I try to close the window with the plot, windows claims that python.exe is not responsing and if I force close then the jupyter kernel restarts.
First: How can I make rpy2 plot inline? Second: If inline plotting is not possible, how to get the plot in a window without python.exe becoming unresponsive? | 2017/03/30 | [
"https://Stackoverflow.com/questions/43110228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998998/"
] | It seems that this is the answer to your question: <https://bitbucket.org/rpy2/rpy2/issues/330/ipython-plotting-wrapper>
```
with rpy2.robjects.lib.grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img:
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
IPython.display.display(IPython.display.Image(data=img.getvalue(), format='png', embed=True))
``` | This is slightly more sopthisticated version of Christian's answer which wraps the plotting and inline embedding into the same context manager:
```py
from contextlib import contextmanager
from rpy2.robjects.lib import grdevices
from IPython.display import Image, display
@contextmanager
def r_inline_plot(width=600, height=600, dpi=100):
with grdevices.render_to_bytesio(grdevices.png,
width=width,
height=height,
res=dpi) as b:
yield
data = b.getvalue()
display(Image(data=data, format='png', embed=True))
```
Usage:
```py
with r_inline_plot(width=1024, height=896, dpi=150):
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
``` |
43,110,228 | I'm learning to use rpy2 in Jupyter notebook. I'm having troubles with the plotting. When I use this example from the rpy2 [docs](http://rpy2.readthedocs.io/en/version_2.8.x/interactive.html?highlight=ipython#ipython-magic-integration-was-rmagic) for interactive work:
```
from rpy2.interactive import process_revents
from rpy2.robjects.packages import importr
from rpy2.robjects.vectors import IntVector
process_revents.start()
graphics = importr("graphics")
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
```
Jupyter opens a new window with the plot. The window "title" reads: R Graphics: Device 2 (ACTIVE) (Not Responding). My Jupyter kernel is active. When I try to close the window with the plot, windows claims that python.exe is not responsing and if I force close then the jupyter kernel restarts.
First: How can I make rpy2 plot inline? Second: If inline plotting is not possible, how to get the plot in a window without python.exe becoming unresponsive? | 2017/03/30 | [
"https://Stackoverflow.com/questions/43110228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998998/"
] | It seems that this is the answer to your question: <https://bitbucket.org/rpy2/rpy2/issues/330/ipython-plotting-wrapper>
```
with rpy2.robjects.lib.grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img:
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
IPython.display.display(IPython.display.Image(data=img.getvalue(), format='png', embed=True))
``` | I think the cleanest solution is to simply use the `%R` magic function. It used to be part of IPython, but got moved to `rpy2`, so you have to load it as an extension first:
```
%load_ext rpy2.ipython
A = np.random.normal(100)
%R -i A hist(A)
```
plots a histogram to the Jupyter console. |
43,110,228 | I'm learning to use rpy2 in Jupyter notebook. I'm having troubles with the plotting. When I use this example from the rpy2 [docs](http://rpy2.readthedocs.io/en/version_2.8.x/interactive.html?highlight=ipython#ipython-magic-integration-was-rmagic) for interactive work:
```
from rpy2.interactive import process_revents
from rpy2.robjects.packages import importr
from rpy2.robjects.vectors import IntVector
process_revents.start()
graphics = importr("graphics")
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
```
Jupyter opens a new window with the plot. The window "title" reads: R Graphics: Device 2 (ACTIVE) (Not Responding). My Jupyter kernel is active. When I try to close the window with the plot, windows claims that python.exe is not responsing and if I force close then the jupyter kernel restarts.
First: How can I make rpy2 plot inline? Second: If inline plotting is not possible, how to get the plot in a window without python.exe becoming unresponsive? | 2017/03/30 | [
"https://Stackoverflow.com/questions/43110228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998998/"
] | I think the cleanest solution is to simply use the `%R` magic function. It used to be part of IPython, but got moved to `rpy2`, so you have to load it as an extension first:
```
%load_ext rpy2.ipython
A = np.random.normal(100)
%R -i A hist(A)
```
plots a histogram to the Jupyter console. | This is slightly more sopthisticated version of Christian's answer which wraps the plotting and inline embedding into the same context manager:
```py
from contextlib import contextmanager
from rpy2.robjects.lib import grdevices
from IPython.display import Image, display
@contextmanager
def r_inline_plot(width=600, height=600, dpi=100):
with grdevices.render_to_bytesio(grdevices.png,
width=width,
height=height,
res=dpi) as b:
yield
data = b.getvalue()
display(Image(data=data, format='png', embed=True))
```
Usage:
```py
with r_inline_plot(width=1024, height=896, dpi=150):
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
``` |
20,444,056 | I have a list of tuples each with 5 pieces of information in it. I need a way to search the list for a result or range of results from a search parameter or parameters.
So I'd like to search for an ID number (string) or name (string - only the whole name) or a range of salary so between (int - 10000-20000).
I read on another post [How to search a list of tuples in Python](https://stackoverflow.com/questions/2917372/how-to-search-a-list-of-tuples-in-python) that you can use list comprehensions
```
t = [[0] for x in l].index('12346')
```
but it wasn't explained all that well and it doesn't satisfy the range of values I need to enter.
This does it's job for one entry. But if 2 people have the same first name or job it will just display the first occurrence. To display the correct tuple I take the value T and send it to the my printing function to display. Which again won't work for multiple entries because I would need to know how many tuples were returned beforehand.
Here are a few tuples, all are very similar.
```
('12349', '30000', 'Wizard', 'Harry', 'Potter')
('12350', '15000', 'Entertainer', 'Herschel Shmoikel', 'Krustofski')
('13123', '75000', 'Consultant', 'David', 'Beckham')
('13124', '150000', 'Manager', 'Alex', 'Ferguson')
('13125', '75000', 'Manager', 'Manuel', 'Pellegrini')
```
Thank you | 2013/12/07 | [
"https://Stackoverflow.com/questions/20444056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2080298/"
] | The Checked property is set right on the XAML loading, when you set IsChecked="True". The tag may be loaded only later when the XAML loading code decides to set this property. That's why you can see uninitialized properties. | simple Solution for all of these type bugs/errors:
```
1- bool bFormLoaded;//=false ;
2- at [YourWinOrControlorWPF]_Loaded(object sender, RoutedEventArgs e)
add this flag at end of function:
bFormLoaded=true;
3-at UseDefaultFoldersCB_Checked(...)
add this line
if(bFormLoaded==false) return;
```
100% |
62,099,166 | I am trying to send data from python server to android client but it is not accepting any data from the server. but it is showing that it is connected with the server. i cant recognize any error.
here is my client code in android java.
```
package com.example.socketinput;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Thread Thread1 = null;
String SERVER_IP="192.168.1.6";
int SERVER_PORT=9857;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread1 = new Thread(new Thread1());
Thread1.start();
}
private PrintWriter output;
private BufferedReader input;
class Thread1 implements Runnable {
public void run() {
Socket socket;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("Server", "Connected");
}
});
new Thread(new Thread2()).start();
} catch (IOException e) {
Log.i("Server", "Error in thread 1");
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("Server", message);
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (IOException e) {
Log.i("Server", "Error in thread 2");
e.printStackTrace();
}
}
}
}
}
```
here is my python server code .
```
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import socket
# In[2]:
socket.gethostname()
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9857))
s.listen(5)
# In[ ]:
while True:
clientsocket, address = s.accept()
print(f"connection from {address} has been established!")
clientsocket.send(bytes("welcome to the server!","utf-8"))
while True:
msg=input()
clientsocket.send(bytes(msg,"utf-8"))
```
android manifent file is-:
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.socketinput">
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
```
Note-Android app and python code is connected on same server.
[](https://i.stack.imgur.com/tD0sN.png) | 2020/05/30 | [
"https://Stackoverflow.com/questions/62099166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6938184/"
] | You should use fake content while testing a layout, **unless your fixed height can match together** *(left col is box1+box5 = 1600px and col right is 1300px so a 300px gap(s)/difference)* : White space are here because of the heights arbitrary given to children.
Your grid woks fine and is fluid :
**Tips** : For testing, use `min-height` on children or the container, else use [fake content](https://lipsum.com/) / [htmlIpsum](https://www.webfx.com/web-design/html-ipsum/).
Your code with a `min-height` on the parent only
```css
.container {
min-height:80vh;/* demo purpose*/
width: 505px;
border: solid red;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}
.box {
border: solid 1px;
width: 250px;
}
.box1 {
background-color: yellow;
grid-area: b1;
}
.box2 {
background-color: blue;
grid-area: b2;
}
.box3 {
background-color: green;
grid-area: b3;
}
.box4 {
background-color: orange;
grid-area: b4;
}
.box5 {
grid-area: b5;
background-color: purple;
}
.box6 {
background-color: gray;
grid-area: b6;
}
```
```html
<div class="container">
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
<div class="box box4">4</div>
<div class="box box5">5</div>
<div class="box box6">6</div>
</div>
```
min-height instead height to the children :
```css
.container {
width: 505px;
border: solid red;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}
.box {
border: solid 1px;
width: 250px;
}
.box1 {
min-height: 1000px;
background-color: yellow;
grid-area: b1;
}
.box2 {
min-height: 200px;
background-color: blue;
grid-area: b2;
}
.box3 {
min-height: 250px;
background-color: green;
grid-area: b3;
}
.box4 {
min-height: 250px;
background-color: orange;
grid-area: b4;
}
.box5 {
min-height: 600px;
grid-area: b5;
background-color: purple;
}
.box6 {
min-height: 400px;
background-color: gray;
grid-area: b6;
}
```
```html
<div class="container">
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
<div class="box box4">4</div>
<div class="box box5">5</div>
<div class="box box6">6</div>
</div>
``` | If you want to maintain the designated heights, you can wrap the column 2 `divs` into a `flex` wrapper:
```
<div class="container">
<div class="box box1">1</div>
<div class="box box5">5</div>
<div class = "flex">
<div class="box box2">2</div>
<div class="box box3">3</div>
<div class="box box4">4</div>
<div class="box box6">6</div>
</div>
</div>
```
And then change your `grid` CSS a bit to accommodate:
```
.container {
width: 505px;
border: solid red;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-areas: "b1 b3" "b5 b3";
}
```
Now the only boxes that need `grid-area` are the 2 on the left (`b1` and `b5`) and the `flex` wrapper (`b3` in my code):
```
.box {
border: solid 1px;
width: 250px;
}
.box1 {
height: 1000px;
background-color: yellow;
grid-area: b1;
}
.box2 {
height: 200px;
background-color: blue;
}
.box3 {
height: 250px;
background-color: green;
grid-area: b3;
}
.box4 {
height: 250px;
background-color: orange;
}
.box5 {
height: 600px;
grid-area: b5;
background-color: purple;
}
.box6 {
height: 400px;
background-color: gray;
}
.flex {
display: flex;
flex-direction: column;
grid-area: b3;
}
```
Check this demo [JSfiddle](https://jsfiddle.net/repwn3jm/2/) |
5,166,488 | python and Tkinter are processing Unicode characters correctly.
But they are not able to display Unicode encoded characters correctly.
I am using Python 3.1 and Tkinter in Ubuntu. I am trying to use Tamil Unicode characters.
All the processing is done correctly. But the display is wrong?
Here is the Wrong display as in Tkinter

Here is the Correct display (as in gedit)

---
Still not solved:
```
from tkinter import *
root = Tk()
root.geometry('200x200')
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
Entry(text="Placeholder text").pack()
var.set("கற்றதனால் ஆய பயனென்கொல் வாலறிவன்\nநற்றாள்தொழாஅர் எனின். ")
label.pack()
root.mainloop()
```
Manjaro:
[](https://i.stack.imgur.com/V1T3w.png)
Windows:
[](https://i.stack.imgur.com/G8r72.png) | 2011/03/02 | [
"https://Stackoverflow.com/questions/5166488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641040/"
] | I had faced similar problems and discovered I used the Zero Width Joiner (U+200D) to explicitly tell the rendering engine to join two characters. That used to work in 2010 but looks like there have been changes in the rendering engine (that I am now aware of) and now in 2011 I find that having the joiner creates the problem ! (It broke my working code) I had to remove the explicit zero width joiners to have my code work again. Hope this helps. | It looks like Tk is mishandling things like 'Class Zero Combining Marks', see:
<http://www.unicode.org/versions/Unicode6.0.0/ch04.pdf#G124820> (Table 4-4)
I assume one of the sequences that do not show correctly are the codepoints: 0BA9
0BC6 (TAMIL SYLLABLE NNNE), where 0BC6 is a reordrant class zero combining mark according to the Unicode standard, which basically means the glyphs get swapped.
The only way to fix it is to file a bug at the Tk bug tracker and hope it gets fixed. |
5,166,488 | python and Tkinter are processing Unicode characters correctly.
But they are not able to display Unicode encoded characters correctly.
I am using Python 3.1 and Tkinter in Ubuntu. I am trying to use Tamil Unicode characters.
All the processing is done correctly. But the display is wrong?
Here is the Wrong display as in Tkinter

Here is the Correct display (as in gedit)

---
Still not solved:
```
from tkinter import *
root = Tk()
root.geometry('200x200')
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
Entry(text="Placeholder text").pack()
var.set("கற்றதனால் ஆய பயனென்கொல் வாலறிவன்\nநற்றாள்தொழாஅர் எனின். ")
label.pack()
root.mainloop()
```
Manjaro:
[](https://i.stack.imgur.com/V1T3w.png)
Windows:
[](https://i.stack.imgur.com/G8r72.png) | 2011/03/02 | [
"https://Stackoverflow.com/questions/5166488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641040/"
] | As per [this comment](https://stackoverflow.com/questions/5166488/tkinter-cannot-display-unicode-characters-correctly-in-manjaro#comment5802238_5166488),
```
from PyQt5.QtWidgets import QApplication,QMainWindow,QLabel
import sys
app=QApplication(sys.argv)
app.setStyle('Fusion')
app.setApplicationName('PyQt5 App')
win=QMainWindow()
label=QLabel()
text='கற்றதனால் ஆய பயனென்கொல் வாலறிவன்\nநற்றாள் தொழாஅர் எனின்.'
label.setText(text)
win.setCentralWidget(label)
win.show()
sys.exit(app.exec_())
```
[](https://i.stack.imgur.com/drvFf.png) | It looks like Tk is mishandling things like 'Class Zero Combining Marks', see:
<http://www.unicode.org/versions/Unicode6.0.0/ch04.pdf#G124820> (Table 4-4)
I assume one of the sequences that do not show correctly are the codepoints: 0BA9
0BC6 (TAMIL SYLLABLE NNNE), where 0BC6 is a reordrant class zero combining mark according to the Unicode standard, which basically means the glyphs get swapped.
The only way to fix it is to file a bug at the Tk bug tracker and hope it gets fixed. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | Generate 4 random numbers, compute their sum, divide each one by the sum and multiply by 40.
If you want Integers, then this will require a little non-randomness. | Building on [@markdickonson](https://stackoverflow.com/a/3590105/75033) by providing some control over distribution between the divisors. I introduce a variance/jiggle as a percentage of the uniform distance between each.
```
def constrained_sum_sample(n, total, variance=50):
"""Return a random-ish list of n positive integers summing to total.
variance: int; percentage of the gap between the uniform spacing to vary the result.
"""
divisor = total/n
jiggle = divisor * variance / 100 / 2
dividers = [int((x+1)*divisor + random.random()*jiggle) for x in range(n-1)]
result = [a - b for a, b in zip(dividers + [total], [0] + dividers)]
return result
```
Sample output:
```
[12, 8, 10, 10]
[10, 11, 10, 9]
[11, 9, 11, 9]
[11, 9, 12, 8]
```
The idea remains to divide the population equally, then randomly move them left or right within the given range. Since each value is still bound to the uniform point we don't have to worry about it drifting.
Good enough for my purposes, but not perfect. eg: the first number will always vary higher, and the last will always vary lower. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | ```
b = random.randint(2, 38)
a = random.randint(1, b - 1)
c = random.randint(b + 1, 39)
return [a, b - a, c - b, 40 - c]
```
(I assume you wanted integers since you said "1-40", but this could be easily generalized for floats.)
Here's how it works:
* cut the total range in two randomly, that's b. The odd range is because there are going to be at least 2 below the midpoint and at least 2 above. (This comes from your 1 minimum on each value).
* cut each of those ranges in two randomly. Again, the bounds are to account for the 1 minimum.
* return the size of each slice. They'll add up to 40. | Generate 4 random numbers, compute their sum, divide each one by the sum and multiply by 40.
If you want Integers, then this will require a little non-randomness. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | ```
b = random.randint(2, 38)
a = random.randint(1, b - 1)
c = random.randint(b + 1, 39)
return [a, b - a, c - b, 40 - c]
```
(I assume you wanted integers since you said "1-40", but this could be easily generalized for floats.)
Here's how it works:
* cut the total range in two randomly, that's b. The odd range is because there are going to be at least 2 below the midpoint and at least 2 above. (This comes from your 1 minimum on each value).
* cut each of those ranges in two randomly. Again, the bounds are to account for the 1 minimum.
* return the size of each slice. They'll add up to 40. | Use [multinomial](https://en.wikipedia.org/wiki/Multinomial_distribution) distribution
```
from numpy.random import multinomial
multinomial(40, [1/4.] * 4)
```
Each variable will be distributed as a binomial distribution with mean `n * p` equal to `40 * 1/4 = 10` in this example. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | There are only 37^4 = 1,874,161 arrangements of four integers in the range [1,37] (with repeats allowed). Enumerate them, saving and counting the permutations that add up to 40.
(This will be a much smaller number, N).
Draw uniformly distributed random integers K in the interval [0, N-1] and return the K-th permutation. This can easily be seen to guarantee a uniform distribution over the space of possible outcomes, with each sequence position identically distributed. (Many of the answers I'm seeing will have the final choice biased lower than the first three!) | If you want true randomness then use:
```
import numpy as np
def randofsum_unbalanced(s, n):
# Where s = sum (e.g. 40 in your case) and n is the output array length (e.g. 4 in your case)
r = np.random.rand(n)
a = np.array(np.round((r/np.sum(r))*s,0),dtype=int)
while np.sum(a) > s:
a[np.random.choice(n)] -= 1
while np.sum(a) < s:
a[np.random.choice(n)] += 1
return a
```
If you want a greater level of uniformity then take advantage of the multinomial distribution:
```
def randofsum_balanced(s, n):
return np.random.multinomial(s,np.ones(n)/n,size=1)[0]
``` |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | If you want true randomness then use:
```
import numpy as np
def randofsum_unbalanced(s, n):
# Where s = sum (e.g. 40 in your case) and n is the output array length (e.g. 4 in your case)
r = np.random.rand(n)
a = np.array(np.round((r/np.sum(r))*s,0),dtype=int)
while np.sum(a) > s:
a[np.random.choice(n)] -= 1
while np.sum(a) < s:
a[np.random.choice(n)] += 1
return a
```
If you want a greater level of uniformity then take advantage of the multinomial distribution:
```
def randofsum_balanced(s, n):
return np.random.multinomial(s,np.ones(n)/n,size=1)[0]
``` | Building on [@markdickonson](https://stackoverflow.com/a/3590105/75033) by providing some control over distribution between the divisors. I introduce a variance/jiggle as a percentage of the uniform distance between each.
```
def constrained_sum_sample(n, total, variance=50):
"""Return a random-ish list of n positive integers summing to total.
variance: int; percentage of the gap between the uniform spacing to vary the result.
"""
divisor = total/n
jiggle = divisor * variance / 100 / 2
dividers = [int((x+1)*divisor + random.random()*jiggle) for x in range(n-1)]
result = [a - b for a, b in zip(dividers + [total], [0] + dividers)]
return result
```
Sample output:
```
[12, 8, 10, 10]
[10, 11, 10, 9]
[11, 9, 11, 9]
[11, 9, 12, 8]
```
The idea remains to divide the population equally, then randomly move them left or right within the given range. Since each value is still bound to the uniform point we don't have to worry about it drifting.
Good enough for my purposes, but not perfect. eg: the first number will always vary higher, and the last will always vary lower. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | ```
b = random.randint(2, 38)
a = random.randint(1, b - 1)
c = random.randint(b + 1, 39)
return [a, b - a, c - b, 40 - c]
```
(I assume you wanted integers since you said "1-40", but this could be easily generalized for floats.)
Here's how it works:
* cut the total range in two randomly, that's b. The odd range is because there are going to be at least 2 below the midpoint and at least 2 above. (This comes from your 1 minimum on each value).
* cut each of those ranges in two randomly. Again, the bounds are to account for the 1 minimum.
* return the size of each slice. They'll add up to 40. | There are only 37^4 = 1,874,161 arrangements of four integers in the range [1,37] (with repeats allowed). Enumerate them, saving and counting the permutations that add up to 40.
(This will be a much smaller number, N).
Draw uniformly distributed random integers K in the interval [0, N-1] and return the K-th permutation. This can easily be seen to guarantee a uniform distribution over the space of possible outcomes, with each sequence position identically distributed. (Many of the answers I'm seeing will have the final choice biased lower than the first three!) |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | Here's the standard solution. It's similar to Laurence Gonsalves' answer, but has two advantages over that answer.
1. It's uniform: each combination of 4 positive integers adding up to 40 is equally likely to come up with this scheme.
and
2. it's easy to adapt to other totals (7 numbers adding up to 100, etc.)
```
import random
def constrained_sum_sample_pos(n, total):
"""Return a randomly chosen list of n positive integers summing to total.
Each such list is equally likely to occur."""
dividers = sorted(random.sample(range(1, total), n - 1))
return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
```
Sample outputs:
```none
>>> constrained_sum_sample_pos(4, 40)
[4, 4, 25, 7]
>>> constrained_sum_sample_pos(4, 40)
[9, 6, 5, 20]
>>> constrained_sum_sample_pos(4, 40)
[11, 2, 15, 12]
>>> constrained_sum_sample_pos(4, 40)
[24, 8, 3, 5]
```
Explanation: there's a one-to-one correspondence between (1) 4-tuples `(a, b, c, d)` of positive integers such that `a + b + c + d == 40`, and (2) triples of integers `(e, f, g)` with `0 < e < f < g < 40`, and it's easy to produce the latter using `random.sample`. The correspondence is given by `(e, f, g) = (a, a + b, a + b + c)` in one direction, and `(a, b, c, d) = (e, f - e, g - f, 40 - g)` in the reverse direction.
If you want *nonnegative* integers (i.e., allowing `0`) instead of positive ones, then there's an easy transformation: if `(a, b, c, d)` are nonnegative integers summing to `40` then `(a+1, b+1, c+1, d+1)` are positive integers summing to `44`, and vice versa. Using this idea, we have:
```
def constrained_sum_sample_nonneg(n, total):
"""Return a randomly chosen list of n nonnegative integers summing to total.
Each such list is equally likely to occur."""
return [x - 1 for x in constrained_sum_sample_pos(n, total + n)]
```
Graphical illustration of `constrained_sum_sample_pos(4, 10)`, thanks to @FM. (Edited slightly.)
```none
0 1 2 3 4 5 6 7 8 9 10 # The universe.
| | # Place fixed dividers at 0, 10.
| | | | | # Add 4 - 1 randomly chosen dividers in [1, 9]
a b c d # Compute the 4 differences: 2 3 4 1
``` | Building on [@markdickonson](https://stackoverflow.com/a/3590105/75033) by providing some control over distribution between the divisors. I introduce a variance/jiggle as a percentage of the uniform distance between each.
```
def constrained_sum_sample(n, total, variance=50):
"""Return a random-ish list of n positive integers summing to total.
variance: int; percentage of the gap between the uniform spacing to vary the result.
"""
divisor = total/n
jiggle = divisor * variance / 100 / 2
dividers = [int((x+1)*divisor + random.random()*jiggle) for x in range(n-1)]
result = [a - b for a, b in zip(dividers + [total], [0] + dividers)]
return result
```
Sample output:
```
[12, 8, 10, 10]
[10, 11, 10, 9]
[11, 9, 11, 9]
[11, 9, 12, 8]
```
The idea remains to divide the population equally, then randomly move them left or right within the given range. Since each value is still bound to the uniform point we don't have to worry about it drifting.
Good enough for my purposes, but not perfect. eg: the first number will always vary higher, and the last will always vary lower. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | Here's the standard solution. It's similar to Laurence Gonsalves' answer, but has two advantages over that answer.
1. It's uniform: each combination of 4 positive integers adding up to 40 is equally likely to come up with this scheme.
and
2. it's easy to adapt to other totals (7 numbers adding up to 100, etc.)
```
import random
def constrained_sum_sample_pos(n, total):
"""Return a randomly chosen list of n positive integers summing to total.
Each such list is equally likely to occur."""
dividers = sorted(random.sample(range(1, total), n - 1))
return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
```
Sample outputs:
```none
>>> constrained_sum_sample_pos(4, 40)
[4, 4, 25, 7]
>>> constrained_sum_sample_pos(4, 40)
[9, 6, 5, 20]
>>> constrained_sum_sample_pos(4, 40)
[11, 2, 15, 12]
>>> constrained_sum_sample_pos(4, 40)
[24, 8, 3, 5]
```
Explanation: there's a one-to-one correspondence between (1) 4-tuples `(a, b, c, d)` of positive integers such that `a + b + c + d == 40`, and (2) triples of integers `(e, f, g)` with `0 < e < f < g < 40`, and it's easy to produce the latter using `random.sample`. The correspondence is given by `(e, f, g) = (a, a + b, a + b + c)` in one direction, and `(a, b, c, d) = (e, f - e, g - f, 40 - g)` in the reverse direction.
If you want *nonnegative* integers (i.e., allowing `0`) instead of positive ones, then there's an easy transformation: if `(a, b, c, d)` are nonnegative integers summing to `40` then `(a+1, b+1, c+1, d+1)` are positive integers summing to `44`, and vice versa. Using this idea, we have:
```
def constrained_sum_sample_nonneg(n, total):
"""Return a randomly chosen list of n nonnegative integers summing to total.
Each such list is equally likely to occur."""
return [x - 1 for x in constrained_sum_sample_pos(n, total + n)]
```
Graphical illustration of `constrained_sum_sample_pos(4, 10)`, thanks to @FM. (Edited slightly.)
```none
0 1 2 3 4 5 6 7 8 9 10 # The universe.
| | # Place fixed dividers at 0, 10.
| | | | | # Add 4 - 1 randomly chosen dividers in [1, 9]
a b c d # Compute the 4 differences: 2 3 4 1
``` | Generate 4 random numbers, compute their sum, divide each one by the sum and multiply by 40.
If you want Integers, then this will require a little non-randomness. |
3,589,214 | So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbing" more. | 2010/08/28 | [
"https://Stackoverflow.com/questions/3589214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433493/"
] | Here's the standard solution. It's similar to Laurence Gonsalves' answer, but has two advantages over that answer.
1. It's uniform: each combination of 4 positive integers adding up to 40 is equally likely to come up with this scheme.
and
2. it's easy to adapt to other totals (7 numbers adding up to 100, etc.)
```
import random
def constrained_sum_sample_pos(n, total):
"""Return a randomly chosen list of n positive integers summing to total.
Each such list is equally likely to occur."""
dividers = sorted(random.sample(range(1, total), n - 1))
return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
```
Sample outputs:
```none
>>> constrained_sum_sample_pos(4, 40)
[4, 4, 25, 7]
>>> constrained_sum_sample_pos(4, 40)
[9, 6, 5, 20]
>>> constrained_sum_sample_pos(4, 40)
[11, 2, 15, 12]
>>> constrained_sum_sample_pos(4, 40)
[24, 8, 3, 5]
```
Explanation: there's a one-to-one correspondence between (1) 4-tuples `(a, b, c, d)` of positive integers such that `a + b + c + d == 40`, and (2) triples of integers `(e, f, g)` with `0 < e < f < g < 40`, and it's easy to produce the latter using `random.sample`. The correspondence is given by `(e, f, g) = (a, a + b, a + b + c)` in one direction, and `(a, b, c, d) = (e, f - e, g - f, 40 - g)` in the reverse direction.
If you want *nonnegative* integers (i.e., allowing `0`) instead of positive ones, then there's an easy transformation: if `(a, b, c, d)` are nonnegative integers summing to `40` then `(a+1, b+1, c+1, d+1)` are positive integers summing to `44`, and vice versa. Using this idea, we have:
```
def constrained_sum_sample_nonneg(n, total):
"""Return a randomly chosen list of n nonnegative integers summing to total.
Each such list is equally likely to occur."""
return [x - 1 for x in constrained_sum_sample_pos(n, total + n)]
```
Graphical illustration of `constrained_sum_sample_pos(4, 10)`, thanks to @FM. (Edited slightly.)
```none
0 1 2 3 4 5 6 7 8 9 10 # The universe.
| | # Place fixed dividers at 0, 10.
| | | | | # Add 4 - 1 randomly chosen dividers in [1, 9]
a b c d # Compute the 4 differences: 2 3 4 1
``` | Use [multinomial](https://en.wikipedia.org/wiki/Multinomial_distribution) distribution
```
from numpy.random import multinomial
multinomial(40, [1/4.] * 4)
```
Each variable will be distributed as a binomial distribution with mean `n * p` equal to `40 * 1/4 = 10` in this example. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.