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 |
|---|---|---|---|---|---|
35,780,768 | I am getting this message when I try to install aws. Anyone have any ideas of what's going on?
```
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/i... | 2016/03/03 | [
"https://Stackoverflow.com/questions/35780768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505587/"
] | What's going on is the shared library was built with one version of the `A` class while the executable binary was built with a different version. At this point you've violated the one definition rule and the compiler is free to do anything, including compiling and linking your code successfully. There is no requirement... | This may compile or build, if the solution has been previously built. This means that it is using old object code. Try to do a clean build of your solution, then rebuild it. Once your solution is cleaned. Then try to compile the inherited class. Another thing that may be of concern is that you have declared your inheri... |
33,312,175 | I want to use [`re.MULTILINE`](https://docs.python.org/2/library/re.html#re.MULTILINE) but **NOT** [`re.DOTALL`](https://docs.python.org/2/library/re.html#re.DOTALL), so that I can have a regex that includes both an "any character" wildcard and the normal `.` wildcard that doesn't match newlines.
Is there a way to do ... | 2015/10/23 | [
"https://Stackoverflow.com/questions/33312175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | To match a newline, or "any symbol" without `re.S`/`re.DOTALL`, you may use any of the following:
1. `(?s).` - the [inline modifier group](https://www.regular-expressions.info/modifiers.html) with `s` flag on sets a scope where all `.` patterns match any char including line break chars
2. Any of the following work-aro... | Match any character (including new line):
-----------------------------------------
Regular Expression: (Note the use of space ' ' is also there)
```
[\S\n\t\v ]
```
Example:
--------
```
import re
text = 'abc def ###A quick brown fox.\nIt jumps over the lazy dog### ghi jkl'
# We want to extract "A quick brown fo... |
66,880,698 | I have a notebook that runs overnight, and prints out a bunch of stuff, including images and such. I want to cause this output to be saved programatically (perhaps at certain intervals). I also want to save the code that was run. In a Jupyter notebook, you could do:
```
from IPython.display import display, Javascript
... | 2021/03/31 | [
"https://Stackoverflow.com/questions/66880698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11632499/"
] | You can use [ipylab](https://github.com/jtpio/ipylab) to access JupyterLab API from Python. To save the notebook just invoke the `docmanager:save` command:
```py
from ipylab import JupyterFrontEnd
app = JupyterFrontEnd()
app.commands.execute('docmanager:save')
```
You can get the full list of commands with `app.com... | JupyterLab has a bulit-in auto-save function. You can configure the time interval using the Advanced Settings Editor, the Document Manager section (see screenshot below).
[](https://i.stack.imgur.com/01vR4.png)
However, if you *really* want a JavaScript solution ... |
66,880,698 | I have a notebook that runs overnight, and prints out a bunch of stuff, including images and such. I want to cause this output to be saved programatically (perhaps at certain intervals). I also want to save the code that was run. In a Jupyter notebook, you could do:
```
from IPython.display import display, Javascript
... | 2021/03/31 | [
"https://Stackoverflow.com/questions/66880698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11632499/"
] | JupyterLab has a bulit-in auto-save function. You can configure the time interval using the Advanced Settings Editor, the Document Manager section (see screenshot below).
[](https://i.stack.imgur.com/01vR4.png)
However, if you *really* want a JavaScript solution ... | I just wanted to share a really small tweak of the other solution by krassowski that works for JupyterLab on MacOS:
```
from IPython.display import display, HTML
script = """
this.nextElementSibling.focus();
this.dispatchEvent(new KeyboardEvent('keydown', {key:'s', keyCode: 83, metaKey: true}));
"""
display(HTML((
... |
66,880,698 | I have a notebook that runs overnight, and prints out a bunch of stuff, including images and such. I want to cause this output to be saved programatically (perhaps at certain intervals). I also want to save the code that was run. In a Jupyter notebook, you could do:
```
from IPython.display import display, Javascript
... | 2021/03/31 | [
"https://Stackoverflow.com/questions/66880698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11632499/"
] | You can use [ipylab](https://github.com/jtpio/ipylab) to access JupyterLab API from Python. To save the notebook just invoke the `docmanager:save` command:
```py
from ipylab import JupyterFrontEnd
app = JupyterFrontEnd()
app.commands.execute('docmanager:save')
```
You can get the full list of commands with `app.com... | I just wanted to share a really small tweak of the other solution by krassowski that works for JupyterLab on MacOS:
```
from IPython.display import display, HTML
script = """
this.nextElementSibling.focus();
this.dispatchEvent(new KeyboardEvent('keydown', {key:'s', keyCode: 83, metaKey: true}));
"""
display(HTML((
... |
42,103,367 | I am using multiprocessing.Pool.imap to run many independent jobs in parallel using Python 2.7 on Windows 7. With the default settings, my total CPU usage is pegged at 100%, as measured by Windows Task Manager. This makes it impossible to do any other work while my code runs in the background.
I've tried limiting the ... | 2017/02/08 | [
"https://Stackoverflow.com/questions/42103367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410133/"
] | The solution depends on what you want to do. Here are a few options:
Lower priorities of processes
-----------------------------
You can [`nice`](https://en.wikipedia.org/wiki/Nice_(Unix)) the subprocesses. This way, though they will still eat 100% of the CPU, when you start other applications, the OS gives preferenc... | **On the OS level
---------------**
you can use `nice` to set a priority to a single command. You could also start a python script with nice. (Below from: <http://blog.scoutapp.com/articles/2014/11/04/restricting-process-cpu-usage-using-nice-cpulimit-and-cgroups>)
>
> **nice**
>
>
> The nice command tweaks the pr... |
42,103,367 | I am using multiprocessing.Pool.imap to run many independent jobs in parallel using Python 2.7 on Windows 7. With the default settings, my total CPU usage is pegged at 100%, as measured by Windows Task Manager. This makes it impossible to do any other work while my code runs in the background.
I've tried limiting the ... | 2017/02/08 | [
"https://Stackoverflow.com/questions/42103367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410133/"
] | The solution depends on what you want to do. Here are a few options:
Lower priorities of processes
-----------------------------
You can [`nice`](https://en.wikipedia.org/wiki/Nice_(Unix)) the subprocesses. This way, though they will still eat 100% of the CPU, when you start other applications, the OS gives preferenc... | In Linux:
Use nice() with a numerical value:
```
#on Unix use ps.nice(10) for very low priority
p.nice(10)
```
[](https://i.stack.imgur.com/WeIMX.png)
[https://en.wikipedia.org/wiki/Nice\_(Unix)#:~:text=nice%20is%20a%20program%20found,CPU%20... |
42,103,367 | I am using multiprocessing.Pool.imap to run many independent jobs in parallel using Python 2.7 on Windows 7. With the default settings, my total CPU usage is pegged at 100%, as measured by Windows Task Manager. This makes it impossible to do any other work while my code runs in the background.
I've tried limiting the ... | 2017/02/08 | [
"https://Stackoverflow.com/questions/42103367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410133/"
] | **On the OS level
---------------**
you can use `nice` to set a priority to a single command. You could also start a python script with nice. (Below from: <http://blog.scoutapp.com/articles/2014/11/04/restricting-process-cpu-usage-using-nice-cpulimit-and-cgroups>)
>
> **nice**
>
>
> The nice command tweaks the pr... | In Linux:
Use nice() with a numerical value:
```
#on Unix use ps.nice(10) for very low priority
p.nice(10)
```
[](https://i.stack.imgur.com/WeIMX.png)
[https://en.wikipedia.org/wiki/Nice\_(Unix)#:~:text=nice%20is%20a%20program%20found,CPU%20... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | (Update on May 28, 2016) Using RealGUD in Emacs
===============================================
For anyone in Emacs, [this thread](https://github.com/rocky/emacs-dbgr/issues/96) shows how to accomplish everything described in the OP (and more) using
1. a new important debugger in Emacs called **RealGUD** which can op... | Running from inside Emacs' IPython-shell and breakpoint set via pdb.set\_trace() should work.
Checked with python-mode.el, M-x ipython RET etc. |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | Did you try [this tip](http://vjethava.blogspot.fr/2010/11/matlabs-keyboard-command-in-python.html)?
>
> Or better still, use ipython, and call:
>
>
>
> ```
> from IPython.Debugger import Tracer; debug_here = Tracer()
>
> ```
>
> then you can just use
>
>
>
> ```
> debug_here()
>
> ```
>
> whenever you want... | Developing New Code
===================
*Debugging inside IPython*
1. Use Jupyter/IPython cell execution to speed up experiment iterations
2. Use %%debug for step through
Cell Example:
```
%%debug
...: for n in range(4):
...: n>2
```
Debugging Existing Code
=======================
*IPython inside debugging*
... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | Prefixing an "!" symbol to commands you type in pdb seems to have the same effect as doing something in an IPython shell. This works for accessing help for a certain function, or even variable names. Maybe this will help you to some extent. For example,
```
ipdb> help(numpy.transpose)
*** No help on (numpy.transpose)
... | If put `import ipdb; ipdb.set_trace()` at cell outside function, it will occur error.
Using `%pdb` or `%debug`, you can only see the filnal error result. You cannot see the code doing step by step.
I use following skill:
```
%%writefile temp.py
.....cell code.....
```
save the code of cell to file **temp.py**.
an... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | What about ipdb.set\_trace() ? In your code :
`import ipdb; ipdb.set_trace()`
**update**: now in Python 3.7, we can write `breakpoint()`. It works the same, but it also obeys to the `PYTHONBREAKPOINT` environment variable. This feature comes from [this PEP](https://www.python.org/dev/peps/pep-0553/).
This allows for... | Did you try [this tip](http://vjethava.blogspot.fr/2010/11/matlabs-keyboard-command-in-python.html)?
>
> Or better still, use ipython, and call:
>
>
>
> ```
> from IPython.Debugger import Tracer; debug_here = Tracer()
>
> ```
>
> then you can just use
>
>
>
> ```
> debug_here()
>
> ```
>
> whenever you want... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | Looks like the approach in @gaborous's answer [is deprecated](https://github.com/ipython/ipython/pull/9731/).
The new approach seems to be:
```
from IPython.core import debugger
debug = debugger.Pdb().set_trace
def buggy_method():
debug()
``` | From python 3.2, you have the `interact` command, which gives you access to the full python/ipython command space. |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | From python 3.2, you have the `interact` command, which gives you access to the full python/ipython command space. | If put `import ipdb; ipdb.set_trace()` at cell outside function, it will occur error.
Using `%pdb` or `%debug`, you can only see the filnal error result. You cannot see the code doing step by step.
I use following skill:
```
%%writefile temp.py
.....cell code.....
```
save the code of cell to file **temp.py**.
an... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | (Update on May 28, 2016) Using RealGUD in Emacs
===============================================
For anyone in Emacs, [this thread](https://github.com/rocky/emacs-dbgr/issues/96) shows how to accomplish everything described in the OP (and more) using
1. a new important debugger in Emacs called **RealGUD** which can op... | Looks like the approach in @gaborous's answer [is deprecated](https://github.com/ipython/ipython/pull/9731/).
The new approach seems to be:
```
from IPython.core import debugger
debug = debugger.Pdb().set_trace
def buggy_method():
debug()
``` |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | Prefixing an "!" symbol to commands you type in pdb seems to have the same effect as doing something in an IPython shell. This works for accessing help for a certain function, or even variable names. Maybe this will help you to some extent. For example,
```
ipdb> help(numpy.transpose)
*** No help on (numpy.transpose)
... | The [Pyzo](http://www.pyzo.org/) IDE has similar capabilities as the OP asked for. You don't have to start in debug mode. Similarly to MATLAB, the commands are executed in the shell. When you set up a break-point in some source code line, the IDE stops the execution there and you can debug and issue regular IPython com... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | (Update on May 28, 2016) Using RealGUD in Emacs
===============================================
For anyone in Emacs, [this thread](https://github.com/rocky/emacs-dbgr/issues/96) shows how to accomplish everything described in the OP (and more) using
1. a new important debugger in Emacs called **RealGUD** which can op... | One option is to use an IDE like [Spyder](https://pythonhosted.org/spyder/) which should allow you to interact with your code while debugging (using an IPython console, in fact). In fact, Spyder is very MATLAB-like, which I presume was intentional. That includes variable inspectors, variable editing, built-in access to... |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | the right, easy, cool, exact answer for the question is to use %run macro with -d flag.
```
In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb> prompt to continue execution.
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
2
... | If put `import ipdb; ipdb.set_trace()` at cell outside function, it will occur error.
Using `%pdb` or `%debug`, you can only see the filnal error result. You cannot see the code doing step by step.
I use following skill:
```
%%writefile temp.py
.....cell code.....
```
save the code of cell to file **temp.py**.
an... |
43,149,637 | I have string in python containing a large text file (over 1MiB).
I need to split it to chunks.
Constrains:
* chunks can be splited only by newline character, and
* len(chunk) must be as big as possbile but smaller than LIMIT (i.e. 100KiB)
Lines longer than LIMIT can be ommited.
Any idea how to implement this nicel... | 2017/03/31 | [
"https://Stackoverflow.com/questions/43149637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/705676/"
] | Following the suggestion of Linuxios you could use rfind to find the last newline within the limit and split at this point. If no newline character is found the chunk is too large and can be dismissed.
```
chunks = []
not_chunked_text = input_text
while not_chunked_text:
if len(not_chunked_text) <= LIMIT:
... | Here is my not-so-pythonic solution:
```
def line_chunks(lines, chunk_limit):
chunks = []
chunk = []
chunk_len = 0
for line in lines:
if len(line) + chunk_len < chunk_limit:
chunk.append(line)
chunk_len += len(line)
else:
chunks.append(chunk)
... |
12,905,300 | I am trying to develop an application that creates an image and fills it with color pixels using bilinear interpolation and then displays it. My code so far is the following:
```
#include <QtCore/QCoreApplication>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
#include <string>
#include <sys/st... | 2012/10/15 | [
"https://Stackoverflow.com/questions/12905300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178770/"
] | The following code is almost the same as William answered, but without using 'for' loop statement.
```
subdirs := A B C
.PHONY: all $(subdirs)
all: $(subdirs)
$(subdirs):
$(MAKE) -C $@
``` | I'm rusty on makefiles and know for sure the following is not the best answer. But it might help for now...
```
TARGETS = A B C
.phoney: all
all:
@for subdir in $(TARGETS); do \
$(MAKE) -C $$subdir all || exit 1; \
done
```
Note that the indents must use a TAB, not spaces |
23,332,259 | I am trying to copy a sheet, `default_sheet`, into a new sheet `new_sheet` in the same workbook.
I did managed to create a new sheet and to copy the values from default sheet. How can I also copy the style of each cell into the new\_sheet cells?
```python
new_sheet = workbook.create_sheet()
new_sheet.title = sheetNam... | 2014/04/28 | [
"https://Stackoverflow.com/questions/23332259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458191/"
] | As of openpyxl 2.5.4, python 3.4: (subtle changes over the older version below)
```python
new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']
from copy import copy
for row in default_sheet.rows:
for cell in row:
new_cell = new_sheet.cell(row=cell.row, column=cell.col_idx,
... | May be this is the convenient way for most.
```
from openpyxl import load_workbook
from openpyxl import Workbook
read_from = load_workbook('path/to/file.xlsx')
read_sheet = read_from.active
write_to = Workbook()
write_sheet = write_to.active
write_sheet['A1'] = read_sheet['A1'].value
wr... |
23,332,259 | I am trying to copy a sheet, `default_sheet`, into a new sheet `new_sheet` in the same workbook.
I did managed to create a new sheet and to copy the values from default sheet. How can I also copy the style of each cell into the new\_sheet cells?
```python
new_sheet = workbook.create_sheet()
new_sheet.title = sheetNam... | 2014/04/28 | [
"https://Stackoverflow.com/questions/23332259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458191/"
] | As of openpyxl 2.5.4, python 3.4: (subtle changes over the older version below)
```python
new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']
from copy import copy
for row in default_sheet.rows:
for cell in row:
new_cell = new_sheet.cell(row=cell.row, column=cell.col_idx,
... | The `StyleableObject` implementation stores styles in a single list, `_style`, and style properties on a cell are actually getters and setters to this array. You can implement the copy for each style individually but this will be slow, especially if you're doing it in a busy inner loop like I was.
If you're willing to... |
23,332,259 | I am trying to copy a sheet, `default_sheet`, into a new sheet `new_sheet` in the same workbook.
I did managed to create a new sheet and to copy the values from default sheet. How can I also copy the style of each cell into the new\_sheet cells?
```python
new_sheet = workbook.create_sheet()
new_sheet.title = sheetNam... | 2014/04/28 | [
"https://Stackoverflow.com/questions/23332259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458191/"
] | The `StyleableObject` implementation stores styles in a single list, `_style`, and style properties on a cell are actually getters and setters to this array. You can implement the copy for each style individually but this will be slow, especially if you're doing it in a busy inner loop like I was.
If you're willing to... | May be this is the convenient way for most.
```
from openpyxl import load_workbook
from openpyxl import Workbook
read_from = load_workbook('path/to/file.xlsx')
read_sheet = read_from.active
write_to = Workbook()
write_sheet = write_to.active
write_sheet['A1'] = read_sheet['A1'].value
wr... |
19,322,350 | I am trying to use f2py to interface my python programs with my Fortran modules.
I am on a Win7 platform.
I use latest Anaconda 64 (1.7) as a Python+NumPy stack.
My Fortran compiler is the latest Intel Fortran compiler 64 (version 14.0.0.103 Build 20130728).
I have been experiencing a number of issues when executin... | 2013/10/11 | [
"https://Stackoverflow.com/questions/19322350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2866568/"
] | I encountered similar problems with my own code some time ago. If I understand the comments correctly you already used the approach that worked for me, so this is just meant as clarification and summary for all those that struggle with f2py and dependencies:
f2py seems to have problems resolving dependecies on externa... | The library path is specified using /LIBPATH not /L |
49,739,245 | I have spent a good amount of time trying to determine what is going wrong exactly, with the code I am using to convert pdf to docx (and doc to docx) using LibreOffice.
I have used both the windows run interface to test-run some of the code I have found to be relevant, and have tried on python as well, neither of whic... | 2018/04/09 | [
"https://Stackoverflow.com/questions/49739245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8492478/"
] | There are a number of problems here. You should first get the `--convert-to` call to work from the command line as @CristiFati commented, and then implement in python.
Here is the code that works on my system. No `//` in the path, and quotes are needed. Also, the folder is `LibreOffice 5` on my system.
```
import sub... | Install pdf2docx package in python
```
source = r'C:\Users\sdDesktop\New Project/Document2.pdf'
destination = r'C:\Users\sd\Desktop\New Project/sample_6.docx'
def Converter_pdf2docx(source,destination):
pdf_file = source
docx_file = destination
cv = Converter(pdf_file)
cv.convert(docx_file, star... |
63,648,764 | I have a program folder for which paths are required:
```
export RBT_ROOT=/path/to/installation/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$RBT_ROOT/lib
export PATH=$PATH:$RBT_ROOT/bin
```
Then the command is run:
```
rbcavity -was -d -r <PRMFILE>
```
rbcavity - is an exe program contained in the program's bin fold... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63648764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12399859/"
] | The issue is that the website filters out requests without a proper `User-Agent`, so just use a random one from MDN:
```py
requests.get("https://apis.digital.gob.cl/fl/feriados/2020", headers={
"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
})... | It might be due to idle timeout. Overriding default socket options can help
```
import socket
from urllib3.connection import HTTPConnection
HTTPConnection.default_socket_options = (
HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
(socket.SOL_TCP, socket.TCP_K... |
28,999,913 | Is there a 'correct' or preferred manner for sending data over a web socket connection?
In my case, I am sending the information from a C# application to a python (tornado) web server, and I am simply sending a string consisting of several elements separated by commas. In python, I use rudimentary techniques to split ... | 2015/03/12 | [
"https://Stackoverflow.com/questions/28999913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190200/"
] | Writing a *custom* encoding (eg, as "k,v,..") is *different* than 'using binary'.
*It is still text*, just a rigid under-defined one-off hand-rolled format that must be manually replicated. (What happens if a key or value contains a comma? What happens if the data needs to contain nested objects? How can null be inte... | First advice would be to use the same format for both ways, not plain text in one direction and JSON in the other.
I personally think `{'foo':0,'bar':1}` is better than `foo,0,bar,1` because everybody understands JSON but for your custom format they might not without some explanations. The idea is you are inventing a... |
33,006,474 | In the cloud, I have multiple instances, each running a container with a different random name, e.g.:
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5dc97950d924 aws_beanstalk/my-app:latest "/bin/sh -... | 2015/10/08 | [
"https://Stackoverflow.com/questions/33006474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478354/"
] | "the correct container"?
To determine what is the "correct" container, your bash script would still need either the id or the name of that container.
For example, I [have a function in my `.bashrc`](https://github.com/VonC/b2d/blob/f9890cb6e1ee14842b8be2dd66a754550db793a9/.bash_aliases#L54):
```
deb() { docker exec ... | Here's my final solution. It edits the instance's .bashrc if it hasn't been edited yet, prints out docker ps, defines the dock function, and enters the container. A user can then type "exit" if they want to access the raw instances, and "exit" again to quit ssh.
```
commands:
bashrc:
command: if ! grep -Fxq "su... |
33,006,474 | In the cloud, I have multiple instances, each running a container with a different random name, e.g.:
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5dc97950d924 aws_beanstalk/my-app:latest "/bin/sh -... | 2015/10/08 | [
"https://Stackoverflow.com/questions/33006474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478354/"
] | "the correct container"?
To determine what is the "correct" container, your bash script would still need either the id or the name of that container.
For example, I [have a function in my `.bashrc`](https://github.com/VonC/b2d/blob/f9890cb6e1ee14842b8be2dd66a754550db793a9/.bash_aliases#L54):
```
deb() { docker exec ... | As VonC indicated, usually you have to make some shell scripting of your own if you find yourself doing something repetitive. I made a tool myself [here](https://github.com/Pithikos/dockerint) which works if you have Bash 4+.
Install
```
wget -qO- https://raw.githubusercontent.com/Pithikos/dockerint/master/docker_aut... |
32,488,029 | I'm using django-twilio to try and respond to text messages coming from Twilio account. As it recommends using the twilio\_View decorator to imrove upon @csrf\_exempt, I'm using it. Problem is, it doesnt work. No matter what I try, I always get 403.
Things I've done:
1. Twilio test account. Added TWILIO\_ACCOUNT\_SID ... | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907157/"
] | Twilio team member here.
Are you importing twiml? Try making the first line of your say-hello function:
```
r = twiml.Response()
``` | I don't see anything obviously wrong in what you are doing, so I would suggest removing the `@twilio_view` decorator and logging the X-Twilio-Signature header in your view to see what it is and manually checking to see if it's correct. (Basically, redoing the logic of the `@twilio_view` decorator in your view, just to ... |
60,286,928 | I am learning Python (python3) and am working with a text file containing semi-JSON format. It is not full JSON because the "keys" are not surrounded by quotes. I am looking to programmatically add quotes around all of these key names. My plan was to "open" this file and parse each "line" as an individual string.
**F... | 2020/02/18 | [
"https://Stackoverflow.com/questions/60286928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8729789/"
] | Avoid using regex to handle structured formats. It will almost always mis-handle certain corner cases.
Since your input is valid YAML, you can install [PyYAML](https://pypi.org/project/PyYAML/), load the input as YAML, and dump the data structure as JSON instead:
```
import yaml
import json
s = 'key_name: { another_k... | While the pattern `([{,]\s*)([^"]*?)(\s*:\s*)` isn't going to cover all corner cases, it should work fine for basic JSON content.
Example usage:
```
>>> import re
>>> data = '{ another_key: "somevalue", second_key: "anotherval" }'
>>> repl_fn = lambda x: f'{x.group(1)}"{x.group(2)}"{x.group(3)}'
>>> re.sub(r'([{,]\s*... |
57,701,538 | I have a `Jupyter` notebook and I'd like to convert it into a `Python` script using the `nbconvert` command from *within* the `Jupyter` notebook.
I have included the following line at the end of the notebook:
```
!jupyter nbconvert --to script <filename>.ipynb
```
This creates a `Python` script. However, I'd like t... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57701538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2957960/"
] | One way to get control of what appears in the output is to tag the cells that you don't want in the output and then use the TagRemovePreprocessor to remove the cells.
[](https://i.stack.imgur.com/gvqcA.png)
The code below also uses the exclude\_markd... | Jupyter nbconvert has made this a little bit easier with a new [template structure](https://nbconvert.readthedocs.io/en/latest/customizing.html).
Templates should be placed in the template path. This can be found by running `jupyter --paths`
Each template should be placed in its own directory within the template dire... |
57,701,538 | I have a `Jupyter` notebook and I'd like to convert it into a `Python` script using the `nbconvert` command from *within* the `Jupyter` notebook.
I have included the following line at the end of the notebook:
```
!jupyter nbconvert --to script <filename>.ipynb
```
This creates a `Python` script. However, I'd like t... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57701538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2957960/"
] | One way to get control of what appears in the output is to tag the cells that you don't want in the output and then use the TagRemovePreprocessor to remove the cells.
[](https://i.stack.imgur.com/gvqcA.png)
The code below also uses the exclude\_markd... | The most obvious solution seems to work for me:
```sh
jupyter nbconvert --to python a_notebook.ipynb --stdout | grep -v -e "^get_ipython" | python
```
Of course, you can't use something like `dirs = !ls` in your notebooks for this to work. |
29,578,217 | I made sure to try installing PyQt4 on mac in many different ways, but I always get the error above.
My attempts have in common installing Python 3.4 from the official website installer, then installing Qt4 from [here](https://download.qt.io/archive/qt/4.8/4.8.6/) and finally installing SIP from the package available i... | 2015/04/11 | [
"https://Stackoverflow.com/questions/29578217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2157820/"
] | If you look a little on what Google has to say, there are several references to that problem. I see you are from Brasil so maybe this is your problem:
<https://github.com/thoughtbot/capybara-webkit/issues/291>
(which refers to: <https://github.com/thoughtbot/capybara-webkit/issues/224>
Also:
* <https://github.com/th... | I had the same problem using GCC installed via MacPorts (tested several versions up to gcc5). The solution for me was using g++ supplied with the XCode command line tools. I uninstalled all MacPorts GCC versions. Below version details of the g++ command that worked.
```
$ g++ --version
Configured with: --prefix=/Appl... |
56,387,349 | I'm using Django Rest Framework and want to be able to delete a Content instance via `DELETE` to `/api/content/<int:pk>/`. I *don't* want to implement any method to respond to `GET` requests.
When I include a `.retrieve()` method as follows, the `DELETE` request **works**:
```
class ContentViewSet(GenericViewSet):
... | 2019/05/31 | [
"https://Stackoverflow.com/questions/56387349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4400877/"
] | >
> 1. How can I allow DELETE without implementing a `.retrieve()` method?
>
>
>
Just remove the **`retrieve()`** method from the view class. Which means, the [**`GenericViewSet`**](https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset) doesn't provide any ***HTTP Actions*** unless it's defined ... | My solution for part 1. is to include the mixin but restrict the `http_method_names`:
```
class ContentViewSet(RetrieveModelMixin, GenericViewSet):
http_method_names = ['delete']
...
```
However, I still don't know why I have to include `RetrieveModelMixin` at all. |
56,387,349 | I'm using Django Rest Framework and want to be able to delete a Content instance via `DELETE` to `/api/content/<int:pk>/`. I *don't* want to implement any method to respond to `GET` requests.
When I include a `.retrieve()` method as follows, the `DELETE` request **works**:
```
class ContentViewSet(GenericViewSet):
... | 2019/05/31 | [
"https://Stackoverflow.com/questions/56387349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4400877/"
] | Wild guess here but did you use a `SimpleRouter` or a `DefaultRouter` to build your `urlpatterns`?
If so, that's your problem. The router uses a viewset and expects to have all methods implemented. More info [here](https://www.django-rest-framework.org/api-guide/routers/#using-include-with-routers)
What you can do is... | My solution for part 1. is to include the mixin but restrict the `http_method_names`:
```
class ContentViewSet(RetrieveModelMixin, GenericViewSet):
http_method_names = ['delete']
...
```
However, I still don't know why I have to include `RetrieveModelMixin` at all. |
64,784,079 | In an attempt to create a JWT in python I have written the following code.
```
#Header
header = str({"alg": "RS256"})
header_binary = header.encode()
header_base64 = base64.urlsafe_b64encode(header_binary)
print(header_base64)
#Claims set (Pay Load)
client_id=""
username=""
URL=""
exp_time=str(round(time.time())+30... | 2020/11/11 | [
"https://Stackoverflow.com/questions/64784079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14233404/"
] | Directly using LTPA in Tomcat is not possible unless you use 3rd party token services. The better way to have SSO experience between WebSphere and Tomcat is to use Windows ADFS as SSO server instead of LDAP. You can setup ADFS as either SAML identity provider and OpenID connect provider, and setup WebSphere and Tomcat ... | The other, simpler approach would be just to use Use Open Liberty instead of Tomcat, which I suggested in other thread. As usually there is no benefit using Tomcat over OpenLibery and LTPA token will work just via configuration in Liberty and can integrate with any older WebSpheres you have in your environment. |
58,843,848 | What I need is simple: a piece of code that will receive a GET request, process some data, and then generate a response. I'm completely new to python web development, so I've decided to use DRF for this purpose because it seemed like the most robust solution, but every example I found online consisted of CRUDs with mod... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58843848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7742448/"
] | Simple way to do thing you want is by using Django REST Framework's `APIView` (or `@api_view` decorator).
Here is an example of it in the docs: <https://www.django-rest-framework.org/api-guide/views/>.
Besides code on that page, you would need to register your view on appropriate route, which can be found here: <htt... | Django and Django REST Framework are pretty heavy products out-of-the-box.
If you want something more lightweight that can handle many incoming requests, you could create a simple Express server using Node.js. This would result in very few lines of code on your end.
Sample Node server:
```
var express = require('exp... |
58,843,848 | What I need is simple: a piece of code that will receive a GET request, process some data, and then generate a response. I'm completely new to python web development, so I've decided to use DRF for this purpose because it seemed like the most robust solution, but every example I found online consisted of CRUDs with mod... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58843848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7742448/"
] | Simple way to do thing you want is by using Django REST Framework's `APIView` (or `@api_view` decorator).
Here is an example of it in the docs: <https://www.django-rest-framework.org/api-guide/views/>.
Besides code on that page, you would need to register your view on appropriate route, which can be found here: <htt... | For DRF:
<https://www.django-rest-framework.org/tutorial/quickstart/>
Another viable option:
Flask:
<https://flask.palletsprojects.com/en/1.1.x/quickstart/> |
28,778,843 | I apologize for my noobiness in java, but I am trying to make a very basic app for someone for their birthday and have only really done any programming in python. I have been trying to implement the code found in [android - how to make a button click play a sound file every time it been pressed?](https://stackoverflow.... | 2015/02/28 | [
"https://Stackoverflow.com/questions/28778843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4616988/"
] | You need to just Put your file in res/raw folder and use
```
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
} else{
try {
mp = MediaPlayer.create(this, R.raw.hello);
mp.prepare();
mp.start(... | You can do it in another way. Put the .mp3 files under res/raw folder and use the following code:
```
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.android);
mediaPlayer.start();
```
Refer this [link](http://www.tutorialspoint.com/android/android_mediaplayer.htm) for better example to ... |
51,115,825 | I have numpy array and two python lists of indexes with positions to increase arrays elements by one. Do numpy has some methods to vectorize this operation without use of `for` loops?
My current slow implementation:
```
a = np.zeros([4,5])
xs = [1,1,1,3]
ys = [2,2,3,0]
for x,y in zip(xs,ys): # how to do it in numpy... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `np.add.at` will do just that, just pass both indexes as a single 2D array/list:
```
a = np.zeros([4,5])
xs = [1, 1, 1, 3]
ys = [2, 2, 3, 0]
np.add.at(a, [xs, ys], 1) # in-place
print(a)
array([[0., 0., 0., 0., 0.],
[0., 0., 2., 1., 0.],
[0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0.]])
``` | ```
>>> a = np.zeros([4,5])
>>> xs = [1, 1, 1, 3]
>>> ys = [2, 2, 3, 0]
>>> a[[xs,ys]] += 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 0.],
[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.]])
``` |
74,033,201 | I have a python dictionary which contains multiple key,values which are actually image indexes. For e.g. the dictionary I have looks something as given below
```
{
1: [1, 2, 3],
2: [1, 2, 3],
3: [1, 2, 3],
4: [4, 5],
5: [4, 5],
6: [6]
}
```
this means that 1 is related to 1, 2 & 3. Similarly ... | 2022/10/11 | [
"https://Stackoverflow.com/questions/74033201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483151/"
] | How about this, use my modification below to remove the first item in the list during each loop. I commented the line which does it.
```
new_dict = dict()
# source is the original dictionary
for k,v in source.items():
ok = True
for k1,v1 in new_dict.items():
if k in v1: ok = False
if ok: new_dict[... | your modified code:
**ver 1:**
```
new_dict = dict()
for k, v in source.items():
if not any(k in v1 for v1 in new_dict.values()):
new_dict[k] = v[1:]
```
**ver 2:**
```
tmp = dict()
for k, v in source.items():
tmp[tuple(v)] = tmp.get(tuple(v), []) + [k]
res = dict()
for k, v in tmp.items():
r... |
74,033,201 | I have a python dictionary which contains multiple key,values which are actually image indexes. For e.g. the dictionary I have looks something as given below
```
{
1: [1, 2, 3],
2: [1, 2, 3],
3: [1, 2, 3],
4: [4, 5],
5: [4, 5],
6: [6]
}
```
this means that 1 is related to 1, 2 & 3. Similarly ... | 2022/10/11 | [
"https://Stackoverflow.com/questions/74033201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483151/"
] | This shows the preferred output:
```
source = {
1: [1, 2, 3],
2: [1, 2, 3],
3: [1, 2, 3],
4: [4, 5],
5: [4, 5],
6: [6]
}
new_dict = {}
seen = set()
for k, v in source.items():
if k in seen: continue
seen.add(k)
new_v = [i for i in v if i not in seen]
seen.update(new_v)
ne... | your modified code:
**ver 1:**
```
new_dict = dict()
for k, v in source.items():
if not any(k in v1 for v1 in new_dict.values()):
new_dict[k] = v[1:]
```
**ver 2:**
```
tmp = dict()
for k, v in source.items():
tmp[tuple(v)] = tmp.get(tuple(v), []) + [k]
res = dict()
for k, v in tmp.items():
r... |
37,584,629 | I am trying to connect to a AWS Redshift server via SSL. I am using psycopg2 library in python to establish the connection and used `sslmode='require'` as a parameter in the connect line. Unfortunately i got this error:
```
sslmode value "require" invalid when SSL support is not compiled in
```
I read many other sim... | 2016/06/02 | [
"https://Stackoverflow.com/questions/37584629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5610841/"
] | This worked for me: <https://stackoverflow.com/a/36489939/101266>
>
> had this same error, which turned out to be because I was using the Anaconda version of psycopg2. To fix it, I had adapt VictorF's solution from here and run:
>
>
>
```
conda uninstall psycopg2
sudo ln -s /Users/YOURUSERNAME/anaconda/lib/libssl... | Is your cluster enabled for SSL connections? Your URL itself will have the SSL info. and you can use the same in your code. |
16,946,051 | I have a log file with arbitrary number of lines. All I need is to extract is one line of data from the log file which starts with a string “Total”. I do not want any other lines from the file.
How do I write a simple python program for this?
This is how my input file looks
```
TestName id eno ... | 2013/06/05 | [
"https://Stackoverflow.com/questions/16946051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180817/"
] | ```
theFile = open('thefile.txt','r')
FILE = theFile.readlines()
theFile.close()
printList = []
for line in FILE:
if ('TestName' in line) or ('Totals' in line):
# here you may want to do some splitting/concatenation/formatting to your string
printList.append(line)
for item in printList:
print... | ```
for line in open('filename.txt', 'r'):
if line.startswith('TestName') or line.startswith('Totals'):
fields = line.rsplit(None, 5)
print '\t'.join(fields[:2] + fields[3:4])
``` |
34,254,594 | I am trying to emulate a piano in python using mingus as suggested in [this question](https://stackoverflow.com/questions/6487180/synthesize-musical-notes-with-piano-sounds-in-python/ "this question"). I am running Ubuntu 14.04, and have already created an audio group and added myself to it.
I am using alsa.
I ran the... | 2015/12/13 | [
"https://Stackoverflow.com/questions/34254594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951705/"
] | The data should be passed like this :-
```
$('#event_delete').on('click', function () {
$('#calendar').fullCalendar('removeEvents', calEvent.id);
$.ajax({
data: {id: calEvent.id},
type: "POST",
url: "http://localhost/book/js/delete_events.php" ... | Instead of reloading the entire page you can call $('#calendar').fullCalendar( 'refetchEvents' ). It will get all the events from your database and rerender them. |
63,687,990 | I have a `setup.py` which contains the following:
```
from pip._internal.req import parse_requirements
def load_requirements(fname):
"""Turn requirements.txt into a list"""
reqs = parse_requirements(fname, session="test")
return [str(ir.requirement) for ir in reqs]
setup(
name="Projectname",
[...... | 2020/09/01 | [
"https://Stackoverflow.com/questions/63687990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50065/"
] | You can only use [PEP 508 - *Dependency specification for Python Software Packages*](https://www.python.org/dev/peps/pep-0508/) requirements. `git://github.com/BioGeek/tta_wrapper.git@master#egg=tta_wrapper` is not valid syntax according to that standard.
`setuptools` does accept the [`name@ url` direct reference synt... | In my case there is no any github link in my requirements, but the line
```
-r common.txt
```
in `./requirements/prod.txt` caused the same error.
I've added stupid condition and now it works for me:
```py
def load_requirements(filename) -> list:
requirements = []
try:
with open(filename) as req:
... |
29,192,068 | On Windows 7 machine, Pycharm (community or professional) and Python 3.4 (tried Anaconda 3 as well) were installed newly. There were not problems running Python scripts interactively in main editor. However, when I tried to select *View > Tool Windows > Python Console*, it generates the following error messages and mor... | 2015/03/22 | [
"https://Stackoverflow.com/questions/29192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018111/"
] | You need to change your working directory. Go to `File->Settings->Build, Execution, Deployment->Console->Python Console` and then change or provide a directory where you have read and write access in the `Working directory` box. | The configuring of pycharm in the presence of various development configurations is a bit of a black art IMHO.
The most effective mechanism I've found for pinning this down is put random strings into the various settings dialogs, Interpreters, consoles, tests , servers and observe the command lines submitted to the int... |
29,192,068 | On Windows 7 machine, Pycharm (community or professional) and Python 3.4 (tried Anaconda 3 as well) were installed newly. There were not problems running Python scripts interactively in main editor. However, when I tried to select *View > Tool Windows > Python Console*, it generates the following error messages and mor... | 2015/03/22 | [
"https://Stackoverflow.com/questions/29192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018111/"
] | The configuring of pycharm in the presence of various development configurations is a bit of a black art IMHO.
The most effective mechanism I've found for pinning this down is put random strings into the various settings dialogs, Interpreters, consoles, tests , servers and observe the command lines submitted to the int... | I had same problem. I reinstalled python and default directories have changed.
Then I just refreshed interpreter here `File->Settings->Build, Execution, Deployment->Console->Python Console` **and here** `File->Settings->Project: <YOUR_PROJECT>->Project Interpreter`.
If you will open new projects interpreter will need... |
29,192,068 | On Windows 7 machine, Pycharm (community or professional) and Python 3.4 (tried Anaconda 3 as well) were installed newly. There were not problems running Python scripts interactively in main editor. However, when I tried to select *View > Tool Windows > Python Console*, it generates the following error messages and mor... | 2015/03/22 | [
"https://Stackoverflow.com/questions/29192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018111/"
] | The configuring of pycharm in the presence of various development configurations is a bit of a black art IMHO.
The most effective mechanism I've found for pinning this down is put random strings into the various settings dialogs, Interpreters, consoles, tests , servers and observe the command lines submitted to the int... | I got it resolved by setting the interpreter in Preferences and project interpreter. |
29,192,068 | On Windows 7 machine, Pycharm (community or professional) and Python 3.4 (tried Anaconda 3 as well) were installed newly. There were not problems running Python scripts interactively in main editor. However, when I tried to select *View > Tool Windows > Python Console*, it generates the following error messages and mor... | 2015/03/22 | [
"https://Stackoverflow.com/questions/29192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018111/"
] | You need to change your working directory. Go to `File->Settings->Build, Execution, Deployment->Console->Python Console` and then change or provide a directory where you have read and write access in the `Working directory` box. | I had same problem. I reinstalled python and default directories have changed.
Then I just refreshed interpreter here `File->Settings->Build, Execution, Deployment->Console->Python Console` **and here** `File->Settings->Project: <YOUR_PROJECT>->Project Interpreter`.
If you will open new projects interpreter will need... |
29,192,068 | On Windows 7 machine, Pycharm (community or professional) and Python 3.4 (tried Anaconda 3 as well) were installed newly. There were not problems running Python scripts interactively in main editor. However, when I tried to select *View > Tool Windows > Python Console*, it generates the following error messages and mor... | 2015/03/22 | [
"https://Stackoverflow.com/questions/29192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018111/"
] | You need to change your working directory. Go to `File->Settings->Build, Execution, Deployment->Console->Python Console` and then change or provide a directory where you have read and write access in the `Working directory` box. | I got it resolved by setting the interpreter in Preferences and project interpreter. |
11,782,147 | I am trying to implement the algorithm found [here](http://www.m.cs.osakafu-u.ac.jp/cbdar2007/proceedings/papers/O1-1.pdf) in python with OpenCV.
I am trying to implement the part of the algorithm that remove irrelevant edge boundaries based on the number of interior boundaries that they have.
* If the current edge b... | 2012/08/02 | [
"https://Stackoverflow.com/questions/11782147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128407/"
] | The main confusion here is probably the fact that the hierarchy returned is a numpy array with more dimensions than necessary. On top of that, it looks like the Python FindContours function returns a tuple that is a LIST of contours, and and NDARRAY of the hierarchy...
You can get a sensible array of hierarchy informa... | **Understanding Contour Hierarchies**
When finding contours in a binary image using [`cv2.findContours()`](https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours), you can use contour hierarchy to select and extract specific contours within the image. Specifically, ... |
37,811,767 | I like to use python interpreter, as it shows the result instantly. But I sometimes make mistakes. Like misspelling or typing 'enter' twice during writing class or function. It's really annoying work to rewrite the code.
Is it possible to add some code to a predefined class or function in the interpreter? | 2016/06/14 | [
"https://Stackoverflow.com/questions/37811767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894129/"
] | When you want to declare an id in XML you do it as `android:id="@+id/myId"`
R is Java class. When you include the above line for an XML view a `public static final int myId` field gets included into the R class. You can reference this from your own classes.
`findViewById(int)` accepts an integer as a parameter. The R ... | When gradle builds your app, it generates a "
```
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/myEditText" />
```
You would then reference it in your code using the generated R class:
```
EditText myEditText = (EditText) findViewById(R.id.myEditText);
``` |
37,811,767 | I like to use python interpreter, as it shows the result instantly. But I sometimes make mistakes. Like misspelling or typing 'enter' twice during writing class or function. It's really annoying work to rewrite the code.
Is it possible to add some code to a predefined class or function in the interpreter? | 2016/06/14 | [
"https://Stackoverflow.com/questions/37811767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894129/"
] | When you want to declare an id in XML you do it as `android:id="@+id/myId"`
R is Java class. When you include the above line for an XML view a `public static final int myId` field gets included into the R class. You can reference this from your own classes.
`findViewById(int)` accepts an integer as a parameter. The R ... | All of the views in a window are arranged in a single tree. You can add views either from code or by specifying a tree of views in one or more XML layout files.
**Views may have an integer id associated with them. These ids are typically assigned in the layout XML files, and are used to find specific views within the ... |
48,250,092 | How do I upload a excel `.xlsx` file to python flask from angular2?
I upload something but it can't be read when I open the excel file.
html for upload dialog:
```
<mat-form-field>
<input matInput placeholder="Filename" [(ngModel)]="filename">
</mat-form-field>
<button type="button" mat-raised-button (click)="i... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48250092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203556/"
] | ```
temp = (ds_list)(malloc(sizeof(ds_list)));
```
will be
```
temp = malloc(sizeof(*temp)));
```
You want to allocate memory for `struct ds_list_element` not `struct ds_list_element*`. Don't hide pointers behind typedef name. It rarely helps.
Also you should check the return value of `malloc` and the casting is ... | Use `ds_list` as structure not a pointer
```
typedef struct ds_list_element {
char value[MAX];
struct ds_list_element *next;
}ds_list;
```
and allocate memory for the structure not a pointer.
Working program:
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
typedef struct ds_lis... |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | From the python 2.6.4 docs at: <http://docs.python.org/reference/expressions.html>
>
>
> The operator not in is defined to have
> the inverse true value of in.
>
>
> The operators is and is not test for
> object identity: x is y is true if and
> only if x and y are the same object. x
> is not y yields the inver... | The remainder of your question has been answered above, but I'll address the last question: the Zen of Python bit.
"There should only be one way to do it" isn't mean't in a mathematical sense. If it were, there'd be no `!=` operator, since that's just the inversion of `==`. Similarly, no `and` and `or` --- you can, af... |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | From the python 2.6.4 docs at: <http://docs.python.org/reference/expressions.html>
>
>
> The operator not in is defined to have
> the inverse true value of in.
>
>
> The operators is and is not test for
> object identity: x is y is true if and
> only if x and y are the same object. x
> is not y yields the inver... | Your documentation reference is nothing to do with syntax. [Try this](http://docs.python.org/reference/expressions.html#notin). Both `is not` and `not in` are two-word operators. |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | From the python 2.6.4 docs at: <http://docs.python.org/reference/expressions.html>
>
>
> The operator not in is defined to have
> the inverse true value of in.
>
>
> The operators is and is not test for
> object identity: x is y is true if and
> only if x and y are the same object. x
> is not y yields the inver... | `x in a` tests whether the element x is in a (which in this case would probably be a list or a string or some such) and returns `True` if it is.
`x not in a` is similar, but returns `False` if x is in a.
On the other hand, `x is not a` is analogous to `x != a` and `not x is a`.
And like you said, x == not 5 will giv... |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | The remainder of your question has been answered above, but I'll address the last question: the Zen of Python bit.
"There should only be one way to do it" isn't mean't in a mathematical sense. If it were, there'd be no `!=` operator, since that's just the inversion of `==`. Similarly, no `and` and `or` --- you can, af... | `x in a` tests whether the element x is in a (which in this case would probably be a list or a string or some such) and returns `True` if it is.
`x not in a` is similar, but returns `False` if x is in a.
On the other hand, `x is not a` is analogous to `x != a` and `not x is a`.
And like you said, x == not 5 will giv... |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | It's easy to check if there's any difference, with the [dis](http://docs.python.org/library/dis.html?highlight=dis#module-dis) module:
```
>>> dis.dis(compile('not a in b','','exec'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 COMPARE_OP ... | The remainder of your question has been answered above, but I'll address the last question: the Zen of Python bit.
"There should only be one way to do it" isn't mean't in a mathematical sense. If it were, there'd be no `!=` operator, since that's just the inversion of `==`. Similarly, no `and` and `or` --- you can, af... |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | Your documentation reference is nothing to do with syntax. [Try this](http://docs.python.org/reference/expressions.html#notin). Both `is not` and `not in` are two-word operators. | `x in a` tests whether the element x is in a (which in this case would probably be a list or a string or some such) and returns `True` if it is.
`x not in a` is similar, but returns `False` if x is in a.
On the other hand, `x is not a` is analogous to `x != a` and `not x is a`.
And like you said, x == not 5 will giv... |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | It's easy to check if there's any difference, with the [dis](http://docs.python.org/library/dis.html?highlight=dis#module-dis) module:
```
>>> dis.dis(compile('not a in b','','exec'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 COMPARE_OP ... | Your documentation reference is nothing to do with syntax. [Try this](http://docs.python.org/reference/expressions.html#notin). Both `is not` and `not in` are two-word operators. |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | It's easy to check if there's any difference, with the [dis](http://docs.python.org/library/dis.html?highlight=dis#module-dis) module:
```
>>> dis.dis(compile('not a in b','','exec'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 COMPARE_OP ... | `x in a` tests whether the element x is in a (which in this case would probably be a list or a string or some such) and returns `True` if it is.
`x not in a` is similar, but returns `False` if x is in a.
On the other hand, `x is not a` is analogous to `x != a` and `not x is a`.
And like you said, x == not 5 will giv... |
12,633,618 | I am new to python. I am working on some other's project but when i tried to run the code it give me the error said above. My all pages are working properly except those in which i had images. Is there any library required for the same??
Any help will be appreciable.
Thanks | 2012/09/28 | [
"https://Stackoverflow.com/questions/12633618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696228/"
] | you need to have `cropresize` package `http://pypi.python.org/pypi/cropresize/` installed on your device.
If it is not there install it from the link
Do `easy_install cropresize` or `pip install cropresize` | Just do [`easy_install cropresize`](http://pypi.python.org/pypi/cropresize/). |
12,633,618 | I am new to python. I am working on some other's project but when i tried to run the code it give me the error said above. My all pages are working properly except those in which i had images. Is there any library required for the same??
Any help will be appreciable.
Thanks | 2012/09/28 | [
"https://Stackoverflow.com/questions/12633618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696228/"
] | you need to have `cropresize` package `http://pypi.python.org/pypi/cropresize/` installed on your device.
If it is not there install it from the link
Do `easy_install cropresize` or `pip install cropresize` | cropresize package needs to be installed! First install pip(Ubuntu/Debian):
```
sudo apt-get install python-pip
```
Then install cropresize using pip:
```
pip install cropresize
``` |
12,633,618 | I am new to python. I am working on some other's project but when i tried to run the code it give me the error said above. My all pages are working properly except those in which i had images. Is there any library required for the same??
Any help will be appreciable.
Thanks | 2012/09/28 | [
"https://Stackoverflow.com/questions/12633618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696228/"
] | you need to have `cropresize` package `http://pypi.python.org/pypi/cropresize/` installed on your device.
If it is not there install it from the link
Do `easy_install cropresize` or `pip install cropresize` | cropresize (all versions) depends on PIL.
Unfortunately, Pillow (installed) does not satisfy this dependency when using pip or easy\_install :( |
12,633,618 | I am new to python. I am working on some other's project but when i tried to run the code it give me the error said above. My all pages are working properly except those in which i had images. Is there any library required for the same??
Any help will be appreciable.
Thanks | 2012/09/28 | [
"https://Stackoverflow.com/questions/12633618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696228/"
] | Just do [`easy_install cropresize`](http://pypi.python.org/pypi/cropresize/). | cropresize package needs to be installed! First install pip(Ubuntu/Debian):
```
sudo apt-get install python-pip
```
Then install cropresize using pip:
```
pip install cropresize
``` |
12,633,618 | I am new to python. I am working on some other's project but when i tried to run the code it give me the error said above. My all pages are working properly except those in which i had images. Is there any library required for the same??
Any help will be appreciable.
Thanks | 2012/09/28 | [
"https://Stackoverflow.com/questions/12633618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696228/"
] | Just do [`easy_install cropresize`](http://pypi.python.org/pypi/cropresize/). | cropresize (all versions) depends on PIL.
Unfortunately, Pillow (installed) does not satisfy this dependency when using pip or easy\_install :( |
33,168,308 | I have the following directory structure
```
-----root
|___docpd
|__docpd (contains settings.py, wsgi.py , uwsgi.ini)
|__static
```
During my vanilla django setup in dev environment , everything was fine (all static files used to load). But now after setting up uwsgi, i found that none of my static fi... | 2015/10/16 | [
"https://Stackoverflow.com/questions/33168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270865/"
] | in settings
```
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.normpath(os.path.join(BASE_DIR, "static")),
)
```
in urls.py
```
urlpatterns = [
#urls
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
``` | You could also do it like so:
```
uwsgi --ini uwsgi.ini --http :8000 --static-map /static=/path/to/staticfiles/
```
or just add this to your .ini file:
```
static-map = /static=/path/to/staticfiles
``` |
33,168,308 | I have the following directory structure
```
-----root
|___docpd
|__docpd (contains settings.py, wsgi.py , uwsgi.ini)
|__static
```
During my vanilla django setup in dev environment , everything was fine (all static files used to load). But now after setting up uwsgi, i found that none of my static fi... | 2015/10/16 | [
"https://Stackoverflow.com/questions/33168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270865/"
] | in settings
```
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.normpath(os.path.join(BASE_DIR, "static")),
)
```
in urls.py
```
urlpatterns = [
#urls
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
``` | I don't know why, but it starts work when I replace this code:
```
if settings.DEBUG:
urlpatterns += [
url(r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve'),
]
```
with this:
```
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL... |
33,168,308 | I have the following directory structure
```
-----root
|___docpd
|__docpd (contains settings.py, wsgi.py , uwsgi.ini)
|__static
```
During my vanilla django setup in dev environment , everything was fine (all static files used to load). But now after setting up uwsgi, i found that none of my static fi... | 2015/10/16 | [
"https://Stackoverflow.com/questions/33168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270865/"
] | I solved problem by doing below:
add
check-static = /your django dir/
in uwsgi.ini file.
it works for me!
Suppose your static assets are under /customers/foobar/app001/public. You want to check each request has a corresponding file in that directory before passing the request to your dynamic app. The --check-stati... | You could also do it like so:
```
uwsgi --ini uwsgi.ini --http :8000 --static-map /static=/path/to/staticfiles/
```
or just add this to your .ini file:
```
static-map = /static=/path/to/staticfiles
``` |
33,168,308 | I have the following directory structure
```
-----root
|___docpd
|__docpd (contains settings.py, wsgi.py , uwsgi.ini)
|__static
```
During my vanilla django setup in dev environment , everything was fine (all static files used to load). But now after setting up uwsgi, i found that none of my static fi... | 2015/10/16 | [
"https://Stackoverflow.com/questions/33168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270865/"
] | I solved problem by doing below:
add
check-static = /your django dir/
in uwsgi.ini file.
it works for me!
Suppose your static assets are under /customers/foobar/app001/public. You want to check each request has a corresponding file in that directory before passing the request to your dynamic app. The --check-stati... | I don't know why, but it starts work when I replace this code:
```
if settings.DEBUG:
urlpatterns += [
url(r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve'),
]
```
with this:
```
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL... |
33,168,308 | I have the following directory structure
```
-----root
|___docpd
|__docpd (contains settings.py, wsgi.py , uwsgi.ini)
|__static
```
During my vanilla django setup in dev environment , everything was fine (all static files used to load). But now after setting up uwsgi, i found that none of my static fi... | 2015/10/16 | [
"https://Stackoverflow.com/questions/33168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270865/"
] | You could also do it like so:
```
uwsgi --ini uwsgi.ini --http :8000 --static-map /static=/path/to/staticfiles/
```
or just add this to your .ini file:
```
static-map = /static=/path/to/staticfiles
``` | I don't know why, but it starts work when I replace this code:
```
if settings.DEBUG:
urlpatterns += [
url(r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve'),
]
```
with this:
```
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL... |
58,471,984 | Could anyone here tell me how to properly append series of missing values onto a python list?
for example,
```
> ls=[1,2,3]
> ls += []*2
> ls
[1,2,3]
```
but this is not the outcome I want. I want:
```
[1,2,3, , ]
```
where the blanks denotes for the missing values.
(note: also what I DON'T want is:
``... | 2019/10/20 | [
"https://Stackoverflow.com/questions/58471984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12205961/"
] | Where are you set dataSource and Deleagte methods of TableView?
use this code
```
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.register(UITabl... | 2 possible reasons:
1. If the cell is designed as prototype cell you **must not** register the cell.
2. `dataSource` and `delegate` of the table view must be connected to the controller in Interface Builder or set in code. |
59,622,544 | My Data frame is below
I am trying to find the age
```
customer_Id DOB
0 268408 1970-02-01
1 268408 1970-02-01
2 268408 1970-02-01
3 268408 1970-02-01
4 268408 1970-02-01
```
shape is of `207518`
while converting the data i got `ValueError: unconverted data remains: 5`
code is below to convert in ... | 2020/01/07 | [
"https://Stackoverflow.com/questions/59622544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can change your function for working with datetimes, also convert to strings is not necessary:
```
def cal_age(x):
y = dt.date.today()
age = y.year - x.year - ((y.month, x.day) < (y.month, x.day))
return age
df_n_4['DOB'] = pd.to_datetime(df_n_4['DOB'],errors='coerce')
df_n_4['Age'] = df_n_4.DOB.apply... | try this code,
```
df['current_date']=pd.datetime.now()
df['age']=(df.current_date-pd.to_datetime(df.DOB)).dt.days/365
``` |
66,484,870 | So I was developing a python program for my school project that asks a customer for their details such as their Firstname,Lastname,Age etc. So I made a function called customer details.
```
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Ag... | 2021/03/05 | [
"https://Stackoverflow.com/questions/66484870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13290732/"
] | You need to return the information from your `customerdetails` function. Since you have a bunch of different variables, you'll be returning a collection -- a tuple, a list, a dict, etc.
Using a tuple or a list means you need to keep track of the order of all the elements, and using a dict means you need to keep track ... | By default, variables declared within a function are local only to that function.
If you want a function to give back multiple values, you can `return` a tuple of values:
```py
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Age = input("A... |
66,484,870 | So I was developing a python program for my school project that asks a customer for their details such as their Firstname,Lastname,Age etc. So I made a function called customer details.
```
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Ag... | 2021/03/05 | [
"https://Stackoverflow.com/questions/66484870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13290732/"
] | You need to return the information from your `customerdetails` function. Since you have a bunch of different variables, you'll be returning a collection -- a tuple, a list, a dict, etc.
Using a tuple or a list means you need to keep track of the order of all the elements, and using a dict means you need to keep track ... | I think you propably wrote the print-functions into another function than the function you defined the variable Firstname etc. |
66,484,870 | So I was developing a python program for my school project that asks a customer for their details such as their Firstname,Lastname,Age etc. So I made a function called customer details.
```
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Ag... | 2021/03/05 | [
"https://Stackoverflow.com/questions/66484870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13290732/"
] | You need to return the information from your `customerdetails` function. Since you have a bunch of different variables, you'll be returning a collection -- a tuple, a list, a dict, etc.
Using a tuple or a list means you need to keep track of the order of all the elements, and using a dict means you need to keep track ... | ```
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Age = input("Age:")
Address =input("Enter your address:")
Postcode = input("Enter your Postcode:")
Email = input("Email:")
Phone = int(input("Phone Number:"))
return Firstname... |
41,994,645 | Is there a more functional way to create a 2d array in Javascript than what I have here? Perhaps using `.apply`?
```
generatePuzzle(size) {
let puzzle = [];
for (let i = 0; i < size; i++) {
puzzle[i] = [];
for (let j = 0; j < size; j++) {
puzzle[i][j] = Math.floor((Math.random() * 200) + 1);
}
... | 2017/02/02 | [
"https://Stackoverflow.com/questions/41994645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718122/"
] | ```
const repeat = (fn, n) => Array(n).fill(0).map(fn);
const rand = () => Math.floor((Math.random() * 200) + 1);
const puzzle = n => repeat(() => repeat(rand, n), n);
```
And then `puzzle(3)`, eg, will return a 3x3 matrix filled with random numbers. | With lodash just like below:
```
const _ = require('lodash');
function generatePuzzle(size) {
return _.times(size, () => _.times(size, () => (Math.random() * 200) + 1));
}
``` |
64,169,510 | I am using XEN hypervisor. For managing virtual Machine I am using **virt-manager** whenever I want to start to Virtual Machine at last when everything is ready and I click the create Button I get the following error
```
Unable to complete install: 'An error occurred, but the cause is unknown'
Traceback (most recent ... | 2020/10/02 | [
"https://Stackoverflow.com/questions/64169510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12966156/"
] | You can iterate over the result of the dynamic query directly:
```
create or replace function gapandoverlapdetection ( table_name text, entity_ids bigint[])
returns table (entity_id bigint, valid tsrange, causes_overlap boolean, causes_gap boolean)
as $$
declare
var_r record;
begin
for var_r in EXECUTE ... | Firstly, decide whether you want to pass the table's name or oid. If you want to identify the table by name, then the parameter should be of `text` type and not `regclass`.
Secondly, if you want the table name to change between executions then you need to [execute the SQL statement dynamically](https://www.postgresql.... |
60,404,756 | ```
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
```
I am cu... | 2020/02/25 | [
"https://Stackoverflow.com/questions/60404756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946446/"
] | That for loop is just taking the indices being used for the split and calling those rows of the original data to form the training and test sets. | StratifiedShuffleSplit is better if you are using a K-fold cross-validation, where you divide the training and testing data in different ways and then calculate the mean of a result in K iterations.
`n_splits` must equals the *K* value and in your case *K* is one, which makes no sense for cross-validation. I think you... |
70,310,388 | I have a list of nested dictionaries (python 3.9) that looks something like this:
```
records = [
{'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
{'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
{'Total:': {'Owner:': {'Available:': {'65 years and over': 2098}}}},
{'To... | 2021/12/10 | [
"https://Stackoverflow.com/questions/70310388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12413845/"
] | Recursion is an easy way to navigate and operate on arbitrarily nested structures:
```
def combine_into(d: dict, combined: dict) -> None:
for k, v in d.items():
if isinstance(v, dict):
combine_into(v, combined.setdefault(k, {}))
else:
combined[k] = v
combined = {}
for recor... | Quick solution: `res = NDict.from_list_of_dict(records).raw_dict`
Test:
```py
>>> from naapc import NDict
>>> records = [
... {'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
... {'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
... {'Total:': {'Owner:': {'Available:': {'6... |
9,638,826 | I'm using python to simulate some automation models, and with the help of matplotlib I'm producing plots like the one shown below.

I'm currently plotting with the following command:
```
ax.imshow(self.g, cmap=map, interpolation='nearest')
```
whe... | 2012/03/09 | [
"https://Stackoverflow.com/questions/9638826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38055/"
] | You can change the color map you are using via the `cmap` keyword. The color map `'Greys'` provides the effect you want. You can find a list of [available maps on the scipy website](http://scipy-cookbook.readthedocs.io/items/Matplotlib_Show_colormaps.html).
```
import matplotlib.pyplot as plt
import numpy as np
np.r... | There is an alternative method to Yann's answer that gives you finer control. Matplotlib's [imshow](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow) can take a `MxNx3` matrix where each entry is the RGB color value - just set them to white `[1,1,1]` or black `[0,0,0]` accordingly. If you ... |
18,080,556 | I have written a project in python which I am now in the process of moving to google app engine. The problem that occurs is when I run this code on GAE:
```
import requests
from google.appengine.api import urlfetch
def retrievePage(url, id):
response = 'http://online2.citybreak.com/Book/Package/Result.aspx?online... | 2013/08/06 | [
"https://Stackoverflow.com/questions/18080556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2656606/"
] | I think this will do it:
```
var text = "aaa bbb eee ccc <br>ddd eee fff ggg hhh iii jjj kkk";
var search = /eee [^e<>]*ggg/g;
console.log(text.search(search)); // a)
console.log(text.replace(search, "newinsertedstring $&")); // b)
``` | ```
var text = "whatever".Replace("eee fff ggg", "newinsertedstring eee fff ggg");
``` |
18,080,556 | I have written a project in python which I am now in the process of moving to google app engine. The problem that occurs is when I run this code on GAE:
```
import requests
from google.appengine.api import urlfetch
def retrievePage(url, id):
response = 'http://online2.citybreak.com/Book/Package/Result.aspx?online... | 2013/08/06 | [
"https://Stackoverflow.com/questions/18080556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2656606/"
] | >
> i want to find the line where the pattern which contains eee AND ggg is
>
>
>
That's a different question, but OK.
```
var text = "aaa bbb eee ccc <br>ddd eee fff ggg hhh iii jjj kkk",
search = "eee ggg";
var lines = text.split("<br>"),
terms = search.split(" "),
firstOccurence = new RegExp(terms... | ```
var text = "whatever".Replace("eee fff ggg", "newinsertedstring eee fff ggg");
``` |
18,080,556 | I have written a project in python which I am now in the process of moving to google app engine. The problem that occurs is when I run this code on GAE:
```
import requests
from google.appengine.api import urlfetch
def retrievePage(url, id):
response = 'http://online2.citybreak.com/Book/Package/Result.aspx?online... | 2013/08/06 | [
"https://Stackoverflow.com/questions/18080556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2656606/"
] | I think this will do it:
```
var text = "aaa bbb eee ccc <br>ddd eee fff ggg hhh iii jjj kkk";
var search = /eee [^e<>]*ggg/g;
console.log(text.search(search)); // a)
console.log(text.replace(search, "newinsertedstring $&")); // b)
``` | >
> i want to find the line where the pattern which contains eee AND ggg is
>
>
>
That's a different question, but OK.
```
var text = "aaa bbb eee ccc <br>ddd eee fff ggg hhh iii jjj kkk",
search = "eee ggg";
var lines = text.split("<br>"),
terms = search.split(" "),
firstOccurence = new RegExp(terms... |
12,558,878 | >
> **Possible Duplicate:**
>
> [Python 3.2.3 programming…Almost had it working](https://stackoverflow.com/questions/12558717/python-3-2-3-programming-almost-had-it-working)
>
>
>
```
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What perc... | 2012/09/24 | [
"https://Stackoverflow.com/questions/12558878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693293/"
] | There is a parentheses missing after `.format(x*(z/100))` that belongs to the preceding `print`.
It should be:
```
print ("Tip: ${}".format(x*(z/100)))
```
**UPDATE:** Not sure if you got it working or not yet, here is the complete code after fixing your unbalanced parentheses...
```
x = float(input("What is/was t... | You missed an end bracket after the third print: `.format(x*(z/100)))`
Here is what appears to be a working version after I fixed the brackets:
```
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What percentage tip would you like to leave?"))
pri... |
12,558,878 | >
> **Possible Duplicate:**
>
> [Python 3.2.3 programming…Almost had it working](https://stackoverflow.com/questions/12558717/python-3-2-3-programming-almost-had-it-working)
>
>
>
```
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What perc... | 2012/09/24 | [
"https://Stackoverflow.com/questions/12558878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693293/"
] | There is a parentheses missing after `.format(x*(z/100))` that belongs to the preceding `print`.
It should be:
```
print ("Tip: ${}".format(x*(z/100)))
```
**UPDATE:** Not sure if you got it working or not yet, here is the complete code after fixing your unbalanced parentheses...
```
x = float(input("What is/was t... | You're missing a close paren on the preceding line:
```
.format(x*(z/100))
``` |
13,221,021 | I'm trying to create a basic blogging application in Python using Web.Py. I have started without a direcotry structure, but soon I needed one. So I created this structure:
```
Blog/
├── Application/
│ ├── App.py
│ └── __init__.py
|
├── Engine/
│ ├── Connection/
│ │ ├── __init__.py
│ │ └── MySQLConnection... | 2012/11/04 | [
"https://Stackoverflow.com/questions/13221021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | No, you simply can't. AutoBean requires everything to be *statically typed*: no polymorphism, and no mixed-typed lists of maps.
You might be interested by RequestFactory's built-in support for JSON-RPC though. | Why do your params all need to be passed back in a list? Surely you're not going to do the same thing with a `String`, an `Integer`, and another `Object`! Just send them all back separately.
Further, you're not sending a custom `Object` over the JSON, you're sending the `objid` of that object... so just send the `Inte... |
34,759,366 | I have a python script that uses a while true and continues to run. In the while loop I have several if statements. Some of the if statements have a `time.sleep` in them. After using this for a while I notice that all of the if statements below the first `time.sleep` are waiting.
Is there way to have the if statement... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5729013/"
] | I have used a Javascript timer in the past to poll the server to test if the session is still active. If I receive a 403 then redirect to the login page.
```
var AutoLogout = {};
AutoLogout.pollInterval = 60000; // Default is 1 minute.
// Force auto logout when session expires
AutoLogout.start = function (heartBea... | I will try to solve your problem
I will suggest to put your logic in action filter
```
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContex... |
35,475,770 | Every forum I have looked at says that:
```
pip install pillow
```
remedies issues with installing pyautogui, however, I have installed pillow and I am still receiving:
```
python setup.py egg_info failed with error code 1
```
Any suggestions? I also tried installing PIL but that failed as well with the same erro... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35475770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365094/"
] | Some of the possible solutions.
1. Use an ajax method to get your resource by passing a key.
2. Use Hidden input fields and load values.
3. Use a dedicated jsp page to declare js variables or even a js function to get values according to key.
like this.
>
>
> ```
> <script type="text/javascript">
>
> var mess... | It is normally bad practice to use scriplets `<% %>` inside your `jsp` files.
You can use the `fmt` tag from the jstl core library to fetch information from your resource bundles.
```
<fmt:bundle basename="bundle">
<fmt:message var="variableName" key="bundleKey" />
</fmt:bundle>
<input type="hidden" name="hidden... |
35,475,770 | Every forum I have looked at says that:
```
pip install pillow
```
remedies issues with installing pyautogui, however, I have installed pillow and I am still receiving:
```
python setup.py egg_info failed with error code 1
```
Any suggestions? I also tried installing PIL but that failed as well with the same erro... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35475770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365094/"
] | It is normally bad practice to use scriplets `<% %>` inside your `jsp` files.
You can use the `fmt` tag from the jstl core library to fetch information from your resource bundles.
```
<fmt:bundle basename="bundle">
<fmt:message var="variableName" key="bundleKey" />
</fmt:bundle>
<input type="hidden" name="hidden... | Here is a different solution.
1. Load bundle like OP did, with the method `getBundle()`.
2. Using the third option on Arun's answer, create a separate JSP file to create a custom JavaScript object.
This is the content of said JSP:
```
<%@page import="com.tenea.intranet.conf.Conf" %>
<%@page import="java.util.Resourc... |
35,475,770 | Every forum I have looked at says that:
```
pip install pillow
```
remedies issues with installing pyautogui, however, I have installed pillow and I am still receiving:
```
python setup.py egg_info failed with error code 1
```
Any suggestions? I also tried installing PIL but that failed as well with the same erro... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35475770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365094/"
] | Some of the possible solutions.
1. Use an ajax method to get your resource by passing a key.
2. Use Hidden input fields and load values.
3. Use a dedicated jsp page to declare js variables or even a js function to get values according to key.
like this.
>
>
> ```
> <script type="text/javascript">
>
> var mess... | Based on what I have tried, you can use jstl library to print the translated messages directly into JavaScript like:
```
alert("<fmt:message key='line1'/>");
```
And if you are using struts2 for handling the locales you can easily define you Bundles getting either the struts2 locale, saved by the i18nInterceptor pre... |
35,475,770 | Every forum I have looked at says that:
```
pip install pillow
```
remedies issues with installing pyautogui, however, I have installed pillow and I am still receiving:
```
python setup.py egg_info failed with error code 1
```
Any suggestions? I also tried installing PIL but that failed as well with the same erro... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35475770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365094/"
] | Some of the possible solutions.
1. Use an ajax method to get your resource by passing a key.
2. Use Hidden input fields and load values.
3. Use a dedicated jsp page to declare js variables or even a js function to get values according to key.
like this.
>
>
> ```
> <script type="text/javascript">
>
> var mess... | Here is a different solution.
1. Load bundle like OP did, with the method `getBundle()`.
2. Using the third option on Arun's answer, create a separate JSP file to create a custom JavaScript object.
This is the content of said JSP:
```
<%@page import="com.tenea.intranet.conf.Conf" %>
<%@page import="java.util.Resourc... |
35,475,770 | Every forum I have looked at says that:
```
pip install pillow
```
remedies issues with installing pyautogui, however, I have installed pillow and I am still receiving:
```
python setup.py egg_info failed with error code 1
```
Any suggestions? I also tried installing PIL but that failed as well with the same erro... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35475770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365094/"
] | Based on what I have tried, you can use jstl library to print the translated messages directly into JavaScript like:
```
alert("<fmt:message key='line1'/>");
```
And if you are using struts2 for handling the locales you can easily define you Bundles getting either the struts2 locale, saved by the i18nInterceptor pre... | Here is a different solution.
1. Load bundle like OP did, with the method `getBundle()`.
2. Using the third option on Arun's answer, create a separate JSP file to create a custom JavaScript object.
This is the content of said JSP:
```
<%@page import="com.tenea.intranet.conf.Conf" %>
<%@page import="java.util.Resourc... |
63,378,402 | I am trying to stream Elasticsearch data into Snowflake. I am testing a python script which ultimately will be deployed as a cloud function/docker app on AWS. For historical I am using the `scroll` API to write x amount of objects into a string and the string to a file. I've used Snowflake's `PUT file://file.json.gz @s... | 2020/08/12 | [
"https://Stackoverflow.com/questions/63378402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9972301/"
] | If you create a Snowflake Stage linked to an S3 when you save to your S3, with whatever you decide to use, it will be automatically on your Snowflake Stage, this way, you can just send a COPY INTO command and save a step or two.
In my opinion, it's a simple and handy solution.
if you need the steps, let me know and I... | You can use snowpipe. You need to create smaller files continuously and using snowpipe, keep on uploading them. You can use Amazon Kinesis Firehose to manage the batches.
Refer to documentation at <https://docs.snowflake.com/en/user-guide/data-load-considerations-prepare.html#continuous-data-loads-i-e-snowpipe-and-file... |
17,160,968 | Can inputting and checking be done in the same line in python?
Eg) in C we have
```
if (scanf("%d",&a))
```
The above statement if block works if an integer input is given. But similarly,
```
if a=input():
```
Doesn't work in python. Is there a way to do it? | 2013/06/18 | [
"https://Stackoverflow.com/questions/17160968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2046858/"
] | No, Python can't do assignment as part of the condition of an `if` statement. The only way to do it is on two lines:
```
a=input()
if a:
// Your code here
pass
```
This is by design, as it means that assignment is maintained as an atomic action, independent of comparison. This can help with readability of th... | You can't do it. This was a deliberate design choice for Python because this construct is good for causing hard to find bugs.
see @Jonathan's comment on the question for an example |
57,860,405 | My understanding of Python asserts is that are meant for debugging and that they don't get executed for "optimized" Python code (`python -O`).
For production app engine code, is `-O` used and thus stripping asserts or will asserts get executed? | 2019/09/09 | [
"https://Stackoverflow.com/questions/57860405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136598/"
] | I ran a test on the platforms I use to know for sure. Asserts do get executed for:
* GAE standard first generation
* GAE flexible | As far as i understand from Python asserts, once you set the global assertions to -0 they all become "null-operations" as in, they will get compiled but won't be evaluated or have they're conditional expressions executed.
They get set like that at the Python interpreter level so i don't think that GAE actually affect... |
25,888,828 | I'm trying to make an script which takes all rows starting by 'HELIX', 'SHEET' and 'DBREF' from a .txt, from that rows takes some specifical columns and then saves the results on a new file.
```
#!/usr/bin/python
import sys
if len(sys.argv) != 3:
print("2 Parameters expected: You must introduce your pdb file and ... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25888828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4027271/"
] | cols\_id, cols\_h and cols\_s seems to be lists, not strings.
You can only write a string in your file so you have to convert the list to a string.
```
modified_data.write(' '.join(cols_id))
```
and similar.
`'!'.join(a_list_of_things)` converts the list into a string separating each element with an exclamation mar... | You need to convert the tuple created on RHS in your assignments to string.
```
# Replace this with statement given below
cols_id = dbref[0], dbref[3:5], dbref[8:10]
# Create a string out of the tuple
cols_id = ''.join((dbref[0], dbref[3:5], dbref[8:10]))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.