qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
56,526,857 | I am developing a software in which I have an OpenGL window. I am creating the GUI of the software using `PyQt5` and for the opengGL Window I am using `QOpengGLWidget` and for object selection, I am using [**Stencil** **Buffer**](https://en.wikibooks.org/wiki/OpenGL_Programming/Object_selection) and reading **STENCIL\_... | 2019/06/10 | [
"https://Stackoverflow.com/questions/56526857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `strip()` does not respect count or order when it removes characters from the end of your string. The argument you passed it, `"-Vaccines"`, contains an "a", so it will remove the "a" from "Rivera". It does not matter that it already removed an "a" from "Vaccines" and it does not matter that it doesn't come between a V... | The problem is that the argument to `strip` isn't used the way you think it is. The argument isn't treated as a sequence of characters, but rather as a set of characters. Any character in the argument string is removed. For example:
```
"abaca".strip("ac")
```
Produces:
```
'b'
```
since all instances of `"a"` an... | 9,397 |
64,211,267 | I want to install package MetaTrader5 on my Linux [Fedora], but this package is supported only for Windows.
**And my question is:** Is it possible to install Windows Python packages on Linux? and after installation import in my python file?
**My Solution**
1. install `wine` (learn more about [wine](https://www.wi... | 2020/10/05 | [
"https://Stackoverflow.com/questions/64211267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13033299/"
] | you can install `wine` to deal with the windows installer files in your fedora.
as per the doc, you can run the following comands one by one to install wine:
`sudo dnf clean all && sudo dnf update`
`dnf config-manager --add-repo https://dl.winehq.org/wine-builds/fedora/32/winehq.repo`
`sudo dnf install winehq-stabl... | Yes it possible to use Wine.
Its simply to do with **CrossOver**, its more stable.
Meta Trader compiled for the Wine.
Ive use this thing. Work correctly Meta Trader and Meta editor. | 9,398 |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
... | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | In your main project, open url.py first. Then check, there should be app\_name declared at first. If it is not, declare it.
For example, my app name is user info which is declared in url.py
```
app_name = "userinfo"
urlpatterns = [
url(r'home/', views.home, name='home'),
url(r'register/', views.registration,... | Maybe someone will find this suggestion helpful.
Go to your applications `urls.py` and type this before the urlpatterns:
```
app_name = 'Your app name'
``` | 9,399 |
59,918,219 | ```
AttributeError at /addpatient_to_db
'QuerySet' object has no attribute 'wardno'
```
Request Method: POST
Request URL: <http://127.0.0.1:8000/addpatient_to_db>
Django Version: 2.2.5
Exception Type: `AttributeError`
Exception Value: `'QuerySet' object has no attribute 'wardno'`
Exception Location: `C:\Users\Sa... | 2020/01/26 | [
"https://Stackoverflow.com/questions/59918219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11056524/"
] | **TLDR:**
**Solution is that you should either provide engine and user\_id in params or you should remove presence true validation and add optional true case (for user association) from model.**
**Explanation:**
If your model says that it should validate presence of `engine` then how can you not provide engine param... | From your log file
```
Started POST "/cars" for ::1 at 2020-01-26 14:45:06 +0000
```
Shows that the create action is being called on the cars controller
The parameters being passed in are
```
{"authenticity_token"=>"Oom+xdVDc0PqSwLbLIEP0R8H6U38+v9ISVql4Fr/0WSxZGSrxzTHccsgghd1U30OugcUBAA1R4BtsB0YigAUtA==", "car"=>{"... | 9,409 |
62,377,906 | I want to run a batch file in a Conda environment, not in the **base** env, but in another virtual environment (here **pylayers**).
I copied the `activate.bat` script from `F:\Anaconda3\Scripts` to `F:\Anaconda3\envs\pylayers\Scripts`.
And my batch script (`installer_win.bat`) is:
```
call F:\Anaconda3\envs\pylayer... | 2020/06/14 | [
"https://Stackoverflow.com/questions/62377906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11051182/"
] | There are two ways to go. I think the first is the cleaner way to go.
Option 1: YAML Definition
=========================
If the entire procedure is only for installations, it can be condensed into a single [YAML environment definition](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environmen... | To run a bat file from a dos prompt inside a new (non-base) conda env, you can try something like this:
prompt> cmd "/c activate ds\_tensorflow && myfile.bat && deactivate"
contents of myfile.bat to show you are in the non-base env:
```
echo hello
python -c "import sys; print(sys.version)"
```
You can replace myfi... | 9,410 |
66,577,552 | I would like to suppress some sensitive information displayed in the logs.
Code:
```
pipeline {
parameters {
string(defaultValue: '', description: '', name: 'pki_client_cacert_password', trim: true)
string(defaultValue: '', description: '', name: 'db_url', trim: true)
}
stages {
stage(... | 2021/03/11 | [
"https://Stackoverflow.com/questions/66577552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234419/"
] | First option is to set it as environment var:
```
withEnv(["MYSECRET=${params.pki_client_cacert_password}",
"MYURL=${env.db_url}"]) {
env.artifacts = sh(
returnStdout: true,
script: '.. python3 .. encrypter_creds.py --db_url=$MYURL ' +
' --pki_client_cacert_password=$MYSECRET... | I have added @MaratC suggestion however that did not help much, so I ended up adding `set +x` and `set -x` more so this question was related to
[Echo off in Jenkins Console Output](https://stackoverflow.com/questions/26797219/echo-off-in-jenkins-console-output)
which worked as expected
```
script{
... | 9,411 |
54,811,697 | I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form.
Is there any other form?
I am used to looping until a con... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54811697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191073/"
] | A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like
```
for(init; condition; post)
//do something
```
that is equivalent to the while loop
```
init;
while(condition)
//do something
post;
```
because Python has while loops, if you wanted t... | (Most Common)Three kinds of loops :
1. `Count controlled` - You dont have this kind of loop in python
2. `Condition controlled` - while loop in python
3. `Collection controlled` - for loop in python | 9,412 |
6,289,699 | >
> **Possible Duplicate:**
>
> [How do I get the name of a function or method from within a Python function or method?](https://stackoverflow.com/questions/245304/how-do-i-get-the-name-of-a-function-or-method-from-within-a-python-function-or-me)
>
>
>
The below code function return it's name.
It works but I s... | 2011/06/09 | [
"https://Stackoverflow.com/questions/6289699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240041/"
] | If I understand correctly - [Inspect](http://docs.python.org/library/inspect.html) is what you are looking for.
```
import inspect
def test():
print inspect.stack()[0][3]
``` | There is no way to access the function name in a python function without using a backtrace.
```
In [1]: import inspect
In [2]: def test():
...: print inspect.stack()[0][3]
...:
In [3]: test()
test
```
So, what you want to use is `inspect.stack()[0][3]` or, if you want to move it into a separate function,... | 9,422 |
614,458 | How do i look for the following pattern using regular expression in python? for the two cases
Am looking for str2 after the "=" sign
* Case 1: `str1=str2`
* Case 2: `str1 = str2`
please note there can be a **space or none** between the either side of the "=" sign
Mine is like this, but only works for one of the ca... | 2009/03/05 | [
"https://Stackoverflow.com/questions/614458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74170/"
] | if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple:
```
>>> case = 'str = str2'
>>> case.partition('=')[2].lstrip()
'str2'
```
it'll be much faster than regexps. and just to show how fast i... | ```
re.search(r'=\s*(.*)', 'str = str2').group(1)
```
or if you just want a single word:
```
re.search(r'=\s*(\w+)', 'str = str2').group(1)
```
Extended to specific initial string:
```
re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1)
```
`\b` = word boundary, so won't match `"somestr=foo"`
It would be qui... | 9,423 |
37,974,645 | I recently started learning ruby, coming from a background in python. This is one of my first programs above a few lines in length, and I have made a mistake somewhere in the syntax that I cannot catch, that is causing the program to fail with the error "unexpected end-of-output, expected keyword\_end"
Here is the cod... | 2016/06/22 | [
"https://Stackoverflow.com/questions/37974645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5506705/"
] | One missing `end` after line 35, i.e. at
```
number = (numberRev / 100).reverse
# HERE! there should be an `end`
if left == 0
return numEnglish
```
In addition, at line 18 and 19 you are asking `number[0]` for the first non-zero digit of... | Some advice:
* use two spaces. It's more common and easier to read and spot such errors.
* use an editor like Sublime Text or a IDE like RubyMine. ST has several add-ons that facilitate debugging. In this case all I had to do is run a "Beautify-Ruby" on the code and it gave me this output.
It looks like you are miss... | 9,433 |
70,630,205 | I don't know how to get the all total price of the product that the customer bought from my system. the price of each item I can get but the price of all the item that have been choose i can't get the output. I'm using python.
Below is my code:
```
#below is the price of products
shopping_cart = {}
option = 1
while... | 2022/01/08 | [
"https://Stackoverflow.com/questions/70630205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just putting `("Not found")` as a statement doesn't print anything. You need to add your item total into `total_cost` immediately after the print statement. There's no point defining a function, since you don't call the function. So, replace everything after that last "else:" with this:
```
else:
total = 0... | You can add `total_cost += total` for every choice,
So its added to the total cost when somebody choose the item and if he add another it also adds to the total cost.
```py
elif option == 6:
print("Foaming Milk")
qnty = int(input("Enter the quantity: "))
total = qnty*12.70
print("Th... | 9,434 |
65,797,818 | I'm trying to understand regex and i have an error message.
I don't understand this message because I don't use list. If I use just print(number) it doesn't delete the [ ] of the result. The goal is to obtain only the number in the sentence as result.
I use python 3.6.
Below my code:
```
import re
user_sentence = inp... | 2021/01/19 | [
"https://Stackoverflow.com/questions/65797818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15039238/"
] | `groups()` (with an `s`) is on the return value of a `re.match`, not a `findall`. If you're looking to print each item in the list returned by a findall, you can print use `join` to join them on a space, or loop over the list. Note that the list may include tuples though (not in your case, but in general). Example of j... | findall returns list type by default and list does not have any such method/attribute. If you try to running print (number), you see a list as the output. But to convert the list elements into number you can add these lines after you have evaluated number
```
number = re.findall("[0-9]+", user_sentence)
#add these lin... | 9,436 |
29,802,931 | I have a csv file of customer ids (`CRM_id`). I need to get their primary keys (an autoincrement int) from the customers table of the database. (I can't be assured of the integrity of the `CRM_id`s so I chose not to make that the primary key).
So:
```
customers = []
with open("CRM_ids.csv", 'r', newline='') as csvfil... | 2015/04/22 | [
"https://Stackoverflow.com/questions/29802931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3790954/"
] | What about changing your query to get what you want?
```
crm_ids = ",".join(customers)
select_customer = "SELECT UNIQUE id FROM customers WHERE CRM_id IN (%s);" % crm_ids
```
MySQL should be fine with even a multi-megabyte query, according to [the manual](http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html)... | how about storing your csv in a dict instead of a list:
```
customers = [c for c in customerfile]
```
becomes:
```
customers = {c['CRM_id']:c for c in customerfile}
```
then select the entire xref:
```
result = cursor.execute('select id, CRM_id from customers')
```
and add the new rowid as a new entry in the d... | 9,438 |
55,351,039 | There is an excel file logging a set of data. Its columns are as below, where each column is seperated by comma.
```
SampleData
year,date,month,location,time,count
2019,20,Jan,Japan,22:33,1
2019,31,Jan,Japan,19:21,1
2019,1,Jan,Japan,8:00,1
2019,4,Jan,Japan,4:28,2
2019,13,Feb,Japan,6:19,1
```
From this data, I would ... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55351039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11258673/"
] | try this
```
from datetime import datetime
data['datetime'] = data[['year','date','month','time']].apply(lambda x: datetime.strptime(str(x['year'])+'-'+str(x['date'])+'-'+str(x['month'])+' '+str(x['time']), "%Y-%d-%b %H:%M").timestamp(), axis=1)
data[['datetime','location','count']]
```
**Output**
```
dat... | You are close, need `%Y%b%d%H:%M` format and then convert to unix time by cast to `int64` with integer division by `10**9`:
```
s = (DataFrame["year"].astype(str)+
DataFrame["month"].astype(str)+
DataFrame["date"].astype(str)+
DataFrame["time"].astype(str))
DataFrame['u_datetime'] = pd.to_datetime(s, fo... | 9,439 |
5,195,295 | I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:
```
reader = csv.reader(open("file.csv", "r... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644926/"
] | The simplest way is to write your script like this:
```
import sys
reader = csv.reader(open(sys.argv[1], "rb"))
```
and then run it like this:
```
python testfile.py file.csv
```
You should put in some error checking, eg:
```
if len(sys.argv) < 2:
print "Usage..."
sys.exit(1)
```
For more power, use th... | You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Other... | 9,441 |
11,724,779 | I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run:
>
> source bin/activate
>
> pip install -r requirements.txt
>
>
>
I get the error:
>
> Downloading/unpacking django-storages
>
>
>
> >
> > Cannot fetch index base URL http ... | 2012/07/30 | [
"https://Stackoverflow.com/questions/11724779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411141/"
] | You can try installing django-storages on its own.. try this?
```
sudo pip install https://bitbucket.org/david/django-storages/get/def732408163.zip
``` | Try giving the proxy settings in the command as such
```
pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt
```
or try
```
export http_proxy=http://user:password@Proxy:PortNumber
``` | 9,449 |
53,162,325 | I use google composer. I have a dag that uses the `panda.read_csv()` function to read a `.csv.gz` file. The DAG keeps trying without showing any errors. Here is the airflow log:
```
*** Reading remote log from gs://us-central1-data-airflo-dxxxxx-bucket/logs/youtubetv_gcpbucket_to_bq_daily_v2_csv/file_transfer_gcp_to_... | 2018/11/05 | [
"https://Stackoverflow.com/questions/53162325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183883/"
] | Based on this discussion [airflow google composer group](https://groups.google.com/forum/#!topic/cloud-composer-discuss/alnKzMjEj8Q) it is a known issue.
One of the reason can be because of overkilling all the composer resources (in my case memory) | I have a [similar issue](https://groups.google.com/forum/#!topic/cloud-composer-discuss/lKsy7X1fy00) recently.
In my case it's beacause the kubernetes worker overload.
You can watch the worker performance on kubernetes dashboard too see whether your case is cluster overloadding issue.
If yes, you can try set the val... | 9,454 |
57,602,726 | I'm wondering why we can have Tensorflow [run in a multi-thread fashion](https://www.tensorflow.org/guide/performance/overview#optimizing_for_cpu) while python can only execute one thread at a time due to [GIL](https://wiki.python.org/moin/GlobalInterpreterLock)? | 2019/08/22 | [
"https://Stackoverflow.com/questions/57602726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7850499/"
] | The GIL's restriction is slightly more subtle: only one thread at a time can be *executing Python bytecode*.
Extensions using Python's C API (like `tensorflow`) can release the GIL if they don't need it. I/O operations like using files or sockets also tend to release the GIL because they generally involve lots of wait... | Most of the `tensorflow` core is written in `C++` and the python APIs are just the wrappers around it. While running the `C++` code regular python restrictions do not apply. | 9,455 |
4,631,377 | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | 2011/01/07 | [
"https://Stackoverflow.com/questions/4631377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567620/"
] | I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
* Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config**
* file-> **rest... | Following, in my opinion will solve the problem
1. Adding the **init**.py to your "~/Desktop/Python\_Tutorials/diveintopython/py" folder
2. Go to Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any ... | 9,456 |
62,504,019 | I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX.
The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-cli... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62504019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12001122/"
] | ```
render(request, template_name, context=None, content_type=None, status=None, using=None)
```
>
> `render()` Combines a given template with a given context dictionary
> and returns an HttpResponse object with that rendered text.
>
>
>
You can either use Django defaults `JsonResponse` class or Django REST fram... | Python has a built in function for converting dicts to json.
```
import json
data = api_response.data
return render(request, json.dumps(data))
```
If you use that in your return statement it should return json. | 9,466 |
16,518,142 | I'm trying out threads in python. I want a spinning cursor to display while another method runs (for 5-10 mins). I've done out some code but am wondering is this how you would do it? i don't like to use globals, so I assume there is a better way?
```
c = True
def b():
for j in itertools.cycle('/-\|'):
if... | 2013/05/13 | [
"https://Stackoverflow.com/questions/16518142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803007/"
] | You could use events:
<http://docs.python.org/2/library/threading.html>
I tested this and it works. It also keeps everything in sync. You should avoid changing/reading the same variables in different threads without synchronizing them.
```
#!/usr/bin/python
from threading import Thread
from threading import Event
im... | This is not properly synchronized. But I will not try to explain it all to you right now because it's a whole lot of knowledge. Try to read this: <http://effbot.org/zone/thread-synchronization.htm>
But in your case it's not that bad that things aren't synchronized correctyl. The only thing that could happen, is that t... | 9,469 |
3,076,798 | I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the `subprocess` module before, nor pipes, so I don't know what to try next.
So far I have this code:
```
a = subprocess.Popen('nano', stdout=subproces... | 2010/06/19 | [
"https://Stackoverflow.com/questions/3076798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104297/"
] | Control-O in Nano writes to **the file being edited**, i.e., *not* to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac:
```
>>> import tempfile
>>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
>>> n = f.name
>>> ... | I'm not sure you can capture what the user has entered into `nano`. After all, that's nano's job.
What you can (and I think should do) to get user input from an editor is to spawn it off with a [temporary file](http://docs.python.org/library/tempfile.html). Then when the user has entered what he wants, he saves and q... | 9,471 |
61,109,903 | I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>.... | 2020/04/08 | [
"https://Stackoverflow.com/questions/61109903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13263274/"
] | Do you like it better that way?
```
if (
!(profile.name.hasError ||
profile.crn.hasError ||
profile.employeesNbr.hasError ||
profile.phoneNumber.hasError ||
profile.userRole.hasError) &&
profile.personCheck.hasError
) {
showModal.modal.error = true;
}... | It would be easy to simplify it into a loop if you were doing the same check for all properties in the profile. Doing a different check for `personCheck` makes it hard to reduce it like that.
You can use an array for all the properties that you want the same check on.
```
if (profile.personCheck.hasError &&
["na... | 9,472 |
65,183,558 | Let's say I want to implement some **list class** in python with extra structure, like a new constructor. I wrote:
```
import random
class Lis(list):
def __init__(self, n):
self = []
for i in range(n):
self.append(random.randint(0, 30))
```
Now doing `Lis(3)` gives me an empty list. ... | 2020/12/07 | [
"https://Stackoverflow.com/questions/65183558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4821555/"
] | You are overriding the object with `self = []`
try the following
```
import random
class Lis(list):
def __init__(self, n):
for i in range(n):
self.append(random.randint(0, 30))
``` | if you want to return a list from object call
```py
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return [1,2,3]
obj = MyClass()
print(obj)
```
[How to return a value from \_\_init\_\_ in Python?](https://stackoverflow.com/questions/2491819/ho... | 9,475 |
12,454,675 | I made a simple server and a simple client with `socket` module in python.
server:
```
# server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
c.send(b'Thank you for your c... | 2012/09/17 | [
"https://Stackoverflow.com/questions/12454675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477871/"
] | From the [`socket` documentation](http://docs.python.org/library/socket.html):
>
> A pair (host, port) is used for the AF\_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.
>
>
>... | Quote from [python documentation](http://docs.python.org/library/socket.html#socket.socket.accept):
>
> `socket.accept()`
>
>
> Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair `(conn, address)` where conn is a new socket object usable to send an... | 9,476 |
54,730,763 | I am trying to understand how RxPy works, I am getting this error
>
> type object 'ObservableBase' has no attribute 'create'
>
>
>
I am using python 3.6 and my code is
```
from rx import Observable
stocks = [
{'TCKR': 'APPL', 'PRICE': 200},
{'TCKR': 'GOOG', 'PRICE': 90},
{'TCKR': 'TSLA', 'PRICE': 120},
... | 2019/02/17 | [
"https://Stackoverflow.com/questions/54730763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291507/"
] | They have updated RxPy module. Install 1.6.1, it will solve the problem. Thanks | I have found the solution,
change the code from
```
from rx import Observable
source = Observable.create(buy_stock_events)
```
to
```
import rx
source = rx.Observable.create(buy_stock_events)
```
and it's working | 9,477 |
54,417,893 | I have a business problem, I have run the regression model in python to predict my target value. When validating it with my test set I came to know that my predicted variable is very far from my actual value. Now the thing I want to extract from this model is that, which feature played the role to deviate my predicted ... | 2019/01/29 | [
"https://Stackoverflow.com/questions/54417893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4634959/"
] | It depends on the estimator you chose, linear models often have a coef\_ method you can call to get the coef used for each feature, given they are normalized this tells you what you want to know.
As told above for tree model you have the feature importance. You can also use libraries like treeinterpreter described her... | You can have a look at this -
[Feature selection](https://scikit-learn.org/stable/modules/feature_selection.html) | 9,478 |
58,558,135 | I'm writing a wrapper or pipeline to create a tfrecords dataset to which I would like to supply a function to apply to the dataset.
I would like to make it possible for the user to inject a function defined in another python file which is called in my script to transform the data.
Why? The only thing the user has to ... | 2019/10/25 | [
"https://Stackoverflow.com/questions/58558135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6489953/"
] | 1. Pass the name of the file as an argument to your script (and function name)
2. Read the file into a string, possibly extracting the given function
3. use Python [exec()](https://www.programiz.com/python-programming/methods/built-in/exec) to execute the code
An example:
```
file = "def fun(*args): \n return args"
... | Ok so I have composed the answer myself now using the information from comments and [this answer](https://stackoverflow.com/a/58558215/6489953).
```py
import importlib, inspect, sys, os
# path is given path to file, funcion_name is name of function and args are the function arguments
# Create package and ... | 9,480 |
45,346,418 | I am trying to generate word vectors using PySpark. Using gensim I can see the words and the closest words as below:
```python
sentences = open(os.getcwd() + "/tweets.txt").read().splitlines()
w2v_input=[]
for i in sentences:
tokenised=i.split()
w2v_input.append(tokenised)
model = word2vec.Word2Vec(w2v_input)
... | 2017/07/27 | [
"https://Stackoverflow.com/questions/45346418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6071445/"
] | The equivalent command in Spark is `model.getVectors()`, which again returns a dictionary. Here is a quick toy example with only 3 words (`alpha, beta, charlie`), adapted from the [documentation](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.feature.Word2Vec):
```python
sc.version
# ... | And as suggested [here](https://stackoverflow.com/questions/48062278/would-model-getvectors-keys-return-all-the-keys-from-a-model),
if you want to include all the words in your document set the MinCount parameter accordingly (default=5):
```
word2vec = Word2Vec()
word2vec.setMinCount(1)
``` | 9,481 |
68,821,867 | I'm trying to install `pyinstaller 3.5` in `python 3.4.3` but i get this error:
```
ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\DTI~1.DES\AppData\Local\Temp\pip-install-_dyh3r_g\pefile\
```
The command i use is this:
```
pip install pyinstaller==3.5
```
I'm using the latest vers... | 2021/08/17 | [
"https://Stackoverflow.com/questions/68821867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15496915/"
] | `pefile` (one of the PyInstaller dependencies) [requires python >= 3.6.0](https://github.com/erocarrera/pefile/blob/master/setup.py#L89) | Try `pip install pyinstaller` This should work
or
If you wanted the specific version you can do that by
`pip install pyinstaller == "3.5"` | 9,482 |
8,011,087 | Disclaimer:
I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option.
This application was developed time ago and several developers have worked on it,
Having said that, the problem is this;
In the api for mobile of this site (just views than returns js... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150647/"
] | In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`.
For example:
```
server {
# the port your site will be served on
listen 8000;
...
underscores_in_headers on;
}
```
And if access to Django goes throu... | The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying.
```
proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7
proxy_set_header X-FORWARDED-FOR # this will do the job
```
So you get it. Underscore could never ap... | 9,483 |
62,187,893 | I am new to python and I would like to print different words from the sentence. Below is the text file
```
Test.txt
1. As more than one social media historian has reminded few people, the Stonewall uprising was a rio-— more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s... | 2020/06/04 | [
"https://Stackoverflow.com/questions/62187893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11144691/"
] | here is your code:
```
datalist = ['few','people','morning','1969','majority','people','evening','1979']
with open('file.txt', 'r') as file:
data = file.read().replace('\n', ' ')
outputlist = data.replace('.','').split(" ")
for data in outputlist:
if data in datalist:
print(data)
``` | Using split("reminded"), you splitted your sentence into two pieces addressable using indexes 0 and 1, but if you want to separate the words of the second part you can do another split on space. For example:
```
line.split('reminded',1)[1].split(" ")
```
In this way you will have a list of string which contains the... | 9,493 |
7,538,628 | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | 2011/09/24 | [
"https://Stackoverflow.com/questions/7538628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151048/"
] | I can't find the way to trigger the commands of `virtualenvwrapper` in shell. But this trick can help: assume your env. name is `myenv`, then put following lines at the beginning of scripts:
```
ENV=myenv
source $WORKON_HOME/$ENV/bin/activate
``` | add these lines to your .bashrc or .bash\_profile
```
export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
```
and reopen your terminal and try | 9,495 |
69,624,176 | I need to make a letter "C" print using python the code I currently have is down below but I'm not sure how to add 2 stars to the end of the letter. Needed in python.
**Here is my current output:**
```
Enter an odd number 5 or greater: 5
***
*
*
*
*
***
```
**Here is my needed Output:**
```
Enter an odd number ... | 2021/10/19 | [
"https://Stackoverflow.com/questions/69624176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17187287/"
] | You can decouple authentication with authorization to allow more flexible connections between all three entities: Browser, HTTP server, and DB.
To make your second example work you could do:
* The HTTP server (US) submits asynchroneously the query to the DB (Asia) and requests a auth token for it.
* The HTTP server (... | Building on @TheImpalers answer:
How about add another table to your remote DB that is just for retrieving query result?
When client asks the backend service for database query, the backend service will generate a UUID or other secure token and tell the DB to run the query and store it under the given UUID. The backe... | 9,505 |
43,556,353 | I have started learning python and using online interpreter for python 2.9-pythontutor
```
x=5,6
if x==5:
print "5"
else:
print "not"
```
It goes in else loop and print not.
why is that?
what exactly x=5,6 means? | 2017/04/22 | [
"https://Stackoverflow.com/questions/43556353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7747088/"
] | `,` is tuple expr, where `x,y` will return a tuple `(x,y)`
so expression `5,6` will return a tuple `(5,6)`
`x` is nether `5` nor `6` but a tuple | When you declared `x = 5, 6` you made it a tuple. Then later when you do `x == 5` this translates to `(5, 6) == 5` which is not true, so the else branch is run.
If instead you did `x[0] == 5` that would be true, and print 5. Because we are accessing the 0 index of the tuple, which is equal to 5. Check out [some tutori... | 9,507 |
8,572,830 | I am building a django application which depends on a python module where a SIGINT signal handler has been implemented.
Assuming I cannot change the module I am dependent from, how can I workaround the "signal only works in main thread" error I get integrating it in Django ?
Can I run it on the Django main thread?
Is... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8572830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898179/"
] | Django's built-in development server has auto-reload feature enabled by default which spawns a new thread as a means of reloading code. To work around this you can simply do the following, although you'd obviously lose the convenience of auto-reloading:
```
python manage.py runserver --noreload
```
You'll also need ... | Although the question does not describe exactly the situation you are in, here is some more generic advice:
The signal is only sent to the main thread. For this reason, the signal handler should be in the main thread.
From that point on, the action that the signal triggers, needs to be communicated to the other thread... | 9,510 |
40,390,705 | I would like to make an intention list like python does.
```
list = [1,2,3,4]
newList = [ i * 2 for i in list ]
```
Using std,iterator and lambda function, it should be possible to do the same things in one line.
```
std::vector<int> list = {1,2,3,4} ;
std::vector<int> newList =
```
Could you complete it ? | 2016/11/02 | [
"https://Stackoverflow.com/questions/40390705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2708072/"
] | [`std::transform`](http://en.cppreference.com/w/cpp/algorithm/transform) lets you transform values and put them somewhere else:
```
std::vector<int> list = {1,2,3,4};
std::vector<int> newList;
std::transform(
list.cbegin(),
list.cend(),
back_inserter(newList),
[](int x) { return x * 2; });
```
But r... | I found this solution. But it's not very nice .
```
std::vector<int> list = {1,2,3,4};
std::vector<int> newList;
std::for_each(list.begin(), list.end(),[&newList](int val){newList.push_back(val*2);});
``` | 9,515 |
11,333,261 | my views.py file code:
```
#!/usr/bin/python
from django.template import loader, RequestContext
from django.http import HttpResponse
#from skey import find_root_tags, count, sorting_list
from search.models import Keywords
from django.shortcuts import render_to_response as rr
def front_page(request):
if request... | 2012/07/04 | [
"https://Stackoverflow.com/questions/11333261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1493850/"
] | ```
{ % for l in list1 %}
```
should be
```
{% for l in list1 %}
```
and
```
{ % endfor %}
```
should be
```
{% endfor %}
``` | never put a space between '{' and '%' | 9,516 |
13,515,471 | I'm generating a bar-chart with matplotlib. It all works well but I can't figure out how to prevent the labels of the x-axis from overlapping each other. Here an example:

Here is some sample SQL for a postgres 9.1 database:
```
drop table if exi... | 2012/11/22 | [
"https://Stackoverflow.com/questions/13515471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1808868/"
] | I think you're confused on a few points about how matplotlib handles dates.
You're not actually plotting dates, at the moment. You're plotting things on the x-axis with `[0,1,2,...]` and then manually labeling every point with a string representation of the date.
Matplotlib will automatically position ticks. However,... | As for your question on how to show only every 4th tick (for example) on the xaxis, you can do this:
```
import matplotlib.ticker as mticker
myLocator = mticker.MultipleLocator(4)
ax.xaxis.set_major_locator(myLocator)
``` | 9,517 |
37,827,920 | I followed [this](http://www.samontab.com/web/2014/06/installing-opencv-2-4-9-in-ubuntu-14-04-lts/#comment-72178) to install opencv. When I tested the C and Java samples, they worked fine. But the python samples resulted in a
```
import cv2
ImportError: No module named cv2
```
How can I fix this?
I am using pyth... | 2016/06/15 | [
"https://Stackoverflow.com/questions/37827920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6417704/"
] | This is a [well known bug](https://connect.microsoft.com/SQLServer/feedback/details/499608/ssms-can-not-paste-more-than-43679-characters-from-a-column-in-grid-mode) in SSMS, You can't paste more than 43679 char from a grid view column and unfortunately this limit can't be increased, You can get around this by displayin... | The datatypes like NCHAR, NVARCHAR, NVARCHAR(MAX) stores half of CHAR, VARCHAR & NVARCHAR(MAX). Because these datatype used to store UNICODE characters. Use these datatypes when you need to store data other then default language (Collation). UNICODE characters take 2 bytes for each character. That's why lenth of NCHAR,... | 9,522 |
65,716,401 | I am trying to install numpy on a macOS
Big Sur but got this error.
I've tried update pip and setuptool, also
update xcode, but the error still appears
```
ERROR: Command errored out with exit status 1:
command: /Users/mac/opt/miniconda3/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private... | 2021/01/14 | [
"https://Stackoverflow.com/questions/65716401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15004197/"
] | Looks like `gcc` compiler or some system library dependencies problem.
Here is mine `gcc` version (MacOS Catalina)
```
$ which gcc
```
```
/usr/bin/gcc
```
```
$ gcc --version
```
```
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDK... | According to similar problem in this link (<https://github.com/numpy/numpy/issues/12026>). You installation tries to compile numpy on your system, which is not necessary. Try to install concrete version of numpy, e.g. `pip3 install numpy==1.19.5` | 9,524 |
41,769,507 | I have a set of strings that's JSONish, but totally JSON uncompliant. It's also kind of CSV, but values themselves sometimes have commas.
The strings look like this:
ATTRIBUTE: Value of this attribute, ATTRIBUTE2: Another value, but this one has a comma in it, ATTRIBUTE3:, another value...
The only two patterns I ca... | 2017/01/20 | [
"https://Stackoverflow.com/questions/41769507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3430943/"
] | **Mistake # 1**
```
if (a=0) // condition will be always FALSE
```
must be
```
if (a==0)
```
or better
```
if (0 == a)
```
**Mistake # 2**
```
scanf("%d", &b); // when b is float
```
instead of
```
scanf("%f", &b);
```
**UPDATE:**
Actually, for case of checking results of `scanf` I personally prefer t... | Code with corrections and comments - also available here - <http://ideone.com/eqzRQe>
```
#include <stdio.h>
#include <math.h>
int main(void) {
float b;
// printf("Eneter a float number");
printf("Enter a float number"); // Corrected typo
fflush(stdout); // Send the buffer to the console so the user ca... | 9,525 |
39,540,128 | I was playing around with the `dis` library to gather information about a function (like what other functions it called). The documentation for [`dis.findlabels`](https://docs.python.org/2/library/dis.html#dis.findlabels) sounds like it would return other function calls, but I've tried it with a handful of functions an... | 2016/09/16 | [
"https://Stackoverflow.com/questions/39540128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1547004/"
] | No, do not explicitly assign a default value to `Freight`.
The warning is legitimate, because you never really assign a value to the field.
You do not assign a value, because the field gets populated by magic. (Incidentally, that's why I do not like magic; but that's a different story altogether.)
So, the best appr... | You essentially have two choices and which way to go really depends on the intent (to suggest one or the other is subjective). First, you could eliminate the warning if the design requirement of your `Orders` type dictates that it should have a null default value.
```
public string Freight = null;
```
The above mere... | 9,526 |
27,872,305 | I have a table with 12 columns and want to select the items in the first column (`qseqid`) based on the second column (`sseqid`). Meaning that the second column (`sseqid`) is repeating with different values in the 11th and 12th columns, which are`evalue`and`bitscore`, respectively.
The ones that I would like to get are... | 2015/01/10 | [
"https://Stackoverflow.com/questions/27872305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1918515/"
] | ```
#!usr/bin/python
import csv
DATA = "data.txt"
class Sequence:
def __init__(self, row):
self.qseqid = row[0]
self.sseqid = row[1]
self.pident = float(row[2])
self.length = int(row[3])
self.mismatch = int(row[4])
self.gapopen = int(row[5... | ```
filename = 'data.txt'
readfile = open(filename,'r')
d = dict()
sseqid=[]
lines=[]
for i in readfile.readlines():
sseqid.append(i.rsplit()[1])
lines.append(i.rsplit())
sorted_sseqid = sorted(set(sseqid))
sdqDict={}
key =None
for sorted_ssqd in sorted_sseqid:
key=sorted_ssqd
evalue=[]
bitsco... | 9,529 |
44,063,297 | In python, I'm trying to extract 4 charterers before and after '©' symbol,this code extracts the characters after ©,can anyone help printing the characters before © (I don't want the entire string to get print,only few characters)
```
import re
html = "This is all test and try things that's going on bro Copyright©... | 2017/05/19 | [
"https://Stackoverflow.com/questions/44063297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6228540/"
] | ```
html = "This is all test and try things that's going on bro Copyright© Bro Code Bro"
html = html.split("©")
print(html[0][-4:])
print(html[1][:4])
```
Output :
```
ight
Bro
``` | Try doing it this way :
```
if "©" in html:
pos_c = html.find("©")
symbol = html[pos_c-4:pos_c]
print symbol
``` | 9,534 |
65,635,575 | I get the following error when I attempt to load a saved `sklearn.preprocessing.MinMaxScaler`
```
/shared/env/lib/python3.6/site-packages/sklearn/base.py:315: UserWarning: Trying to unpickle estimator MinMaxScaler from version 0.23.2 when using version 0.24.0. This might lead to breaking code or invalid results. Use a... | 2021/01/08 | [
"https://Stackoverflow.com/questions/65635575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7253453/"
] | The issue is you are training the scaler on a machine with an older verion of sklearn than the machine you're using to load the scaler.
Noitce the `UserWarning`
`UserWarning: Trying to unpickle estimator MinMaxScaler from version 0.23.2 when using version 0.24.0. This might lead to breaking code or invalid results. U... | I solved this issue with `pip install scikit-learn==0.23.2` in my conda or cmd. Essentially downgrading the scikit module helped. | 9,541 |
40,511,177 | I am actually new to python. While learning it I came across this piece of code.
Python official document says when encounter with continue statement,
control will shift to the beginning of the loop, but in this case it is shifting to final statement and executing from there onward. Is this a bug in python or what? C... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40511177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6250108/"
] | The `finally` code is always executed in a `try/except` block.
The `continue` doesn't skip it (or it would be a bug in python). | The `finally` clause **must be executed** no matter what happens, and so it is.
This is why it's called `finally`: it doesn't matter whether what you have *tried* succeeded or raised an *except*ion, it is *always* executed. | 9,546 |
30,080,491 | I am trying to reproduce the algorithm described in the Isolation Forest paper in python. <http://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf?q=isolation>
This is my current code:
```
import numpy as np
import sklearn as sk
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.decomposition i... | 2015/05/06 | [
"https://Stackoverflow.com/questions/30080491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2411173/"
] | ```
self.anomaly_score_ = _anomaly_score(self.all_anomaly_score_, n_samples)
```
You're calculating \_anomaly\_score with n\_samples which is total number of samples. However, you are building trees with subsamples. Therefore, when you're calculating the average search length '\_c(n)' you should use sample\_size inst... | There is a pull-request in scikit-learn: <https://github.com/scikit-learn/scikit-learn/pull/4163> | 9,551 |
46,572,148 | I am receiving the following error message in spyder.
Warning: You are using requests version , which is older than requests-oauthlib expects, please upgrade to 2.0.0 or later.
I am not sure how i upgrade requests. I am using python 2.7 as part of an anaconda installation | 2017/10/04 | [
"https://Stackoverflow.com/questions/46572148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7426556/"
] | **1)** To the best of my knowledge as of early Nov, 2017 you are correct: there is no commonly available way to compile Swift to WebAssembly. Maybe some enterprising hacker somewhere has made it happen but if so she hasn't shared her code with us yet.
**2)** In order to enable Wasm support you will probably need to ha... | WebAssembly target would be like a generic unix target for llvm, so I think someone needs develop that port.
Please note that Swift -> Wasm in browser would be pretty much useless because Wasm has no DOM or DOM API access so you still need JavaScript to do anything meaningful, thus the question: why would anyone bothe... | 9,556 |
30,229,231 | I got a problem when I am using python to save an image from url either by urllib2 request or urllib.urlretrieve. That is the url of the image is valid. I could download it manually using the explorer. However, when I use python to download the image, the file cannot be opened. I use Mac OS preview to view the image. T... | 2015/05/14 | [
"https://Stackoverflow.com/questions/30229231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4898319/"
] | It is the simplest way to download and save the image from internet using **urlib.request** package.
Here, you can simply pass the image URL(from where you want to download and save the image) and directory(where you want to save the download image locally, and give the image name with .jpg or .png) Here I given "loc... | download and save image to directory
====================================
```
import requests
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en... | 9,566 |
31,550,622 | I can call MATLAB from my system python:
```
>>> import matlab.engine
>>>
```
but when I load a virtual environment, I now get a segfault:
```
>>> import matlab.engine
Segmentation fault: 11
```
I've run the [setup.py install instructions](http://www.mathworks.com/help/matlab/matlab_external/install-the-matlab-e... | 2015/07/21 | [
"https://Stackoverflow.com/questions/31550622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362703/"
] | I did this:
```
cd "matlabroot\extern\engines\python"
python setup.py install --prefix="installdir"
```
Where the `installdir` is my virtualenv, `matlabroot` the directory for the MatLab install.
Seems to work with my windows server, so far, so good.
Reference here:
<https://www.mathworks.com/help/matlab/matlab_e... | I ran the "`python setup.py install`" from `matlabroot\extern\engines\python` with my virtual environment active. Note that I did use `venv`. | 9,576 |
37,465,816 | The Getting Started docs for aiohttp give the following client example:
```
import asyncio
import aiohttp
async def fetch_page(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
assert response.status == 200
return await response.read()
loop = asynci... | 2016/05/26 | [
"https://Stackoverflow.com/questions/37465816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58866/"
] | Just don't use the result of `session.get()` as a context manager; use it as a coroutine directly instead. The request context manager that `session.get()` produces would normally [*release* the request](http://pythonhosted.org/aiohttp/client_reference.html#aiohttp.ClientResponse.release) on exit, but [so does using `r... | `aiohttp`'s [examples](https://github.com/KeepSafe/aiohttp/tree/master/examples) implemented using 3.4 syntax. Based on [json client example](https://github.com/KeepSafe/aiohttp/blob/master/examples/client_json.py) your function would be:
```
@asyncio.coroutine
def fetch(session, url):
with aiohttp.Timeout(10):
... | 9,578 |
52,211,917 | Trying to create a batch script for windows that runs a program with python3 if available else python2.
I know the script can be executed with `$py -2 script.py`
and py3 with `$py -3 script.py`.
and if I run `py -0`, it returns all the python versions.
How do I build this script?
I do not want to check if the pytho... | 2018/09/06 | [
"https://Stackoverflow.com/questions/52211917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252492/"
] | Not a full solution, but a method to detect which version of Python is installed:
You can check if Python 3 is installed by running `py -3 --version` and then checking the `%ERRORLEVEL%` variable in the batch script. If it is 0, then `py -3 --version` was successful, i.e. Python 3 is installed on the system. If it is ... | You can do it without temporary file
```
set PYTHON_MAJOR_VERSION=0
for /f %%i in ('python -c "import sys; print(sys.version_info[0])"') do set PYTHON_MAJOR_VERSION=%%i
``` | 9,579 |
67,644,959 | Since the code was cryptic I decided to reformulate it.
This code is trying to remove the second element from a linked list (the node with number 2 on "int data"). The first parameter of remove\_node is the address of the first pointer of the list, so if I have to remove the first pointer of the list I am able to star... | 2021/05/22 | [
"https://Stackoverflow.com/questions/67644959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15996314/"
] | First of all, if the first `while` loop stops due to `*address_of_ptr == NULL`, then the line
`address_of_ptr = &((*address_of_ptr)->next);`
will cause undefined behavior, due to deferencing a `NULL` pointer. However, this will not happen with the sample input provided by the function `main`, so it is not the cause o... | This line:
```
begin_list = &previous->next;
```
You might be mis-thinking how pointers to pointers work. Since `begin_list` is a `t_list **`, you generally want to assign to `*begin_list`. Also, since `previous->next` is already an address, you don't want to assign the address to `*begin_list`, just the value, so t... | 9,581 |
50,187,041 | I need help with my python program. I'm doing a calculator.
The numbers must be formed, but for some reason they do not add up.
It seems that I did everything right, but the program does not work.
Please help me. [Picture](https://i.stack.imgur.com/777SB.png)
Code:
```
a = input('Enter number A \n');
d = input('En... | 2018/05/05 | [
"https://Stackoverflow.com/questions/50187041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9744650/"
] | Please don't post screenshots. Copy and paste text and use the {} CODE markdown.
What data type is returned by input()? It's always a string. It doesn't matter what you type.
Where is the variable c actually calculated in this program? Line 4.
What types of data are used to compute c? Two strings.
What happens when... | `a` and `b` are strings.
`a + b` concatenates strings `a` and `b`.
You need to convert the strings to int:
`c = int(a) + int(b)`
And remove the lines:
```
if str(d) == "+":
int(c) == "a + b"
``` | 9,585 |
9,776,332 | I wrote a python program that needs to call aircrack program to some tasks, but I run into trouble with the privilege. Initially the aircrack program is called in command line, it requires "sudo" at the beginning. After that I checked the location of the executable and found that it locates under `/usr/sbin/`. Right no... | 2012/03/19 | [
"https://Stackoverflow.com/questions/9776332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] | first, none of us can replace the chmod man page (so i'll start by quoting it):
```
A numeric mode is from one to four octal digits (0-7), derived by adding up the bits
with values 4, 2, and 1. Omitted digits are assumed to be leading zeros. The first
digit selects the set user ID (4) and set group ID (2)... | You have to set the suid flag for all users.
```
sudo chmod ogu+sxr /usr/sbing/airodump-ng
``` | 9,588 |
7,377,494 | I'm trying to scrape a page using python
The problem is, I keep getting Errno54 Connection reset by peer.
The error comes when I run this code -
```
urllib2.urlopen("http://www.bkstr.com/webapp/wcs/stores/servlet/CourseMaterialsResultsView?catalogId=10001&categoryId=9604&storeId=10161&langId=-1&programId=562&term... | 2011/09/11 | [
"https://Stackoverflow.com/questions/7377494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/915672/"
] | ```
$> telnet www.bkstr.com 80
Trying 64.37.224.85...
Connected to www.bkstr.com.
Escape character is '^]'.
GET /webapp/wcs/stores/servlet/CourseMaterialsResultsView?catalogId=10001&categoryId=9604&storeId=10161&langId=-1&programId=562&termId=100020629&divisionDisplayName=Stanford&departmentDisplayName=ILAC&courseDispl... | I came across a similar error just recently. The connection was dropping out and being reset. I tried cookiejars, extended delays and different headers/useragents, but nothing worked. In the end the fix was simple. I went from urllib2 to requests. The old;
```
import urllib2
opener = urllib2.build_opener()
buf = opene... | 9,589 |
50,983,646 | I have a dataframe like this:
```
df = pd.DataFrame({'timestamp':pd.date_range('2018-01-01', '2018-01-02', freq='2h', closed='right'),'col1':[np.nan, np.nan, np.nan, 1,2,3,4,5,6,7,8,np.nan], 'col2':[np.nan, np.nan, 0, 1,2,3,4,5,np.nan,np.nan,np.nan,np.nan], 'col3':[np.nan, -1, 0, 1,2,3,4,5,6,7,8,9], 'col4':[-2, -1, 0,... | 2018/06/22 | [
"https://Stackoverflow.com/questions/50983646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6435921/"
] | Since it's a response header i assume you mean this:
```
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
``` | Another option if you are not using `Context`:
```
func setResponseHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
h.ServeHTTP(w, r)
}
}
```
`setResponseHeader` is essentially a decorator of... | 9,590 |
41,846,085 | I am doing this python programming and stuck with an issue.
The program cannot call the value of the n\_zero when I put it in the conditional statement.
Here's the program
```
import numpy as np
n_zero=int(input('Insert the amount of 0: '))
n_one =int(input('Insert the amount of 1: '))
n_two =int(input('Insert the... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41846085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7456346/"
] | In python you don't cast the left value variable as you don't specify the left value type.
```
n_zero=int(input('Insert the amount of 0: '))
```
**Regarding your edit:**
What exactly are you trying to reach? if multiply than use the operator \*
```
if len(data)==(2*(n_zero)-1):
...
``` | ```
if len(data) == (2(n_zero) - 1):
```
should become:
```
if len(data) == (2 * (n_zero) - 1):
```
Note `*` in second example. You must explicitly provide operator, Python will not assume that You want to multiply those 2 numbers if You don't tell it. | 9,592 |
62,191,477 | somebody can explain why docker does not wanna run Django server
Thats my structure of project:
```
app
bankproject
env
docker-compose.yml
Dockerfile
manage.py
requirements.txt
```
There is my file Docker:
```
# pull official base image
FROM python:3.8.0-alpine
# set work dir... | 2020/06/04 | [
"https://Stackoverflow.com/questions/62191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13678793/"
] | You haven't declared a `ref` and passed it to `HeaderComponent`, see [`useRef` hook](https://reactjs.org/docs/hooks-reference.html#useref).
```
const App = () => {
const calendarRef = useRef();
React.useEffect(() => {
console.log(calendarRef.current);
}, []);
return (
<div className="App">
<Hea... | You should define a ref in the App component and pass it on to the HeaderComponent
```
const App = () => {
let calendarRef = useRef();
return (
<div className="App">
<HeaderComponent calendarRef={calendarRef} />
<Calendar ref={calendarRef} height="100vh" />
</div>
);
};
export default App;
... | 9,593 |
32,080,635 | I am looking into Python's **Least Recently Used (LRU) cache** implementation [here](http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/).
Can someone please explain what the `_make_key` function is doing?
```
def _make_key(args, kwds, typed,
kwd_mark = (object(),),... | 2015/08/18 | [
"https://Stackoverflow.com/questions/32080635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4677617/"
] | The function is converting a set of function arguments to a sequence that (a) can be hashed and (b) returns the same hash value for the same arguments, if a function is invoked multiple times with the same arguments.
Obviously, `args` and `kwargs` are intended to be the positional and keyword arguments of a generic fu... | Summary
-------
The *\_make\_key()* function flattens the arguments into a compact tuple that can be used to determine whether the arguments for two calls are the same.
Generated keys
--------------
The call `f(10, 20, x=30, y=40)` and `f(10, 20, y=40, x=30)` both have the same key:
```
(10, 20, <object object at 0... | 9,594 |
51,361,441 | I want to rewrite a `python` code for calculating accumulated result of `max`. I refered to numpy [documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html)
Input:
`[7200,7050,7300,7500,7440,7200,7300,7280,7400]`
Output:
`[7200, 7200, 7300, 7500, 7500, 7500, 7500, 7500, 7500]`
... | 2018/07/16 | [
"https://Stackoverflow.com/questions/51361441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3911211/"
] | Something like this is inline, more or less:
```js
var max = 0;
var input = [7200, 7050, 7300, 7500, 7440, 7200, 7300, 7280, 7400];
var output = input.map(function(e) {
return max > e ? max : max = e;
});
console.log(output);
```
Inspired by [Pierre's answer](https://stackoverflow.com/a/51361720/2959522), here... | One line solution with `Array.from()` :
```js
var arr = [7200, 7050, 7300, 7500, 7440, 7200, 7300, 7280, 7400];
var output = Array.from({length:arr.length}, (el,i) => Math.max(...arr.slice(0,i+1)))
console.log(output);
``` | 9,595 |
53,057,646 | Here is my code for upload a file to S3 bucket sing boto3 in python.
```
import boto3
def upload_to_s3(backupFile, s3Bucket, bucket_directory, file_format):
s3 = boto3.resource('s3')
s3.meta.client.upload_file(backupFile, s3Bucket, bucket_directory.format(file_format))
upload_to_s3('/tmp/backup.py', 'bsfbac... | 2018/10/30 | [
"https://Stackoverflow.com/questions/53057646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3440631/"
] | A CAN transceiver is just a high speed step down converter. (on a basic level)
CAN protocol works in a variant of voltage ranges. MCP2551 is a set CAN transceiver suitable for 12V and 24V systems. With added features to help with the physical layer like `externally-controlled slope` for reduced RFI emissions, `detecti... | For software, look for the CANtact open source project on Github. It is an implementation for the STM32F042. I had to adapt the project to build it under Atollic but it was not too hard and it works. It provides a SLCAN type of interface over a virtual COM port over USB, which is very fast and convenient.
There is als... | 9,597 |
59,433,681 | I have the following data in terms of dataframe
```
data = pd.DataFrame({'colA': ['a', 'c', 'a', 'e', 'c', 'c'], 'colB': ['b', 'd', 'b', 'f', 'd', 'd'], 'colC':['SD100', 'SD200', 'SD300', 'SD400', 'SD500', 'SD600']})
```
I want the output as attached
[enter image description here][2]
I want to achieve this using pa... | 2019/12/21 | [
"https://Stackoverflow.com/questions/59433681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12054665/"
] | You can try:
```
Column A Column B Column C
0 a b SD100
1 c d SD200
2 a b SD300
3 e f SD400
4 c d SD500
5 c d SD600
```
---
```
>>> df.groupby(['Column A', 'Column B']).agg(list)
C... | I don't know why you want to make multindex, but you can simply `sort_values` or use `groupby`.
```py
import pandas as pd
df = pd.DataFrame({"ColumnA":['a','c','a','e','c','c'],
"ColumnB":['b','d','b','f','d','d'],
"ColumnC":['SD100','SD200','SD300','SD400','SD500','SD600']})
print(df... | 9,598 |
10,308,639 | I want to install the newest version of `numpy` (a numerical library for Python), and the version (v1.6.1) is not yet in the [Ubuntu Oneiric repositories](https://launchpad.net/ubuntu/oneiric/+source/python-numpy). When I went ahead to manually install it, I read in the [INSTALL](https://github.com/numpy/numpy/blob/mas... | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781938/"
] | From the same `INSTALL` file you referenced...
```
How to check the ABI of blas/lapack/atlas
-----------------------------------------
One relatively simple and reliable way to check for the compiler used to build
a library is to use ldd on the library. If libg2c.so is a dependency, this
means that g77 has been used.... | I know of no easy way, though you may find `readelf -a /usr/lib/$SHARED_OBJECT` illuminating, where `$SHARED_OBJECT` is something like `/usr/lib/atlas-base/liblapack_atlas.so.3gf.0` (you'll have to look in your `/usr/lib` to see what your exact filename is).
However, there is another, quite different way to get inform... | 9,601 |
69,102,556 | I'm having troubles with grouping my list
so let's say I have this:
```
data = [
{'records-0': '1'}, {'records-0-item1': '2'}, {'records-0-item2': '3'},{'records-0-item3': '4'},
{'records-1': '1'}, {'records-1-item1': '2'}, {'records-1-item2': '3'},
]
```
What I'm trying to have is my list sorted based on the index... | 2021/09/08 | [
"https://Stackoverflow.com/questions/69102556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11868566/"
] | One way is to use [default\_dict](https://docs.python.org/3/library/collections.html#collections.defaultdict).
First, just define a helper method to get the key from the string:
```
def get_key_from(string):
return int(string.split('-')[1])
```
Then
```
from collections import defaultdict
sortedData_res = def... | I suggest you reformat your sortedData and remove lists. You could gather your data only into dict.
*Edited* example: (should work as is)
```py
def sort_data(l_: list):
d_ = dict()
for d in l_:
for k, v in d.items():
i = re.split('-', k)[1]
if not d_.get(int(i)):
... | 9,602 |
24,946,479 | Are most functions for http requests synchronous by default?
I came from Javascript and usage of AJAX and just started working with http requests in Python. To my surprise, it seems as though http request functions by default are synchronous, so I do not need to deal with any asynchronous behavior. For example, I'm w... | 2014/07/25 | [
"https://Stackoverflow.com/questions/24946479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502780/"
] | It's the language, in python most apis are synchronous by default, and the async version is usually an "advanced" topic. If you were using nodejs, they would be async; even if using javascript, the reason ajax is asynchronous is because of the nature of the browser. | `requests` is completely synchronous/blocking. [`grequests`](https://github.com/kennethreitz/grequests) is what you are looking for:
>
> GRequests allows you to use Requests with Gevent to make asynchronous
> HTTP Requests easily.
>
>
>
See also:
* [Asynchronous Requests with Python requests](https://stackoverf... | 9,603 |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you could use `pip install pypiwin32` instead. | If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32 | 9,604 |
70,456,516 | Here is the minimal code needed to reproduce the problem.
I call an API with a callback function that prints what comes out of the API call.
If I run this code in Jupyter, I get the output. If I run it with `python file.py` I don't get any output. I already checked the API's code, but that does nothing weird. Setting... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12210524/"
] | Because you're using a websocket, the callback is executed by a different thread, which means that if you don't wait, the main thread (which is to receive the `print`'s output) will already be killed.
Add a `sleep(1)` (that's seconds, not ms) at the end and the output will show.
PS: The reason Jupyter *does* show the... | ```
import time
from python_bitvavo_api.bitvavo import Bitvavo
# %%
def generic_callback(response):
print(f"log function=get_markets, {response=}")
bitvavo = Bitvavo({"DEBUGGING": False})
websocket = bitvavo.newWebsocket()
# Wait N.1 required to receive output, otherwise the main thread is killed
time.sleep(1)
... | 9,614 |
28,622,452 | I want to print the files in subdirectory which is 2-level inside from root directory. In shell I can use the below find command
```
find -mindepth 3 -type f
./one/sub1/sub2/a.txt
./one/sub1/sub2/c.txt
./one/sub1/sub2/b.txt
```
In python How can i accomplish this. I know the basis syntax of os.walk, glob and fnmatch... | 2015/02/20 | [
"https://Stackoverflow.com/questions/28622452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4566486/"
] | You could use `.count()` method to find the depth:
```
import os
def files(rootdir='.', mindepth=0, maxdepth=float('inf')):
root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
for dirpath, dirs, files in os.walk(rootdir):
depth = dirpath.count(os.path.sep) - root_depth
if mindepth ... | You cannot specify any of this to [os.walk](https://docs.python.org/2/library/os.html#os.walk).
However, you can write a function that does what you have in mind.
```
import os
def list_dir_custom(mindepth=0, maxdepth=float('inf'), starting_dir=None):
""" Lists all files in `starting_dir`
starting from a `min... | 9,615 |
45,445,455 | In python I might have a function like this:
```
def sum_these(x, y=None):
if y is None:
y = 1
return x + y
```
What is the equivalent use in julia? To be exact I know I could probably do:
```
function sum_these(x, y=0)
if y == 0
y = 1
end
x + y
end
```
However I'd rather ... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45445455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6411264/"
] | Maybe use multiple dispatch with an empty fallback?
```
function f(x, y=nothing)
...
do_something(x, y)
...
return something
end
do_something(x, y) = nothing
function do_something(x, y::Void)
...
end
```
add other relevant vars to `do_something` as necessary, and return something or mutate as ne... | Your question is a bit confusing. It seems like what you want is
```
function sum_these(x, y=1)
return x + y
end
```
But that doesn't quite do what you are asking either, since even if you call `sum_these(3, 0)` in your example, it replaces 0 with 1.
Also in Python, I would use
```
def sum_these(x, y=1):
r... | 9,616 |
48,216,974 | The curve is:
```
import numpy as np
import scipy.stats as sp
from scipy.optimize import curve_fit
from lmfit import minimize, Parameters, Parameter, report_fit#
import xlwings as xw
import os
import pandas as pd
```
I tried running a simply curve fit from scipy:
This returns
```
Out[156]:
(array([ 1., 1.]), arra... | 2018/01/11 | [
"https://Stackoverflow.com/questions/48216974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504877/"
] | The curve fitting runs smoothly when we provide a good starting point. We can get one
* by linear regression on `sp.norm.ppf(x_data)` and `np.log(y_data)`
* or by fitting the free (non-clipped) model first
Alternatively, if you want the computer to find the solution without "help"
* use a stochastic algorithm like b... | I think that part of the problem is that you have only 5 observations, 2 at the same value of `x` and the model does not perfectly represent your data. I also recommend trying to fit in the log of the model to the log of the data. And, if you expect `n2` to be ~10, you should use that as a starting value.
Arbitrarily... | 9,619 |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html>
I use the following method to execute commands on a password protected client:
```
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
... | ThePracticalOne - you are hero!
I had problems with exec\_command (which is a member of Client)
I tried to run powershell commands over ssh on Windows server, and only your example with
```
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
```
and
```
while True:
... | 9,622 |
25,086,088 | I've spent the better part of an afternoon trying to import the xlrd module, it works when i do it in the shell but when i try to run any file I get an import error.
Please could somebody provide a solution? (I'm a beginner, so please be excruciatingly specific)
This code:
```
#!/usr/bin/python
import os
os.chdir("... | 2014/08/01 | [
"https://Stackoverflow.com/questions/25086088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3900424/"
] | They are overlapping because you've given them all absolute position and left 0. Absolute position removes the element from the normal flow of the page and puts it exactly where you indicate using the top/left/right/bottom properties. They will overlap as long as they have the same parent and same position properties. | They are overlapping because you are using position absolute. instead place the divs at the top of the html page and do this instead:
```
<div id="left" style="float:left;width:60%;height:100%;background:#e6e6e6;">
<div id="map" style="float:left;width:60%;height:400px">Map goes here.</div>
<div id="details" style="fl... | 9,632 |
55,550,259 | I would like to find a way to reverse the bits of each character in a string using python.
For example, if my first character was `J`, this is ASCII `0x4a` or `0b01001010`, so would be reversed to `0x52` or `0b01010010`. If my second character was `K`, this is `0b01001011`, so would be reversed to `0xd2` or `0b1101001... | 2019/04/06 | [
"https://Stackoverflow.com/questions/55550259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4263190/"
] | If speed is your goal and you are working with ASCII so you only have 256 8-bit values to handle, calculate the reversed-byte values beforehand and put them in a `bytearray`, then look them up by indexing into the `bytearray`. | ```
a=bin(ord("a"))
'0b'+a[::-1][0:len(a)-2]
```
If you want to do it for a lot of characters, then there are only 256 ascii characters. Store the reversed strings in a hashmap and do lookups on the hashmap. Time complexity of those lookups is O(1), but there's a fix setup time. | 9,634 |
22,384,783 | I am trying to use C# classes from python, using python.net on mono / ubuntu.
So far I managed to do a simple function call with one argument work. What I am now trying to do is pass a python callback to the C# function call.
I tried the following variations below, none worked. Can someone show how to make that work?... | 2014/03/13 | [
"https://Stackoverflow.com/questions/22384783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477436/"
] | Try to pass `Action` or `Func` instead of just raw function:
I used IronPython here (because right now I don't have mono installed on any of my machines but according of Python.NET [documentation](http://pythonnet.sourceforge.net/readme.html) I think it should work
Actually your code is almost ok but you need to impor... | It looks like you should define your Delegate explicitly:
```
class MC {
// Define a delegate type
public delegate void Callback();
public double method2(Callback f) {
Console.WriteLine("Executing method2" );
/* ... do f() at some point ... */
/* also tried f.DynamicInvoke() */
... | 9,636 |
56,692,868 | I am trying to write a mock lottery simulator as a thought excercize and for some introductory python practice, where each team would have 2x the odds of getting the first pick as the team that preceded them in the standings. The code below works (although I am sure there is a more efficient way to write it), but now I... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56692868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10918881/"
] | Instead of doing your sampling like this, I would use a discrete distribution for the probability of getting the team i, and sample using random.choices. We update the distribution after the sampling by discarding all the tickets from that team (since it cannot appear again).
```
from random import choices
ticket_amou... | Here is what you want I think, but as the other comment said it runs very slow and I would not try 10 million times, its slow enough as is.
```
from collections import Counter
for i in range(1,10000):
random.shuffle(total)
countList.append(total[0])
print Counter(countList)
```
add the for loop to the end o... | 9,637 |
56,533,066 | I'm trying to write a request using Python Requests which sends a request to Docusign. I need to use the legacy authorization header, but unfortunately it seems most documentation for this has been removed. When I send the request I get an error as stated in the title.
From research, I found that special characters i... | 2019/06/10 | [
"https://Stackoverflow.com/questions/56533066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6490748/"
] | I'm able to reproduce this behavior: It looks like DocuSign doesn't accept Single Quotes around the sub-parameters of the x-DocuSign-Authentication header value.
Your example fails:
```
{'Username': '[email protected]', 'Password': 'xxxxxxxxxx', 'IntegratorKey': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}
```
This has more... | Since you are having success using Postman, it will help to get exactly what is being sent via your request. For this use:
```py
response = requests.get(your_url, headers=your_headers)
x = response.request.headers()
print(x)
```
This will show you exactly what requests is preparing and sending off. If you post that ... | 9,639 |
18,139,910 | I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request.
I prototyped a simple Flask app for demonstrating my problem:
```
#!/usr/bin/env python
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def run... | 2013/08/09 | [
"https://Stackoverflow.com/questions/18139910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236401/"
] | According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions):
>
> ...
> What this means is that the user could look at the contents of your
> cookie but not modify it, unless they know the secret key used for
> signing.
>
>
> In order to use sessions you **have to set a secret ke... | Under `app = Flask(__name__)` place this: `app.secret_key = os.urandom(24)`. | 9,641 |
52,113,440 | Looking for data splitter line by line, by using python
* RegEx?
* Contain?
As example file "file" contain:
```
X
X
Y
Z
Z
Z
```
I need the clean way to split this file into 3 different ones, based on letter
**As a sample:**
```
def split_by_platform(FILE_NAME):
with open(FILE_NAME, "r+") as infile:
... | 2018/08/31 | [
"https://Stackoverflow.com/questions/52113440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | EDIT thanks to @bruno desthuilliers, who reminded me of the correct way to go here:
Iterate over the file object (not 'readlines'):
```
def split_by_platform(FILE_NAME, out1, out2, out3):
with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3:
for line... | This should do it:
```
with open('my_text_file.txt') as infile, open('x.txt', 'w') as x, open('y.txt', 'w') as y, open('z.txt', 'w') as z:
for line in infile:
if line.startswith('X'):
x.write(line)
elif line.startswith('Y'):
y.write(line)
elif line.startswith('Z'):
... | 9,644 |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | Upgrade the numpy to solve the error
```
pip install numpy --upgrade
``` | ensure that you're using python 3.x by running it as
```py
python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
``` | 9,646 |
69,837,913 | I am trying to unpickle a file but i get this error while running the following code:
```
import pickle
import pandas as pd
import numpy
unpickled_df = pd.read_pickle("./ToyData.pickle")
unpickled_df
```
or
```
import pickle
# load : get the data from file
data = pickle.load(open('ToyData.pickle', "rb"))
```
erro... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69837913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17326771/"
] | You cannot pickle.load files in a newly updated version of xarray that were made in a previous version of xarray.
This is a known error that has no solution as "pickling is not recommended for long-term storage".
<https://github.com/pydata/xarray/discussions/5642>
.hdf or .json are better alternatives for long-term s... | I had the same problem with `results = torch.load("results.pth.tar")` and get "`AttributeError: Can't get attribute 'PandasIndexAdapter' on <module 'xarray.core.indexing'`".
I solve it by changing the version I have on my computer by the version the file.pth.tar was saved with.
In my case the file was saved with xarra... | 9,656 |
68,964,555 | I don't know why I am getting this error, the official document reference
<https://scikit-learn.org/stable/modules/generated/sklearn.metrics.det_curve.html#sklearn.metrics.det_curve>
**Code:**
```
import numpy as np
from sklearn.metrics import det_curve
fpr, fnr, thresholds = det_curve(y_test, y_pred)
print(fpr, ... | 2021/08/28 | [
"https://Stackoverflow.com/questions/68964555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385107/"
] | Looks like some issue with a missing package. Try the following:
```
pip uninstall -v scikit-learn
pip install -v scikit-learn
```
This might install the related dependencies along with it. | Same kind of problem happened to me in my Jupyter notebook. I uninstall and re-install both scikit-learn and imblearn. It didn't work. Then **restarting the kernel** and running again solved the problem. | 9,657 |
36,314,411 | Given a file with resolution-compressed binary data, I would like to convert the sub-byte bits into their integer representations in python. By this I mean I need to interpret `n` bits from a file as an integer.
Currently I am reading the file into `bitarray` objects, and am converting subsets of the objects into int... | 2016/03/30 | [
"https://Stackoverflow.com/questions/36314411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176806/"
] | The whole solution :)
Only javascript section is modified.
```
<div id="divCountries" class="fieldRow">
<div class="leftLabel labelWidth20">
<label for="txtcountries">Country:</label>
</div>
<div class="LeftField">
<div class="formField34">
<select id="txtCountries" type="text" name="Countries" alt="Countries... | See this [fiddle](https://jsfiddle.net/lalu050/Lcu4jp91/)
---------------------------------------------------------
That was because the value that was returned from `document.getElementById("txtCountries").value` was `UnitedStates` and not `United States`.
Please note that the option for United States was as follows... | 9,658 |
59,307,832 | I'm slowly trying to get my head around classes. I have a few working examples which i kinda understand but can someone please explain to me why this doesn’t work?
```
class python:
def __init__(self,name):
self.name=name
def changename(self,newname):
self.name=newname
abc=python('python')
print abc.nam... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59307832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6037160/"
] | You can have an HTML5 `audio` tag in base64 encoding as so:
```html
<audio controls autoplay loop src="data:audio/ogg;base64,BASE64CODE" />
```
No need for a `type`! :) | If your audio files are over about 20MB then you might run into performance problems and errors in some browsers (notably Firefox). For this reason I recommend converting the Base64 into a binary Blob as described [here](https://stackoverflow.com/a/40329529/1417989) using the [convertDataURIToBinary](https://gist.githu... | 9,660 |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | I wrote an explanation about this in my answer to this question.
[How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal)
In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it... | The first time it considers it to be input, the second time it's for keeps!
This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered. | 9,661 |
43,518,430 | How to convert
```
json_decode = [{"538":["1,2,3","hello world"]},{"361":["0,9,8","x,x,y"]}]
```
to
```
{"538":["1,2,3","hello world"],"361":["0,9,8","x,x,y"]}
```
in python? | 2017/04/20 | [
"https://Stackoverflow.com/questions/43518430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6742101/"
] | ***Try like this:***
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edittext = (EditText) findViewbyId(R.id.edittext);
editText.setText("DefaultValue");
}
``` | Add in xml layout file
```
android:text="defaultVal"
```
In onClick method or constructor/init method in java
```
editText.setText("DefaultValue");
``` | 9,669 |
17,803,254 | I want to find my public ip adress from python program.
So far this is the only site
<http://www.whatismyip.com/>
and
<http://whatismyip.org/>
which gives ip without proxy rest all give the proxy.
Now .org site is using image and first one writes ip across many span elements so i can't grab with urllib.
Any other... | 2013/07/23 | [
"https://Stackoverflow.com/questions/17803254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667349/"
] | I usually use <http://httpbin.org/>:
```
import requests
ip = requests.get('http://httpbin.org/ip').json()['origin']
``` | Use [lxml](http://lxml.de/)
```
import urllib
import lxml.html
u = urllib.urlopen('http://www.whatismyip.com/')
html = u.read()
u.close()
root = lxml.html.fromstring(html)
print ''.join(x.text for x in root.cssselect('#greenip *'))
``` | 9,670 |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1).
```
string.Join("\n", errorMessages);
``` | Use join
```
string.Join(System.Environment.NewLine, errorMessages);
``` | 9,671 |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Here is the fastest, accurate and efficient implementation as per my tests:
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df.set_value(i, 'HA_Open', ((df.get_... | Numpy version working with Numba
```
@jit(nopython=True)
def heiken_ashi_numpy(c_open, c_high, c_low, c_close):
ha_close = (c_open + c_high + c_low + c_close) / 4
ha_open = np.empty_like(ha_close)
ha_open[0] = (c_open[0] + c_close[0]) / 2
for i in range(1, len(c_close)):
ha_open[i] = (c_open[i ... | 9,681 |
37,187,962 | I have problem with python selenium phantomjs which i couldn't solve. element.location returns wrong location. when I see cropped image it is showing part of desired image and also unwanted one. It worked on firefox perfectly but doesn't work on phantomjs.
Here is code:
```
def screenOfElement(self, _element):
_l... | 2016/05/12 | [
"https://Stackoverflow.com/questions/37187962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3425211/"
] | You can use square brackets to create a reference to an array:
```
pass_in( $str, [qw(A B C D E)]);
```
[perldoc perlref](http://perldoc.perl.org/perlref.html#Making-References) | In order to pass an in array, you have must an array to pass!
`qw()` does not create an array. It just puts a bunch of scalars on the stack. That for which you are looking is `[ ]`. It conveniently creates an array, initializes the array using the expression within, and returns a reference to the array.
```
pass_in( ... | 9,691 |
23,183,868 | I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
```
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Tra... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23183868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words:
```
>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True
``` | `isnumeric()` only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:
```
In [4]:
s = u'This is my string'
isnum = s.isnumeric()
```
This will now store False.
Note: I also changed your variable name in case you imported the module string. | 9,692 |
46,257,064 | I'm trying to create a piece of code in python that allows the user to enter their username, password and date of birth and then allows them to change this information. This is what I have so far.
```
import sqlite3
conn=sqlite3.connect("Database.db")
cursor=conn.cursor()
def createTable():
cursor.execute("CREAT... | 2017/09/16 | [
"https://Stackoverflow.com/questions/46257064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8619721/"
] | When I've copied it and run the first error that occurred said that variable `user` is not defined. Therefore you need to either send it to function `modifyData` from `enterData` or ask the user for it.
Then I've got the error you've mentioned. Just remove the single quotes around `?`
Code:
```
def modify_data():
... | You probably want `raw_input`, not `input`.
`raw_input` reads data from standard input and returns it. `input()` is equivelant to `eval(raw_input())`: i.e., it evaluates the input as Python code.
I'm not 100% sure if this is your root problem though, if you've already been using quotes around your input? Or maybe you... | 9,697 |
67,670,537 | I have an Amazon S3 server filled with multiple buckets, each bucket containing multiple subfolders. There are easily 50,000 files in total. I need to generate an excel sheet that contains the path/url of each file in each bucket.
For eg, If I have a bucket called b1, and it has a file called f1.txt, I want to be able... | 2021/05/24 | [
"https://Stackoverflow.com/questions/67670537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8018877/"
] | Do you have access to the aws cli? `aws s3 ls --recursive {bucket}` will list all nested files in a bucket.
Eg this bash command will list all buckets, then recursively print all files in each bucket:
```
aws s3 ls | while read x y bucket; do aws s3 ls --recursive $bucket | while read x y z path; do echo $path; done;... | Amazon s3 inventory can help you with this use case.
Do evaluate that option. refer: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-inventory.html> | 9,698 |
52,169,443 | Currently, I'm facing an issue with uploading (using python) EMOJI data to the BIG QUERY
This is sample code which I'm trying to upload to BQ:
```
{"emojiCharts":{"emoji_icon":"\ud83d\udc4d","repost": 4, "doc": 4, "engagement": 0, "reach": 0, "impression": 0}}
{"emojiCharts":{"emoji_icon":"\ud83d\udc49","repost": ... | 2018/09/04 | [
"https://Stackoverflow.com/questions/52169443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As user 'numeral' mentions in their comment:
>
> Check out [charbase.com/1f618-unicode-face-throwing-a-kiss](http://charbase.com/1f618-unicode-face-throwing-a-kiss) What you want is to convert the javascript escape characters to actual unicode data.
>
>
>
, you need to change the encoding of the emojis for them t... | Python does not support "surrogate characters" representation which is composed of multiple UTF-16 characters and some emojis (over `0xFFFF`) use them. For example, can be represented by `\U0001f3e6` (UTF-32) in Python and some languages uses `\ud83c\udfe6`. For those values are less than `0xFFFF`, python and other lan... | 9,700 |
68,633,577 | I am a beginner in python and I have started with web scraping, I want to extract data from a tourist site I need the names of the hotels, the arrangements available in each hotel and the price but I got stuck in the list of arrangements, each hotel can have several arrangements but it doesn't work and I don't know why... | 2021/08/03 | [
"https://Stackoverflow.com/questions/68633577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16571797/"
] | You are assigning `0` to `stringArray`, `booleanArray` and `numberArray`. A `0` isn't an array, so you can't add values to it like that. ([Assigning values to a primitive type is a noop](https://stackoverflow.com/a/5201148).)
Assign an array to those values and use `.push()` on them to add values to those arrays. (Usi... | Change the values of zero to an array like this:
```
let sortedData = {
stringArray: [],
booleanArray: [],
numberArray: [],
}
```
```
// set value on array item
// ||
// \/
sortedData.stringArray[i] === 'something'
``` | 9,701 |
15,021,877 | I am developing a GUI with PyQt, to perform visual analysis of the data collected during some experiments. The GUI asks the user to indicate the directory where the data to be analyzed is located:
```
class ExperimentAnalyzer(QtGui.QMainWindow):
## other stuff here
def loadExperiment(self):
directory ... | 2013/02/22 | [
"https://Stackoverflow.com/questions/15021877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1759574/"
] | You can do in this way:
```
$(function(){
$('.yourelem, .targetDiv').click(function(ev){
$('.targetDiv').slideDown('fast');
ev.stopPropagation();
});
$(document).click(function(){
$('.targetDiv').slideUp('fast');
});
});
```
[See the action in jsbin](http://jsbin.com/ayuhol/1/edit)
-------------... | Try this :
HTML
```
<a id="show" href="#">show</a>
<div class="test" style="display: none;">
hey
</div>
```
JS
```
$('a#show').click(function(event) {
event.stopPropagation();
$('.test').toggle();
});
$('html').click(function() {
$('.test').hide();
});
``` | 9,706 |
43,222,378 | I'm working on my python script to extract multiple strings from a .csv file but I can't recover the Spanish characters (like á, é, í) after I open the file and read the lines.
This is my code so far:
```
import csv
list_text=[]
with open(file, 'rb') as data:
reader = csv.reader(data, delimiter='\t')
for row ... | 2017/04/05 | [
"https://Stackoverflow.com/questions/43222378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7817760/"
] | When you print a list it shows all the cancelled characters, that way `\n` and other characters don't throw off the list display, so if you print the string it will work properly:
```
'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'.decode('utf-8')
``` | 1. use unicodecsv instead of csv , csv doesn't support well unicode
2. open the file with codecs, and 'utf-8'
**see code below**
```
import unicodecsv as csv
import codecs
list_text=[]
with codecs.open(file, 'rb','utf-8') as data:
reader = csv.reader(data, delimiter='\t')
for row in reader:
print r... | 9,711 |
4,673,166 | I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback:
```
File "./lib/cgi_app.py", line 139, in run res = method()
File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring,... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/355689/"
] | >
> gaierror: [Errno -2] Name or service not known
>
>
>
This error often indicates a failure of your DNS resolver. Does `ping secure.authorize.net` return successful replies from the same server that receives the gaierror? Does the hostname have a typo in it? | pass the port separately from the host:
```
conn = httplib.HTTPSConnection("secure.authorize.net", 443, ....)
``` | 9,714 |
63,587,626 | I am receiving the following download error when I attempt to install Jupyter Notebook on Windows:
```
ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\*redacted*\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\loca... | 2020/08/25 | [
"https://Stackoverflow.com/questions/63587626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14166558/"
] | Try uninstalling virtualenv or pipenv (whichever you are using) and then reinstalling. If this doesn't work try installing conda. There are two versions of it:
Anaconda
Miniconda
I would recommend going with miniconda as it is a lightweight installation but does not have a GUI. Here is the [link](https://docs.conda.i... | The easiest way to setup Jupyter Notebook is using pip if you do not require conda. Since you are new to python, first create a new virtual environment using virtualenv.
Installing pip (Ignore if already installed):
Download get-pip.py for Windows and run `python get-pip.py`
Installing virtualenv: `pip install virtua... | 9,720 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.