qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
19,298,147 | I always get this error for this code:
```
Traceback (most recent call last):
File "E:/ankosh/trial13.py", line 14, in <module>
if grades_mix[index_no]=="HM1":
IndexError: list index out of range)
```
I would really appreciate the help.
```
`file_pointer=open("C:/python27/Doc/student_grades.txt", "r")
r... | 2013/10/10 | [
"https://Stackoverflow.com/questions/19298147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2833577/"
] | You have, in abbreviated form:
```
while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
```
with no break statement to ever get out of the loop (which, how about `while True`?). Sooner or later you're going to go out of range. | The error message
```
IndexError: list index out of range
```
indicates that you are using an index that does not exist in the array. Try to check the size of the array by printing out its length
print "length of array grades\_mix =" ,len(grades\_mix)
If the length of the array is less than or equal to 1, then you... | 2,987 |
2,408,677 | I'm trying to implement the calculation of correlation coefficient of people between two sets of data in php.
I'm just trying to do the porting python script that can be found at this url
<http://answers.oreilly.com/topic/1066-how-to-find-similar-users-with-python/>
my implementation is the following:
```
class LB_Si... | 2010/03/09 | [
"https://Stackoverflow.com/questions/2408677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76593/"
] | Your algorithm looks mathematically correct but numerically unstable. Finding the sum of squares explicitly is a recipe for disaster. What if you have numbers like `array(10000000001, 10000000002, 10000000003)`? A numerically stable one-pass algorithm for calculating the variance can be [found on Wikipedia](http://en.w... | try my package here
<http://www.phpclasses.org/browse/package/5854.html> | 2,988 |
17,550,136 | My background is in more managed languages (C#, python) but I am becoming more experienced in C/C++. I am familiar with why the selection by reference (.) and selection through pointer operation (->) operators are different. In all cases I have encountered, if you use the incorrect one, it will result in a compile erro... | 2013/07/09 | [
"https://Stackoverflow.com/questions/17550136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2518451/"
] | In C++ you can overload the `->`-operator, which is used in pretty much all smart pointer implementations. However, some of those also have their own methods, i.e. to release a reference.
```
struct test {
int x;
};
std::shared_ptr<int> ptr(new test);
// Write to member x of the allocated object
ptr->x = 3;
// R... | You cannot apply `->` to a reference to a basic type and you cannot apply `.` to a pointer, but you can apply both to a user-defined type and they will have different meanings. The simplest example is a smart pointer, like `std::shared_ptr`:
```
struct A { int x; };
std::shared_ptr<A> p(new A);
p->x = 10;
p.reset();
... | 2,990 |
72,623,017 | As of may 30th, smtp is no longer accepted.
<https://support.google.com/accounts/answer/6010255?hl=en&ref_topic=7188673>
What is the new way to make a simple python emailer rather than a full application with the "login with google" option?
Not sure why I was asked for the code and error, given that I already diagno... | 2022/06/14 | [
"https://Stackoverflow.com/questions/72623017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12339133/"
] | Correction after May 30 2022, sending the users actual password is no longer accepted by googles smtp server
You should configuring an [apps password](https://support.google.com/accounts/answer/185833?hl=en#:%7E:text=An%20App%20Password%20is%20a,2%2DStep%20Verification%20turned%20on.) this works. Then replace the pass... | ```
import smtplib
host = "server.smtp.com"
server = smtplib.SMTP(host)
FROM = "testpython@test.com"
TO = "bla@test.com"
MSG = "Subject: Test email python\n\nBody of your message!"
server.sendmail(FROM, TO, MSG)
server.quit()
print ("Email Send")
``` | 2,993 |
65,526,849 | I run through the following steps to attempt to start up an app for production:
```
-Setup a virtualenv for the python dependencies: virtualenv -p /usr/bin/python3.8 ~/app_env
-Install pip dependencies: . ~/app_env/bin/activate && pip install -r ~/app/requirements.txt
-Un-comment the lines for privilege dropping in ... | 2021/01/01 | [
"https://Stackoverflow.com/questions/65526849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12027484/"
] | What solved it for me was apparently just reinstalling UWSGI, like in [this](https://stackoverflow.com/questions/21669354/rebuild-uwsgi-with-pcre-support?noredirect=1&lq=1) thread, in my virtual env while forcing it to ignore the cache so it could know to use the pcre library I installed.
In order, doing this
```
uws... | I tried to solve this error but it did not work no matter what I did and then reinstalled uwsgi, but the following 2 lines solved my problem
```
sudo find / -name libpcre.so.*
```
#change the path of the /home/anaconda3/lib/libpcre.so.1 with the one appears after above one.
```
sudo ln -s /home/anaconda3/lib/libpcr... | 2,994 |
41,285,789 | I came across a python library which has docs, which start like this:
>
> Quickstart
>
>
> Include foolib in your requirements.txt file.
>
>
>
AFAIK dependencies should be specified via `install_requires` in `setup.py`.
Should I talk the maintainer of the library and create a pull-request for the docs? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41285789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633961/"
] | Both are acceptable. The difference is that specifying something in your `install_requires` will auto-download / install that package when you install the package using setup.py. Having a `requirements.txt` makes it easier to see at a glance what the requirements are. I personally prefer seeing libraries with a `requir... | Add your dependencies in a requirements file and then parse this file in the setup.py. This will help you to:
* Easily install dependencies without installing the entire package through pip
* Get only one source for your dependencies
* Get all way to install your package available (pip, easy\_install, command line, et... | 2,995 |
55,721,564 | Here is the 'smem' command I run on the Redhat/CentOS Linux system. I expect the output be printed without the fields with zero size however I would expect the heading columns.
```
smem -kt -c "pid user command swap"
PID User Command Swap
7894 root /sbin/agetty --noclear tty1 ... | 2019/04/17 | [
"https://Stackoverflow.com/questions/55721564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11096022/"
] | Like this?:
```
$ awk '$NF!=0' file
PID User Command Swap
7850 root /sbin/auditd 236.0K
...
7883 root /opt/traps/bin/trapsd 64.0K
----------------------------------------------------
54 10 5.1M
```
But instead ... | Could you please try following, for extra precautions removing the space from last fields(in case it is there).
```
smem -kt -c "pid user command swap" | awk 'FNR==1{print;next} {sub(/[[:space:]]+$/,"")} $NF==0{next} 1'
``` | 2,996 |
35,282,609 | I'm a new Python programmer working through the book *Automate the Boring Stuff with Python*. One of the end-of-chapter projects is to build a mad libs program. Based on what has been introduced so far, I think that the author intends for me to use regular expressions.
Here is my code:
```
#! python3
#
# madlibs.py -... | 2016/02/09 | [
"https://Stackoverflow.com/questions/35282609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5901044/"
] | This is covered in detail in [BashFAQ #004](http://mywiki.wooledge.org/BashFAQ/004). Notably, [use of `ls` for this purpose is an antipattern and should be avoided](http://mywiki.wooledge.org/ParsingLs).
```
shopt -s dotglob # if including hidden files is desired
files=( "$dir"/* )
[[ -e $files || -L $files ]] && ec... | **Robust pure Bash** solutions:
For background on ***why* a pure Bash solution with globbing is superior to using `ls`**, see **[Charles Duffy's helpful answer](https://stackoverflow.com/a/35282784/45375)**, which also contains a **`find`-based alternative**, which is **much faster and less memory-intensive with *larg... | 2,997 |
13,283,253 | I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
```
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
```
Trac... | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328021/"
] | Django introduced a messages app in 1.2 ([release notes](https://docs.djangoproject.com/en/dev/releases/1.2/#messages-framework)), and deprecated the old user messages API.
In Django 1.4, the old message\_set API has been removed completely, so you'll have to update your code. If you follow the [messages docs](https:/... | What is in your `INSTALLED_APPS` in your `settings.py`?
Do you have `'django.contrib.messages',` included there?
Something like:
```
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.c... | 3,000 |
64,518,660 | I am currently working with an API in python and trying to retrieve previous institution ID's from certain authors.
I have come to this point
```py
my_auth.hist_names['affiliation']
```
which outputs:
```
[{'@_fa': 'true',
'@id': '60016491',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/... | 2020/10/24 | [
"https://Stackoverflow.com/questions/64518660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12758690/"
] | @Anton Sizikov,
Thanks for reply, but my problem was another. Unlike Downloadpipelineartifact@2, the DownloadBuildArtifacts@0 task did not work by entering the project name and pipeline for me:
```
- task: DownloadBuildArtifacts@0
inputs:
buildType: 'current'
project: 'Leaf'
... | Based on your log I can see that your artifact was downloaded to `$(Build.ArtifactStagingDirectory)` directory, which is `D:\a\1\a` in your case. Then you run `dir` command there:
```sh
Successfully downloaded artifacts to D:\a\1\a
2020-10-24T22:25:48.7993950Z Directory of D:\a\1\a
2020-10-24T22:25:48.7994230Z
2020-... | 3,005 |
32,342,262 | I am looking for a way to search a large string for a large number of equal length substrings.
My current method is basically this:
```
offset = 0
found = []
while offset < len(haystack):
current_chunk = haystack[offset*8:offset*8+8]
if current_chunk in needles:
found.append(current_chunk)
offset += 1
``... | 2015/09/01 | [
"https://Stackoverflow.com/questions/32342262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2448592/"
] | More Pythonic, much faster:
```
for needle in needles:
if needle in haystack:
found.append(needle)
```
Edit: With some limited testing here are test results
**This algorithm:**
0.000135183334351
**Your algorithm:**
0.984048128128
Much faster. | I think that you can break it up on a multicore and parallelize your search. Something along the lines of:
```
from multiprocessing import Pool
text = "Your very long string"
"""
A generator function for chopping up a given list into chunks of
length n.
"""
def chunks(l, n):
for i in xrange(0, len(l), n):
yiel... | 3,006 |
37,661,456 | I would like to use spark jdbc with python. First step was to add a jar:
```
%AddJar http://central.maven.org/maven2/org/apache/hive/hive-jdbc/2.0.0/hive-jdbc-2.0.0.jar -f
```
However, the response:
```
ERROR: Line magic function `%AddJar` not found.
```
How can I add JDBC jar files in a python script? | 2016/06/06 | [
"https://Stackoverflow.com/questions/37661456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] | Presently, this is not possible only from a python notebook; but it is understood as an important requirement. What you can do until this is supported, is from the same spark service instance of your python notebook, create a scala notebook and `%AddJar` from there. Then all python notebooks of that same spark service ... | I don't think this is possible in Notebook's Python Kernel as %Addjar is scala kernel magic function in notebook.
You would need to rely on the service provider to add this jar to python kernel.
Another thing you could try is sc.addjar() but not sure how would it work.
[Add jar to pyspark when using notebook](https:... | 3,007 |
36,533,759 | I have a file.dat of this type but with a lot more data:
```
Apr 1 18:15 [n1_Cam_A_120213_O.fits]:
4101.77 1. -3.5612 3.561 -0.278635 4.707 6.448 #data1
0.03223 0. 0.05278 0.05278 0.00237 0.4393 0.4125 #error1
4088.9 1. -0.404974 0.405 -0.06538 5.819 0. #data2
0. 0. 0... | 2016/04/10 | [
"https://Stackoverflow.com/questions/36533759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6184340/"
] | Try to write **system("pause");** before **return 0;** at the end of your program and press ctrl + F5. | Try this:
```
std::cin.get();
if (oper == 1)
ans = num1*num2;
else if(oper == 2)
ans = num1 / num2;
else if(oper == 3)
ans = num1 + num2;
else if(oper == 4)
ans = num1 - num2;
std::cout << ans;
std::cin.get();//this will block and prevent the console from closing until you press a key
return 0... | 3,010 |
57,257,751 | I've created my application in python and I want the application to be executed only one at a time. So I have used the singleton approach:
```py
from math import fmod
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL
import tendo
import pywinusb.hid as hid
import sys
import os
import time
import threadin... | 2019/07/29 | [
"https://Stackoverflow.com/questions/57257751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6078511/"
] | >
> Hello, it's me again! So, I have found the solution. I search a lot and I found very different ways to make the program runs only one time (singleinstance).
>
>
>
>
> In summary, it's possible to use a lock file, using the library OS, but if the computer shutdowns in a energy fall, this file will stay locking... | I had the same problem and I didn't find a way to use the singleinstance of tendo. If You need a solution right now, you can create a file using the "os" library, and put a variable there that when the program is running it is 1, else is 0, so you just have to verify that variable in the beginning of your program.
This... | 3,011 |
5,871,621 | I have a list of cities (simple cvs file) and I want to populate the citeis table while creating the City model.
Class description:
```
class City(models.Model):
city = modeld.CharField('city_name', max_length=50)
class Meta:
berbuse_name =....
...........
def __unicode__(self):
r... | 2011/05/03 | [
"https://Stackoverflow.com/questions/5871621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288219/"
] | We do something like this, usually.
```
import csv
from my_django_app.forms import CityForm
with open( "my file", "rb" ) as source:
rdr = csv.DictReader( source )
for row in rdr:
form= CityForm( **row )
if form.is_valid():
form.save()
else:
print form.errors
``... | [Providing initial data for models](http://docs.djangoproject.com/en/1.3/howto/initial-data/). | 3,012 |
30,397,107 | I want to build a simple tool that uses functions from an open source project from GitHub, SourceForge, etc. (e.g., a project such as <https://github.com/vishnubob/python-midi/>).
I searched the documentation but could not find the right way to do this. (I assume I need to point PyCharm at the source somehow and "impo... | 2015/05/22 | [
"https://Stackoverflow.com/questions/30397107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4929051/"
] | Yes there is a convention. Use `bower` if a package exists. If it doesn't, download the repo into the `vendor` folder. Import the file in your `Brocfile.js`
```
app.import('vendor/path_to/main_js_file.js');
``` | Yes, use bower or place them in `vendor/`. Then register them in `ember-cli-build.js`
Here's the documentation: <https://guides.emberjs.com/v2.14.0/addons-and-dependencies/managing-dependencies/> | 3,013 |
4,589,696 | I apologize up front for the dumbness of this question, but I can't figure it out and its driving me crazy.
In ruby I can do:
```
irb(main):001:0> s = "\t\t\n"
=> "\t\t\n"
irb(main):003:0> puts s
=> nil
irb(main):004:0> puts s.inspect
"\t\t\n"
```
Is there an equivalent of ruby's `inspect` function in ... | 2011/01/04 | [
"https://Stackoverflow.com/questions/4589696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561964/"
] | [`repr()`](http://docs.python.org/library/functions.html#repr):
```
>>> print repr('\t\t\n')
'\t\t\n'
``` | You can use repr or (backticks), I am doing the exactly the same things as you did above.
```
>>> s = "\t\t\n"
>>> s
'\t\t\n'
>>> print s
>>> repr(s)
"'\\t\\t\\n'"
>>> print repr(s)
'\t\t\n'
>>> print `s`
'\t\t\n'
``` | 3,014 |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will ... | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Thanks for your responses. Most were very good and provided good links so I'll just say that and answer my own question.
Caspin posted this [link](http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
He also mentioned that Google Tests used ULP comparison and when I looked at t... | >
> What is the best way to avoid problems
> like this?... In Python or in general.
>
>
>
What problem? You're working with physical measurements. Unless you have some *really* sophisticated equipment, the error in your measurements is going to be several orders of magnitude higher than floating-point epsilon. So... | 3,015 |
45,078,474 | I want to implement import feature with required and optional parameters, to run this in this way:
```
python manage.py import --mode archive
```
where `--mode` is required and `archive` also.
I'm using argparse library.
```
class Command(BaseCommand):
help = 'Import'
def add_arguments(self, parser):
... | 2017/07/13 | [
"https://Stackoverflow.com/questions/45078474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7985656/"
] | You created a positional argument (no `--` option in front of the name). Positional arguments are *always* required. You can't use `required=True` for such options, just drop the `required`. Drop the `default` too; a required argument can't have a default value (it would never be used anyway):
```
parser.add_argument(... | I think that `--mode archive` is supposed to mean "mode is archive", in other words `archive` is the *value* of the `--mode` argument, not a separate argument. If it were, it would have to be `--archive` which is not what you want.
Just leave out the definition of `archive`. | 3,025 |
15,768,136 | In python 2.7, I want to run:
$ ./script.py initparms.py
This is a trick to supply a parameter file to script.py, since initparms.py contains several python variables e.g.
```
Ldir = '/home/marzipan/jelly'
LMaps = True
# etc.
```
script.py contains:
```
X = __import__(sys.argv[1])
Ldir = X.Ldir
LMaps = X.Lmaps
... | 2013/04/02 | [
"https://Stackoverflow.com/questions/15768136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021819/"
] | You can use [`execfile`](http://docs.python.org/2/library/functions.html#execfile):
```
execfile(sys.argv[1])
```
Of course, the usual warnings with `exec` or `eval` apply (Your script has no way of knowing whether it is running trusted or untrusted code).
My suggestion would be to not do what you're doing and inst... | You could do something like this:
```
import os
import imp
import sys
try:
module_name = sys.argv[1]
module_info = imp.find_module(module_name, [os.path.abspath(os.path.dirname(__file__))] + sys.path)
module_properties = imp.load_module(module_name, *module_info)
except ImportError:
pass
else:
try... | 3,026 |
70,668,633 | I am currently on a Discord Bot interacting with the Controlpanel API. (<https://documenter.getpostman.com/view/9044962/TzY69ub2#02b8da43-ab01-487d-b2f5-5f8699b509cd>)
Now, I am getting an KeyError when listing a specific user.
```
headers = {
'Accept': 'application/json',
'Authorization': 'Bearer <censored>'... | 2022/01/11 | [
"https://Stackoverflow.com/questions/70668633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17903752/"
] | This KeyError happens usually when the Key doesn't exist(not exist or even a typo). in your case I think you dont have the 'data' key in your response and your should use something like:
```
data.json()
```
if you can post the complete response it would be more convinient to give you some hints. | The endpoint you're hitting does not return a list but a single object.
You should use the generic endpoint : `{{url}}/api/users`
Also I don't think you want to recreate your `embed` object for each user.
```py
headers = {
'Authorization': 'Bearer <censored>'
}
url = 'https://<censored>'
endpoint = '/api/users'... | 3,029 |
41,281,072 | I would like to make a file with 3 main columns but my current file has different number of columns per row.
an example of my file is like this:
```
BPIFB3,chr20;ENST00000375494.3
PXDN,chr2,ENST00000252804.4;ENST00000483018.1
RP11,chr2,ENST00000607956.1
RNF19B,chr1,ENST00000373456.7;ENST00000356990.5;ENS... | 2016/12/22 | [
"https://Stackoverflow.com/questions/41281072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7310023/"
] | **If** your input is actually well-formed, you can do this:
```
for row in reader:
for thing in row[2].split(';'):
writer.writerow(row[:2]+[thing])
```
But as it exists, your first row has malformed data that doesn't match the rest of your rows. So if that *is* an example of your data, then [you could tr... | Try this:
```
import csv
with open('data.tbl') as f, open('out.tbl', 'w') as out:
reader = csv.reader(f, delimiter='\t')
writer = csv.writer(out, delimiter='\t')
for row in reader:
if len(row) == 3:
writer.writerow(row)
else:
n = len(row)
writer.writerow... | 3,030 |
17,517,718 | I am working on a project which aims to fetch some data from some websites and then stores into database. But these websites contains different charsets such as utf-8, gbk. The fetched data is unicode so i wonder when to convert to string is the right way. I convert to string immediately for now, but it seems that the ... | 2013/07/08 | [
"https://Stackoverflow.com/questions/17517718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674199/"
] | Your `start_time` (`Time.now.in_time.zone`) is populated on the page load/render. Whereas the `updated_at` is re-populated when you save the model. Your times are only off by a few seconds, which indicates that it took the person a few seconds to submit the form.
Based on the updated requirement of it being when a sta... | 1 . You set a static time in the view witch gets generated on page load.
2 . Set the time in the controller when you save the object. Basic example:
```
@object = Object.new(params[:object].merge(:start_time => Time.now))
if @object.save
redirect_to 'best side in da world'
else
render :new
end
``` | 3,033 |
8,397,617 | I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What would be the best way to control the mouse and keyboard in th... | 2011/12/06 | [
"https://Stackoverflow.com/questions/8397617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027427/"
] | To trigger an event simply call the relevant event function in jQuery on the element, with no handler function defined, like this:
```
$("#2").click();
```
Or there is also `trigger()`, which accepts the event type as a parameter:
```
$("#2").trigger('click');
```
However it's worth noting that `Id` attributes be... | You can use `trigger`:
```
$('#2').trigger('click');
```
<http://api.jquery.com/trigger/> | 3,034 |
51,209,598 | Here is a sample of json data I created from defaultdict in python.
```
[{
"company": [
"ABCD"
],
"fullname": [
"Bruce Lamont",
"Ariel Zilist",
"Bruce Lamont",
"Bobby Ramirez"
],
"position": [
" The Hesh",
" Server",
" HESH",
... | 2018/07/06 | [
"https://Stackoverflow.com/questions/51209598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7655640/"
] | you are adding an extra comma in the end for profile\_url array. The proper json should be
```
[{
"company": [
"ABCD"
],
"fullname": [
"Bruce Lamont",
"Ariel Zilist",
"Bruce Lamont",
"Bobby Ramirez"
],
"position": [
" The Hesh",
" Server",
... | ```
import json
j = '[{"company":["ABCD"],"fullname":["Bruce Lamont","Ariel Zilist","Bruce Lamont","Bobby Ramirez"],"position":[" The Hesh"," Server"," HESH"," Production Assistant"],"profile_url":["http://www.url1.com","http://www.url2.com","http://www.url3.com","http://www.url4.com"]}]'
json_obj = json.loads(j)
`... | 3,038 |
55,962,661 | I am very new to python and have trouble printing the length of a variable I have created.
I have tried len(), and I have tried converting to lists, arrays and tuples and so on and cannot get it to print the length correctly.
```
print(k1_idx_label0)
len(k1_idx_label0)
```
And the output is ---
```
(array([ 0... | 2019/05/03 | [
"https://Stackoverflow.com/questions/55962661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11338333/"
] | The tuple has just `1` element, if you want to know the size of that element inside the tuple:
```
len(k1_idx_label0[0])
```
if you want to know the size of **all** elements in the tuple:
```
[len(e) for e in k1_idx_label0]
``` | Try:
```
print(len(k1_idx_label0[0]))
``` | 3,039 |
24,890,259 | **I'm not looking for a solution (I have two ;) ), but on insight to compare the strengths and weaknesses of each solution considering python's internals. Thanks !**
With a coworker, we wish to extract the difference between two successive list elements, for all elements. So, for list :
```
[1,2,4]
```
the expected... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24890259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481478/"
] | With a generator:
```
def diff_elements(lst):
"""
>>> list(diff_elements([]))
[]
>>> list(diff_elements([1]))
[]
>>> list(diff_elements([1, 2, 4, 7]))
[1, 2, 3]
"""
as_iter = iter(lst)
last = next(as_iter)
for value in as_iter:
yield value - last
last = value... | If I understood your question I suggest you use something like that:
```
diffList = lambda l: [(l[i] - l[i-1]) for i in range(1, len(l))]
answer = diffList( [ 1,2,4] )
```
This function will give you a list with the differences between all consecutive elements in the input list.
This one is similar with your first ... | 3,042 |
12,805,699 | recently i understand the great advantage to use the list comprehension. I am working with several milion of points (x,y,z) stored in a special format \*.las file. In python there are two way to work with this format:
```
Liblas module [http://www.liblas.org/tutorial/python.html][1] (in a C++/Python)
laspy module [ht... | 2012/10/09 | [
"https://Stackoverflow.com/questions/12805699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1493192/"
] | Python is case-sensitive. Too me it looks like you ask for attribute `x`, but it should be an uppercase `X`. | Try
```
import numpy as np
...
points = np.array([f.X, f.Y]).T
``` | 3,044 |
39,190,274 | I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.
A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comment out th... | 2016/08/28 | [
"https://Stackoverflow.com/questions/39190274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2071737/"
] | That's because of
>
> Let `shiftCount` be the result of masking out all but the least significant 5 bits of `rnum`, that is, compute `rnum & 0x1F`.
>
>
>
of how the `<<` operation is defined. See <http://www.ecma-international.org/ecma-262/6.0/#sec-left-shift-operator-runtime-semantics-evaluation>
So according t... | JavaScript defines a left-shift by 32 to do nothing, presumably because it smacks up against the 32-bit boundary. You cannot actually shift anything more than 31 bits across.
Your approach of first shifting 31 bits, then a final bit, works around JavaScript thinking that shifting so much doesn't make sense. Indeed, it... | 3,046 |
531,487 | I'm looking for a python browser widget (along the lines of pyQT4's [QTextBrowser](http://doc.trolltech.com/3.3/qtextbrowser.html) class or [wxpython's HTML module](http://www.wxpython.org/docs/api/wx.html-module.html)) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget cla... | 2009/02/10 | [
"https://Stackoverflow.com/questions/531487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110/"
] | It may not be ideal for your purposes, but you might want to take a look at the Python bindings to KHTML that are part of PyKDE. One place to start looking is the KHTMLPart class:
<http://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html>
Since the API for this class is based on the signals and slots paradigm used in Qt... | I would also love such a thing. I suspect one with Python bindings does not exist, but would be really happy to be wrong about this.
One option I recently looked at (but never tried) is the [Webkit](http://webkit.org/) browser. Now this has some bindings for Python, and built against different toolkits (I use GTK). Ho... | 3,048 |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you are looking for [crontab](http://en.wikipedia.org/wiki/Crontab) rather than loop. | Sounds like you want to use something like cron instead, but... if you are sure you want something to run in the same terminal-window every N minutes (or seconds, actually), you could use the 'watch' command.
```
watch -n 60 python myscripy.py
``` | 3,050 |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***... | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | Everything from the request is just a string. The modelbinder matches up keys in the request body with property names, and then attempts to coerce them to the appropriate type. If the property is not posted or is posted with an empty string, that will obviously fail when trying to convert to an int. As a result, you en... | >
> non-nullable required types.
>
>
>
You do not. It is either required - then there is no sense in it being nullable - or it is not required, then you nullable makes sense, but it makes no sense to require it.
Attributes are always for the whole request. You are in a logical problem because you try to use them ... | 3,056 |
1,250,779 | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have... | 2009/08/09 | [
"https://Stackoverflow.com/questions/1250779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64313/"
] | Class attributes are often used to allow overriding defaults in subclasses. For example, BaseHTTPRequestHandler has class constants sys\_version and server\_version, the latter defaulting to `"BaseHTTP/" + __version__`. SimpleHTTPRequestHandler overrides server\_version to `"SimpleHTTP/" + __version__`. | Encapsulation is a good principle: when an attribute is inside the class it pertains to instead of being in the global scope, this gives additional information to people reading the code.
In your situations 1-4, I would thus avoid globals as much as I can, and prefer using class attributes, which allow one to benefit ... | 3,062 |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
-------... | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | The null filehandle [diamond operator](http://perldoc.perl.org/perlop.html#I%2fO-Operators) `<>` has its place in building command line tools. It acts like `<FH>` to read from a handle, except that it magically selects whichever is found first: command line filenames or STDIN. Taken from perlop:
```
while (<>) {
... ... | @Schwern mentioned turning warnings into errors by localizing `$SIG{__WARN__}`. You can do also do this (lexically) with `use warnings FATAL => "all";`. See `perldoc lexwarn`.
On that note, since Perl 5.12, you've been able to say `perldoc foo` instead of the full `perldoc perlfoo`. Finally! :) | 3,067 |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
... | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | I found a way to do this. We used GatsbyJS for a project and it relies on a
.env.production file for the env variables. I tried to pass them as
`env:` to the github action, but that didn't work and they were ignored.
Here is what I did. I base 64 encoded the .env.production file:
```
base64 -i .env.production
```
A... | Here is how to solve your actual problem of securely logging into an SSH server using a secret stored in GitHub Actions, named `GITHUB_ACTIONS_DEPLOY`.
Let's call this "beep", because it will cause an audible bell on the server you login to. Maybe you use this literally ping a server in your house when somebody pushes... | 3,077 |
44,150,069 | I've implemented the "xor problem" with cntk (python).
Currently it solves the problem only occasionally. How could I implement a more reliable network?
I guess the problem gets solved whenever the starting random weights are near optimal. I have tried `binary_cross_entropy` as the loss function but it didn't improve... | 2017/05/24 | [
"https://Stackoverflow.com/questions/44150069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635993/"
] | One option is to apply the [`TO_JSON_STRING` function](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#to_json_string) to the results of your query. For example,
```
#standardSQL
SELECT TO_JSON_STRING(t)
FROM (
SELECT x, y
FROM YourTable
WHERE z = 10
) AS t;
```
If you wan... | I'm using a service account to access the BigQuery REST API to get the response in JSON format.
In order to use a service account, you will have to go to credentials (<https://console.cloud.google.com/apis/credentials>) and choose a project.
[](ht... | 3,087 |
36,054,382 | I have succeeded ran the code in C++,with the code below:
```
int countOnes(int num) {
int count =0;
while (num) {
count ++;
num = num & (num-1);
}
return count;
}
```
but it didn't work in Python version:
```
def countOnes(num):
count = 0
while(num):
count += 1
... | 2016/03/17 | [
"https://Stackoverflow.com/questions/36054382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6075620/"
] | The reason this function works differently in the two languages is that they have different fundamental number types. In C++, `int` is indeed often a 32 bit integer in two's complement representation, though the language standard allows other representations. In Python, however, the standard number type has arbitrary p... | Python doesn't have "32-bit integers". Its integers are arbitrary (read:infinite) length. This means that -1 is *not* 0xffffffff, but is instead an infinitely long binary sequence of 1s. | 3,088 |
68,116,542 | I am trying to recode an existing python script to Java.
It includes this following line:
```
r = requests.get('https://{}/redfish/v1/{}'.format(ip, query), auth=('ADMIN', 'ADMIN'), verify=False)
```
I don't have a lot of experience in Python and didn't write the script myself. So far I've only been able to figure o... | 2021/06/24 | [
"https://Stackoverflow.com/questions/68116542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8298497/"
] | First, read [this tutorial on the java HTTP client](https://openjdk.java.net/groups/net/httpclient/intro.html). (Note that it requires jdk11 or up).
From there it should be fairly simply; that `.format()` thing is just replacing the `{}` with the provided ip and query parts. The auth part is more interesting. The veri... | At first, you can use `String.format` for the formatting:
```java
String url=String.format("https://%s/redfish/v1/%s",ip,query);
```
You could also use `MessageFormat` if you want to.
For connecting, you can create a `URL`-object and creating a `URLConnection` (in your case `HttpsURLConnection`) and opening an `Inp... | 3,090 |
44,962,225 | I imported a table with the years that each coach served as the football coach. Some of the years listed look like this: "1903–1910, 1917, 1919"
I am aiming for [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]
In my original DataFrame this list is an object.
I have tried:
`x = "1903–1910, 1917, 1919"`
... | 2017/07/07 | [
"https://Stackoverflow.com/questions/44962225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8268427/"
] | The hyphen you see is not really a hyphen. It could be some other character, like an unicode en-dash which would look very similar.
Try to copy-paste the actual character into the split string.
Looking at the text you posted, here's the difference:
```
➜ ~ echo '1903–1910' | xxd
00000000: 3139 3033 e280 9331 3931 3... | Your character is not an hyfen, it's a dash:
```
>>> "–" == "-"
False
>>> x = "1903–1910, 1917, 1919"
>>> x.split("–")
['1903', '1910, 1917, 1919']
``` | 3,091 |
34,902,486 | There are many posts about 'latin-1' codec , however those answers can't solve my problem, maybe it's my question, I am just a rookie to learn Python, somewhat. When I used `cwd(dirname)` to change directory of FTP site, the unicodeerror occurred. Note that `dirname` included Chinese characters, obviously, those charac... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34902486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5816236/"
] | No need to edit ftplib source code. Just set `ftp.encoding` property in your code:
```
ftp.encoding = "UTF-8"
ftp.cwd(dirname)
```
A similar question, about FTP output, rather then input:
[List files with UTF-8 characters in the name in Python ftplib](https://stackoverflow.com/q/53091871/850848) | I solved this problem by editing `ftplib.py`. On my machine, it is under `C:\Users\<user>\AppData\Local\Programs\Python\Python36\Lib`.
You just need to replace `encoding = "latin-1"` with `encoding = "utf-8"` | 3,094 |
30,433,983 | This is what I have in my `Procfile`:
```
web: gunicorn --pythonpath meraki meraki.wsgi
```
and when I do `foreman start`, I get this error:
```
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
```
the reason, as far as I can see in the traceback, is:
```
ImportError: No module named wsgi
```... | 2015/05/25 | [
"https://Stackoverflow.com/questions/30433983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137194/"
] | You've confused yourself by following an unnecessarily complicated structure. You don't need that outer meraki directory, and your Procfile and requirements.txt should be in the same directory as manage.py. Then you can remove the pythonpath parameter and all should be well. | As Roseman said, it is unnecessarily complicated structure.If you want it to do so,Try
```
web: gunicorn --pythonpath /path/to/meraki meraki.wsgi
```
That is `/absolutepath/to/secondmeroki(out of 3)` which contains `apps`. | 3,095 |
71,266,145 | I wrote a python function called `plot_ts_ex` that takes two arguments `ts_file` and `ex_file` (and the file name for this function is `pism_plot_routine`). I want to run this function from a bash script from terminal.
When I don't use variables in the bash script in pass the function arguments (in this case `ts_file =... | 2022/02/25 | [
"https://Stackoverflow.com/questions/71266145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18308686/"
] | When you use single quotes the variables aren’t going to be expanded, you should use double quotes instead:
```
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c "import pism_plot_routine; pism_plot_routine.plot_ts_ex('$ts_name', '$ex_name')"
```
---
You can also use sys.argv, argum... | You are giving the value `$ts_name` to python as string, bash does not do anything with it. You need to close the `'`, so that it becomes a string in bash, and then open it again for it to become a string in python.
The result will be something like this:
```
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10k... | 3,096 |
36,915,188 | I have a large csv file with 25 columns, that I want to read as a pandas dataframe. I am using `pandas.read_csv()`.
The problem is that some rows have extra columns, something like that:
```
col1 col2 stringColumn ... col25
1 12 1 str1 3
...
33657 2 3 ... | 2016/04/28 | [
"https://Stackoverflow.com/questions/36915188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5841927/"
] | If you want Coded UI to launch your forms application on start of a test, use the method
```
ApplicationUnderTest.Launch("FORMS_APP_PATH");
```
You can check the precise method details on MSDN.
Update:
To handle changing paths I created a new Forms solution and called it LabPlus.
I then added a CodedUI test proje... | My fix:
1. add reference from test project to WinForm project
2. decorate test class with `[DeploymentItem('your-app.exe')]` attribute
3. add `ApplicationUnderTest.Launch("your-app.exe");` to the test method | 3,097 |
37,009,587 | I'm making a python app to automate some tasks in AutoCAD (drawing specific shapes in specific layers and checking the location of some circles).
For the first part, drawing things, it was easy to use the AutoCAD Interop library, as you could easily put objects in the active document without doing anything on AutoCAD,... | 2016/05/03 | [
"https://Stackoverflow.com/questions/37009587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266184/"
] | You can iterate through list of available resources using method of Assembly class:
```
var names = someInstance.GetType()
.GetTypeInfo()
.Assembly
.GetManifestResourceNames();
```
And then load resource by full name from the list above:
```
var stream = someAssembly.GetManife... | You need to get Assembly which you embedded resource then call GetManifestResourceStream.
I have sample with namespace YourProjectNameSpace have MyFolder contain MyFile.json:
```
public class EndpointBuilder
{
private static String _filePath = "YourProjectNameSpace.MyFolder.MyFile.json";
public async Task<E... | 3,098 |
718,040 | <http://pypi.python.org/pypi/simplejson>
I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..
I am on a Windows System | 2009/04/04 | [
"https://Stackoverflow.com/questions/718040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32372/"
] | I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python.
Once you've installed EasyInstall, you should be able to go to a command window and type:
```
easy_install simplejson
```
This may require putting easy\_install.exe on your PATH first, I don... | If you have Python 2.6 installed then you already have simplejson - just import `json`; it's the same thing. | 3,099 |
16,330,838 | I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g.
```
text = "s:11011 i:11010 ::110011 :110010 d:11000"
```
should split into
```
[s,11011,i,11010,:,110011, ,110010,d,11000]
```
after following the Regular Expressions HOWTO on t... | 2013/05/02 | [
"https://Stackoverflow.com/questions/16330838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753000/"
] | Note this assumes that your data has format like `X:101010`:
```
>>> re.findall(r'(.+?):(.+?)\b ?',text)
[('s', '11011'), ('i', '11010'), (':', '110011'), (' ', '110010'), ('d', '11000')]
```
Then `chain` them up:
```
>>> list(itertools.chain(*_))
['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '110... | ```
>>> text = "s:11011 i:11010 ::110011 :110010 d:11000"
>>> [x for x in re.split(r":(:)?|\s(\s)?", text) if x]
['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000']
``` | 3,109 |
65,856,151 | I am using anaconda and python 3.8. Now some of my codes need to be run with python 2. so I create a separate python 2.7 environment in conda like below:
after that, I installed spyder, then launcher spyder amd spyder is showing I am still using python 3.8
how do i do to use python 2.7 in spyder with a new environmen... | 2021/01/23 | [
"https://Stackoverflow.com/questions/65856151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983652/"
] | According to the documentation [here](https://docs.anaconda.com/anaconda/user-guide/tasks/switch-environment/), this should create a python2.7 virtual environment (29 April 2021) with spyder installed. I verified that spyder version 3.3.6 is python2.7 compatible
```
conda create -y -n py27 python=2.7 spyder=3.3.6
```... | You can manage environments from Ananconda's Navigator. <https://docs.anaconda.com/anaconda/navigator/getting-started/#navigator-managing-environments> | 3,114 |
8,638,880 | I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, w... | 2011/12/26 | [
"https://Stackoverflow.com/questions/8638880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/206349/"
] | >
> I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the is operator.
>
>
>
This is your misconception: concerning the `int`s and `long`s, that is valid ... | This is a properly behavior.
```
x == y #True because they have a the same value
x is y #False because x isn't reference to y
id(x) == id(y) #False because as the above
```
But:
```
x = input()
y = x #rewrite reference of x to another variable
y == x and x is y and id(x) == id(y) #True
``` | 3,119 |
9,887,224 | Does apache or nginx must be installed before I can run my PHP files in browser?
Django itself has a run-server for testing python codes.Is there any similar way to test PHP files? | 2012/03/27 | [
"https://Stackoverflow.com/questions/9887224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1188895/"
] | Your options is:
* Install web server, as you said.
* Use [web server](http://php.net/manual/en/features.commandline.webserver.php), as JohnP suggested.
* Install php-cli, run your script from console, save output to html file and open it in a browser.
Actually, you can't normally "run" php files in browser. Browser ... | Yes. You need something like nginx or Apache. Either install one of those (on say your local machine). **OR**, see JohnP's comment - a new feature released recently. | 3,127 |
2,765,664 | I have got some code to pass in a variable into a script from the command line. I can pass any value into `function` for the `var` arg. The problem is that when I put `function` into a class the variable doesn't get read into `function`. The script is:
```
import sys, os
def function(var):
print var
class functi... | 2010/05/04 | [
"https://Stackoverflow.com/questions/2765664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234435/"
] | you might find [`getattr`](http://docs.python.org/library/functions.html#getattr) useful:
```
>>> argv = ['function.py', 'run', 'Hello']
>>> class A:
def run(self, *args):
print(*args)
>>> getattr(A(), argv[1])(*argv[2:])
Hello
``` | It sounds like rather than:
```
self.function = self.module.__dict__[self.functionName]
```
you want to do something like (as @SilentGhost mentioned):
```
self.function = getattr(some_class, self.functionName)
```
The tricky thing with retrieving a method on a class (not an object instance) is that you are going ... | 3,129 |
65,661,996 | How Do I pass values say `12,32,34` to formula `x+y+z` in python without assigning manually?
I have tried using `**args` but the results is `None`.
```
def myFormula(*args):
lambda x, y: x+y+z(*args)
print(myFormula(1,2,3))
``` | 2021/01/11 | [
"https://Stackoverflow.com/questions/65661996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14911024/"
] | try this:
```py
formula = lambda x,y,z: x+y+z
print(formula(1,2,3))
```
there is no need to use \*args there.
here is an example of using a function for a formula
```py
# a = (v - u)/t
acceleration = lambda v, u, t: (v - u)/t
print(acceleration(23, 12, 5)
``` | Just use `sum`:
```
print(sum([1, 2, 3]))
```
Output:
```
6
```
If you want a `def` try this:
```
def myFormula(*args):
return sum(args)
print(myFormula(1, 2, 3))
```
Output:
```
6
``` | 3,130 |
55,929,577 | I'm trying to run a python program in the online IDE SourceLair. I've written a line of code that simply prints hello, but I am embarrassed to say I can't figure out how to RUN the program.
I have the console, web server, and terminal available on the IDE already pulled up. I just don't know how to start the program.... | 2019/04/30 | [
"https://Stackoverflow.com/questions/55929577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11434891/"
] | Can I ask you why you are using SourceLair?
Well I just figured it out in about 2 mins....its the same as using any other editor for python.
All you have to do is to run it in the terminal. python (nameoffile).py | Antonis from SourceLair here.
In SourceLair, you get a fully featured terminal, plus a web server for running your Python applications.
For simple files, as you correctly found out, all you have to do is save the file and run it through your terminal, using `python <your-file.py>`.
If you want to run a complete web ... | 3,133 |
60,099,737 | I have a compiled a dataframe that contains USGS streamflow data at several different streamgages. Now I want to create a Gantt chart similar to [this](https://stackoverflow.com/questions/31820578/how-to-plot-stacked-event-duration-gantt-charts-using-python-pandas). Currently, my data has columns as site names and a da... | 2020/02/06 | [
"https://Stackoverflow.com/questions/60099737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10382580/"
] | The reason this is happening is because you have pd.MultiIndex column headers. I can tell you have MultiIndex column headers by tuples in your column names from pd.DataFrame.info() results.
See this example below:
```
df = pd.DataFrame(np.random.randint(100,999,(5,5))) #create a dataframe
df.columns = pd.MultiIndex.... | Well, as @EdChum said above, .dt is a pd.DataFrame attribute, not a pd.Series method. If you want to get the date difference, use the `apply()` pd.Dataframe method. | 3,134 |
16,247,002 | I have a script using DaemonRunner to create a daemon process with a pid file. The problem is that if someone tried to start it without stopping the currently running process, it will silently fail. What's the best way to detect an existing process and alert the user to stop it first? Is it as easy as checking the pidf... | 2013/04/27 | [
"https://Stackoverflow.com/questions/16247002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629195/"
] | since DaemonRunner handles its own lockfile, it's more wisely to refer to that one, to be sure you can't mess up. Maybe this block can help you with that:
Add
`from lockfile import LockTimeout`
to the beginning of the script and surround `daemon_runner.doaction()` like this
```
try:
daemon_runner.do_action... | This is the solution that I decided to use:
```
lockfile = runner.make_pidlockfile('/tmp/myapp.pid', 1)
if lockfile.is_locked():
print 'It looks like a daemon is already running!'
exit()
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
```
Is this a best practice or is there a ... | 3,135 |
7,554,576 | i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error
```
Can't open specified script file
Usage: monkeyrunner [options] SCRIPT_FILE
-s MonkeyServer IP Address.
-p MonkeyServer TCP Port.
-v MonkeyServer Logging level (ALL, FINEST, FIN... | 2011/09/26 | [
"https://Stackoverflow.com/questions/7554576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/946040/"
] | scriptfile should be a full path file name
try below
`monkeyrunner c:\test_script\first.py` | Under all unix/linux families OS the sha bang syntax can be used.
Edit the first line of your script with the results of the following command:
```
which monkeyrunner
```
for example, if monkeyrunner (usually provided with android sdk) has been installed under /usr/local/bin/sdk write:
```
#!/usr/local/bin/sdk/to... | 3,136 |
21,302,971 | I initially had `python 2.7.3` i downloaded from the sourcee and did `make install`
and after downloading i run `python`
but again my system is showing `2.7.3`
I didn't get any error while installing | 2014/01/23 | [
"https://Stackoverflow.com/questions/21302971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113427/"
] | Since you are on Ubuntu, I recommend following the steps outlined [here](http://heliumhq.com/docs/installing_python_2.7.5_on_ubuntu) to install a new Python version. The steps there are for Python 2.7.5 but should be equally applicable to Python 2.7.6. | The version you installed is probably in /usr/local/bin/python . Try calling it with the complete path. You may want to change your path settings or remove the previously installed version using your package manager if it was installed by the system. | 3,146 |
59,987,601 | Good morning!
I am trying to remove duplicate rows from a csv file with panda.
I have 2 files, A.csv and B.csv
I want to delete all rows in A that exist in B.
File A.csv:
```
Pedro,10,rojo
Mirta,15,azul
Jose,5,violeta
```
File B.csv:
```
Pedro,
ignacio,
fernando,
federico,
```
Output file output.csv:
```
Mir... | 2020/01/30 | [
"https://Stackoverflow.com/questions/59987601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12814128/"
] | Search based on Many-to-Many Relationship
=========================================
Talking about articles and authors, when each article may have many authors, let's say you are going to search based on a `term` and find *Articles where the article name or article abstract contains the term or one of the authors of t... | You are doing a lot of things wrong :
1. you can not use `.ToString()` on classes or lists. so first you have to remove or change these lines. for example :
```cs
sort = sort.Where(s => OfficerIDs.ToString().Contains(searchString));
sort = sort.OrderBy(s => officerList.ToString()).ThenBy(s => s.EventDate);
s... | 3,147 |
3,870,312 | I am trying to solve problem related to model inheritance in Django. I have four relevant models: `Order`, `OrderItem` which has ForeignKey to `Order` and then there is `Orderable` model which is model inheritance superclass to children models like `Fee`, `RentedProduct` etc. In python, it goes like this (posting only ... | 2010/10/06 | [
"https://Stackoverflow.com/questions/3870312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303184/"
] | Try inherit OrderItemInlineAdmin's Form a define your own Form there. But fingers crossed for that. | I'm looking for a solid answer to this very thing, but you should check out FeinCMS. They are doing this quite well.
See, for example, the FeinCMS [inline editor](https://github.com/matthiask/feincms/blob/master/feincms/admin/item_editor.py). I need to figure out how to adapt this to my code. | 3,148 |
34,910,115 | I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension.
```
coupons = []
for source in sources:
for coupon in source:
if coupon.code_used not in coupons:
coupons.append(coupon.code_used)
``` | 2016/01/20 | [
"https://Stackoverflow.com/questions/34910115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3977548/"
] | You cannot access the list you currently creating, but if the order is not important you can use a `set`:
```
coupons = set(coupon.code_used for source in sources for coupon in source)
``` | ```
used_codes = set(coupon.code_used for source in sources for coupon in source)
``` | 3,149 |
40,674,526 | I'm having trouble deploying my app to heroku, I'm using the heroku\_deploy.sh from documentation and get
```
Deploying Heroku Version 82d8ec66d98120ae24c89b88dc75e4d1c225461e
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'source_blob'
Traceback (most recent call last):
File "<s... | 2016/11/18 | [
"https://Stackoverflow.com/questions/40674526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67505/"
] | If you want to destroy the window when its closed just specifiy
```
closeAction : 'destroy'
```
instead of
```
closeAction : 'hide'
```
If doing so ExtJS destroys, and thus removes, all items completely. Additional, if specifying `destroy` as close action you will not need the additional listener (`onCardLayoutWi... | ### Thanks to oberbics and Evan Trimboli
I solve the problem, just because I assign a rownumberer like this:
>
> new Ext.grid.RowNumberer({width: 40}),
>
>
>
however, when I replace it with xtype config, it works well.
>
> {xtype: 'rownumberer'}
>
>
>
```
Ext.define('MyWebServer.view.qualityassign.Allocate... | 3,155 |
5,445,166 | I am developing a 3d shooter game that I would like to run on Computers/Phones/Tablets and would like some help to choose which engine to use.
* I would like to write the application once and port it over to Android/iOS/windows/mac with ease.
* I would like to make the application streamable over the internet.
* The e... | 2011/03/26 | [
"https://Stackoverflow.com/questions/5445166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509895/"
] | You've mentioned iOS -- that pretty much limits you to going native or using web stack. Since native is not what you want (because that'd be different for each platform you mention), you can go JavaScript. The ideal thing for that would be WebGL, but support is still experimental and not available in phone systems. You... | Well I see you've checked Unity3D already, but I can't think of any other engines work on PC, Telephones and via streaming internet that suport 3D (for 2D check EXEN or any others).
I'm also pretty sure that you can use Unity code-based, and it supports a couple of different languages, but for Unity to work you can't... | 3,156 |
34,755,636 | I am trying to show time series lines representing an effort amount using matplotlib and pandas.
I've got my DF's to all to overlay in one plot, however when I do python seems to strip the x axis of the date and input some numbers. (I'm not sure where these come from but at a guess, not all days contain the same data... | 2016/01/12 | [
"https://Stackoverflow.com/questions/34755636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3509416/"
] | When you use `getClass().getResource(...)` you are loading a resource, not specifying a path to a file. In the case where the class loader loads classes from the file system, these essentially equate to the same thing, and it does actually work (though even then there's no technical reason it has to). When the class lo... | A bit late but this can maybe help someone. If you are using IntelliJ, your `resources` folder may not be marked as THE resources folder, which has the following icon:
[](https://i.stack.imgur.com/LWBaw.png)
This is the way I fixed it:
[, quick and dirty [doctests](http://docs.python.org/2/library/doctest.html) for JavaScript and CoffeeScript. I'd like to make the library less dirty by using a JavaScript parser rather than regular expressions to locate comments.
I'd like to use [Esp... | 2013/02/06 | [
"https://Stackoverflow.com/questions/14722788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312785/"
] | Most AST-producing parsers throw away comments. I don't know what Esprima or Acorn do, but that might be the issue.
.... in fact, Esprima lists comment capture as a current bug:
<http://code.google.com/p/esprima/issues/detail?id=197>
... Acorn's code is right there in GitHub. It appears to throw comments away, too.
... | You can already use Esprima to achieve what you want:
1. Parse the code, get the comments (as an array).
2. Iterate over the comments, see if each is what you are interested in.
3. If you need to transform the comment, note its range. Collect all transformations.
4. Apply the transformation back-to-first so that the r... | 3,160 |
48,548,878 | I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5
Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback?
I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since create... | 2018/01/31 | [
"https://Stackoverflow.com/questions/48548878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3541909/"
] | The issue is likely related to [this open bug](https://code.djangoproject.com/ticket/25012) in Django. You have some test data in one of the fields that you are now converting to a ForeignKey.
For instance, maybe `department` used to be a `CharField` and you added an employee who has "test" as their `department` value... | The simplest way that works for me is changing the foreign key to a character field, Make migrations, migrate. Then change back the field to be a foreign key. This way, you will force a database alteration which is very important | 3,161 |
45,073,617 | I am use AWS with REL 7. the default EC2 mico instance has already install python.
but it encounter below error when i try to install pip by yum.
sudo yum install pip
====================
Loaded plugins: amazon-id, rhui-lb, search-disabled-repos
No package pip available.
Error: Nothing to do
Anyone advise on how to... | 2017/07/13 | [
"https://Stackoverflow.com/questions/45073617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8035222/"
] | To install pip3.6 in Amazon Linux., there is no python36-pip.
If you install python34-pip, it will also install python34 and point to it.
The best option that worked for me is the following:
```
#Download get-pip to current directory. It won't install anything, as of now
curl -O https://bootstrap.pypa.io/get-pip.py
... | The above answers seem to apply to python3 not python2
I'm running an instance where the default Python is 2.7
```
python --version
Python 2.7.14
```
I just tried to python-pip but it gave me pip for 2.6
To install pip for python 2.7 I installed the package pyton27-pip
```
sudo yum -y install python27-pip
```
Th... | 3,168 |
53,093,487 | How can I specify multi-stage build with in a `docker-compose.yml`?
For each variant (e.g. dev, prod...) I have a multi-stage build with 2 docker files:
* dev: `Dockerfile.base` + `Dockerfile.dev`
* or prod: `Dockerfile.base` + `Dockerfile.prod`
File `Dockerfile.base` (common for all variants):
```
FROM python:3.6
... | 2018/10/31 | [
"https://Stackoverflow.com/questions/53093487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3858883/"
] | As mentioned in the comments, a multi-stage build involves a single Dockerfile to perform multiple stages. What you have is a common base image.
You could convert these to a non-traditional multi-stage build with a syntax like (I say non-traditional because you do not perform any copying between the layers and instead... | you can use as well concating of docker-compose files, with including both `dockerfile` pointing to your existing dockerfiles and run `docker-compose -f docker-compose.yml -f docker-compose.prod.yml build` | 3,178 |
37,871,964 | I am calling a second python script that is written for the command line from within my script using
```
os.system('insert command line arguments here')
```
this works fine and runs the second script in the terminal. I would like this not to be output in the terminal and simply have access to the lists and variable... | 2016/06/17 | [
"https://Stackoverflow.com/questions/37871964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1244051/"
] | You have a [circular import](http://effbot.org/zone/import-confusion.htm#circular-imports):
`models.py` is importing `db` from core, and `core.py` is importing `User` from models
You should move this line:
```
from users.models import User
```
to the bottom of `core.py`. That way when `models.py` tries to import `... | It works when you import user from .models in django with version 2 and above | 3,179 |
34,113,000 | I have the following python Numpy function; it is able to take X, an array with an arbitrary number of columns and rows, and output a Y value predicted by a least squares function.
What is the Math.Net equivalent for such a function?
Here is the Python code:
```
newdataX = np.ones([dataX.shape[0],dataX.shape[1]... | 2015/12/06 | [
"https://Stackoverflow.com/questions/34113000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834415/"
] | I think you are looking for the functions on this page: <http://numerics.mathdotnet.com/api/MathNet.Numerics.LinearRegression/MultipleRegression.htm>
You have a few options to solve :
* Normal Equations : `MultipleRegression.NormalEquations(x, y)`
* QR Decomposition : `MultipleRegression.QR(x, y)`
* SVD : `MultipleRe... | You can call numpy from .NET using pythonnet (C# CODE BELOW IS COPIED FROM GITHUB):
The only "funky" part right now with pythonnet is passing numpy arrays. It is possible to convert them to Python lists at the interface, though this reduces performance for some situations.
<https://github.com/pythonnet/pythonnet/tree... | 3,180 |
27,914,930 | I'm trying to install OpenStack python novaclient using pip install python-novaclient
This task fails: netifaces.c:185:6 #error You need to add code for your platform
I have no idea what code it wants.
Does anyone understand this? | 2015/01/13 | [
"https://Stackoverflow.com/questions/27914930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518012/"
] | This has to do with the order that libraries are imported in the netifaces setup.py and is fixed in version 10.3+ (which you need to install from source). Here's how to install 10.4 (current latest release):
```
mkdir -p /tmp/install/netifaces/
cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://py... | I landed on this question while doing something similar:
```
pip install rackspace-novaclient
```
And this is what my error looked like:
```
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-G5GwYu/netifaces/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().repl... | 3,181 |
71,870,864 | I'm writing a python tool with modules at different 'levels':
* A low-level module, that can do everything, with a bit of work
* A higher level module, with added "sugar" and helper functions
I would like to be able to share function signatures from the low-level module to the higher one, so that intellisense works w... | 2022/04/14 | [
"https://Stackoverflow.com/questions/71870864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486378/"
] | While `args` [won't be null](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line#command-line-arguments) (See the green **Tip** box in the link), it might be an Array of length 0.
So `args[0]` doesn't exist because it refers to the first item in the array, which doesn't hav... | How do you start Main function (program)? Do you pass arguments to Main function? If not, lenght of your args array is 0 (you don't have any fields in that array). | 3,186 |
56,695,227 | I'm using `tf.estimator` API with TensorFlow 1.13 on Google AI Platform to build a DNN Binary Classifier. For some reason I don't get a `eval` graph but I do get a `training` graph.
Here are two different methods for performing training. The first is the normal python method and the second is using GCP AI Platform in ... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56695227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008596/"
] | With the comment and suggestions as well as tweaking the parameters, here is the result which works for me.
The code to start the tensorboard, train the model etc. Using ------- to denote a notebook cell
---
```
%%bash
# clean model output dirs
# This is so that the trained model is deleted
output_dir=${PWD}/${TRAIN... | In `estimator.train_and_evaluate()` you specify a `train_spec` and an `eval_spec`. The `eval_spec` often has a different input function (e.g. development evaluation dataset, non-shuffled)
Every N steps, a checkpoint from the train process is saved, and the eval process loads those same weights and runs according to th... | 3,189 |
71,276,514 | I had everything working fine, then out of nowhere I keep getting this
```
PS C:\Users\rygra\Documents\Ryan Projects\totalwine-product-details-scraper> ensurepip
ensurepip : The term 'ensurepip' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or... | 2022/02/26 | [
"https://Stackoverflow.com/questions/71276514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18312732/"
] | Add param `android:exported` in `AndroidManifest.xml` file under `activity`
Like below code:
```
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.int... | Goto **AndroidManifest.xml** and add the following line to each activity
```
<activity
android:name=".MainActivity"
android:exported="true" />
``` | 3,190 |
12,755,804 | I am trying to run a python script on my mac .I am getting the error :-
>
> ImportError: No module named opengl.opengl
>
>
>
I googled a bit and found that I was missing pyopengl .I installed pip.I go to the directory pip-1.0 and then say
>
> sudo pip install pyopengl
>
>
>
and it installs correctly I beli... | 2012/10/06 | [
"https://Stackoverflow.com/questions/12755804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/592667/"
] | Is it in the PYTHON-PATH? Maybe try something like this:
```
import sys
sys.path.append(opengl-dir)
import opengl.opengl
```
Replace the opengl-dir with the directory that you have installed in...
Maybe try what RocketDonkey is suggesting...
I don't know, really... | Thanks guys! I figured it out.It was infact a separate module which I needed to copy over to the "site-packages" location and it worked fine.So in summary no issues with the path just that the appropriate module was not there. | 3,191 |
11,713,871 | I am playing with Heroku to test how good it is for Django apps.
I created a simple project with two actions:
1. return simple hello world
2. generate image and send it as response
I used `siege -c10 -t30s` to test both Django dev server and gunicorn (both running on Heroku). These are my results:
**Simple hello w... | 2012/07/29 | [
"https://Stackoverflow.com/questions/11713871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513686/"
] | Are settings the same? Django 1.4 dev server is multithreaded by default and there is only 1 sync worker in gunicorn default config. | You're going to have to set up [application profiling](http://docs.python.org/library/profile.html) to gain some insight into where exactly the problem is located. | 3,192 |
45,877,080 | I'm trying to create a dropdown menu in HTML using info from a python script. I've gotten it to work thus far, however, the html dropdown displays all 4 values in the lists as 4 options.
Current: **Option 1:** Red, Blue, Black Orange; **Option 2:** Red, Blue, Black, Orange etc. (Screenshot in link)
[Current](https://i... | 2017/08/25 | [
"https://Stackoverflow.com/questions/45877080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8515504/"
] | you have a typo, replace `colours` to `colour`
```
<option value= "{{colour}}" SELECTED>{{colours}}</option>"
```
replace to
```
<option value= "{{colour}}" SELECTED>{{ colour }}</option>"
<!-- ^^^^ -->
``` | You need to use `{{colour}}` in both places (instead of `{{colours}}` in the second place):
```
<select name="colour" method="GET" action="/">
{% for colour in colours %}
<option value="{{colour}}" SELECTED>{{colour}}</option>"
{% endfor %}
</select>
```
Note that using `selected` inside the loop wil... | 3,194 |
37,691,552 | I have the following code that is leveraging multiprocessing to iterate through a large list and find a match. How can I get all processes to stop once a match is found in any one processes? I have seen examples but I none of them seem to fit into what I am doing here.
```
#!/usr/bin/env python3.5
import sys, itertool... | 2016/06/08 | [
"https://Stackoverflow.com/questions/37691552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109254/"
] | You can check [this question](https://stackoverflow.com/questions/33447055/python-multiprocess-pool-how-to-exit-the-script-when-one-of-the-worker-process/33450972#33450972) to see an implementation example solving your problem.
This works also with concurrent.futures pool.
Just replace the `map` method with `apply_as... | `multiprocessing` isn't really designed to cancel tasks, but you can simulate it for your particular case by using `pool.imap_unordered` and terminating the pool when you get a hit:
```
def do_job(first_bits):
for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)):
# CHECK FOR MAT... | 3,195 |
21,995,255 | i'm trying to use BeautifulSoup on my NAS, that is the model in the title, but i am not able to install it, with the `ipkg list` there isn't a package named BeautifulSoup.
On my NAS i have this version of python:
```
Python 2.5.6 (r256:88840, Feb 16 2012, 08:51:29)
[GCC 3.4.3 20041021 (prerelease)] on linux2
```
So... | 2014/02/24 | [
"https://Stackoverflow.com/questions/21995255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678833/"
] | In this case I suppose that you can't even install pip to manage your Python dependencies. One way of doing so would be to download the source from <http://www.crummy.com/software/BeautifulSoup/bs3/download//3.x/>, download the tarball for your preferred version. Once done, unzip it cd into the folder and type:
```
$ ... | You can if you install python3 from the package manager:
```
ashton@NASty:~/bin/three/$ pip install beautifulsoup4 -- user
Requirement already satisfied: beautifulsoup4 in
/volume1/@appstore/py3k/usr/local/lib/python3.5/site-packages (4.8.0)
Requirement already satisfied: soupsieve>=1.2 in
/volume1/@appstore/py3k/u... | 3,196 |
39,215,663 | I think I have the same issue as [here on SO.](https://stackoverflow.com/questions/28323644/flask-sqlalchemy-backref-not-working) Using python 3.5, flask-sqlalchemy, and sqlite. I am trying to establish a one (User) to many (Post) relationship.
```
class User(db_blog.Model):
id = db_blog.Column(db_blog.Integer, pr... | 2016/08/29 | [
"https://Stackoverflow.com/questions/39215663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5795832/"
] | If you add the newly created `post` to the `posts` attribute of the user, it will work:
```
>>> u = User(nickname="John Doe", email="jdoe@email.com")
>>> u
<User: John Doe>
>>> db_blog.session.add(u)
>>> p = Post(body="Body of post", title="Title of Post")
>>> p
<Title: Title of Post
Post: Body of post
Author: None>
>... | You added your own `__init__` to `Post`. While it accepts keyword arguments, it does nothing with them. You can either update it to use them
```
def __init__(self, body, title, **kwargs):
self.body = body
self.title = title
for k, v in kwargs:
setattr(self, k, v)
```
Or, ideally, you can just re... | 3,197 |
15,481,808 | I'm trying to set the figure size with `fig1.set_size_inches(5.5,3)` on python, but the plot produces a fig where the x label is not completely visibile. The figure itself has the size I need, but it seems like the axis inside is too tall, and the x label just doesn't fit anymore.
here is my code:
```
fig1 = plt.fig... | 2013/03/18 | [
"https://Stackoverflow.com/questions/15481808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862909/"
] | You could order the save method to take the artist of the x-label into consideration.
This is done with the bbox\_extra\_artists and the tight layout.
The resulting code would be:
```
import matplotlib.pyplot as plt
fig1 = plt.figure()
fig1.set_size_inches(5.5,4)
fig1.set_dpi(300)
ax = fig1.add_subplot(111)
ax.grid(... | It works for me if I initialize the figure with the `figsize` and `dpi` as `kwargs`:
```
from numpy import random
from matplotlib import pyplot as plt
driveDistance = random.exponential(size=100)
fig1 = plt.figure(figsize=(5.5,4),dpi=300)
ax = fig1.add_subplot(111)
ax.grid(True,which='both')
ax.hist(driveDistance,100)... | 3,198 |
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 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... | 3,199 |
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... | 3,204 |
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... | 3,205 |
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> | 3,206 |
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... | 3,208 |
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... | 3,209 |
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... | 3,212 |
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* | 3,213 |
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... | 3,215 |
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/)** | 3,216 |
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" | 3,226 |
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[$... | 3,227 |
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... | 3,228 |
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 | 3,229 |
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>);
``` | 3,230 |
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... | 3,233 |
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])` | 3,243 |
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,246 |
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... | 3,251 |
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... | 3,252 |
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`. | 3,253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.