qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
55,233,846 | I'm trying to send HTTP post rest API call to the flask server. I'm able to do it in postman but How can I call it using python requests module?
payloads are key-project value-daynight and key-file value-
postman request is as shown in the image
[postman](https://i.stack.imgur.com/i8ZMT.png)
when I tried I ended up g... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55233846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865641/"
] | Just recently ran into this. One thing to look out for is to ensure nodeIntegration is set to true when creating your renderer windows.
```
mainWindow = new electron.BrowserWindow({
width: width,
height: height,
webPreferences: {
nodeIntegration: true
}
});
``` | AFAIU the recommended way is to use `contextBridge` module (in the `preload.js` script). It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.
<https://www.electronjs.org/docs/latest/tutorial/context-isolation>
Following this way, I also found that i... |
55,233,846 | I'm trying to send HTTP post rest API call to the flask server. I'm able to do it in postman but How can I call it using python requests module?
payloads are key-project value-daynight and key-file value-
postman request is as shown in the image
[postman](https://i.stack.imgur.com/i8ZMT.png)
when I tried I ended up g... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55233846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865641/"
] | Also faced this issue, new answer:
```js
mainWindow = new electron.BrowserWindow({
width: width,
height: height,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
``` | AFAIU the recommended way is to use `contextBridge` module (in the `preload.js` script). It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.
<https://www.electronjs.org/docs/latest/tutorial/context-isolation>
Following this way, I also found that i... |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, an... | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.
On Windows, the [PyHook](http://pypi.python.org/pypi/pyHook/1.4/) library would give you the func... | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unles... |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, an... | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It looks like you need <http://patorjk.com/keyboard-layout-analyzer/>
This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.
To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and ... | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unles... |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, an... | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | As the current X server's *Record* extension seems to be broken, using `pykeylogger` for Linux doesn't really help. Take a look at [`evdev`](http://svn.navi.cx/misc/trunk/python/evdev/) and its `demo` function, instead. The solution is nastier, but it does at least work.
It comes down to setting up a hook to the devic... | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unles... |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, an... | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It looks like you need <http://patorjk.com/keyboard-layout-analyzer/>
This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.
To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and ... | Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.
On Windows, the [PyHook](http://pypi.python.org/pypi/pyHook/1.4/) library would give you the func... |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, an... | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It looks like you need <http://patorjk.com/keyboard-layout-analyzer/>
This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.
To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and ... | As the current X server's *Record* extension seems to be broken, using `pykeylogger` for Linux doesn't really help. Take a look at [`evdev`](http://svn.navi.cx/misc/trunk/python/evdev/) and its `demo` function, instead. The solution is nastier, but it does at least work.
It comes down to setting up a hook to the devic... |
14,001,578 | What's the correct way to specify a hg dependency in `tox.ini`. e.g.
```
[testenv]
deps =
hg+https://code.google.com/p/python-progressbar/
```
Unfortunately this does not work, and the following is spewed out:
```
ERROR: invocation failed, logfile: /Users/brad/project/.tox/py33-dj/log/py33-dj-1.log
ERROR: actio... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14001578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253686/"
] | It's possible to specify the mercurial dependency in two ways within `deps = …`:
* `-ehg+https://code.google.com/p/python-progressbar/#egg=progressbar` (no space)
* `hg+https://code.google.com/p/python-progressbar/`
tox treats each line in `deps` as a single argument to `pip install` (whitespace included).
pip supp... | typically this is a artifact of a broken mercurial installation that refers to env python
in virtualenv for python 3 the env python is simply the worst thing to work with |
50,617,233 | I have a dataset (Product\_ID,date\_time, Sold) which has products sold on various dates. The dates are not consistent and are given for 9 months with random 13 days or more from a month. I have to segregate the data in a such a way that the for each product how many products were sold on 1-3 given days, 4-7 given days... | 2018/05/31 | [
"https://Stackoverflow.com/questions/50617233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9846590/"
] | You can first convert dates to dtetimes and get days by [`dt.day`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.day.html):
```
df['DATE_LOCATION'] = pd.to_datetime(df['DATE_LOCATION'], dayfirst=True)
days = df['DATE_LOCATION'].dt.day
```
Then binning by [`cut`](http://pandas.pydata.org/pand... | Assume your dataframe named df.
```
df["DATE_LOCATION"] = pd.to_datetime(df.DATE_LOCATION)
df["DAY"] = df.DATE_LOCATION.dt.day
def flag(x):
if 1<=x<=3:
return '1-3'
elif 4<=x<=7:
return '4-7'
elif 8<=x<=15:
return '8-15'
else:
return '>16' # maybe you mean '>=16'.
df["... |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing t... | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | Use a thread ([longer example here](http://www.wellho.net/solutions/python-python-threads-a-first-example.html)):
```
from threading import Thread
class WindowThread(Thread):
def run(self):
callCppFunctionHere()
WindowThread().start()
``` | QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run code after the application has been started, you should resort to Qt's event handling mechanism.
From <http://doc.trolltech.com/4.5/qapplication.html#exec> :
>
> To make your application ... |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing t... | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | Use a thread ([longer example here](http://www.wellho.net/solutions/python-python-threads-a-first-example.html)):
```
from threading import Thread
class WindowThread(Thread):
def run(self):
callCppFunctionHere()
WindowThread().start()
``` | I assume you're already using [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing t... | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run code after the application has been started, you should resort to Qt's event handling mechanism.
From <http://doc.trolltech.com/4.5/qapplication.html#exec> :
>
> To make your application ... | I assume you're already using [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? |
32,867,501 | I have a python program that takes a .txt file with a list of information. Then the program proceeds to number every line, then remove all returns. Now I want to add returns to the lines that are numbered without double spacing so I can continue to edit the file. Here is my program.
```
import sys
from time import sle... | 2015/09/30 | [
"https://Stackoverflow.com/questions/32867501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5391570/"
] | You can inject the `$location` service if you are using html5 mode.
Because you are using URLs without a base root (such as a ! or a #), you need to explicitly add a `<base>` tag that defines the "root" of your application OR you can configure `$locationProvider` to not require a base tag.
HTML:
```
<head>
<base h... | You can use `$location.search()`.
```
var parameters = $location.search();
console.log(parameters);
-> object{
foo: foovalue,
bar: barvalue
}
```
SO these values will be accessible with `parameters.foo` and `parameters.bar` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('inpu... | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=inp... |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('inpu... | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('inpu... | This works for me:
```
# Upload file
elem = driver.find_element_by_name("File")
elem.send_keys(r"D:\test\testfile04.txt")
elem = driver.find_element_by_partial_link_text("Upload File")
elem.click()
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('inpu... | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", wi... |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=inp... |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=inp... | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", wi... |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` | This works for me:
```
# Upload file
elem = driver.find_element_by_name("File")
elem.send_keys(r"D:\test\testfile04.txt")
elem = driver.find_element_by_partial_link_text("Upload File")
elem.click()
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", wi... |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | This works for me:
```
# Upload file
elem = driver.find_element_by_name("File")
elem.send_keys(r"D:\test\testfile04.txt")
elem = driver.find_element_by_partial_link_text("Upload File")
elem.click()
``` | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", wi... |
16,504,990 | How is it possible I am getting a permission denied using the below? I am using python 2.7 and ubuntu 12.04
Below is my mapper.py file
```
import sys
import json
for line in sys.stdin:
line = json.loads(line)
key = "%s:%s" % (line['user_key'],line['item_key'])
value = 1
sys.stdout.write('%s\t%s\n' % ... | 2013/05/12 | [
"https://Stackoverflow.com/questions/16504990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203556/"
] | Your `mapper.py` file needs to be executable (on some executable partition) so `chmod a+x mapper.py`
The underlying [execve(2)](http://man7.org/linux/man-pages/man2/execve.2.html) syscall is failing with
```
EACCES Execute permission is denied for the file or a script or ELF
interpreter.
EACCES The ... | you can add 'python' to the command, like so
```
cat /home/ubuntu/workspace/logging/data.txt | python /home/ubuntu/workspace/logging/mapper.py
``` |
65,647,986 | I am trying to interface a micropython board with python on my computer using serial read and write, however I can't find a way to read usb serial data in micropython that is non-blocking.
Basicly I want to call the input function without requiring an input to move on. (something like <https://github.com/adafruit/circ... | 2021/01/09 | [
"https://Stackoverflow.com/questions/65647986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13016068/"
] | Instead of typing xlsx, type xlsx like this:
```
import xlsxwriter
import pandas as pd
from pandas import DataFrame
path = ('mypath.xlsx')
xl = pd.ExcelFile(path)
print(xl.sheet_names)
```
It'll work. | The module name is xlsxwriter not xlxswriter, so replace that line with:
```
import xlsxwriter
``` |
26,856,793 | I am trying to load as a pandas dataframe a file that has Chinese characters in its name.
I've tried:
```
df=pd.read_excel("url/某物2008.xls")
```
and
```
import sys
df=pd.read_excel("url/某物2008.xls", encoding=sys.getfilesystemencoding())
```
But the response is something like: "no such file or directory "url/\xa1... | 2014/11/11 | [
"https://Stackoverflow.com/questions/26856793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827060/"
] | ```
df=pd.read_excel(u"url/某物2008.xls", encoding=sys.getfilesystemencoding())
```
may work... but you may have to declare an encoding type at the top of the file | try this for unicode conversion:
`df=pd.read_excel(u"url/某物2008.xls", encoding='utf-8')` |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible... | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | ```
class Child(Parent):
def __getattribute__(self, attr):
if attr == 'goodbye':
raise AttributeError()
return super(Child, self).__getattribute__(attr)
``` | This Python example shows how to design classes to achieve child class inheritance:
```
class HelloParent(object):
def hello(self):
print 'Hello world'
class Parent(HelloParent):
def goodbye(self):
print 'Goodbye world'
class Child(HelloParent):
pass
``` |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible... | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | The solution depends on why you want to do it. If you want to be safe from future erroneous use of the class, I'd do:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
def goodbye(self):
raise NotImplemented... | This Python example shows how to design classes to achieve child class inheritance:
```
class HelloParent(object):
def hello(self):
print 'Hello world'
class Parent(HelloParent):
def goodbye(self):
print 'Goodbye world'
class Child(HelloParent):
pass
``` |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible... | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | The solution depends on why you want to do it. If you want to be safe from future erroneous use of the class, I'd do:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
def goodbye(self):
raise NotImplemented... | ```
class Child(Parent):
def __getattribute__(self, attr):
if attr == 'goodbye':
raise AttributeError()
return super(Child, self).__getattribute__(attr)
``` |
67,350,490 | I am trying to make a simple flask app using putty but it is not working
here is my hello.py file:
```
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World'
```
command I am running in putty (when in the file directory of hello.py)
pip install flask
python -c "impo... | 2021/05/01 | [
"https://Stackoverflow.com/questions/67350490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12333529/"
] | I used my terminal on my window machine instead of putty which is a remote machine | Check your wlan0 inet adress by typing ifconfig in bash and use it, also try to add the following code in your flask app:
```
if __name__ == '__main__':
app.run(debug=True, port=5000, host='wlan0 IP Add')
```
Run the application by typing >>sudo python3 hello.py
Did this work? |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). You'll either need to wrap the number temporarily in a string or format `123456` with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).
Option 1:
```
>>> sample={ 'first_value'... |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | The leading zero makes the value an [octal number](http://en.wikipedia.org/wiki/Octal). |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). You'll either need to wrap the number temporarily in a string or format `123456` with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).
Option 1:
```
>>> sample={ 'first_value'... | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero makes the value an [octal number](http://en.wikipedia.org/wiki/Octal). | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). You'll either need to wrap the number temporarily in a string or format `123456` with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).
Option 1:
```
>>> sample={ 'first_value'... | The leading zero makes the value an [octal number](http://en.wikipedia.org/wiki/Octal). |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the applicat... | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | `setf` returns the original flag value, so you can simply store that then put it back when you're done.
The same is true of `precision`.
So:
```
// Change flags & precision (storing original values)
const auto original_flags = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision =... | You can use flags() method to save and restore all flags or unsetf() the one returned by setf
```
std::ios::fmtflags oldFlags( cout.flags() );
cout.setf(std::ios::fixed);
cout.setf(std::ios::showpoint);
std::streamsize oldPrecision(cout.precision(2));
// output whatever you should.
cout.flags( oldFlags );
co... |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the applicat... | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | `setf` returns the original flag value, so you can simply store that then put it back when you're done.
The same is true of `precision`.
So:
```
// Change flags & precision (storing original values)
const auto original_flags = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision =... | Your problem is that you share the formatting state with someone else. Obviously you can decide to track the changes and to correct them. But there is a saying: The best way to solve a problem is to prevent it from happening.
In your case, you need to have your own formatting state and to not share it with anyone else... |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the applicat... | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | You can use flags() method to save and restore all flags or unsetf() the one returned by setf
```
std::ios::fmtflags oldFlags( cout.flags() );
cout.setf(std::ios::fixed);
cout.setf(std::ios::showpoint);
std::streamsize oldPrecision(cout.precision(2));
// output whatever you should.
cout.flags( oldFlags );
co... | Your problem is that you share the formatting state with someone else. Obviously you can decide to track the changes and to correct them. But there is a saying: The best way to solve a problem is to prevent it from happening.
In your case, you need to have your own formatting state and to not share it with anyone else... |
68,403,642 | I need to share well described data and want to do this in a modern way that avoids managing bureaucratic documentation no one will read. Fields require some description or note (eg. "values don't include ABC because XYZ") which I'd like to associate to columns that'll be saved with `pd.to_<whatever>()`, but I don't kn... | 2021/07/16 | [
"https://Stackoverflow.com/questions/68403642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4107349/"
] | Would the following rough sketch be something you could live with:
**Step 1**: Create json structure out of `df` like you did
```
df.to_json('temp.json', orient='table', indent=4, index=False)
```
**Step 2**: Add the column description to the so produced json-file as you already did (could be done easily in a struc... | I didn't see that there will be such an option but I think you can just add a description inside of each variable:
```
schema = {'first':{'Variable':'x',"description": "example string","value": 2},"second":{"Variable":"y","description": "example string","value": 3}}
```
It creates a table:
```
... |
53,340,120 | I would like to install the package : newsapi in Python
I run the command
```
pip3 install newsapi-python
```
The package was succefully installed. But I import him in Anaconda :
```
from newsapi import NewsApiClient
>> ModuleNotFoundError: No module named 'newsapi'
```
I would like to know how to solve this ki... | 2018/11/16 | [
"https://Stackoverflow.com/questions/53340120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10651723/"
] | I think the issue is you aren't importing vue-router into your app. Only into router.js and then you don't import all of router.js into your app, only the createRouter function. Try this:
```
//routes.js
import Home from "../components/Home/Home.vue";
import About from "../components/About.vue";
import FallBackPage f... | To change route
```
this.$router.push({ path: '/' })
this.$router.push({ name: 'Home' })
```
//main.js
```
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import { routes } from "./router/router";
Vue.use(VueRouter);
export function createApp() {
const router = new VueRo... |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user--... | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
... | I think the following does what you are looking for, where the `consecutive_zero` function is an adaptation of the top answer [here](https://codereview.stackexchange.com/questions/138550/count-consecutive-ones-in-a-binary-list).
Hope this helps!
```
import pandas as pd
from itertools import groupby
df = pd.DataFrame... |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user--... | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
... | If you have a large dataset and speed is essential, you might want to try the high-performance [pyrle](https://github.com/pyranges/pyrle) library.
Setup:
```
# pip install pyrle
# or
# conda install -c bioconda pyrle
import numpy as np
np.random.seed(0)
import pandas as pd
from pyrle import Rle
size = int(1e7)
numbe... |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user--... | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
... | get max number of consecutive zeros on series:
```
def max0(sr):
return (sr != 0).cumsum().value_counts().max() - (0 if (sr != 0).cumsum().value_counts().idxmax()==0 else 1)
max0(pd.Series([1,0,0,0,0,2,3]))
```
>
> 4
>
>
> |
69,339,582 | I would like to compute the **hash of the contents (sequence of *bits*)** of a file (whose length could be any number of bits, and so not necessarily a multiple of the *trendy* eight) and send that file to a friend along with the hash-value. My friend should be able to compute the same hash from the file contents. I wa... | 2021/09/26 | [
"https://Stackoverflow.com/questions/69339582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8341274/"
] | First of all, the `hash()` function in Python is not the same as **cryptographic hash functions** in general. Here're the differences:
### `hash()`
>
> A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if ... | I arrived at `sha256hexdigestFromFile`, an alternative to @Lincoln Yan 's `calculateSHA256Hash`, after reviewing the [standard](http://dx.doi.org/10.6028/NIST.FIPS.180-4) for SHA-256.
This is also a response to my comment about `2048`.
```
def sha256hexdigestFromFile(filePath, blocks = 1):
'''Return as a str the ... |
51,797,321 | I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
del_list = [0, 4, 11]
desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]
```
Here is what I have done
```
x = [12, 45, 55,... | 2018/08/11 | [
"https://Stackoverflow.com/questions/51797321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10211342/"
] | This question already has an answer here. [How to delete elements from a list using a list of indexes?](https://stackoverflow.com/questions/38647439/how-to-delete-elements-from-a-list-using-a-list-of-indexes).
BTW this will do for you
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
val... | You can sort the `del_list` list in descending order and then use the `list.pop()` method to delete specified indexes:
```
for i in sorted(del_list, reverse=True):
x.pop(i)
```
so that `x` would become:
```
[45, 55, 6, 37, 656, 78, 8, 99, 9]
``` |
51,797,321 | I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
del_list = [0, 4, 11]
desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]
```
Here is what I have done
```
x = [12, 45, 55,... | 2018/08/11 | [
"https://Stackoverflow.com/questions/51797321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10211342/"
] | You could also use enumerate:
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
new_x = []
for index, element in enumerate(x):
if index not in index_list:
new_x.append(element)
print(new_x)
``` | You can sort the `del_list` list in descending order and then use the `list.pop()` method to delete specified indexes:
```
for i in sorted(del_list, reverse=True):
x.pop(i)
```
so that `x` would become:
```
[45, 55, 6, 37, 656, 78, 8, 99, 9]
``` |
53,501,778 | I have installed `mysql connector` , which already has a built in sql adapter, i also don't need to install `mysqlclient` as i have mysql connector. But when i start python manage.py migrate, it is asking me to download mysqlclient. But i can not install `mysqlclient`. Can anyone help me how to fix the problem. Thanks
... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53501778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Maybe you need to install mysql-connector-c connector and after:
```
pip install mysqlclient==1.3.13
``` | [There are two backends](https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers) for using MySQL with python
* mysqlclient - recommended by the docs, but can be tricky to install on Windows
* mysql connector - doesn't always support the latest Django version.
First you need to decide which backend ... |
13,578,923 | Can anybody figure out how the python code below works and give me a possible way to port it to Objective-C (iOS) to work in my own project?
`month_id = calendar.timegm(datetime(year, month, 1, hour, 0, 0).timetuple()) * 1000`
Thanks a ton! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13578923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981575/"
] | calendar.timegm converts the given time to time in seconds since epoch of 1970. More information at <http://docs.python.org/3/library/calendar.html?highlight=calendar.timegm#calendar.timegm> | open a python interpreter, then enter this:
```
>>> import calendar
>>> from datetime import datetime
```
then input your line of code, and you should be able to get a pretty good idea. |
40,514,205 | I am developing a slack bot with plugins using entry points. I want to dynamically add a plugin during runtime.
I have a project with this structure:
```
+ ~/my_project_dir/
+ my_projects_python_code/
+ plugins/
- plugin1.py
- plugin2.py
- ...
- pluginN.py
- setup.py
- ... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40514205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496918/"
] | I needed to do something similar to load a dummy plugin for test purposes. This differs slightly from your use-case in that I was specifically trying to avoid needing to define the entry points in the package (as it is just test code).
I found I could dynamically insert entries into the pkg\_resources data structures ... | It's more than at least 5 years, since the time when I first asked myself almost the same question, and your question now is an impulse to finally find it out.
For me it was as well interesting, if one can add entry points from the same directory as the script without installation of a package. Though I always knew th... |
40,514,205 | I am developing a slack bot with plugins using entry points. I want to dynamically add a plugin during runtime.
I have a project with this structure:
```
+ ~/my_project_dir/
+ my_projects_python_code/
+ plugins/
- plugin1.py
- plugin2.py
- ...
- pluginN.py
- setup.py
- ... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40514205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496918/"
] | I needed to do something similar to load a dummy plugin for test purposes. This differs slightly from your use-case in that I was specifically trying to avoid needing to define the entry points in the package (as it is just test code).
I found I could dynamically insert entries into the pkg\_resources data structures ... | I had to change a bit solution by @j3p0uk to work for me. I wanted to use this inside an unit test (`unittest` framework). What I did is:
```
def test_entry_point(self):
distribution = pkg_resources.Distribution(__file__)
entry_point = pkg_resources.EntryPoint.parse('plugin1 = plugins.plugin1:plugin1_class', d... |
51,004,898 | I'm trying to programmatically retrieve ASIN numbers for over 500+ books.
example: Product Catch-22 by Joseph Heller
Amazon URL: [https://www.amazon.com/Catch-22-Joseph-Heller/dp/3866155239](https://rads.stackoverflow.com/amzn/click/com/3866155239)
I can get the product numbers manually by searching for each product ... | 2018/06/23 | [
"https://Stackoverflow.com/questions/51004898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9751133/"
] | <https://isbndb.com/> charges for the API :(
so...
Went the Google Web Scrape Route
```
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup
import requests
import time
def get_amazon_link(book_title):
url = 'https://www.google.com/search?q=amazon+novel+'+book_title
print(url)
ur... | According to Amazon's customer service page:
<https://www.amazon.co.uk/gp/help/customer/display.html?nodeId=898182>
>
> ASIN stands for Amazon Standard Identification Number. Almost every
> product on our site has its own ASIN, a unique code we use to identify
> it. For books, the ASIN is the same as the ISBN numb... |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives... | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```... | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == ... |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives... | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```... | ```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>>
>>> a = 1
>>> b = 1
>>> c = len(battleships)
>>> c-b,a-1
(3, 0)
```
Now `battleships[c-b][a-1]` can be broken into two parts:
`battleships[c-b]` and... |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives... | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```... | When you are having problem understanding any new thing in programming change the program a bit.
I'll give you an example. I changed it a bit.
```
battleships = [['0','p','0','s','3'],
['0','p','0','s','8'],
['p','p','0','s','2']]
print "len(battleships) =",len(battleships)
print "battl... |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives... | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == ... | ```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>>
>>> a = 1
>>> b = 1
>>> c = len(battleships)
>>> c-b,a-1
(3, 0)
```
Now `battleships[c-b][a-1]` can be broken into two parts:
`battleships[c-b]` and... |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives... | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == ... | When you are having problem understanding any new thing in programming change the program a bit.
I'll give you an example. I changed it a bit.
```
battleships = [['0','p','0','s','3'],
['0','p','0','s','8'],
['p','p','0','s','2']]
print "len(battleships) =",len(battleships)
print "battl... |
56,434,745 | I'm trying to load MySQL JDBC driver from a python app. I'm not invoking 'bin/pyspark' or 'spark-submit' program; instead I have a Python script in which I'm initializing 'SparkContext' and 'SparkSession' objects.
I understand that we can pass '--jars' option when invoking 'pyspark', but how do I load and specify jdbc ... | 2019/06/03 | [
"https://Stackoverflow.com/questions/56434745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208108/"
] | I think you want do something like this
```py
from pyspark.sql import SparkSession
# Creates spark session with JDBC JAR
spark = SparkSession.builder \
.appName('stack_overflow') \
.config('spark.jars', '/path/to/mysql/jdbc/connector') \
.getOrCreate()
# Creates your DataFrame with spark session with JDB... | Answer is to create SparkContext like this:
```py
spark_conf = SparkConf().set("spark.jars", "/my/path/mysql_jdbc_driver.jar")
sc = SparkContext(conf=spark_conf)
```
This will load mysql driver into classpath. |
5,835,043 | I'm trying to use the ipy.vim script to set up a small python dev environment, but I'm running into a connection problem. When I type ipy\_vimserver.setup("demo") I get this error:
```
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_in... | 2011/04/29 | [
"https://Stackoverflow.com/questions/5835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731470/"
] | I found it ! Thank you Anders
```
function UnixToDateTime(USec: Longint): TDateTime;
const
// Sets UnixStartDate to TDateTime of 01/01/1970
UnixStartDate: TDateTime = 25569.0;
begin
Result := (USec / 86400) + UnixStartDate;
end;
``` | That is the [unix timestamp](http://en.wikipedia.org/wiki/Unix_time) for Fri, 29 Apr 2011 11:42:31 GMT.
**Edit**
According to [IBS](http://ibs.sourceforge.net/documentation.html#introduction), it uses postgresql as its backend database. You should be able to convert it using [to\_timestamp](http://www.postgresql.org/... |
39,190,714 | Sorry if this has already been answered using terminology I don't know to search for.
I have one project:
```
project1/
class1.py
class2.py
```
Where `class2` imports some things from `class1`, but each has its own `if __name__ == '__main__'` that uses their respective classes I run frequently. But then, I ... | 2016/08/28 | [
"https://Stackoverflow.com/questions/39190714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191812/"
] | EDIT 2: Added code to class2.py to attach the parent directory to the PYTHONPATH to comply with how Python3 module imports work.
```
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
```
Removed relative import of Class1.
Folder structure:
```
project2
- class3.py
- project1
... | You could run `class2.py` from inside the `project2` folder, i.e. with the current working directory set to the `project2` folder:
```
user@host:.../project2$ python project1/class2.py
```
On windows that would look like this:
```
C:\...project2> python project1/class2.py
```
Alternatively you could modify the py... |
63,994,247 | I'm new to Docker. I'm trying to create a dockerfile which basically sets kubectl (Kubernetes client), helm 3 and Python 3.7. I used:
```
FROM python:3.7-alpine
COPY ./ /usr/src/app/
WORKDIR /usr/src/app
```
Now I'm trying to figure out how to add `kubectl` and `helm`. What would be the best way to install those two... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63994247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808098/"
] | Working Dockerfile. This will install the latest and stable versions of `kubectl` and `helm-3`
```
FROM python:3.7-alpine
COPY ./ /usr/src/app/
WORKDIR /usr/src/app
RUN apk add curl openssl bash --no-cache
RUN curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/... | Python should be available from a python base image I guess.
My take would be s.th like
```
ENV K8S_VERSION=v1.18.X
ENV HELM_VERSION=v3.X.Y
ENV HELM_FILENAME=helm-${HELM_VERSION}-linux-amd64.tar.gz
```
and then in the Dockerfile
```
RUN curl -L https://storage.googleapis.com/kubernetes-release/release/${K8S_VERSION... |
61,856,478 | I'm developing a python script to deploy an Azure Function App. For this reason I can't use another Python version to make this easier.
In azure portal I get this error:
[Azure Function app pyarrow module not found](https://i.stack.imgur.com/QM50w.png)
When I try to install it via VS Code with pip I get this error: [... | 2020/05/17 | [
"https://Stackoverflow.com/questions/61856478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13562280/"
] | As you use `conda` as the package manager, you should also use it to install `pyarrow` and `arrow-cpp` using it. In your above output VSCode uses `pip` for the package management. You should consider reporting this as a bug to VSCode. Your current environment is detected as `venv` and not as `conda` environment as you ... | Thank you for your answer.
In fact, I think I can't change the environment because this `venv` is actually the environment used by Azure Functions. Is there any way I can use `conda` installed packages in the azure function |
36,465,337 | I am using a Dymo USB scale with PyUSB and everything is really great apart from the scale's automatic shutdown after three minutes. I would like to keep it running as long as my python program is running. Is there any way to do this using python?
I am new to PyUSB and have followed this tutorial successfully so far: ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36465337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4083055/"
] | As Ignacio said, there doesn't seem to be any computing way to do this. We eventually managed to stop the automatic shutdown by wiring a timer directly to the button which changes the units mode from grams to ounces. "Pressing" this every few seconds prevents the shutdown, and a little bit of extra coding allows for re... | Here is a hardware description to open/modify and code to toggle the scale button of DYMO (to avoid auto-shutdown)
<https://learn.adafruit.com/data-logging-iot-weight-scale/code-walkthrough> |
16,114,358 | is there a way to trace all the calls made by a web page when loading it? Say for example I went in a video watching site, I would like to trace all the GET calls recursively until I find an mp4/flv file. I know a way to do that would be to follow the URLs recursively, but this solution is not always suitable and quite... | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300843/"
] | The following code may be what you are looking for. The object should flash for the total amount of `time` changing its color after `intervalTime`
```
using UnityEngine;
using System.Collections;
public class FlashingObject : MonoBehaviour {
private Material mat;
private Color[] colors = {Color.yellow, Color... | The answer above is great, but it does not stop flashing, because it takes far too long for the float to reach 5f.
The trick is to set the first parameter in the **Flash** function to something smaller, like 1f, instead of 5f. Take this script, and attach it to any game object. It will flash between yellow and red for... |
64,354,599 | What is the best way to create software client (service) that installs and then runs in the background. When you turn on the device (where the service is installed), this service will automatically send network availability information of device to web server. On web server will be only state of devices on network. (on... | 2020/10/14 | [
"https://Stackoverflow.com/questions/64354599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14449220/"
] | Use
```
(?m)^<hr>\r?\nBitmap:[\s\S]*?(?=^<hr>$|\Z)
```
See [proof](https://regex101.com/r/i64K0W/4).
**Explanation**
```
--------------------------------------------------------------------------------
(?m) set flags for this block (with ^ and $
matching start and e... | This works: `<hr>\nBitmap:.*\n(?:.*\n){1,2}`
See: <https://regex101.com/r/i64K0W/3>
The problem in your regex was the `*`, which is greedy. |
60,907,340 | Try to open file that exists with visual Studio Code 1.43.2
This is the py file:
```
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
```
This is the result:
```
PS C:\Users\Osori> & C:/Python/Python38-32/python.exe "c:/Users/Osori/Desktop/python_work/9_files and excepti... | 2020/03/28 | [
"https://Stackoverflow.com/questions/60907340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143836/"
] | Below is for BigQuery Standard SQL
```
#standardSQL
SELECT *,
COUNTIF(New_Session_Flag = 1) OVER(PARTITION BY Fullvisitorid ORDER BY Visitid) Rank_Session_Order
FROM `project.dataset.table`
``` | The answer by Mikhail Berlyant using a conditional window count is corret and works. I am answering because I find that a window sum is even simpler (and possibly more efficient on a large dataset):
```
select
t.*,
sum(new_session_flag) over(partition by fullvisitorid order by visid_id) rank_session_order
from... |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/l... |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Ok, so I still don't quite understand what's going on with pip3 in my device, but I found a way to install packages with pip in the right Python version:
```
python3 -m pip install [package]
```
It worked to install numpy which was my primary objective. | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/l... |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | For python 3.x, the command is `pip3` |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | For python 3.x, the command is `pip3` | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/l... |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Ok, so I still don't quite understand what's going on with pip3 in my device, but I found a way to install packages with pip in the right Python version:
```
python3 -m pip install [package]
```
It worked to install numpy which was my primary objective. | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/l... |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Ok, so I still don't quite understand what's going on with pip3 in my device, but I found a way to install packages with pip in the right Python version:
```
python3 -m pip install [package]
```
It worked to install numpy which was my primary objective. | For python 3.x, the command is `pip3` |
40,219,946 | I have a large data set (millions of rows) in memory, in the form of **numpy arrays** and **dictionaries**.
Once this data is constructed I want to store them into files;
so, later I can load these files into memory quickly, without reconstructing this data from the scratch once again.
**np.save** and **np.load** f... | 2016/10/24 | [
"https://Stackoverflow.com/questions/40219946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2101900/"
] | It's a structured array. Use `d2.item()` to retrieve the actual dict object first:
```
import numpy as np
d1={'key1':[5,10], 'key2':[50,100]}
np.save("d1.npy", d1)
d2=np.load("d1.npy")
print d1.get('key1')
print d2.item().get('key2')
```
result:
```
[5, 10]
[50, 100]
``` | [pickle](https://docs.python.org/3/library/pickle.html) module can be used. Example code:
```
from six.moves import cPickle as pickle #for performance
from __future__ import print_function
import numpy as np
def save_dict(di_, filename_):
with open(filename_, 'wb') as f:
pickle.dump(di_, f)
def load_dict... |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/e... | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | See your .bashrc file. Miniconda adds their paths and change the default, find this file and then change or add the path you want, or remove the anaconda/miniconda path.
In your .bashrc (probably ~/.bashrc) you will see something like:
```
# added by Miniconda3 4.3.14 installer
export PATH="/path/to/miniconda3/bin:$P... | Here is a way to do this on the fly without editing one's init files:
```
(base) ➜ ~ which python
/home/xxx/anaconda3/bin/python
(base) ➜ ~ echo $PATH
/home/xxx/anaconda3/bin:/home/xxx/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bi... |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/e... | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | See your .bashrc file. Miniconda adds their paths and change the default, find this file and then change or add the path you want, or remove the anaconda/miniconda path.
In your .bashrc (probably ~/.bashrc) you will see something like:
```
# added by Miniconda3 4.3.14 installer
export PATH="/path/to/miniconda3/bin:$P... | Or you can also just use conda deactivate. For a regular python environment, deactivate or source deactivate should work, but if you try that, you get a hint to use conda deactivate instead.
```
(base) mooreb@ubtest2:~$ deactivate
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
(base) mo... |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/e... | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | Or you can also just use conda deactivate. For a regular python environment, deactivate or source deactivate should work, but if you try that, you get a hint to use conda deactivate instead.
```
(base) mooreb@ubtest2:~$ deactivate
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
(base) mo... | Here is a way to do this on the fly without editing one's init files:
```
(base) ➜ ~ which python
/home/xxx/anaconda3/bin/python
(base) ➜ ~ echo $PATH
/home/xxx/anaconda3/bin:/home/xxx/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bi... |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object... | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is... | please be more clear when asking questions next time. I assume you want this
```
>>> import _functools
>>> _functools.__file__
'/usr/lib/python2.6/lib-dynload/_functools.so'
``` |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object... | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is... | It is a shared object `_functools.so`, written in C. I guess, it is imported by the actual `functools` module. Why are you trying to import from it? Sure, it is possible, however, you can just as well `from functools import partial`. |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object... | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is... | For Python2.6,
The `_functools` module is a builtin. You can see that if you simply type `import _functools ; repr(_functools)` and hit enter at your interpreter prompt.
If you want to see the C source of the module, check out <http://hg.python.org/cpython/file/d7e85ddb1336/Modules/_functoolsmodule.c>
This `_functoo... |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object... | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is... | The behaviour of the `functools.partial()` function is described in [PEP 309](http://www.python.org/dev/peps/pep-0309/) in which it was defined. The although the actual implementations of built-ins are often in C PEP's including this one usually contain [example implementations in Python](http://www.python.org/dev/peps... |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive d... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | [ReSharper](http://www.jetbrains.com/resharper/) can do much of the work for you.
You will need to declare a basic class:
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
}
}
```
Then, choose ReSharper > Edit > Generate Code (Alt+I... | 1. If you have access to the source code, rename and fix in the source
code.
2. If you don't have access (and you can do it legally) use some
tool like Reflector or [dotPeek](http://www.jetbrains.com/decompiler/) to get the source code and then,
goto to the first point. |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive d... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | It seems the best answer is "There is no such tool". So, I'll be taking a stab at writing my own later as an off-hours project. If I ever get something useful working I'll github it and update here.
UPDATE
Visual Studio 2012 Fakes seem to be promising. <http://msdn.microsoft.com/en-us/library/tfs/hh549175(v=vs.110).as... | 1. If you have access to the source code, rename and fix in the source
code.
2. If you don't have access (and you can do it legally) use some
tool like Reflector or [dotPeek](http://www.jetbrains.com/decompiler/) to get the source code and then,
goto to the first point. |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive d... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | It seems the best answer is "There is no such tool". So, I'll be taking a stab at writing my own later as an off-hours project. If I ever get something useful working I'll github it and update here.
UPDATE
Visual Studio 2012 Fakes seem to be promising. <http://msdn.microsoft.com/en-us/library/tfs/hh549175(v=vs.110).as... | [ReSharper](http://www.jetbrains.com/resharper/) can do much of the work for you.
You will need to declare a basic class:
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
}
}
```
Then, choose ReSharper > Edit > Generate Code (Alt+I... |
40,254,007 | I am looking for a way to store multiple values for each key (just like we can in python using dictionary) using Go.
Is there a way this can be achieved in Go? | 2016/10/26 | [
"https://Stackoverflow.com/questions/40254007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902984/"
] | Based on your response in comments I would suggest something like the following using a struct (though if you are only interested in a single value like `name` for each item in your slice then you could just use a `map[int][]string{}`
```
type Thing struct {
name string
age int
}
myMap := map[int][]Thing{}
... | In go, the key/value collection is called a `map`. You create it with `myMap := map[keyType]valType{}`
Usually something like `mapA := map[string]int{}`. If you want to store multiple values per key, perhaps something like:
`mapB := map[string][]string{}` where each element is itself a slice of strings. You can then ... |
61,496,129 | I need to run selenium-side-runner in docker.I wrote in the dockerfile to install Google Chrome and googledrive. But when the code is executed, the error is as follows:
```
WebDriverError: unknown error: Chrome failed to start: exited abnormally.
(unknown error: DevToolsActivePort file doesn't exist)
(The process s... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61496129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13054579/"
] | A hack
======
Instead of installing a browser by hand, I would recommend using already available images like <https://github.com/SeleniumHQ/docker-selenium>.
A solution (recommended)
========================
From an architectural point of view, each Docker container should have only one purpose. In your case, the co... | You could use [this project](https://github.com/nixel2007/docker-selenium-side-runner), put your .side files in side directory and run `docker-composer up` |
40,314,960 | I have a csv file with columns id, name, address, phone. I want to read each row such that I store the data in two variables, `key` and `data`, where data contains name, address and phone. I want to do this because I want to append another column country in each row in a new csv. Can anyone help me with the code in pyt... | 2016/10/29 | [
"https://Stackoverflow.com/questions/40314960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2433565/"
] | `key, *data = row` is Python 3 syntax. For Python 2 you can do this:
```
key, data = row[0], row[1:]
``` | You can try the code below. I have put two option one is to make a list for each row, and other is comma separated. Based on the usage you can use either one.
```
import csv
dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
data = []
print row
key,data = row[0],row[1:]
dict[key] ... |
38,290,965 | I am a beginner in Python.
I use Python 2.7 with ElementTree to parse XML files.
I have a big XML file (~700 MB), which contains multiple root instances, for example:
```
<?xml version="1.0" ?> <foo> <bar> <sometag> Mehdi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
<?xml version="1.0"... | 2016/07/10 | [
"https://Stackoverflow.com/questions/38290965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811059/"
] | You can try [this](https://jsfiddle.net/loginshivam/jq4c4wg7/2/)
```
<input value="0" id="id">
```
give a id to input field
on button click call a function
```
<button onclick="myFunction()">Add +10</button>
<script>
function myFunction() {
document.getElementById("id").value = parseInt(document.get... | You can use a click counter like [this](https://stackoverflow.com/questions/22402777/html-javascript-button-click-counter)
and edit it replacing `+= 1` with `+= 10`.
Here my code,
```js
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.ad... |
38,290,965 | I am a beginner in Python.
I use Python 2.7 with ElementTree to parse XML files.
I have a big XML file (~700 MB), which contains multiple root instances, for example:
```
<?xml version="1.0" ?> <foo> <bar> <sometag> Mehdi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
<?xml version="1.0"... | 2016/07/10 | [
"https://Stackoverflow.com/questions/38290965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811059/"
] | Try this or [fiddleLink](http://jsfiddle.net/AyanGhatak/dpa8ctwz).
ParseInt helps in converting the string value to numbers and add them instead of concatenating. Let me know if you still have some trouble.
```js
var tag1Elem = document.getElementById("tag1");
// The callback function to increse the value.
function... | You can use a click counter like [this](https://stackoverflow.com/questions/22402777/html-javascript-button-click-counter)
and edit it replacing `+= 1` with `+= 10`.
Here my code,
```js
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.ad... |
61,679,525 | **Is it possible to have a variable that is defined in a python file be passed through to a html file in the same directory and used in a 'script' tag?**
Synopsis:
Im producing a flask website that pulls data from a database and uses it to create a line chart in chartjs. Flask uses jijna to manage templates. The data... | 2020/05/08 | [
"https://Stackoverflow.com/questions/61679525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13486528/"
] | For beginners who try to put Flask and ChartJS together, a common approach seems to be to write Jinja code which uses loops to output Javascript, or manually uses Jinja expressions within the JS. This can quick become a maintenence nightmare.
Here's my approach which lets you define the data you want charted in Python... | You can use the same jinja templating feature to access your Variable in js too.
Maybe if you want strings you should enclose them like this `"{{variable}}"` |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just itera... | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdt... | Why not create a dict with lambda functions?
```
methods = {
'method1': lambda val: val+1,
'method2': lambda val: val+2,
}
for key, val in dict.iteritems():
methods[key](val)
``` |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just itera... | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdt... | One way to do this is to have a dictionary of functions to call, and then use the key to locate the actual function that you wish to call:
```
function_table = { "key_1": function_1, "key_2": function_2 }
for key, value in my_dict.items():
f = function_table .get(key, None)
if f is not None:
f(value)
... |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just itera... | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdt... | Just to complicate things, if you are always going to have two methods that you are going to call then something like this will work:
```py
# Here are my two functions
func_list=[lambda x: x*2,lambda x:x*3]
# Here is my dictionary
my_dict = {'item1':5,'item2':2}
# Now the fun part:
for key,value in my_dict.items():... |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TAB... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a p... | A JSONField data type has been added to Django for certain databases to improve handling of JSON. More info is available in this post: [Django 1.9 - JSONField in Models](https://stackoverflow.com/questions/37007109/django-1-9-jsonfield-in-models) |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TAB... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a p... | You can try this:
```py
from django.contrib.postgres.fields import JSONField
class Test(models.Model):
data = models.JSONField()
``` |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TAB... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a p... | First install `django-jsonfield` pypi package:
```
pip install django-jsonfield
```
Then simply use it:
```
from jsonfield import JSONField
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
``` |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TAB... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | A JSONField data type has been added to Django for certain databases to improve handling of JSON. More info is available in this post: [Django 1.9 - JSONField in Models](https://stackoverflow.com/questions/37007109/django-1-9-jsonfield-in-models) | First install `django-jsonfield` pypi package:
```
pip install django-jsonfield
```
Then simply use it:
```
from jsonfield import JSONField
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
``` |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TAB... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | You can try this:
```py
from django.contrib.postgres.fields import JSONField
class Test(models.Model):
data = models.JSONField()
``` | First install `django-jsonfield` pypi package:
```
pip install django-jsonfield
```
Then simply use it:
```
from jsonfield import JSONField
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
``` |
38,043,683 | I'm writing a git pre-commit hook, but it requires user input and hooks don't run in an interactive terminal. With Python I could do something like this to get access to user input:
```
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically suppose... | 2016/06/26 | [
"https://Stackoverflow.com/questions/38043683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973/"
] | You may try:
```
STDIN.reopen("/dev/tty")
``` | This seems to work:
```
file = File.open("/dev/tty")
line = file.gets
p line
```
You can't reassign STDIN and we don't have a reassignable global variable for it. I don't know much about this, maybe reopen and dup can be used for that. But otherwise you can use that `file` instead of `STDIN` in your program, I guess... |
38,043,683 | I'm writing a git pre-commit hook, but it requires user input and hooks don't run in an interactive terminal. With Python I could do something like this to get access to user input:
```
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically suppose... | 2016/06/26 | [
"https://Stackoverflow.com/questions/38043683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973/"
] | by combining @julian-portalier's answer and @asterite's we have working way to redefine stdin:
```
STDIN.reopen(File.open("/dev/tty", "a+"))
```
Which, I believe, is just [FileDescriptor#reopen](http://crystal-lang.org/api/IO/FileDescriptor.html#reopen)
`STDIN`, `STDOUT`, and `STDERR` can all be reopened this way. | This seems to work:
```
file = File.open("/dev/tty")
line = file.gets
p line
```
You can't reassign STDIN and we don't have a reassignable global variable for it. I don't know much about this, maybe reopen and dup can be used for that. But otherwise you can use that `file` instead of `STDIN` in your program, I guess... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.