qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
50,669,200 | 
I need your help in understanding the distribution plot. I was going through tutorial on [this link](http://devarea.com/python-machine-learning-example-linear-regression/#.WxQmilMvxsN). At the end of the post they have mentioned:
>
> We can see fro... | 2018/06/03 | [
"https://Stackoverflow.com/questions/50669200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8285020/"
] | Reading through your comments, it is difficult to understand where exactly you are having a problem. I'm going to assume it's because you did not know how to write the other initializer due to your first comment:
```
`my object is simple "stuct" and I could not make "(dictionary: data)" -call.`
```
Here's the initia... | I finally found that simply swift firestore sdk still missing that function but it seams like it is in works and you can find discussion about that in [here](https://github.com/firebase/firebase-ios-sdk/issues/627)
>
> ...We've had something like this on our radar for a bit. Essentially we want to provide an equival... |
21,611,328 | I'm trying to unzip a file with `7z.exe` and the password contains special characters on it
EX. `&)kra932(lk0¤23`
By executing the following command:
```
subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip'])
```
`7z.exe` launches fine but it says the password is wrong.
This is a f... | 2014/02/06 | [
"https://Stackoverflow.com/questions/21611328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2065094/"
] | There is a big security risk in passing the password on the command line. With administrative rights, it is possible to retrieve that information (startup info object) and extract the password. A better solution is to open 7zip as a process, and feed the password into its standard input.
Here is an example of a comman... | I'd suggest using a raw string and the shlex module (esp. on Windows) and NOT supporting any encoding other than ASCII.
```
import shlex
import subprocess
cmd = r'7z.exe x -y -p^&moreASCIIpasswordchars file.zip'
subprocess.call(shlex.split(cmd))
```
Back to the non-ASCII character issue...
I'm pretty sure in Pytho... |
21,611,328 | I'm trying to unzip a file with `7z.exe` and the password contains special characters on it
EX. `&)kra932(lk0¤23`
By executing the following command:
```
subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip'])
```
`7z.exe` launches fine but it says the password is wrong.
This is a f... | 2014/02/06 | [
"https://Stackoverflow.com/questions/21611328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2065094/"
] | There is a big security risk in passing the password on the command line. With administrative rights, it is possible to retrieve that information (startup info object) and extract the password. A better solution is to open 7zip as a process, and feed the password into its standard input.
Here is an example of a comman... | Try to put double quotes between your password, otherwise the cmd parser would any parse special character as is instead of taking it as part of the password.
For example,
`7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip` won't work.
But `7z.exe x -y -p"s^&)kratsaslkd932(lkasdf930¤23" file.zip` would definite... |
74,611,463 | I have this code
```
import numpy
a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1)
print(a)
```
50% of the times I execute it it prints a normal array, 50% of times it prints this
```
[[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000 1.00000000e+000 1.0... | 2022/11/29 | [
"https://Stackoverflow.com/questions/74611463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15673832/"
] | You can use [apache\_beam.io.jdbc](https://beam.apache.org/releases/pydoc/current/apache_beam.io.jdbc.html) to read from your MySQL database, and the [BigQuery I/O](https://beam.apache.org/documentation/io/built-in/google-bigquery/) to write on BigQuery.
Beam knowledge is expected, so I recommend looking at [Apache Be... | If you only want to copy data from `MySQL` to `BigQuery`, you can firstly export your `MySql` data to `Cloud Storage`, then load this file to a `BigQuery` table.
I think no need using `Dataflow` in this case because you don't have complex transformations and business logics. It only corresponds to a copy.
[Export](ht... |
62,482,387 | I have done everything the documentation says to.
* I added pip path and it is working but the python command is not working. [Image of path to my python38 DLL](https://i.stack.imgur.com/HSGzo.png)
* The pip path which I added: `C:\Users\Harshal\AppData\Local\Programs\Python\Python38\Scripts
python path : C:\Users\Ha... | 2020/06/20 | [
"https://Stackoverflow.com/questions/62482387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10537108/"
] | In some cases, `py` command works as well as `python` command, so you can try `py`:
```
py -V
py -m pip # this is for pip, exactly for this python version
``` | Add your python to system environment variables like your path.
or Reinstall python and check the Add to path Checkbox while installing
```
Add to path
``` |
64,652,322 | I'm currently struggling with python's bit operations as in python3 there is no difference anymore between 32bit integers (int) and 64bit integers (long).
What I want is an **efficient** function that takes any integer and cuts the most significant 32 bits and then converts these 32 bits back to an integer with the co... | 2020/11/02 | [
"https://Stackoverflow.com/questions/64652322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10684977/"
] | Significantly simpler solution: Let [`ctypes`](https://docs.python.org/3/library/ctypes.html) do the work for you.
```
from ctypes import c_int32
def int32(val):
return c_int32(val).value
```
That just constructs a `c_int32` type from the provided Python `int`, which truncates as you desire, then extracts the v... | use bitstring library which is excellent.
```
from bitstring import BitArray
x = BitArray(bin='11000100010100010110101011111010')
print(x.int)
``` |
20,534,999 | Here is an example of failure from a shell.
```
>>> from traits.api import Dict
>>> d=Dict()
>>> d['Foo']='BAR'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Dict' object does not support item assignment
```
I have been searching all over the web, and there is no indication of... | 2013/12/12 | [
"https://Stackoverflow.com/questions/20534999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2121874/"
] | I think your basic problem has to do with notification issues for traits that live outside the model object, and not with "how to access those objects" per se [edit: actually no this is not your problem at all! But it is what I thought you were trying to do when I read your question with my biased mentality towards pro... | Okay, I found the answer (kindof) in this question: [Traits List not reporting items added or removed](https://stackoverflow.com/questions/19041426/traits-list-not-reporting-items-added-or-removed)
when including Dict or List objects as attributes in a class one should NOT do it this way:
```
class Foo(HasTraits):
... |
66,047,199 | So what i am basically trying to do is groups a set of mongo docs having the same `key:value` pair and return them in the form of a list of list.
EX:
```
{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}
```
Output:
```
{"result": [ [{"client":"abp","product":"a"},{"clien... | 2021/02/04 | [
"https://Stackoverflow.com/questions/66047199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12408855/"
] | I would group by client and then create and array of product using $push. $push allows you to insert each grouped object in an array.
```
db.yourcollection.aggregate([
{
$group: {
_id: '$client',
products: {$push: {client: '$client', product: '$product'}}
}
}])
``` | ```
from operator import itemgetter
from itertools import groupby
x=[{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}]
x.sort(key=itemgetter('client'),reverse=True)
d=[list(g) for (k,g) in groupby(x,itemgetter('client'))]
final = {}
final['result']=d
Output:
{'result': [[{... |
34,651,824 | Currently `--resize` flag that I created is boolean, and means that all my objects will be resized:
```
parser.add_argument("--resize", action="store_true", help="Do dictionary resize")
# ...
# if resize flag is true I'm re-sizing all objects
if args.resize:
for object in my_obects:
object.do_resize()
`... | 2016/01/07 | [
"https://Stackoverflow.com/questions/34651824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524743/"
] | In order to optionally accept a value, you need to set [`nargs`](https://docs.python.org/2/library/argparse.html#nargs) to `'?'`. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s [`const`](https://docs.pyt... | You can add `default=False`, `const=True` and `nargs='?'` to the argument definition and remove `action`. This way if you don't pass `--resize` it will store False, if you pass `--resize` with no argument will store `True` and otherwise the passed argument. Still you will have to refactor the code a bit to know if you ... |
34,651,824 | Currently `--resize` flag that I created is boolean, and means that all my objects will be resized:
```
parser.add_argument("--resize", action="store_true", help="Do dictionary resize")
# ...
# if resize flag is true I'm re-sizing all objects
if args.resize:
for object in my_obects:
object.do_resize()
`... | 2016/01/07 | [
"https://Stackoverflow.com/questions/34651824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524743/"
] | In order to optionally accept a value, you need to set [`nargs`](https://docs.python.org/2/library/argparse.html#nargs) to `'?'`. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s [`const`](https://docs.pyt... | Use `nargs` to accept different number of command-line arguments
Use `default` and `const` to set the default value of resize
see here for details: <https://docs.python.org/3/library/argparse.html#nargs>
```
parser.add_argument('-resize', dest='resize', type=int, nargs='?', default=False, const=True)
>>tmp.py -resi... |
24,818,096 | I am new to python app development. When I tried a code I'm not able to see its output. My sample code is:
```
class name:
def __init__(self):
x = ''
y = ''
print x,y
```
When i called the above function like
```
some = name()
some.x = 'yeah'
some.x.y = 'hell'
```
When i called `some.... | 2014/07/18 | [
"https://Stackoverflow.com/questions/24818096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843420/"
] | First of all, you are defining the class with the wrong way, you should;
```
class name:
def __init__(self):
self.x = ''
self.y = ''
print x,y
```
Then, you are calling the wrong way, you should;
```
some = name()
some.x = 'yeah'
some.y = 'hell'
```
The problem is, `x` and `y` are `str... | `x` and `y` are two different variables on your instance `some`.
When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`.
So what you want to do is:
```
some = name()
some.x = 'hell'
some.... |
24,818,096 | I am new to python app development. When I tried a code I'm not able to see its output. My sample code is:
```
class name:
def __init__(self):
x = ''
y = ''
print x,y
```
When i called the above function like
```
some = name()
some.x = 'yeah'
some.x.y = 'hell'
```
When i called `some.... | 2014/07/18 | [
"https://Stackoverflow.com/questions/24818096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843420/"
] | `x` and `y` are two different variables on your instance `some`.
When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`.
So what you want to do is:
```
some = name()
some.x = 'hell'
some.... | These are different variables. So when you do chain .y onto some.x you are looking for a member variable y of a string which does not exist
```
some = name()
some.x = 'yeah'
some.y = 'hell'
```
if you want to make a single string out of both x and y you can use + to concatenate them together as follows
```
s = some... |
24,818,096 | I am new to python app development. When I tried a code I'm not able to see its output. My sample code is:
```
class name:
def __init__(self):
x = ''
y = ''
print x,y
```
When i called the above function like
```
some = name()
some.x = 'yeah'
some.x.y = 'hell'
```
When i called `some.... | 2014/07/18 | [
"https://Stackoverflow.com/questions/24818096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843420/"
] | `x` and `y` are two different variables on your instance `some`.
When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`.
So what you want to do is:
```
some = name()
some.x = 'hell'
some.... | When you perform `some.x` you are no longer dealing with the `some`, you are dealing with the type that `some.x` is. Since `'foo'.y` doesn't make sense, you cannot do it with `some.x` either since it is of the same type as `'foo'`. |
24,818,096 | I am new to python app development. When I tried a code I'm not able to see its output. My sample code is:
```
class name:
def __init__(self):
x = ''
y = ''
print x,y
```
When i called the above function like
```
some = name()
some.x = 'yeah'
some.x.y = 'hell'
```
When i called `some.... | 2014/07/18 | [
"https://Stackoverflow.com/questions/24818096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843420/"
] | First of all, you are defining the class with the wrong way, you should;
```
class name:
def __init__(self):
self.x = ''
self.y = ''
print x,y
```
Then, you are calling the wrong way, you should;
```
some = name()
some.x = 'yeah'
some.y = 'hell'
```
The problem is, `x` and `y` are `str... | These are different variables. So when you do chain .y onto some.x you are looking for a member variable y of a string which does not exist
```
some = name()
some.x = 'yeah'
some.y = 'hell'
```
if you want to make a single string out of both x and y you can use + to concatenate them together as follows
```
s = some... |
24,818,096 | I am new to python app development. When I tried a code I'm not able to see its output. My sample code is:
```
class name:
def __init__(self):
x = ''
y = ''
print x,y
```
When i called the above function like
```
some = name()
some.x = 'yeah'
some.x.y = 'hell'
```
When i called `some.... | 2014/07/18 | [
"https://Stackoverflow.com/questions/24818096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843420/"
] | First of all, you are defining the class with the wrong way, you should;
```
class name:
def __init__(self):
self.x = ''
self.y = ''
print x,y
```
Then, you are calling the wrong way, you should;
```
some = name()
some.x = 'yeah'
some.y = 'hell'
```
The problem is, `x` and `y` are `str... | When you perform `some.x` you are no longer dealing with the `some`, you are dealing with the type that `some.x` is. Since `'foo'.y` doesn't make sense, you cannot do it with `some.x` either since it is of the same type as `'foo'`. |
72,462,419 | Given a website (for example stackoverflow.com) I want to download all the files under:
```
(Right Click) -> Inspect -> Sources -> Page
```
Please Try it yourself and see the files you get.
**How can I do that in python?**
I know how to retrive page source but not the source files.
I tried searching this multiple ... | 2022/06/01 | [
"https://Stackoverflow.com/questions/72462419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19248696/"
] | To download website source files (mirroring websites / copy source files from websites) you may try [`PyWebCopy`](https://github.com/rajatomar788/pywebcopy/) library.
To save any single page -
```
from pywebcopy import save_webpage
save_webpage(
url="https://httpbin.org/",
project_folder="E://savedpages//... | The easiest way to do this is definitely not with Python.
As you seem to know, you can download code to a single site w/ Command click > View Page Source or the sources tab of inspect element. To download all the files in a website's structure, you should use a web-scraper.
For Mac, SiteSucker is your best option if ... |
63,158,692 | **Summarize the problem:**
The Python package basically opens PDFs in batch folder, reads the first page of each PDF, matches keywords, and dumps compatible PDFs in source folder for OCR scripts to kick in. The first script to take all PDFs are **MainBankClass.py**. I am trying to use a docker-compose file to include ... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63158692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12961386/"
] | >
> single application in a single container ... need networks for different py files to communicate
>
>
>
You only have one container. Docker networks are for multiple containers to talk to one another. And Docker Compose has a default bridge network defined for all services, so you shouldn't need that if you wer... | So after days of searching regarding my case, I am closing this thread with an implementation of **single application in a single container** suggested on [this link](https://forums.docker.com/t/is-it-possible-to-run-python-package-with-multiple-py-scripts-in-docker-compose-yml/97094/8) from docker forum. Instead of go... |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text.
This code should work:
```
#!/usr/bin/python
print "Cont... | Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving. |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | OK last guess:
Trying changing that shebang line to:
```
#!/usr/bin/env python
```
or
```
#!/usr/bin/local/env python
```
It would also be helpful to know your platform / hosting provider. | If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct.
1. Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line.
2. Make sure there is space after print "Content-type: text/html" ie.
... |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | This is the exact behavior you would get if your Python script does not have the executable permission set.
Try:
```
chmod a+x foo.py
```
(where foo.py is your script name).
See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information. | One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text.
This code should work:
```
#!/usr/bin/python
print "Cont... |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct.
1. Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line.
2. Make sure there is space after print "Content-type: text/html" ie.
... | I tried many approaches to get Python working with Apache properly and finally settled with using **Apache + mod\_WSGI + [web.py](http://webpy.org/cookbook/mod_wsgi-apache)** . It sounds like a lot, but it is much simpler than using the complicated frameworks like Django out there.
(You're right, don't bother with mo... |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | This is the exact behavior you would get if your Python script does not have the executable permission set.
Try:
```
chmod a+x foo.py
```
(where foo.py is your script name).
See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information. | I tried many approaches to get Python working with Apache properly and finally settled with using **Apache + mod\_WSGI + [web.py](http://webpy.org/cookbook/mod_wsgi-apache)** . It sounds like a lot, but it is much simpler than using the complicated frameworks like Django out there.
(You're right, don't bother with mo... |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | You may also get a better error message by adding this line at the top of your Python script:
`import cgitb; cgitb.enable()`
Also, the header should be capitalized `Content-Type`, not `Content-type`, although I doubt that that is breaking anything. | This ended up being a `dos2unix` issue for me. Ran `dos2unix test.py test.py` and it worked. The `\r\n` combinations were the problem. Had to `yum install dos2unix` to get it installed. |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | do you have something like this at the top before you print anything else?
```
print "Content-type: text/html\n"
```
If you already have this, then post your code. | You can also get some of this same foolishness if you have DOS style end of lines on a linux web server. (That just chewed up about two hours of my morning today.) Off to update my vim.rc on this windows box that I need to use. |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | do you have something like this at the top before you print anything else?
```
print "Content-type: text/html\n"
```
If you already have this, then post your code. | If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct.
1. Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line.
2. Make sure there is space after print "Content-type: text/html" ie.
... |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | This is the exact behavior you would get if your Python script does not have the executable permission set.
Try:
```
chmod a+x foo.py
```
(where foo.py is your script name).
See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information. | Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving. |
378,811 | I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper lin... | 2008/12/18 | [
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] | Two things spring immediately to mind.
1. Make sure you are outputting the `Content-Type: text/html` header
2. Make sure you are adding two newlines ("\n") after the headers before you output "Hello, world" or whatever. | You can also get some of this same foolishness if you have DOS style end of lines on a linux web server. (That just chewed up about two hours of my morning today.) Off to update my vim.rc on this windows box that I need to use. |
58,604,645 | I want to get all the installed patches on an `AWS EC2 instance`, So I run this code in `boto3`:
```
response = client.describe_instance_patches(InstanceId=instance_id, Filters=[{'Key': 'State','Values': ['Installed',]} ])
```
My instance has a patch with a negative timestamp :
```
{
"Patches": [
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58604645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2337243/"
] | Assuming this is nothing to with service worker/PWA, the solution could be implemented by returning the front end version by letting the server return the current version of the Vue App everytime.
`axiosConfig.js`
```
axios.interceptors.response.use(
(resp) => {
let fe_version = resp.headers['fe-version'] || 'd... | A possible problem could be that the browser is caching the `index.html` file.
Try to disable cache for `index.html` like this:
```
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" conten... |
49,604,025 | I'm trying to translate code that generates a Voronoi Diagram from Javascript into Python. This is a struggle because I don't know Javascript. I think I can sort-of make it out, but I'm still running into issues with things I don't understand. Please help me figure out what is wrong with my code.
The code I've written... | 2018/04/02 | [
"https://Stackoverflow.com/questions/49604025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944978/"
] | This seems a little bit like homework, so lets try to get you on the right track over outright providing the code to accomplish this.
You're going to want to create a loop that performs your code a certain number of times. Let's say we just want to output a certain string 5 times. As an example, here's some really sim... | This worked for me. It creates a table using the .messagebox module. You can enter your name into the entry label. Then, when you click the button it returns "Hello (name)".
```
from tkinter import *
from tkinter.messagebox import *
master = Tk()
label1 = Label(master, text = 'Name:', relief = 'groove', width = 19)
e... |
55,927,009 | I'm trying to write a script that creates a playlist on my spotify account in python, from scratch and not using a module like *spotipy*.
My question is how do I authenticate with my client id and client secret key using the *requests* module or grab an access token using those credentials? | 2019/04/30 | [
"https://Stackoverflow.com/questions/55927009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9128668/"
] | Try this full Client Credentials Authorization flow.
First step – get an authorization token with your credentials:
```
CLIENT_ID = " < your client id here... > "
CLIENT_SECRET = " < your client secret here... > "
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
url='https://accounts.spo... | As it is referenced [here](https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/), you have to give the Bearer token to the Authorization header, and using requests it is done by declaring the "headers" optional:
```py
r = requests.post(url="https://api.spotify.com/v1/users/{your-use... |
72,230,877 | So I had created a python web scraper for my college capstone project that scraped around the web and followed links based on a random selection from the page. I utilized Python's request module to return links from a get request. I had it working flawlessly along with a graphing program that showed the program working... | 2022/05/13 | [
"https://Stackoverflow.com/questions/72230877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13450139/"
] | `Requests.Response.links` doesn't work like that [1]. It looks for [Links in the Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link), not link elements in the Response body.
What you want is to extract link *elements* from the Response body, so I would recommend something like `lxml` or `beautifuls... | Parsing links with `beautifulsoup4` is a possible solution:
```py
import requests
from bs4 import BeautifulSoup
def get_links(url: str) -> list[str]:
with requests.get(url) as response:
soup = BeautifulSoup(response.text, features='html.parser')
links = []
for link in soup.find_all('a'):
... |
62,556,358 | Sometimes when I run the code it gives me the correct output, other times it says "List index out of range" and other times it just continues following code. I found the code on: <https://www.codeproject.com/articles/873060/python-search-youtube-for-video>
How can I fix this?
```
searchM = input("Enter the movie you ... | 2020/06/24 | [
"https://Stackoverflow.com/questions/62556358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13757098/"
] | The error occurs when no 'search results' have been obtained, such that search\_results[0] cannot be found.
I would suggest you use an 'if/else' statement, something like:
```
if len(search_results) == 0:
print("No search results obtained. Please try again.")
else:
print("Click on the link to watch the trail... | search[0] will return the first element of the list. However, if there are no elements in the list, there will not be a first element in the list, and "List index out of range". I recommend adding an if statement to check if the length of search\_results is greater than 0 and then printing search[0]. Hope this helps!
... |
51,140,417 | For the past 4 days I have been working to get taskwarrior and taskwarrior server running on windows 10. It has proven quite a challenge for me.
I followed the steps written below: "Building the Stable Version" on <https://taskwarrior.org/docs/build.html> and created a folder:
```
C:\taskwarrior
```
Opened Develope... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51140417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] | I'm not sure that it is still relevant to your problem, but I was able to build taskwarrior v2.5.1 under 64-bit cygwin (on Win7), using the `cmake` line from here: [TW-1845 Cygwin build fails, missing get\_current\_dir\_name](https://github.com/GothenburgBitFactory/taskwarrior/issues/1861)
Namely, this `cmake` line fo... | I am likely to have misunderstood the context. GnuTLS Appears to be a program that works/is made for a linux/debian operating system.
Nevertheless, the following two solutions were effective in:
1. Finding and using the UUID library in Windows.
2. Solving the XY-problem and using GnuTLS on a "windows pc" (with Linux... |
33,355,299 | I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2483176/"
] | If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just:
```
In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list]
Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
And, similarly via [`itertools.chain()`](https://stackove... | You could use this recursive subroutine
```
def flatten(lst, n):
if n == 0:
return lst
return flatten([j for i in lst for j in i], n - 1)
mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]
flatten(mylist, 1)
#=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
flatten(mylist, 2)
#=> [1, 2,... |
33,355,299 | I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2483176/"
] | If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just:
```
In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list]
Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
And, similarly via [`itertools.chain()`](https://stackove... | This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after:
```
def flatten(lists,n):
if n == 1:
return [x for xs in lists for x in xs]
else:
return [flatten(xs,n-1) for xs in lists]
>>> flatten(my_list,1)
[[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4... |
33,355,299 | I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2483176/"
] | If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just:
```
In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list]
Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
And, similarly via [`itertools.chain()`](https://stackove... | For this particular case,
```
In [1]: [sum(x,[]) for x in my_list]
Out[1]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
is the shortest and the fastest method:
```
In [7]: %timeit [sum(x,[]) for x in my_list]
100000 loops, best of 3: 5.93 µs per loop
``` |
33,355,299 | I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2483176/"
] | This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after:
```
def flatten(lists,n):
if n == 1:
return [x for xs in lists for x in xs]
else:
return [flatten(xs,n-1) for xs in lists]
>>> flatten(my_list,1)
[[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4... | You could use this recursive subroutine
```
def flatten(lst, n):
if n == 0:
return lst
return flatten([j for i in lst for j in i], n - 1)
mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]
flatten(mylist, 1)
#=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
flatten(mylist, 2)
#=> [1, 2,... |
33,355,299 | I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2483176/"
] | This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after:
```
def flatten(lists,n):
if n == 1:
return [x for xs in lists for x in xs]
else:
return [flatten(xs,n-1) for xs in lists]
>>> flatten(my_list,1)
[[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4... | For this particular case,
```
In [1]: [sum(x,[]) for x in my_list]
Out[1]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
is the shortest and the fastest method:
```
In [7]: %timeit [sum(x,[]) for x in my_list]
100000 loops, best of 3: 5.93 µs per loop
``` |
35,494,331 | How can I get generics to work in Python.NET with CPython. I get an error when using the subscript syntax from [Python.NET Using Generics](http://pythonnet.sourceforge.net/readme.html#generics)
```
TypeError: unsubscriptable object
```
With Python 2.7.11 + pythonnet==2.1.0.dev1
```
>python.exe
Python 2.7.11 (v2.7.1... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35494331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742745/"
] | You can get the generic class object explicitly:
```
EventHandler = getattr(System, 'EventHandler`1')
```
The number indicates the number of generic arguments. | That doesn't work because there are both generic and non-generic versions of the `EventHandler` class that exist in the `System` namespace. The name is overloaded. You need to indicate that you want the generic version.
I'm not sure how exactly Python.NET handles overloaded classes/functions but it seems like it has a... |
30,189,013 | is the code he wants me to enter that fails
```
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
```
is the code I modified after seeing e... | 2015/05/12 | [
"https://Stackoverflow.com/questions/30189013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4891078/"
] | Here is one method:
```
select v.*
from vusearch as v
where v.JobId = (select max(v2.JobId)
from vusearch as v2
where v2.AddressId = v.AddressId
);
``` | Managed to get it fixed - I probably hadn't provided enough information as I was trying to keep my explanation simple.
Many thanks for your help Gordon
((vuSearch.PDID) IN ( (SELECT Max(v2.PDID) FROM vuSearch AS v2 GROUP BY v2.PAID))) |
51,947,819 | I have a pandas dataframe with 5 years daily time series data. I want to make a monthly plot from whole datasets so that the plot should shows variation (std or something else) within monthly data. Simillar figure I tried to create but did not found a way to do that:
[? If you do, this may help you:
```
df['month'] = df.index.strftime("%m-%d")
df['year'] = df.index.year
df.set_index(['month']).drop(['year'],1).plot()
``` |
67,010,037 | I am not an expert in python. When I run this code, I get an error stating that the source is empty. It occurs in the statement that converts bgr to rgb from a live video feed. I also attached some of the error code below. I did try to resolve it changing some of it, but it did not work out. So, if you have any ideas, ... | 2021/04/08 | [
"https://Stackoverflow.com/questions/67010037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14020038/"
] | You can use `Series.isin`:
```
In [1998]: res = df1[df1.id_number.isin(df2.id_number) & df1.accuracy.ge(85)]
In [1999]: res
Out[1999]:
Name Contact_number id_number accuracy
0 Eric 9786543628 AZ256hy 90
1 Jack 9786543628 AZ98kds 85
```
**EDIT:** If you want only certain columns:
... | Edit:
I made changes to the conditions. This should work
```
df = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet1')
df2 = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet2')
df.loc[(df['id_number'] == df2['id_number']) & (df['accuracy']>= 85),['Name','Contact_number', 'id_number']]
``` |
28,458,785 | How can I pass a `sed` command to `popen` without using a raw string?
When I pass an sed command to `popen` in the list form I get an error: `unterminated address regex` (see first example)
```python
>>> COMMAND = ['sed', '-i', '-e', "\$amystring", '/home/map/myfile']
>>> subprocess.Popen(COMMAND).communicate(input=N... | 2015/02/11 | [
"https://Stackoverflow.com/questions/28458785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659599/"
] | The difference between the two forms is that with `shell=True` as an argument, the string gets passed as is to the shell, which then interprets it. This results in (with bash):
```
sed -i -e \$amystring /home/map/myfile
```
being run.
With the list args and the default `shell=False`, python calls the executable dir... | There is not such thing as a raw string. There are only raw string *literals*.
A literal -- it is something that you type in the Python source code.
`r'\$amystring'` and `'\\$amystring'` are the same *strings objects* despite being represented using different string *string literals*.
As [@Jonathan Villemaire-Krajde... |
65,354,710 | I was trying to Connect and Fetch data from BigQuery Dataset to Local Pycharm Using Pyspark.
I ran this below Script in Pycharm:
```
from pyspark.sql import SparkSession
spark = SparkSession.builder\
.config('spark.jars', "C:/Users/PycharmProjects/pythonProject/spark-bigquery-latest.jar")\
.getOrCreate()
co... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65354710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10030455/"
] | Start your file system references with `file:///c:/...` | You need to replace `/` with `\` for the path to work |
29,580,828 | I'm starting with Docker. I have started with a Hello World script in Python 3. This is my Dockerfile:
```
FROM ubuntu:latest
RUN apt-get update
RUN apt-get install python3
COPY . hello.py
CMD python3 hello.py
```
In the same directory, I have this python script:
```
if __name__ == "__main__":
print("Hello W... | 2015/04/11 | [
"https://Stackoverflow.com/questions/29580828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026283/"
] | Thanks to Gerrat, I solved it this way:
```
COPY hello.py hello.py
```
instead of
```
COPY . hello.py
``` | You need to install python this way and confirm it with the -y.
RUN apt-get update && apt-get install python3-dev -y |
25,561,020 | Below are the snippets of my code regarding file upload.
Here is my HTML code where I will choose and upload the file:
```html
<form ng-click="addImportFile()" enctype="multipart/form-data">
<label for="importfile">Import Time Events File:</label><br><br>
<label for="select_import_file">SELECT FILE:</label><b... | 2014/08/29 | [
"https://Stackoverflow.com/questions/25561020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3988760/"
] | Hi I can finally upload the file, I change the angular part, I change it by this:
```
$scope.addImportFile = function() {
var f = document.getElementById('file').files[0]; console.log(f);
var formData = new FormData();
formData.append('file', f);
$http({method: 'POST', url: '... | The first thing is about the post request. Without ng-click="addImportFile()", the browser will usually take care of serializing form data and sending it to the server. So if you try:
```
<form method="put" enctype="multipart/form-data" action="http://127.0.0.1:5000/api/v1.0/upload_file">
<label for="importfile">I... |
62,497,777 | Can't start server using Apache + Django
OS: MacOS Catalina
Apache: 2.4.43
Python: 3.8
Django: 3.0.7
Used by Apache from Brew.
mod\_wsgi installed via pip.
The application is created through the standard command
```
django-admin startproject project_temp
```
The application starts when the command... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62497777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7060063/"
] | `&str` is an immutable slice, it somewhat similar to [`std::string_view`](https://en.cppreference.com/w/cpp/string/basic_string_view), so you cannot modify it. Instead, you may use iterator and collect a new [`String`](https://doc.rust-lang.org/std/string/struct.String.html):
```rust
let removed: String = foo
.cha... | Kitsu's solution w/o lambda
```
fn remove(start: usize, stop: usize, s: &str) -> String {
let mut rslt = "".to_string();
for (i, c) in s.chars().enumerate() {
if start > i || stop < i + 1 {
rslt.push(c);
}
}
rslt
}
```
…as fast as `replace_range` but can handle unicode cha... |
9,511,825 | I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the... | 2012/03/01 | [
"https://Stackoverflow.com/questions/9511825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | Your problem is that you're using -INFINITY and +INFINITY as win/loss scores. You should have scores for win/loss that are higher/lower than any other positional evaluation score, but not equal to your infinity values. This will guarantee that a move will be chosen even in positions that are hopelessly lost. | It's been a long time since i implemented minimax so I might be wrong, but it seems to me that your code, if you encounter a winning or losing move, does not update the best variable (this happens in the (board.checkEnd()) statement at the top of your method).
Also, if you want your algorithm to try to win with as muc... |
9,511,825 | I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the... | 2012/03/01 | [
"https://Stackoverflow.com/questions/9511825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | It's been a long time since i implemented minimax so I might be wrong, but it seems to me that your code, if you encounter a winning or losing move, does not update the best variable (this happens in the (board.checkEnd()) statement at the top of your method).
Also, if you want your algorithm to try to win with as muc... | If you can detect that a position is truly won or lost, then that implies you are solving the endgame. In this case, your evaluation function should be returning the final score of the game (e.g. 64 for a total victory, 31 for a narrow loss), since this can be calculated accurately, unlike the estimates that you will e... |
9,511,825 | I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the... | 2012/03/01 | [
"https://Stackoverflow.com/questions/9511825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | Your problem is that you're using -INFINITY and +INFINITY as win/loss scores. You should have scores for win/loss that are higher/lower than any other positional evaluation score, but not equal to your infinity values. This will guarantee that a move will be chosen even in positions that are hopelessly lost. | If you can detect that a position is truly won or lost, then that implies you are solving the endgame. In this case, your evaluation function should be returning the final score of the game (e.g. 64 for a total victory, 31 for a narrow loss), since this can be calculated accurately, unlike the estimates that you will e... |
6,539,267 | I started coding an RPG engine in python and I want it to be very scripted(buffs, events). I am experimenting with events and hooking. I would appreciate if you could tell me some matured opensource projects(so i can inspect the code) to learn from. Not necessarily python, but it would be ideal.
Thanks in advance. | 2011/06/30 | [
"https://Stackoverflow.com/questions/6539267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492162/"
] | As Daenyth suggested, [pygame](http://pygame.org/) is a great place to start. There are plenty of projects linked to on their page.
The other library that is quite lovely for this type of thing is [Panda3D.](http://www.panda3d.org/) Though I haven't yet used it, the library comes with samples, and it looks like there ... | You might have a look at `pygame`, it's pretty common for this sort of thing. |
63,129,698 | I'm using subprocess to spawn a `conda create` command and capture the resulting `stdout` for later use. I also immediately print the `stdout` to the console so the user can still see the progress of the subprocess:
```
p = subprocess.Popen('conda create -n env1 python', stdout=subprocess.PIPE, stderr=subprocess.STDOU... | 2020/07/28 | [
"https://Stackoverflow.com/questions/63129698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1963945/"
] | Although I'm sure pexpect would have worked in this case, I decided it would be overkill. Instead I used MisterMiyagi's insight and replaced `readline` with `read`.
The final code is as so:
```
p = subprocess.Popen('conda create -n env1 python', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while p.poll() is None... | For this use case I recommend using [pexpect](https://pypi.org/project/pexpect/). *stdin != stdout*
Example use case where it conditionally sends to *stdin* on prompts on *stdout*
```
def expectgit(alog):
TMPLOG = "/tmp/pexpect.log"
cmd = f'''
ssh -T [email protected] ;\
echo "alldone" ;
'''
with open(TMPLOG... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | Two problems:
First, you should initiate `smallest` with the last element if you want to search from the end of array:
```
int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]);
```
Secondly, you should reassign `smallest`:
```
if(startIndex>=0) {
smallest = findMinAux(arr,startIndex,smallest);
}
``` | See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well.
```
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12, 32, 45, 435, -1, 3... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | Two problems:
First, you should initiate `smallest` with the last element if you want to search from the end of array:
```
int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]);
```
Secondly, you should reassign `smallest`:
```
if(startIndex>=0) {
smallest = findMinAux(arr,startIndex,smallest);
}
``` | Actually, this implementation works fine
```
public static int findMinAux(int[] arr, int startIndex, int smallest) {
if(startIndex < 0)
return smallest;
if(arr[startIndex] < smallest){
smallest = arr[startIndex];
}
return findMinAux(arr, startIndex - 1, smallest... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | Two problems:
First, you should initiate `smallest` with the last element if you want to search from the end of array:
```
int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]);
```
Secondly, you should reassign `smallest`:
```
if(startIndex>=0) {
smallest = findMinAux(arr,startIndex,smallest);
}
``` | This approach works with a single method and an overloaded version so you don't have to pass the initial values
```
public static int findMin(int[] arr) {
int index = 0;
int min = Integer.MAX_VALUE;
min = Math.min(arr[index], min);
return findMin(arr,index+1,min);
}
private static int ... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | Two problems:
First, you should initiate `smallest` with the last element if you want to search from the end of array:
```
int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]);
```
Secondly, you should reassign `smallest`:
```
if(startIndex>=0) {
smallest = findMinAux(arr,startIndex,smallest);
}
``` | ```
class Minimum {
int minelem;
int minindex;
Minimum() {
minelem = Integer.MAX_VALUE;
minindex = -1;
}
}
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25};
findMin(testArr);
}
public static int findMin(int[] a... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | Actually, this implementation works fine
```
public static int findMinAux(int[] arr, int startIndex, int smallest) {
if(startIndex < 0)
return smallest;
if(arr[startIndex] < smallest){
smallest = arr[startIndex];
}
return findMinAux(arr, startIndex - 1, smallest... | See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well.
```
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12, 32, 45, 435, -1, 3... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | This approach works with a single method and an overloaded version so you don't have to pass the initial values
```
public static int findMin(int[] arr) {
int index = 0;
int min = Integer.MAX_VALUE;
min = Math.min(arr[index], min);
return findMin(arr,index+1,min);
}
private static int ... | See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well.
```
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12, 32, 45, 435, -1, 3... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | ```
class Minimum {
int minelem;
int minindex;
Minimum() {
minelem = Integer.MAX_VALUE;
minindex = -1;
}
}
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25};
findMin(testArr);
}
public static int findMin(int[] a... | See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well.
```
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12, 32, 45, 435, -1, 3... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | ```
class Minimum {
int minelem;
int minindex;
Minimum() {
minelem = Integer.MAX_VALUE;
minindex = -1;
}
}
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25};
findMin(testArr);
}
public static int findMin(int[] a... | Actually, this implementation works fine
```
public static int findMinAux(int[] arr, int startIndex, int smallest) {
if(startIndex < 0)
return smallest;
if(arr[startIndex] < smallest){
smallest = arr[startIndex];
}
return findMinAux(arr, startIndex - 1, smallest... |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | ```
class Minimum {
int minelem;
int minindex;
Minimum() {
minelem = Integer.MAX_VALUE;
minindex = -1;
}
}
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25};
findMin(testArr);
}
public static int findMin(int[] a... | This approach works with a single method and an overloaded version so you don't have to pass the initial values
```
public static int findMin(int[] arr) {
int index = 0;
int min = Integer.MAX_VALUE;
min = Math.min(arr[index], min);
return findMin(arr,index+1,min);
}
private static int ... |
73,818,926 | I am trying to send 2 params to the backend through a get request that returns some query based on the params I send to the backend. I am using React.js front end and flask python backend.
My get request looks like this:
```
async function getStatsData() {
const req = axios.get('http://127.0.0.1:5000/stat/', {
... | 2022/09/22 | [
"https://Stackoverflow.com/questions/73818926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19603491/"
] | In your backend route you are expecting the values in url as dynamic segment, but from axios you are sending it as [query sring](https://en.wikipedia.org/wiki/Query_string).
**Solution:**
You can modify the axios request like this to send the values as dynamic segment:
```
const user = 0;
const flashcard_id = 1;... | Send the parameters like this:
```
const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`)
```
and in Flask you receive the parameters like this:
```
@app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS'])
def stats(user, flashcard_id):
``` |
52,154,682 | After installing python 3.7 from python.org, running the Install Certificate.command resulted in the below error. Please, can you provide some guidance? Why does Install Certificate.command result in error?
[Some background]
Tried to install python via anaconda, brew and python.org, even installing version 3.6.6, hopi... | 2018/09/03 | [
"https://Stackoverflow.com/questions/52154682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10297557/"
] | wanted to answer my own question as I seem to have fixed most of the issues. The solution:
1. Created a pip directory and then a pip.conf file in $HOME/Library/Application Support
2. To the pip.conf added code
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
3. Started installing using
$ pi... | You don't need to run Install Certificate.command.
You should reinstall Xcode command line tools that contains Python.
```sh
pip3 uninstall -y -r <(pip requests certifi)
brew uninstall --ignore-dependencies python3
sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install
sudo xcode-select -r
python3 -m... |
39,739,195 | I have a JSON object that I'd like to transform using jq from one form to another (of course, I could use javascript or python and iterate, but jq would be preferable). The issue is that the input contains long arrays that needs to be broken into multiple smaller arrays whenever data stops repeating within the first ar... | 2016/09/28 | [
"https://Stackoverflow.com/questions/39739195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160967/"
] | Is it doable? Of course!
First you'll want to group the data by rows then columns. Then with the groups, build your values/sources arrays.
```
.headers as $headers | .data
# make the data easier to access
| map({ row: .[0], col: .[1], val: .[2], src: .[3] })
# keep it sorted so they are in expected order ... | Since the primary data source here can be thought of as a
two-dimensional matrix, it may be worth considering a
matrix-oriented approach to the problem, especially if it is
intended that empty rows in the input matrix are not simply omitted, or if
the number of columns in the matrix is not initially known.
To spice th... |
39,739,195 | I have a JSON object that I'd like to transform using jq from one form to another (of course, I could use javascript or python and iterate, but jq would be preferable). The issue is that the input contains long arrays that needs to be broken into multiple smaller arrays whenever data stops repeating within the first ar... | 2016/09/28 | [
"https://Stackoverflow.com/questions/39739195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160967/"
] | Is it doable? Of course!
First you'll want to group the data by rows then columns. Then with the groups, build your values/sources arrays.
```
.headers as $headers | .data
# make the data easier to access
| map({ row: .[0], col: .[1], val: .[2], src: .[3] })
# keep it sorted so they are in expected order ... | Here is a solution that uses **reduce**, **getpath** and **setpath**
```
.headers as $headers
| reduce .data[] as [$r,$c,$v,$s] (
{headers:$headers, values:{}, sources:{}}
; setpath(["values", $r, $c]; (getpath(["values", $r, $c]) // []) + [$v])
| setpath(["sources", $r, $c]; (getpath(["sources", $r, $c]) ... |
50,967,329 | I am trying to create a script that will
* look at each word in a text document and store in a list (WordList)
* Look at a second text document and store each word in a list (RandomText)
* Print out the words that appear in both lists
I have come up with the below which stores the text in a file, however I can't seem... | 2018/06/21 | [
"https://Stackoverflow.com/questions/50967329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7276704/"
] | Add `tools:replace="android:label"` to your `<application>` tag in AndroidManifest.xml as suggested in error logs.
This error might have occurred because AndroidManifest.xml of some jar file or library might also be having the `android:label` attribute defined in its `<application>` tag which is causing merger conflic... | add uses-SDK tools in the Manifest file
```
<uses-sdk tools:replace="android:label" />
``` |
5,217,513 | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game developmen... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5217513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647813/"
] | Short answer: Yes, it is.
But this heavily depends on your problem :) | This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc. |
5,217,513 | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game developmen... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5217513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647813/"
] | Each language has strengths and weaknesses.
Also, each implementation of a language has strengths and weaknesses. [CPython](http://en.wikipedia.org/wiki/CPython) is not the same as [Jython](http://en.wikipedia.org/wiki/Jython) and [PyPy](http://en.wikipedia.org/wiki/PyPy) is different again.
Python is very good in th... | Short answer: Yes, it is.
But this heavily depends on your problem :) |
5,217,513 | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game developmen... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5217513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647813/"
] | Each language has strengths and weaknesses.
Also, each implementation of a language has strengths and weaknesses. [CPython](http://en.wikipedia.org/wiki/CPython) is not the same as [Jython](http://en.wikipedia.org/wiki/Jython) and [PyPy](http://en.wikipedia.org/wiki/PyPy) is different again.
Python is very good in th... | This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc. |
5,217,513 | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game developmen... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5217513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647813/"
] | Yes, Yes and Yes. Python is for Real Programmers.
Must Read <http://www.paulgraham.com/pypar.html>
Refer For More. <http://wiki.python.org/moin/LanguageComparisons> | This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc. |
5,217,513 | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game developmen... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5217513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647813/"
] | Each language has strengths and weaknesses.
Also, each implementation of a language has strengths and weaknesses. [CPython](http://en.wikipedia.org/wiki/CPython) is not the same as [Jython](http://en.wikipedia.org/wiki/Jython) and [PyPy](http://en.wikipedia.org/wiki/PyPy) is different again.
Python is very good in th... | Yes, Yes and Yes. Python is for Real Programmers.
Must Read <http://www.paulgraham.com/pypar.html>
Refer For More. <http://wiki.python.org/moin/LanguageComparisons> |
28,865,785 | I am using python to take a very large string (DNA sequences) and try to make a suffix tree out of it. My program gave a memory error after a long while of making nested objects, so I thought in order to increase performance, it might be useful to create buffers from the string instead of actually slicing the string. B... | 2015/03/04 | [
"https://Stackoverflow.com/questions/28865785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The result makes sense. The check inside your ifs is truey in both cases (probably because both BL1, BN1 exist).
What you need to do in your code is retrieve the selected index and then use it.
Give an id to your dropdown list:
```
<select id="dropdownList">
....
```
And then use it in your code to retrieve the se... | 1st: You are defining the variable *price* multiple times.
2nd: Your code checks for 'value' and of cause, it always has a value.
I guess, what you really want to check is, whether an option is selected or not annd then use its value.
```js
function BookingFare() {
var price = 0;
var BN1 = document.getElementByI... |
28,865,785 | I am using python to take a very large string (DNA sequences) and try to make a suffix tree out of it. My program gave a memory error after a long while of making nested objects, so I thought in order to increase performance, it might be useful to create buffers from the string instead of actually slicing the string. B... | 2015/03/04 | [
"https://Stackoverflow.com/questions/28865785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The result makes sense. The check inside your ifs is truey in both cases (probably because both BL1, BN1 exist).
What you need to do in your code is retrieve the selected index and then use it.
Give an id to your dropdown list:
```
<select id="dropdownList">
....
```
And then use it in your code to retrieve the se... | I think this is what you are looking for.
```html
<script>
function BookingFare() {
var price = 0;
//var ofAdults = getElementById('adults').value;
//var ofChildren = getElementById('children').value;
var bristol = document.getElementById('bristol').value;
console.log(... |
49,883,623 | Am trying to solve project euler question :
>
> 2520 is the smallest number that can be divided by each of the numbers
> from 1 to 10 without any remainder. What is the smallest positive
> number that is evenly divisible by all of the numbers from 1 to 20?
>
>
>
I've come up with the python solution below, but ... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49883623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5126615/"
] | You can use a generator expression and the all function:
```
def smallest_m():
start = 1
while True:
if all(start % i == 0 for i in range(2, 20+1)):
print(start)
break
else:
start+=1
smallest_m()
``` | Try this
```
n = 2520
result = True
for i in range(1, 11):
if (n % i != 0):
result = False
print(result)
``` |
49,883,623 | Am trying to solve project euler question :
>
> 2520 is the smallest number that can be divided by each of the numbers
> from 1 to 10 without any remainder. What is the smallest positive
> number that is evenly divisible by all of the numbers from 1 to 20?
>
>
>
I've come up with the python solution below, but ... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49883623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5126615/"
] | Here is one solution which utilizes a generator. The smallest number I see is 232792560.
```
def smallest_m(n):
for k in range(20, n, 20):
match = True
for i in range(1, 21):
if k % i != 0:
match = False
break
else:
if match:
... | Try this
```
n = 2520
result = True
for i in range(1, 11):
if (n % i != 0):
result = False
print(result)
``` |
49,883,623 | Am trying to solve project euler question :
>
> 2520 is the smallest number that can be divided by each of the numbers
> from 1 to 10 without any remainder. What is the smallest positive
> number that is evenly divisible by all of the numbers from 1 to 20?
>
>
>
I've come up with the python solution below, but ... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49883623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5126615/"
] | You can use a generator expression and the all function:
```
def smallest_m():
start = 1
while True:
if all(start % i == 0 for i in range(2, 20+1)):
print(start)
break
else:
start+=1
smallest_m()
``` | Here is one solution which utilizes a generator. The smallest number I see is 232792560.
```
def smallest_m(n):
for k in range(20, n, 20):
match = True
for i in range(1, 21):
if k % i != 0:
match = False
break
else:
if match:
... |
21,735,023 | I am a python newb so please forgive me. I have searched on Google and SA but couldn't find anything. Anyway, I am using the python library [Wordpress XMLRPC](http://python-wordpress-xmlrpc.readthedocs.org/en/latest/overview.html).
`myblog`, `myusername`, and `mypassword` are just placeholders to hide my real website... | 2014/02/12 | [
"https://Stackoverflow.com/questions/21735023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3302735/"
] | Variant 3 is ok (but I'd rather use a loop instead of hard-coded options). Your mistake is that you compare 'option1', 'option2' and so one when your real values are '1', '2', '3'. Also as @ElefantPhace said, don't forget about spaces before **selected**, or you'll get invalid html instead. So it would be this:
```
<s... | Here is all three of your variants, tested and working as expected. They are all basically the same, you were just using the wrong variable names, and different ones from example to example
1)
```
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt">';
foreach ($opt... |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html).
[Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/)
>
> However, if I try to stop and start the server again to test any modifications, I... | It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late. |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance:
```
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
```
I'm still not sure why closing the socket didn't free it up for the next run of the ... | It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html).
[Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/)
>
> However, if I try to stop and start the server again to test any modifications, I... |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | The `[Err 98] Address already in use` is due to the fact the socket was `.close()` but it's still waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request (see [TIME\_WAIT](https://en.wikipedia.org/wiki/Transmission_Control_Protocol)). By default you ar... | It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html).
[Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/)
>
> However, if I try to stop and start the server again to test any modifications, I... |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance:
```
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
```
I'm still not sure why closing the socket didn't free it up for the next run of the ... | It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late. |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | The `[Err 98] Address already in use` is due to the fact the socket was `.close()` but it's still waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request (see [TIME\_WAIT](https://en.wikipedia.org/wiki/Transmission_Control_Protocol)). By default you ar... | It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late. |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance:
```
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
```
I'm still not sure why closing the socket didn't free it up for the next run of the ... | The `[Err 98] Address already in use` is due to the fact the socket was `.close()` but it's still waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request (see [TIME\_WAIT](https://en.wikipedia.org/wiki/Transmission_Control_Protocol)). By default you ar... |
5,988,617 | According to the python doc, vertical bars literal are used as an 'or' operator. It matches A|B,where A and B can be arbitrary REs.
For example, if the regular expression is as following:
ABC|DEF,it matches strings like these:
"ABC", "DEF"
But what if I want to match strings as following:
"ABCF", "ADEF"
Perhaps wh... | 2011/05/13 | [
"https://Stackoverflow.com/questions/5988617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/166482/"
] | These will work:
```
A(BC|DE)F
A(?:BC|DE)F
```
The difference is the number of groups generated: 1 with the first, 0 with the second.
Yours will match either `ABC` or `DEF`, with 2 groups, one containing nothing and the other containing the matched fragment (`BC` or `DE`). | The only difference between parentheses in Python regexps (and perl-compatible regexps in general), and parentheses in formal regular expressions, is that in Python, parens store their result. Everything matched by a regular expression inside parentheses is stored as a "submatch" or "group" that you can access using th... |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph.
The first set of vertices represent the A agents, the second set of vertices represen... | This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem.
We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are n... |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | The members of the two teams and the slots define a tripartite graph `A-S-B`, with edges given by the possible moves. The bipartite subgraphs consisting of the slots and members of just one team are of interest; call these `A-S` for the graph with team A members and `S-B` for team B members. You can use the `S-B` graph... | This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem.
We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are n... |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | This is a brute force solution, but perhaps less brute than the obvious one of enumerating all possibilities. As noted by the other solutions, this problem has to do with [matchings](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) on a [bipartite graph](http://en.wikipedia.org/wiki/Bipartite_graph).
**Step 1... | This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem.
We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are n... |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | The members of the two teams and the slots define a tripartite graph `A-S-B`, with edges given by the possible moves. The bipartite subgraphs consisting of the slots and members of just one team are of interest; call these `A-S` for the graph with team A members and `S-B` for team B members. You can use the `S-B` graph... | If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph.
The first set of vertices represent the A agents, the second set of vertices represen... |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | This is a brute force solution, but perhaps less brute than the obvious one of enumerating all possibilities. As noted by the other solutions, this problem has to do with [matchings](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) on a [bipartite graph](http://en.wikipedia.org/wiki/Bipartite_graph).
**Step 1... | If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph.
The first set of vertices represent the A agents, the second set of vertices represen... |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | The members of the two teams and the slots define a tripartite graph `A-S-B`, with edges given by the possible moves. The bipartite subgraphs consisting of the slots and members of just one team are of interest; call these `A-S` for the graph with team A members and `S-B` for team B members. You can use the `S-B` graph... | This is a brute force solution, but perhaps less brute than the obvious one of enumerating all possibilities. As noted by the other solutions, this problem has to do with [matchings](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) on a [bipartite graph](http://en.wikipedia.org/wiki/Bipartite_graph).
**Step 1... |
53,557,240 | I have an input, which is a word.
if my input contains `python`, print `True`. if not, print `False`.
for example:
if the input is `puytrmhqoln` print `True`(because it contains python's letter, however, there is some letter between `python`)
if the input is `pythno` print `False` (because in types o after n) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53557240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688308/"
] | I found the answer.
```
import sys
inputs = sys.stdin.readline().strip()
word = "python"
for i in range(len(inputs)):
if word == "": break
if inputs[i] == word[0]:
word = word[1:]
if word == "":
print("YES")
else:
print("NO")
```
it works for words like `hello` with double letter, also `pyth... | Iterate over each character of your string. And see whether the current character is identical to the currently next one in your string you are looking for:
```
strg = "pythrno"
lookfor = "python"
longest_substr = ""
index = 0
max_index = len(lookfor)
for c in strg:
if c == lookfor[index] and index < max_index:
... |
53,557,240 | I have an input, which is a word.
if my input contains `python`, print `True`. if not, print `False`.
for example:
if the input is `puytrmhqoln` print `True`(because it contains python's letter, however, there is some letter between `python`)
if the input is `pythno` print `False` (because in types o after n) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53557240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688308/"
] | I found the answer.
```
import sys
inputs = sys.stdin.readline().strip()
word = "python"
for i in range(len(inputs)):
if word == "": break
if inputs[i] == word[0]:
word = word[1:]
if word == "":
print("YES")
else:
print("NO")
```
it works for words like `hello` with double letter, also `pyth... | I hope this code will be useful:
Variant 1 (looks for the whole word):
```
s_word = 'python'
def check(word):
filtered_word = "".join(filter(lambda x: x in tuple(s_word), tuple(word)))
return filtered_word == s_word
print(check('puytrmhqoln'))
# returns True
print(check('pythno'))
# returns False
```
Vari... |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'`
Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib... | The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
`C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\... |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'`
Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib... | Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me! |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'`
Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib... | If you **can not locate epsg file** at all, you can download it here:
<https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg>
And copy this file to your PATH, e.g. to:
os.environ['PROJ\_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af\_0\Lib\site-packages\... |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
`C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\... | Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me! |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | In Windows 10 command line: first find the directory where the **epsg** file is stored:
```
where /r "c:\Users\username" epsg.*
```
...
**c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share**\epsg
...
then either in command line:
```
activate envname
SET PROJ_LIB=c:\Users\username\AppData\Loc... | The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
`C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\... |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
`C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\... | If you **can not locate epsg file** at all, you can download it here:
<https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg>
And copy this file to your PATH, e.g. to:
os.environ['PROJ\_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af\_0\Lib\site-packages\... |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | In Windows 10 command line: first find the directory where the **epsg** file is stored:
```
where /r "c:\Users\username" epsg.*
```
...
**c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share**\epsg
...
then either in command line:
```
activate envname
SET PROJ_LIB=c:\Users\username\AppData\Loc... | Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me! |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | If you **can not locate epsg file** at all, you can download it here:
<https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg>
And copy this file to your PATH, e.g. to:
os.environ['PROJ\_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af\_0\Lib\site-packages\... | Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.