qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
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 im... | 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.
Als... | 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')
roo... |
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 im... | 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.GetListItem... | 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')
roo... |
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 im... | 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.GetListItem... | 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_h... |
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 im... | 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_h... | 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')
roo... |
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... | 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=... | ```
<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" na... |
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 variab... | 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'^d... | 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/pa... | 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'^d... | 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.
Becaus... | 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 co... |
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 dictu... | 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, elemen... | 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.xp... |
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 dictu... | 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,... | 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.xp... |
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 dictu... | 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, elemen... | 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,... |
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 Boomer... | 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 ... | 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),"Gen... |
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... | 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... | 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.... | 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 w... | 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('o... | ```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 temporar... |
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 wa... | 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 ... | 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 wa... | 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 ... | 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 !== "" ?... |
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 wa... | 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 !== "" ?... |
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 wa... | 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 = t... | 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 a... |
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 wa... | 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 ... | 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 = t... |
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 wa... | 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 !== "" ?... | 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 wa... | 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 = t... |
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 wa... | 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 a... |
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 wa... | 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 wa... | 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 !== "" ?... | 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 a... |
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, po... | 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 ... | 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 c... | 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, pe... | 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[$... |
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 Fo... | 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',... | 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 L... |
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 "con... | 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 m... | 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 ra... | 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... | 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 ra... | 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.ge... | 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 ra... | 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... | 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.ge... |
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 s... | 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 neve... | 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]
Ou... |
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 s... | 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 neve... | `[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 l... |
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 s... | 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 neve... | 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 s... | 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,... | 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 neve... |
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 s... | 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]
Ou... |
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 s... | 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,... | [`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 s... | 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,... | 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]
Ou... |
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 s... | 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,... | 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 s... | 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]
Ou... |
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 s... | 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]
pr... | 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]
pr... | 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 contai... |
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]
pr... | 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,... | 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/pyga... | 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,... | 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/pyga... | 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 y... |
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,... | 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/pyga... | 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 tr... |
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,... | 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 tr... |
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,... | 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 y... | 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 tr... |
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 =... | 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 sec... | 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=k... |
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 = {
... | 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 tr... | 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 m... |
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):
... | 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):
... | 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):
... | 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 mus... | 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
impor... |
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'
```
[:
```
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 = "... |
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'
```
[:
```
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'
```
[ 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'
```
[:
```
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'
```
[ 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 = "... |
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'
```
[:
```
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'
```
[:
```
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 = "... |
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'
```
[ 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'
```
[ you can skip this step.
```
# from yo... | 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 = "... |
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'
```
[ you can skip this step.
```
# from yo... | **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 a... | 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 ... | 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.r... |
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=re... | 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:
`... | 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" : {
... |
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=re... | 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:
`... | 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(Filt... |
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, et... | 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:
... |
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:
... | 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
exce... |
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, et... | 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
exce... |
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 specif... | 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 someth... | 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,
... |
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 specif... | 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 someth... | 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... |
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 specif... | 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,
... | 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... |
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(Ge... | 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/a... | 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... | 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];
$a... | 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,... |
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... | 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/service... | 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 ... |
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 : ... | 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(... |
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 : ... | 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:
```
Stri... | ```
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(... |
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 : ... | 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:
```
Stri... | 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... | 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 ... |
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
f... | 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(IPyt... | 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, he... |
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
f... | 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(IPyt... | 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
f... | 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, he... |
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 a... | 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.AppCompatActiv... | 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 testin... | 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>
<di... |
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 a... | 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 pr... | 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 ac... |
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 a... | 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=... | 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 ac... |
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 "grabbin... | 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 posi... |
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 "grabbin... | 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 ... | 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 "grabbin... | 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 ... | 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 "grabbin... | 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 permutatio... | 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.c... |
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 "grabbin... | 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.c... | 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 posi... |
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 "grabbin... | 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 ... | 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 permutatio... |
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 "grabbin... | 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.)
```
... | 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 posi... |
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 "grabbin... | 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.)
```
... | 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 "grabbin... | 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.)
```
... | 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.